query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
listlengths
0
101
negative_scores
listlengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
Parse will attempt to parse a configuration file
func (p *Parser) Parse() (*ast.ConfigurationFile, error) { f := ast.NewConfigurationFile() for !p.curTokenIs(token.EOF) { stmt := p.parseStatement() if stmt != nil { f.Statements = append(f.Statements, stmt) } p.Next() } var err error if len(p.errors) > 0 { err = fmt.Errorf("parsing error: there were %d errors while parsing configuration file", len(p.errors)) } return f, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Parse(cfg string) error {\n\tif cfg == \"\" {\n\t\treturn fmt.Errorf(\"use -c to specify configuration file\")\n\t}\n\n\tif !file.IsExist(cfg) {\n\t\treturn fmt.Errorf(\"configuration file %s is nonexistent\", cfg)\n\t}\n\n\tConfigFile = cfg\n\n\tconfigContent, err := file.ToTrimString(cfg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"read configuration file %s fail %s\", cfg, err.Error())\n\t}\n\n\tvar c GlobalConfig\n\terr = json.Unmarshal([]byte(configContent), &c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parse configuration file %s fail %s\", cfg, err.Error())\n\t}\n\n\tconfigLock.Lock()\n\tdefer configLock.Unlock()\n\tconfig = &c\n\n\tlog.Println(\"load configuration file\", cfg, \"successfully\")\n\treturn nil\n}", "func (c Config) Parse(file string) (initializedConfig Config) {\n\tif _, err := os.Stat(file); os.IsNotExist(err) {\n\t\tlog.WithFields(log.Fields{\"file\": file, \"error\": err}).Panic(\"File does not exist\")\n\t}\n\n\tb, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"file\": file, \"error\": err}).Panic(\"Can't parse config file\")\n\t}\n\n\tif err = json.Unmarshal(b, &initializedConfig); err != nil {\n\t\tlog.WithFields(log.Fields{\"file\": file, \"error\": err}).Panic(\"Can't unmarshal JSON\")\n\t}\n\n\treturn\n}", "func Parse(filename string) (*Config, error) {\n\t// I get the raw configuration data...\n\trawConfig := parseRawConfig(filename)\n\t// ... and I parse it accordingly to its version\n\tswitch rawConfig.Version {\n\tcase \"1.0\":\n\t\treturn parseVersion1dot0(rawConfig, path.Dir(filename))\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown config file version \\\"%s\\\"\", rawConfig.Version)\n\t}\n}", "func (hc *Hailconfig) Parse() error {\n\tfiles, err := hc.loader.Load()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to load\")\n\t}\n\tf := files[0] // Currently only on .hailconfig file is supported.\n\thc.f = f\n\t_, err = toml.DecodeReader(hc.f, &hc.config)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to decode\")\n\t}\n\treturn nil\n}", "func Parse(filepath string) (config Config, err error) {\n\tlog.Printf(\"read config file: %q\\n\", filepath)\n\tconfigBytes, err := ioutil.ReadFile(filepath)\n\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\terr = json.Unmarshal(configBytes, &config)\n\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\treturn config, nil\n}", "func (c *Config) Parse(flagSet *pflag.FlagSet) error {\n\t// Load config file if specified.\n\tvar (\n\t\tmeta *toml.MetaData\n\t\terr error\n\t)\n\tif configFile, _ := flagSet.GetString(\"config\"); configFile != \"\" {\n\t\tmeta, err = configutil.ConfigFromFile(c, configFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Ignore the error check here\n\tconfigutil.AdjustCommandLineString(flagSet, &c.Log.Level, \"log-level\")\n\tconfigutil.AdjustCommandLineString(flagSet, &c.Log.File.Filename, \"log-file\")\n\tconfigutil.AdjustCommandLineString(flagSet, &c.Metric.PushAddress, \"metrics-addr\")\n\tconfigutil.AdjustCommandLineString(flagSet, &c.Security.CAPath, \"cacert\")\n\tconfigutil.AdjustCommandLineString(flagSet, &c.Security.CertPath, \"cert\")\n\tconfigutil.AdjustCommandLineString(flagSet, &c.Security.KeyPath, \"key\")\n\tconfigutil.AdjustCommandLineString(flagSet, &c.BackendEndpoints, \"backend-endpoints\")\n\tconfigutil.AdjustCommandLineString(flagSet, &c.ListenAddr, \"listen-addr\")\n\tconfigutil.AdjustCommandLineString(flagSet, &c.AdvertiseListenAddr, \"advertise-listen-addr\")\n\n\treturn c.adjust(meta)\n}", "func (*Config) Parse(filename string) (y config.Configer, err error) {\n\tcnf, err := ReadYmlReader(filename)\n\tif err != nil {\n\t\treturn\n\t}\n\ty = &ConfigContainer{\n\t\tdata: cnf,\n\t}\n\treturn\n}", "func (c *Config) Parse() error {\n\ts := flag.String(\"c\", \"\", \"configuration file for channer server\")\n\ta := flag.String(\"a\", \"\", \"client asset setting which is generated by webpack\")\n\tdevdb := flag.String(\"devdb\", \"\", \"specify development database hostname\")\n\tflag.Parse()\n\terr := c.Load(*s)\n\tc.AssetsConfigPath = *a\n\tc.DBHost = *devdb\n\treturn err\n}", "func Parse(src []byte, filename string) (c *Config, err error) {\n\tvar diags hcl.Diagnostics\n\n\tfile, diags := hclsyntax.ParseConfig(src, filename, hcl.Pos{Line: 1, Column: 1})\n\tif diags.HasErrors() {\n\t\treturn nil, fmt.Errorf(\"config parse: %w\", diags)\n\t}\n\n\tc = &Config{}\n\n\tdiags = gohcl.DecodeBody(file.Body, nil, c)\n\tif diags.HasErrors() {\n\t\treturn nil, fmt.Errorf(\"config parse: %w\", diags)\n\t}\n\n\treturn c, nil\n}", "func (c *Config) Parse() (interface{}, error) {\n\treturn c.Execute()\n}", "func (c *Config) Parse(path string) error {\n\tvar err error\n\tif path, err = filepath.Abs(path); err != nil {\n\t\treturn err\n\t}\n\tf, err := os.Open(filepath.Clean(path))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() { catch(f.Close()) }()\n\treturn json.NewDecoder(f).Decode(c)\n}", "func (p *Parser) Parse(c *Configuration) (err *ConfigurationError) {\n\tif p != nil {\n\t\tif p.lexer.NextToken(); p.lexer.Token.Kind == TkError {\n\t\t\treturn &ConfigurationError{\n\t\t\t\tFilename: p.lexer.Filename,\n\t\t\t\tLine: p.lexer.Token.Line,\n\t\t\t\tColumn: p.lexer.Token.Column,\n\t\t\t\tmsg: p.lexer.Token.Value.(string),\n\t\t\t}\n\t\t}\n\t\tfor p.lexer.Token.Kind != TkEOF {\n\t\t\tif err := p.parseConfig(c, \"\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func Parse() error {\n\tif err := parseFlags(); err != nil {\n\t\tlog.Fatalln(\"Error parsing flags:\", err)\n\t}\n\tif err := parseConfigFile(); err != nil {\n\t\tlog.Fatalln(\"Error parsing config file:\", err)\n\t}\n\treturn nil\n}", "func (cfg *Configurator) Parse(tgt interface{}) error {\n\tif tgt != nil && cfg.ProgramName != \"\" {\n\t\tif exepath.ProgramNameSetter == \"default\" {\n\t\t\texepath.ProgramName = cfg.ProgramName\n\t\t}\n\n\t\tconfigurable.Register(cstruct.MustNew(tgt, cfg.ProgramName))\n\t}\n\n\tadaptflag.Adapt()\n\tadaptenv.Adapt()\n\tflag.Parse()\n\tif cfg.ProgramName != \"\" {\n\t\terr := adaptconf.Load(cfg.ProgramName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tcfg.configFilePath = adaptconf.LastConfPath()\n\treturn nil\n}", "func (c *Config) Parse(filename string) error {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := JSONUnmarshal(f, &c); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Parse(r io.Reader, filename, format string) (*Config, error) {\n\tsrc, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar config Config\n\treturn &config, hclsimple.Decode(\"config.hcl\", src, nil, &config)\n}", "func (c *Config) Parse() error {\n\treturn envconfig.Process(\"\", c)\n}", "func Parse() (*Config, error) {\n\tconfigBytes, err := findConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn parseConfigFile(configBytes)\n}", "func (c *Config) Parse(path string) (Config, error) {\n\tconfigFile, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn *c, err\n\t}\n\t// check file existence\n\tif _, existErr := os.Stat(path); existErr != nil && os.IsNotExist(existErr) {\n\t\treturn *c, errors.New(\"config file does not exist at \" + path)\n\t}\n\t// parse file\n\terr = yaml.Unmarshal(configFile, c)\n\tif err != nil {\n\t\treturn *c, errors.New(\"config file cannot be parsed, check your syntax \")\n\t}\n\treturn *c, err\n}", "func ParseFile(filePath string) error {\n\t// read configuration file\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\treturn Parse(bufio.NewScanner(file))\n}", "func Parse() (*Configuration, error) {\n\tmanager := viper.New()\n\tmanager.AutomaticEnv()\n\n\tmanager.SetConfigType(configType)\n\tmanager.AddConfigPath(\".\")\n\n\tif err := manager.ReadInConfig(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfiguration := new(Configuration)\n\tif err := mapToStructure(manager, configuration); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn configuration, nil\n}", "func Parse(fpath string) (Settings, error) {\n\tbase := defaultSettings()\n\n\tsettings, err := parseConfig(fpath, base)\n\tif err != nil {\n\t\treturn Settings{}, err\n\t}\n\n\tif err := validate(settings); err != nil {\n\t\treturn Settings{}, err\n\t}\n\n\treturn settings, nil\n}", "func (c *Config) Parse(arguments []string) error {\n\t// Parse first to get config file.\n\terr := c.FlagSet.Parse(arguments)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif c.printVersion {\n\t\tfmt.Printf(GetRawSyncerInfo())\n\t\treturn flag.ErrHelp\n\t}\n\n\t// Load config file if specified.\n\tif c.configFile != \"\" {\n\t\terr = c.configFromFile(c.configFile)\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t}\n\n\t// Parse again to replace with command line options.\n\terr = c.FlagSet.Parse(arguments)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif len(c.FlagSet.Args()) != 0 {\n\t\treturn errors.Errorf(\"'%s' is an invalid flag\", c.FlagSet.Arg(0))\n\t}\n\n\tc.adjust()\n\n\treturn nil\n}", "func (c *ConfigParser) Parse() (err error) {\n\terr = nil\n\tfd, err := os.Open(c.fname)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer fd.Close()\n\tvar section string\n\tscanner := bufio.NewScanner(fd)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tswitch {\n\t\tcase c.regexp(\"secMatch\").MatchString(line):\n\t\t\tsection = c.regexp(\"secMatch\").FindStringSubmatch(line)[1]\n\t\t\tif c.HasSection(section) {\n\t\t\t\tetext := fmt.Sprintf(\"Duplicate section found: '%s'\", section)\n\t\t\t\terr = errors.New(etext)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tc.addSection(section)\n\t\t\t}\n\t\tcase c.regexp(\"confPair\").MatchString(line):\n\t\t\tif section == \"\" {\n\t\t\t\tetext := fmt.Sprintf(\"Option pair not declared within a section: '%s'\", line)\n\t\t\t\terr = errors.New(etext)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpair := c.regexp(\"confPair\").FindStringSubmatch(line)\n\t\t\tkey := pair[1]\n\t\t\tval := pair[2]\n\t\t\tif c.HasOption(section, key) {\n\t\t\t\tetext := fmt.Sprintf(\"Duplicate option '%s' found in section '%s'.\", key, section)\n\t\t\t\terr = errors.New(etext)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\terr = c.addSecOpt(section, key, val)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\terr = c.interpolation()\n\tif err != nil {\n\t\treturn\n\t}\n\tc.parsed = true\n\tflat, err := c.GetFlatConfigMap()\n\tif err != nil {\n\t\treturn\n\t}\n\t// Iterate over the list of registered options, see if they're set\n\tvar etext, value string\n\tfor key, option := range c.Options {\n\t\tklist := strings.Split(key, \"-\")\n\t\tif len(klist) == 1 {\n\t\t\t// If this is a top-level option, check for it in flat. Error\n\t\t\t// only if it's Required value is True\n\t\t\tif value, ok := flat[key]; !ok {\n\t\t\t\tif option.Required() {\n\t\t\t\t\tetext = fmt.Sprintf(\"Top-level option %s has not been set but is required.\", key)\n\t\t\t\t\terr = errors.New(etext)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toption.Set(value)\n\t\t\t}\n\t\t} else {\n\t\t\tname := klist[0]\n\t\t\tsection := klist[1]\n\t\t\tif !c.HasSection(section) {\n\t\t\t\tfmt.Println(\"No section: \", section)\n\t\t\t\tif option.Required() {\n\t\t\t\t\tetext = fmt.Sprintf(\"Option %s was expected in section %s but this section does not exist.\", name, section)\n\t\t\t\t\terr = errors.New(etext)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvalue, err = c.GetOption(section, name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif option.Required() {\n\t\t\t\t\t\tetext = fmt.Sprintf(\"Option %s does not exist in section %s.\", name, section)\n\t\t\t\t\t\terr = errors.New(etext)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\toption.Set(value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (cfg *Config) Parse(file string) error {\n\tb, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = yaml.Unmarshal(b, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Config) Parse() error {\n\tc.pgUser = os.Getenv(\"PG_USER\")\n\tc.pgPass = os.Getenv(\"PG_PASS\")\n\tc.pgDB = os.Getenv(\"PG_DB\")\n\tc.pgHost = os.Getenv(\"PG_HOST\")\n\tif c.pgHost == \"\" {\n\t\treturn errors.New(\"Missing PG_HOST\")\n\t}\n\tif c.pgUser == \"\" {\n\t\treturn errors.New(\"Missing PG_USER\")\n\t}\n\tif c.pgPass == \"\" {\n\t\treturn errors.New(\"Missing PG_PASS\")\n\t}\n\tif c.pgDB == \"\" {\n\t\treturn errors.New(\"Missing PG_DB\")\n\t}\n\treturn nil\n}", "func parseFile(s *setup) error {\n\tif _, err := os.Stat(s.configFilePath); os.IsNotExist(err) {\n\t\t// Config file is not present. We ignore this when we are using\n\t\t// the default config file, but we escalate if the user provided\n\t\t// the config file explicitely.\n\t\tif s.customConfigFile {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"config file at %v does not exist\", s.configFilePath)\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tcontent, err := ioutil.ReadFile(s.configFilePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"error reading config file at %v: %v\", s.configFilePath, err)\n\t}\n\n\treturn parseFileContent(s, content)\n}", "func (c *Config) Parse(src string) (*Config, error) {\n\tif src == \"\" {\n\t\treturn nil, errors.New(\"nothing to parse, config file is empty\")\n\t}\n\ttmpl, err := template.New(\"cfg\").Funcs(template.FuncMap{\"password\": getPass, \"prompt\": prompt}).Parse(src)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not parse template %s: %v\", tmpl.Name(), err)\n\t}\n\n\tv := viper.New()\n\tv.SetConfigType(\"yaml\")\n\n\tdata, err := unmarshal(v, c.data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpr, pw := io.Pipe()\n\tgo func(pw *io.PipeWriter, data interface{}) {\n\t\tif err := tmpl.Execute(pw, &data); err != nil {\n\t\t\tpw.CloseWithError(err)\n\t\t\treturn\n\t\t}\n\t\tpw.Close()\n\t}(pw, data)\n\n\tvar buf bytes.Buffer\n\tif err := v.ReadConfig(io.TeeReader(pr, &buf)); err != nil {\n\t\treturn nil, err\n\t}\n\tc.text = buf.String()\n\n\tif err := v.Unmarshal(c); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}", "func (c *Config) Parse(arguments []string) error {\n\t// Parse first to get config file.\n\terr := c.FlagSet.Parse(arguments)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif c.printVersion {\n\t\tfmt.Printf(utils.GetRawInfo(\"importer\"))\n\t\treturn flag.ErrHelp\n\t}\n\n\t// Load config file if specified.\n\tif c.configFile != \"\" {\n\t\terr = c.configFromFile(c.configFile)\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t}\n\n\t// Parse again to replace with command line options.\n\terr = c.FlagSet.Parse(arguments)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\t// Non-flag arguments is not empty\n\tif len(c.FlagSet.Args()) != 0 {\n\t\treturn errors.Errorf(\"'%s' is an invalid flag\", c.FlagSet.Arg(0))\n\t}\n\n\treturn nil\n}", "func Parse(dir, filename string) (cfg *Config, err error) {\n\tcfg = new(Config)\n\tbody, err := ioutil.ReadFile(dir + \"/\" + filename)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = yaml.Unmarshal(body, cfg)\n\tif err != nil {\n\t\treturn\n\t}\n\tcfg.Home = dir\n\treturn\n}", "func (c *Config) Parse(arguments []string) error {\n\t// Parse first to get config file.\n\terr := c.flagSet.Parse(arguments)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\t// Load config file if specified.\n\tvar meta *toml.MetaData\n\tif c.configFile != \"\" {\n\t\tmeta, err = configutil.ConfigFromFile(c, c.configFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Parse again to replace with command line options.\n\terr = c.flagSet.Parse(arguments)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif len(c.flagSet.Args()) != 0 {\n\t\treturn errors.Errorf(\"'%s' is an invalid flag\", c.flagSet.Arg(0))\n\t}\n\n\tc.Adjust(meta)\n\treturn nil\n}", "func Parse() (*Config, error) {\n\tvar cfg Config\n\n\t// with config file loaded into env values, we can now parse env into our config struct\n\terr := envconfig.Process(\"app\", &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// alias sqlite to sqlite3\n\tif cfg.Database.Driver == \"sqlite\" {\n\t\tcfg.Database.Driver = \"sqlite3\"\n\t}\n\n\t// use absolute path to sqlite3 database\n\tif cfg.Database.Driver == \"sqlite3\" {\n\t\tcfg.Database.Name, _ = filepath.Abs(cfg.Database.Name)\n\t}\n\n\treturn &cfg, nil\n}", "func (c *Config) Parse(args []string) error {\n\tif len(args) != 2 {\n\t\treturn errors.New(\"Expected one arg\")\n\t}\n\n\targs = strings.Split(args[1], \" (\")\n\n\tvar err error\n\n\tc.Size, err = c.dimensions(args[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Points, err = c.coordinates(args[1:])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.check(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Parse(env environ.Values, r io.Reader) (*run.Config, error) {\n\tc := Config{}\n\tm, err := toml.DecodeReader(r, &c)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"error parsing config file\")\n\t}\n\tundec := m.Undecoded()\n\tif len(undec) > 0 {\n\t\tlog.Println(\"Warning: unknown values present in config file:\", undec)\n\t}\n\n\tif len(c.Schemas) == 0 {\n\t\treturn nil, errors.New(\"no schemas specified in config\")\n\t}\n\n\tif c.NameConversion == \"\" {\n\t\treturn nil, errors.New(\"no NameConversion specified in config\")\n\t}\n\tif len(c.ExcludeTables) > 0 && len(c.IncludeTables) > 0 {\n\t\treturn nil, errors.New(\"both include tables and exclude tables\")\n\t}\n\tif c.OutputDir == \"\" {\n\t\tc.OutputDir = \".\"\n\t}\n\n\tinclude, err := parseTables(c.IncludeTables, c.Schemas)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texclude, err := parseTables(c.ExcludeTables, c.Schemas)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg := &run.Config{\n\t\tConfigData: data.ConfigData{\n\t\t\tConnStr: c.ConnStr,\n\t\t\tDBType: c.DBType,\n\t\t\tSchemas: c.Schemas,\n\t\t\tNullableTypeMap: c.NullableTypeMap,\n\t\t\tTypeMap: c.TypeMap,\n\t\t\tPostRun: c.PostRun,\n\t\t\tExcludeTables: exclude,\n\t\t\tIncludeTables: include,\n\t\t\tOutputDir: c.OutputDir,\n\t\t\tStaticDir: c.StaticDir,\n\t\t\tPluginDirs: c.PluginDirs,\n\t\t\tNoOverwriteGlobs: c.NoOverwriteGlobs,\n\t\t},\n\t\tParams: c.Params,\n\t}\n\td, err := getDriver(strings.ToLower(c.DBType))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg.Driver = d\n\n\tenviron.FuncMap[\"plugin\"] = environ.Plugin(c.PluginDirs)\n\n\tt, err := template.New(\"NameConversion\").Funcs(environ.FuncMap).Parse(c.NameConversion)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"error parsing NameConversion template\")\n\t}\n\tcfg.NameConversion = t\n\n\tif len(c.TemplateEngine.CommandLine) != 0 {\n\t\tfor _, s := range c.TemplateEngine.CommandLine {\n\t\t\tt, err = template.New(\"EngineCLI\").Funcs(environ.FuncMap).Parse(s)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithMessage(err, \"error parsing TemplateEngine CLI template\")\n\t\t\t}\n\t\t\tcfg.TemplateEngine.CommandLine = append(cfg.TemplateEngine.CommandLine, t)\n\t\t}\n\t\tcfg.TemplateEngine.UseStdin = c.TemplateEngine.UseStdin\n\t\tcfg.TemplateEngine.UseStdout = c.TemplateEngine.UseStdout\n\t}\n\n\tuseEngine := len(c.TemplateEngine.CommandLine) != 0\n\tcfg.SchemaPaths, err = parseOutputTargets(c.SchemaPaths, useEngine)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"error parsing SchemaPaths\")\n\t}\n\n\tcfg.TablePaths, err = parseOutputTargets(c.TablePaths, useEngine)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"error parsing TablePaths\")\n\t}\n\n\tcfg.EnumPaths, err = parseOutputTargets(c.EnumPaths, useEngine)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"error parsing EnumPaths\")\n\t}\n\n\tif len(cfg.EnumPaths) == 0 && len(cfg.TablePaths) == 0 && len(cfg.SchemaPaths) == 0 {\n\t\treturn nil, errors.New(\"no output paths defined, so no output will be generated\")\n\t}\n\n\tcfg.ConnStr = os.Expand(c.ConnStr, func(s string) string {\n\t\treturn env.Env[s]\n\t})\n\treturn cfg, nil\n}", "func Parse(reader io.Reader, location string) (conf Config, err error) {\n\t// decode conf file, don't care about the meta data.\n\t_, err = toml.NewDecoder(reader).Decode(&conf)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\tfor _, m := range conf.Maps {\n\t\tfor k, p := range m.Parameters {\n\t\t\tp.Normalize()\n\t\t\tm.Parameters[k] = p\n\t\t}\n\t}\n\n\tconf.LocationName = location\n\n\tconf.ConfigureTileBuffers()\n\n\treturn conf, nil\n}", "func Parse(r io.Reader) (*Config, error) {\n\tvar f file\n\tmd, err := toml.DecodeReader(r, &f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif u := md.Undecoded(); len(u) > 0 {\n\t\treturn nil, fmt.Errorf(\"unrecognized configuration keys: %s\", u)\n\t}\n\n\t// Must configure at least one interface.\n\tif len(f.Interfaces) == 0 {\n\t\treturn nil, errors.New(\"no configured interfaces\")\n\t}\n\n\tc := &Config{\n\t\tInterfaces: make([]Interface, 0, len(f.Interfaces)),\n\t}\n\n\t// Validate debug configuration if set.\n\tif f.Debug.Address != \"\" {\n\t\tif _, err := net.ResolveTCPAddr(\"tcp\", f.Debug.Address); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"bad debug address: %v\", err)\n\t\t}\n\t\tc.Debug = f.Debug\n\t}\n\n\ts, err := parseStorage(f.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.Storage = *s\n\n\t// Don't bother to check for valid interface names; that is more easily\n\t// done when trying to create a listener. Instead, check for things\n\t// like subnet validity.\n\tfor _, ifi := range f.Interfaces {\n\t\tif ifi.Name == \"\" {\n\t\t\treturn nil, errors.New(\"empty interface name\")\n\t\t}\n\n\t\t// Narrow down the location of a configuration error.\n\t\thandle := func(err error) error {\n\t\t\treturn fmt.Errorf(\"interface %q: %v\", ifi.Name, err)\n\t\t}\n\n\t\t// Default to 1 hour leases, but parse a different value if specified.\n\t\tdur := 1 * time.Hour\n\t\tif ifi.LeaseDuration != \"\" {\n\t\t\td, err := time.ParseDuration(ifi.LeaseDuration)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid lease duration: %v\", err)\n\t\t\t}\n\n\t\t\tdur = d\n\t\t}\n\n\t\tsubnets := make([]wgipam.Subnet, 0, len(ifi.Subnets))\n\t\tfor _, s := range ifi.Subnets {\n\t\t\tsub, err := parseSubnet(s)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, handle(err)\n\t\t\t}\n\n\t\t\tsubnets = append(subnets, *sub)\n\t\t}\n\n\t\tif err := checkSubnets(subnets); err != nil {\n\t\t\treturn nil, handle(err)\n\t\t}\n\n\t\tc.Interfaces = append(c.Interfaces, Interface{\n\t\t\tName: ifi.Name,\n\t\t\tLeaseDuration: dur,\n\t\t\tSubnets: subnets,\n\t\t})\n\t}\n\n\treturn c, nil\n}", "func Parser() {\n\tif err = conf.Parse(configLocation); err != nil {\n\t\tlogger.Logger.Panicln(err)\n\t}\n\n\tparseMysql()\n\tparseGrpc()\n\tparseHTTP()\n\tparseVolumeHandle()\n}", "func Parse(file string) error {\n\tonce.Do(func() {\n\t\t// Reading the flags\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error in ReadFile:\", err)\n\t\t}\n\t\tif err := json.Unmarshal(data, &Cfg); err != nil {\n\t\t\tlog.Println(\"Error in Unmarshal:\", err)\n\t\t}\n\t})\n\treturn nil\n}", "func ParseFile(filename string) (*Config, error) {\n\tvar config Config\n\treturn &config, hclsimple.DecodeFile(filename, nil, &config)\n}", "func ParseConfig(filepath string) error {\n\tf, err := ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconf := make(map[string]interface{})\n\n\terr = json.Unmarshal(f, &conf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconList := make(map[string]Elem)\n\tconfig = list{self: \"\", value: conList}\n\n\tlog.Printf(\"about to parse config\\n\")\n\tparseMap(conf, &config)\n\tlog.Printf(\"parsed config\\n\")\n\n\treturn nil\n}", "func ParseFile(p string) (*Config, error) {\n\tf, err := os.Open(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn Parse(f)\n}", "func Parse(rawConfig []byte) (Config, error) {\n\tvar config Config\n\tif err := toml.Unmarshal(rawConfig, &config); err != nil {\n\t\treturn Config{}, err\n\t}\n\treturn config, nil\n}", "func Parse(config interface{}) {\n\t// load config to flag\n\tloadRawConfig(pflag.CommandLine, config)\n\n\t// parse flags\n\tutil.InitFlags()\n\tif err := goflag.CommandLine.Parse([]string{}); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// parse config file if exists\n\tif err := decJSON(pflag.CommandLine, config); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}", "func ParseFile(path string) (*Config, error) {\n\n\t// Read file\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Unable to open config.json. Please check the file is present\")\n\t}\n\n\tdefer file.Close()\n\n\tconfig := Config{}\n\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &config, nil\n}", "func Parser() {\n\tif err = conf.Parse(configLocation); err != nil {\n\t\tlogger.Logger.Panicln(err)\n\t}\n\n\tparseHTTP()\n\n}", "func ParseFile(configFilePath string) (*Config, error) {\n\t// Read the config file\n\tconfigData, err := ioutil.ReadFile(configFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Parse the config JSON\n\tconfig := Config{}\n\terr = json.Unmarshal(configData, &config)\n\tif err != nil {\n\t\treturn nil, errors.New(\"invalid config file\")\n\t}\n\n\t// Validate the ports\n\tif config.TelnetPort <= 0 {\n\t\treturn nil, errors.New(\"invalid telnet port\")\n\t}\n\n\tif config.WebPort <= 0 {\n\t\treturn nil, errors.New(\"invalid web port\")\n\t}\n\n\t// Validate the web client path\n\tinfo, err := os.Stat(config.WebClientPath)\n\tif (err != nil && os.IsNotExist(err)) || !info.IsDir() {\n\t\treturn nil, errors.New(\"invalid web client path\")\n\t}\n\n\treturn &config, nil\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 parseConfig(pathToFile string) error {\n\tf, err := os.Open(pathToFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ti := 0\n\tfor scanner.Scan() {\n\t\ti++\n\t\ttrip := parseLine(i, scanner.Text())\n\t\tif trip.IsValid() {\n\t\t\tallTriplets = append(allTriplets, trip)\n\t\t}\n\t}\n\n\tif i == 0 {\n\t\treturn errors.New(\"Empty config file\")\n\t}\n\n\treturn nil\n}", "func ParseFile(path string) (*Config, error) {\n\tdat, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn Parse(string(dat))\n}", "func Parse(config string) test.Error {\n\tlines := strings.Split(config, \"\\n\")\n\n\tif len(lines) == 1 {\n\t\treturn parseConfigRule(lines[0])\n\t}\n\n\tfor i, ln := range lines {\n\t\terr := parseConfigRule(ln)\n\t\tif err != nil {\n\t\t\treturn err.Prepend(\"error on line %d: \", i+1)\n\t\t}\n\t}\n\n\treturn nil\n}", "func Parse() *Config {\n\tcfg := &Config{\n\t\tIPFSNode: \"https://ipfs.infura.io:5001\",\n\t\tHandleHiddenFiles: false,\n\t}\n\tprintVersion := false\n\n\tflag.StringVar(&cfg.IPFSNode, \"node\", cfg.IPFSNode, \"The url of IPFS node to use.\")\n\tflag.BoolVar(&cfg.HandleHiddenFiles, \"H\", cfg.HandleHiddenFiles, \"Include files that are hidden. Only takes effect on directory add.\")\n\tflag.BoolVar(&printVersion, \"v\", printVersion, \"Print program version.\")\n\n\tflag.CommandLine.Usage = func() {\n\t\tout := flag.CommandLine.Output()\n\t\t_, _ = fmt.Fprintf(out, `USAGE:\n %s [options] <path>...\n\nARGUMENTS\n\n <path>... - The path to a file to be added to ipfs.\n\nOPTIONS\n\n`, os.Args[0])\n\t\tflag.PrintDefaults()\n\t\t_, _ = fmt.Fprintf(out, `\nDESCRIPTION\n\n Adds contents of <path> to ipfs. Note that directories are added recursively, to form the ipfs\n MerkleDAG.\n`)\n\t}\n\tflag.Parse()\n\n\tif printVersion {\n\t\t_, _ = fmt.Fprintf(flag.CommandLine.Output(), \"Version: %s\\tBuildTime: %v\\tGitHash: %s\\n\", Version, BuildTime, GitHash)\n\t\tos.Exit(0)\n\t}\n\n\tif flag.NArg() == 0 {\n\t\t_, _ = fmt.Fprintln(flag.CommandLine.Output(), \"the <path> to a file is not provided\")\n\t\tflag.CommandLine.Usage()\n\t\tos.Exit(3)\n\t}\n\n\tcfg.Paths = flag.Args()\n\n\treturn cfg\n}", "func Parse() error {\n\terr := ex.FlagSet.Parse(os.Args[1:])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ex.ParseEnv(os.Environ())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcf := ex.FlagSet.Lookup(DefaultConfigFlagName)\n\tif cf == nil {\n\t\treturn nil\n\t}\n\tpath := cf.Value.String()\n\tif len(path) > 0 {\n\t\tinfo, err := os.Stat(path)\n\t\tif err != nil || info.IsDir() {\n\t\t\treturn errors.New(\"Invalid config file.\")\n\t\t}\n\t\text := filepath.Ext(path)\n\t\tswitch ext {\n\t\tcase \".toml\":\n\t\t\treturn ex.ParseTOML(path)\n\t\tdefault:\n\t\t\treturn errors.New(\"Unsupported config file.\")\n\t\t}\n\t}\n\treturn nil\n}", "func Parse(input string) (*ast.File, error) {\n\tswitch lexMode(input) {\n\tcase lexModeHcl:\n\t\treturn hclParser.Parse([]byte(input))\n\tcase lexModeJson:\n\t\treturn jsonParser.Parse([]byte(input))\n\t}\n\n\treturn nil, fmt.Errorf(\"unknown config format\")\n}", "func Parse(p Provider) (*Config, error) {\n\tv, err := p.Provide()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Config{v: v}, nil\n}", "func (c *configInitializer) parseConfig(configFile string) {\n\tfd, err := os.Open(configFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fd.Close()\n\n\tcfgBytes, err := ioutil.ReadAll(fd)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal([]byte(cfgBytes), c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Parse() error {\n\tcfg, err := executor.Parse()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif cfg.General.ExternalUI != \"\" {\n\t\troute.SetUIPath(cfg.General.ExternalUI)\n\t}\n\n\tif cfg.General.ExternalController != \"\" {\n\t\tgo route.Start(cfg.General.ExternalController, cfg.General.Secret)\n\t}\n\n\texecutor.ApplyConfig(cfg, true)\n\treturn nil\n}", "func Parse(r io.Reader) (*Config, error) {\n\tout, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseBytes(out)\n}", "func Parse(rd io.Reader) (*Configuration, error) {\n\tin, err := ioutil.ReadAll(rd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := NewParser(\"thatiq\", []VersionedParseInfo{\n\t\t{\n\t\t\tVersion: MajorMinorVersion(0, 1),\n\t\t\tParseAs: reflect.TypeOf(v0_1Configuration{}),\n\t\t\tConversionFunc: func(c interface{}) (interface{}, error) {\n\t\t\t\tif v0_1, ok := c.(*v0_1Configuration); ok {\n\t\t\t\t\tif v0_1.Log.Level == Loglevel(\"\") {\n\t\t\t\t\t\tv0_1.Log.Level = Loglevel(\"info\")\n\t\t\t\t\t}\n\n\t\t\t\t\treturn (*Configuration)(v0_1), nil\n\t\t\t\t}\n\t\t\t\treturn nil, fmt.Errorf(\"Expected *v0_1Configuration, received %#v\", c)\n\t\t\t},\n\t\t},\n\t})\n\n\tconfig := new(Configuration)\n\terr = p.Parse(in, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config, nil\n}", "func (c *Config) Parse(data []byte) error {\n\treturn yaml.Unmarshal(data, c)\n}", "func parseConfig() {\n\tif parsed {\n\t\treturn\n\t}\n\tkingpin.Parse()\n\tparsed = true\n\treturn\n}", "func Parser() {\n\tif err = conf.Parse(configLocation); err != nil {\n\t\tlogger.Logger.Panicln(err)\n\t}\n\n\tparseMysql()\n\tparseHTTP()\n\tparseIpmi()\n\tparseWOL()\n}", "func Parse(conf interface{}) (*ConfInfo, error) {\n\treturn ParseWithOptions(conf, Options{})\n}", "func Parse(data []byte) (*Configfile, error) {\n\tr := &Configfile{\n\t\tfilename: \"config.yaml\",\n\t}\n\n\tif err := yaml.Unmarshal(data, r); err != nil {\n\t\treturn r, err\n\t}\n\treturn r, nil\n}", "func parseConfig(path string) (config *Config, err error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer file.Close()\n\tdata, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn\n\t}\n\tconfig = &Config{}\n\tif err = json.Unmarshal(data, config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn\n}", "func Parse(data []byte) (*Config, error) {\n\tc, err := Decode(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func (c *Conf) Parse() error {\n\treturn conftags.Parse(&c.Server)\n}", "func (c *Config) ParseFile(filepath string) (err error) {\n\t_, err = toml.DecodeFile(filepath, c)\n\treturn\n}", "func parseConfig(fileName string) (*Config, error) {\n\t// read config\n\tf, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tfb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cfg Config\n\terr = json.Unmarshal(fb, &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cfg, nil\n}", "func (c *Cli) Parse() entity.Config {\n\tflag.Parse()\n\treturn entity.Config{\n\t\tInput: *c.input,\n\t\tOutput: *c.output,\n\t\tTemplate: *c.template,\n\t\tType: c.parseType(),\n\t\tQuiet: *c.quiet,\n\t\tHelp: *c.help,\n\t\tNoExample: *c.noExample,\n\t}\n}", "func ParseFile(file string) (*Config, error) {\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn Parse(data)\n}", "func Parse(cfg *Configurator, tgt interface{}) error {\n\tif cfg == nil {\n\t\tcfg = &Configurator{}\n\t}\n\n\treturn cfg.Parse(tgt)\n}", "func Parser() {\n\tif err = conf.Parse(configLocation); err != nil {\n\t\tlogger.Logger.Panicln(err)\n\t}\n\n\tparseHTTP()\n\tparseFlute()\n\tparseCello()\n\tparseHarp()\n\tparseViola()\n\tparseViolin()\n\tparseViolinNoVnc()\n\tparsePiano()\n}", "func ParseConfig(cfg string) {\n\tif cfg == \"\" {\n\t\tlog.Fatalln(\"Config file not specified: use -c $filename\")\n\t}\n\n\tif !file.IsExist(cfg) {\n\t\tlog.Fatalln(\"Config file specified not found:\", cfg)\n\t}\n\n\tconfigContent, err := file.ToTrimString(cfg)\n\tif err != nil {\n\t\tlog.Fatalln(\"Read config file\", cfg, \"error:\", err.Error())\n\t}\n\n\tvar c GlobalConfig\n\terr = json.Unmarshal([]byte(configContent), &c)\n\tif err != nil {\n\t\tlog.Fatalln(\"Parse config file\", cfg, \"error:\", err.Error())\n\t}\n\n\t// set config\n\tconfigLock.Lock()\n\tdefer configLock.Unlock()\n\tConfig = &c\n\n\tprintDebug(2, \"ParseConfig:\", cfg, \"[DONE.]\")\n}", "func ParseCfgFile(cfgFile string) (*Config, error) {\n\tlogrus.Info(\"**** FILE PROVIDED**** \", cfgFile)\n\tif cfgFile == \"\" {\n\t\treturn nil, fmt.Errorf(\"no config file provided\")\n\t}\n\n\tfilename, err := getAbsFilename(cfgFile)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tyamlFile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg := &Config{}\n\terr = yaml.Unmarshal(yamlFile, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\temptyurl := URL{}\n\tif cfg.KairosdbURL == emptyurl {\n\t\treturn nil, fmt.Errorf(\"kairosdb-url is mandatory\")\n\t}\n\n\tif cfg.Server.Port == \"\" {\n\t\tcfg.Server.Port = defaultServerPort\n\t}\n\n\tif cfg.MetricnamePrefix != \"\" {\n\t\tregex, err := NewRegexp(\".*\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trelabelConfig := &RelabelConfig{\n\t\t\tSourceLabels: model.LabelNames{model.MetricNameLabel},\n\t\t\tRegex: regex,\n\t\t\tAction: RelabelAddPrefix,\n\t\t\tPrefix: cfg.MetricnamePrefix,\n\t\t}\n\n\t\tcfg.MetricRelabelConfigs = append(cfg.MetricRelabelConfigs, relabelConfig)\n\t}\n\n\terr = validateMetricRelabelConfigs(cfg.MetricRelabelConfigs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.Timeout == 0*time.Second {\n\t\tlogrus.Infof(\"timeout not provided. Setting it to default value of %s\", defaultTimeout)\n\t\tcfg.Timeout = defaultTimeout\n\t}\n\tif cfg.Timeout > maxTimeout {\n\t\treturn nil, fmt.Errorf(\"timeout %d is too high. It should be between %v and %v\", cfg.Timeout, minTimeout, maxTimeout)\n\t}\n\n\tif cfg.Timeout < minTimeout {\n\t\treturn nil, fmt.Errorf(\"timeout %d is too low. It should be between %v and %v\", cfg.Timeout, minTimeout, maxTimeout)\n\t}\n\n\treturn cfg, nil\n}", "func (c *Config) parse() (interface{}, error) {\n\tdefer func() { c.parsed = true }()\n\tif c.parsed {\n\t\tc.Reset()\n\t}\n\tc.setupEnvAndFlags(c.cfg)\n\tc.Cmd.Flags().Visit(func(arg0 *pflag.Flag) {\n\t\tif arg0.Name == \"help\" {\n\t\t\tos.Exit(0)\n\t\t}\n\t})\n\n\tif len(os.Args) > 1 && len(c.Args) == 0 {\n\t\tc.Args = os.Args[1:]\n\t}\n\t_, flags, _ := c.Cmd.Find(c.Args)\n\tc.Cmd.ParseFlags(flags)\n\tconfigFile := c.Viper.GetString(\"config\")\n\tif configFile != \"\" {\n\t\t_, err := os.Stat(configFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tc.Viper.SetConfigFile(configFile) // name of config file\n\t\t// Find and read the config file\n\t\tif err = c.Viper.ReadInConfig(); err != nil { // Handle errors reading the config file\n\t\t\treturn nil, err\n\t\t}\n\t\tif err = c.Viper.Unmarshal(c.cfg); err != nil { // Handle errors reading the config file\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar err error\n\tif err = c.getCfg(c.cfg); err != nil {\n\t\treturn c.cfg, err\n\t}\n\treturn c.cfg, nil\n}", "func Parse(ops *ServerOption) error {\n\tconf.Parse(ops)\n\treturn nil\n}", "func ParseConfig(src []byte) (c *Config, err error) {\n\t// Create the empty configuration.\n\tc = &Config{\n\t\tHosts: make([]HostConfig, 0),\n\t}\n\n\t// Create a scanner.\n\ts := newConfigScanner(src)\n\n\t// Iterate across the tokens.\n\tvar host *HostConfig\n\tvar match *HostMatchConfig\n\tvar keyword string\n\targs := make([]string, 0, 1)\n\n\tfor {\n\t\ttok, lit := s.Scan()\n\t\tif err = s.Err(); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Handle illegal characters.\n\t\tif tok == CT_ILLEGAL {\n\t\t\terr = &ParseError{\"unexpected or illegal character in configuration file\"}\n\t\t\treturn\n\t\t}\n\n\t\t// Handle end-of-file state.\n\t\tif tok == CT_EOF {\n\t\t\tbreak\n\t\t}\n\n\t\t// Handle end-of-line.\n\t\tif tok == CT_EOL {\n\t\t\t// Handle complete lines.\n\t\t\tif keyword != \"\" {\n\t\t\t}\n\t\t}\n\n\t\t// Handle normal states.\n\t\tswitch {\n\t\tcase tok == CT_KEYWORD:\n\t\t\tif keyword == \"\" {\n\t\t\t\tkeyword = lit\n\t\t\t} else {\n\t\t\t\targs = append(args, lit)\n\t\t\t}\n\n\t\tcase tok == CT_EQUAL:\n\t\t\tbreak\n\n\t\tcase tok == CT_STRING:\n\t\t\tif keyword == \"\" {\n\t\t\t\terr = &ParseError{\"expected configuration keyword at beginning of line\"}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\targs = append(args, lit)\n\n\t\tcase tok == CT_EOL && keyword != \"\":\n\t\t\tkwLower := strings.ToLower(keyword)\n\n\t\t\tif host == nil && kwLower != \"host\" {\n\t\t\t\terr = &ParseError{\"expected Host directive before other configuration diretives\"}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tswitch kwLower {\n\t\t\tcase \"host\":\n\t\t\t\thost = &HostConfig{\n\t\t\t\t\tHostPatterns: args,\n\t\t\t\t\tOptions: make(ConfigOptionMap),\n\t\t\t\t\tMatches: make([]HostMatchConfig, 0),\n\t\t\t\t}\n\t\t\t\tmatch = nil\n\t\t\t\tc.Hosts = append(c.Hosts, *host)\n\n\t\t\tcase \"match\":\n\t\t\t\tif len(args) < 1 {\n\t\t\t\t\terr = &ParseError{\"a Match directive must at specify contain a condition type\"}\n\t\t\t\t}\n\n\t\t\t\tmatch = &HostMatchConfig{\n\t\t\t\t\tConditionType: args[0],\n\t\t\t\t\tConditionArgs: args[1:],\n\t\t\t\t\tOptions: make(ConfigOptionMap),\n\t\t\t\t}\n\t\t\t\thost.Matches = append(host.Matches, *match)\n\n\t\t\tdefault:\n\t\t\t\tif match != nil {\n\t\t\t\t\tmatch.Options.Set(keyword, args)\n\t\t\t\t} else {\n\t\t\t\t\thost.Options.Set(keyword, args)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tkeyword = \"\"\n\t\t\targs = make([]string, 0, 1)\n\t\t}\n\t}\n\n\treturn\n}", "func ParseConfig(f *os.File) i3conf {\n\tmod := ModKeys[DefaultModKey]\n\n\tv := make(map[string]string)\n\tm := make(map[string]string)\n\n\tic := i3conf{path: f.Name(), modifier: mod, variables: v, conf: m}\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tflds := s.Fields(scanner.Text())\n\t\tif len(flds) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tswitch flds[0] {\n\t\tcase \"set\":\n\t\t\tif s.Contains(line, \"Mod\") {\n\t\t\t\tmod = ModKeys[flds[2]]\n\t\t\t\tic.modifier = mod\n\t\t\t\tic.variables[flds[1]] = mod\n\t\t\t} else {\n\t\t\t\tic.variables[flds[1]] = s.Join(flds[2:], \" \")\n\t\t\t}\n\t\tcase \"bindsym\":\n\t\t\tic.conf[flds[1]] = s.Join(flds[2:], \" \")\n\t\t\tic.AddToConfig(flds)\n\t\tdefault:\n\t\t\tcontinue // Is this necessary?\n\t\t}\n\t}\n\treturn ic\n}", "func Parse(configBytes []byte) (*Cfg, error) {\n\tvar gc Cfg\n\n\terr := json.Unmarshal(configBytes, &gc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = gc.checkErrors()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &gc, err\n}", "func (c *Configurator) Parse(arguments []string, environment map[string]string) error {\n\terr := c.env().Parse(environment)\n\tif err != nil {\n\t\tswitch c.errorHandling {\n\t\tcase ContinueOnError:\n\t\t\treturn err\n\t\tcase ExitOnError:\n\t\t\tfmt.Fprintln(c.out(), err)\n\t\t\tos.Exit(2)\n\t\tcase PanicOnError:\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\terr = c.flag().Parse(arguments)\n\tif err == flag.ErrHelp {\n\t\tc.usage()\n\n\t\tswitch c.errorHandling {\n\t\tcase ContinueOnError:\n\t\t\treturn err\n\t\tcase ExitOnError, PanicOnError:\n\t\t\t// Exit here without outputting the error\n\t\t\tos.Exit(2)\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tswitch c.errorHandling {\n\t\tcase ContinueOnError:\n\t\t\treturn err\n\t\tcase ExitOnError:\n\t\t\tfmt.Fprintln(c.out(), err)\n\t\t\tos.Exit(2)\n\t\tcase PanicOnError:\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func ParseConfig(path string) Config {\n file, err := os.Open(path)\n if err != nil {\n log.Panicf(\"Can't load config: %s\", err.Error())\n }\n decoder := json.NewDecoder(file)\n var config Config\n err = decoder.Decode(&config)\n if err != nil {\n log.Panicf(\"Can't parse config file: %s. Error: %s\", path, err.Error())\n }\n return config\n}", "func ParseConfig() model.Configuration {\n\tvar configuration = model.Configuration{}\n\tfile, err := loadFileConfig()\n\tif err != nil {\n\t\treturn configuration\n\t}\n\tdecoder := json.NewDecoder(file)\n\tdecoder.Decode(&configuration)\n\treturn configuration\n}", "func ParseConfigFile() Configuration {\n\tfile, _ := os.Open(\"config.json\")\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\tconfiguration := Configuration{}\n\terr := decoder.Decode(&configuration)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif configuration.StartDate.IsZero() {\n\t\tconfiguration.StartDate = time.Now().Local()\n\t}\n\tif configuration.EndDate.IsZero() {\n\t\tconfiguration.EndDate = time.Now().Local()\n\t}\n\treturn configuration\n}", "func Parse(config interface{}) { Define(config); flag.Parse() }", "func parse(yml []byte) *Conf {\n\tc := new(Conf)\n\te := yaml.Unmarshal(yml, c)\n\tutil.LogPanic(e)\n\treturn c\n}", "func (m *Motifini) ParseConfigFile() error {\n\t// Preload our defaults.\n\tm.Conf = &Config{}\n\tm.Info.Println(\"Loading Configuration File:\", m.Flag.ConfigFile)\n\tswitch buf, err := ioutil.ReadFile(m.Flag.ConfigFile); {\n\tcase err != nil:\n\t\treturn err\n\tcase strings.Contains(m.Flag.ConfigFile, \".json\"):\n\t\treturn json.Unmarshal(buf, &m.Conf)\n\tcase strings.Contains(m.Flag.ConfigFile, \".xml\"):\n\t\treturn xml.Unmarshal(buf, &m.Conf)\n\tdefault:\n\t\treturn toml.Unmarshal(buf, &m.Conf)\n\t}\n}", "func parseConfig(file *os.File) (Config, error) {\n\tbuilderConfig := Config{}\n\ttomlMetadata, err := toml.NewDecoder(file).Decode(&builderConfig)\n\tif err != nil {\n\t\treturn Config{}, errors.Wrap(err, \"decoding toml contents\")\n\t}\n\n\tundecodedKeys := tomlMetadata.Undecoded()\n\tif len(undecodedKeys) > 0 {\n\t\tunknownElementsMsg := config.FormatUndecodedKeys(undecodedKeys)\n\n\t\treturn Config{}, errors.Errorf(\"%s in %s\",\n\t\t\tunknownElementsMsg,\n\t\t\tstyle.Symbol(file.Name()),\n\t\t)\n\t}\n\n\treturn builderConfig, nil\n}", "func Parse(data []byte) (*Config, error) {\n\tvar err error\n\tc := &Config{}\n\tif err = yaml.Unmarshal(data, c); err != nil {\n\t\treturn c, err\n\t}\n\terr = c.validate()\n\treturn c, err\n}", "func parseConfig(path string) (Config, error) {\n\tconfig := Config{}\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\treturn config, err\n\t}\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\treturn config, nil\n}", "func (conf *Config) ParseConfigFile(path string) error {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(data, &conf); err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"config\": conf,\n\t}).Info(\"Config file parsed\")\n\n\treturn nil\n}", "func FuzzConfigurationParse(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\trd := bytes.NewReader(data)\n\t\t_, _ = Parse(rd)\n\t})\n}", "func Parse() error {\n\treturn ParseFromEnvironment(defaultEnvironment)\n}", "func (s *S) TestConfig_Parse(c *check.C) {\n\t// Parse configuration.\n\tvar conf Config\n\tif _, err := toml.Decode(`\n\t\t[meta]\n\t\t\tdebug = true\n\t\t\tdir = \"/var/lib/megam/gulp/meta\"\n\t\t\tnsq = \"192.168.1.100:4161\"\n\n`, &c); err != nil {\n\t\t//t.Fatal(err)\n\t}\n\n\tc.Assert(conf.NSQd, check.Equals, \"192.168.1.100:4161\")\n}", "func Parse(r io.Reader) (INI, error) {\n\tconf := New()\n\n\tif err := conf.parse(r); err != nil {\n\t\treturn nil, err\n\t}\n\treturn conf, nil\n}", "func Parse() (commandLine CommandLine) {\n\tflag.StringVar(&commandLine.Log, \"log\", \"info\", \"log level (trace|debug|info|warn|error|fatal)\")\n\tflag.StringVar(&commandLine.ConfigFolder, \"config\", \"./\", \"config file directory path\")\n\tflag.Parse()\n\treturn\n}", "func (s *ossServer) parseConfig(path string) (*dataRun.Config, error) {\n\tpath = s.resolvePath(path)\n\t// Use demo configuration if no config path is specified.\n\tif path == \"\" {\n\t\treturn nil, errors.New(\"missing config file\")\n\t}\n\n\tconfig := dataRun.NewConfig()\n\tif err := config.FromTomlFile(path); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config, nil\n}", "func (c *Config) ParseConfig(filename string) *Config {\n\tyamlFile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Printf(\"yamlFile.Get err #%v \", err)\n\t}\n\terr = yaml.Unmarshal(yamlFile, c)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unmarshal: %v\", err)\n\t}\n\treturn c\n}", "func parseConfiguration() Config {\n\n\t// the package import path should be supplied via flag or environment variable\n\tconfig := Config{}\n\n\t// initialize a string for our ignore values\n\tvar ignore string\n\tvar arguments string\n\n\t// parse additional information from the command line\n\tflag.StringVar(&config.ProjectPath, \"project\", \"\", \"the path of the project relative to the go source directory\")\n\tflag.StringVar(&config.Directory, \"directory\", \"\", \"(optional) relative path to the directory of the current go package to watch\")\n\tflag.StringVar(&ignore, \"ignore\", \"\", \"(optional) directories to ignore when watching for changes\")\n\tflag.StringVar(&arguments, \"args\", \"\", \"(optional) arguments to pass to the service on start\")\n\tflag.Parse()\n\n\t// try to parse the data from the environment if not supplied via flag\n\tif config.ProjectPath == \"\" {\n\t\tconfig.ProjectPath = os.Getenv(\"PROJECT\")\n\t}\n\n\tif config.Directory == \"\" {\n\t\tconfig.Directory = os.Getenv(\"DIRECTORY\")\n\t}\n\n\tif ignore == \"\" {\n\t\tignore = os.Getenv(\"IGNORE\")\n\t}\n\n\tif arguments == \"\" {\n\t\targuments = os.Getenv(\"ARGUMENTS\")\n\t}\n\n\t// set the project path to tmp if not specified -> this will break package\n\t// imports that are contained in the same project directory\n\tif config.ProjectPath == \"\" {\n\t\tconfig.ProjectPath = tmpProjectPath\n\t}\n\n\t// ensure that the subdirectory starts with a slash\n\tif config.Directory != \"\" && strings.HasPrefix(config.Directory, \"/\") == false {\n\t\tconfig.Directory = \"/\" + config.Directory\n\t}\n\n\tif ignore != \"\" {\n\t\tconfig.Ignore = strings.Split(ignore, \",\")\n\n\t\tfor index, value := range config.Ignore {\n\t\t\tvalue = strings.TrimSpace(value)\n\t\t\tconfig.Ignore[index] = strings.TrimLeft(value, \"/\")\n\t\t}\n\t}\n\n\tif arguments != \"\" {\n\t\tconfig.Arguments = strings.Split(arguments, \" \")\n\t}\n\n\treturn config\n\n}", "func (parser envParser) Parse(r io.Reader) (interface{}, error) {\n\tcnf, ok := r.(*conf)\n\tif !ok {\n\t\treturn nil, errs.New(0, \"provided reader must be a a *conf pointer\")\n\t}\n\tcnf.values = ValueMap{}\n\tfor _, e := range os.Environ() {\n\t\tp1 := strings.Split(e, \"\\n\")\n\t\tif len(p1) > 0 {\n\t\t\tp2 := strings.Split(p1[0], \"=\")\n\t\t\tswitch {\n\t\t\tcase \"_\" == p2[0]:\n\t\t\t\tcontinue\n\t\t\tcase strings.HasPrefix(p2[0], \"BASH_FUNC_\"):\n\t\t\t\tcontinue\n\t\t\tcase \"\" != cnf.envPrefix && !strings.HasPrefix(p2[0], cnf.envPrefix):\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcnf.values[p2[0]] = NewVal(String, os.Getenv(p2[0]))\n\t\t}\n\t}\n\treturn cnf, nil\n}", "func parseConfig(configFile string) error {\n\tdata, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tlog.Println(\"Unable to read config file\", err)\n\t\treturn err\n\t}\n\t//log.Println(string(data))\n\terr = json.Unmarshal(data, &Config)\n\tif err != nil {\n\t\tlog.Println(\"Unable to parse config\", err)\n\t\treturn err\n\t}\n\tif Config.StompIterations == 0 {\n\t\tConfig.StompIterations = 3 // number of Stomp attempts\n\t}\n\tif Config.ContentType == \"\" {\n\t\tConfig.ContentType = \"application/json\"\n\t}\n\tif Config.StompSendTimeout == 0 {\n\t\tConfig.StompSendTimeout = 1000 // miliseconds\n\t}\n\tif Config.StompRecvTimeout == 0 {\n\t\tConfig.StompRecvTimeout = 1000 // miliseconds\n\t}\n\t//log.Printf(\"%v\", Config)\n\treturn nil\n}" ]
[ "0.7959544", "0.7713189", "0.77075493", "0.7688069", "0.7596493", "0.75740665", "0.75603443", "0.75329983", "0.7495221", "0.74803764", "0.7468595", "0.7455103", "0.7432136", "0.74304706", "0.74287313", "0.7399076", "0.73904854", "0.7304604", "0.7284187", "0.72573584", "0.72511345", "0.72295207", "0.7166644", "0.7130073", "0.70929205", "0.70761013", "0.70642513", "0.7062837", "0.7060815", "0.7057471", "0.7047446", "0.70469046", "0.7044871", "0.7029907", "0.7027942", "0.7025773", "0.7013932", "0.7000175", "0.6997146", "0.69964284", "0.6961865", "0.6955214", "0.69474727", "0.6911483", "0.68914104", "0.68804586", "0.6874966", "0.6857136", "0.6851858", "0.68375325", "0.6817845", "0.681705", "0.6810922", "0.68109155", "0.6793587", "0.67861336", "0.67772084", "0.6754161", "0.67408276", "0.67377776", "0.6734892", "0.6729153", "0.67241335", "0.671916", "0.67186195", "0.67133766", "0.67081785", "0.6695055", "0.6684957", "0.66744316", "0.66637266", "0.6637013", "0.6633615", "0.66163486", "0.6581378", "0.6576833", "0.6575264", "0.6551263", "0.6546006", "0.65317726", "0.6526151", "0.65208733", "0.65186435", "0.6509888", "0.65098524", "0.6507564", "0.6494099", "0.64854014", "0.64832795", "0.6470867", "0.64676", "0.64632857", "0.6459745", "0.6445966", "0.64451045", "0.6444412", "0.6424692", "0.64199215", "0.64140254", "0.6405808" ]
0.7084995
25
Next will roll the parser forward by one token
func (p *Parser) Next() { p.curr = p.peek p.peek = p.l.NextToken() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Parser) next() *Token {\n\tif len(p.tokens) > 0 {\n\t\tt := p.tokens[0]\n\t\tp.tokens = p.tokens[1:]\n\t\treturn t\n\t}\n\treturn p.lexer.NextToken()\n}", "func (p *parser) next() (t token) {\n\tp.fill()\n\tif len(p.buf) > 0 {\n\t\tt = p.buf[0]\n\t\tp.buf = p.buf[1:]\n\t}\n\tp.fill()\n\n\treturn\n}", "func (c *Compiler) next() {\n\tc.tokenIndex++\n}", "func (p *Parser) nextToken() {\n\tp.curToken = p.peekToken\n\tp.peekToken = p.l.NextToken()\n}", "func (p *Parser) nextToken() {\n\tp.curToken = p.peekToken\n\tp.peekToken = p.l.NextToken()\n}", "func (pars *Parser) nextToken() {\n\tpars.thisToken = pars.peekToken\n\tpars.peekToken = pars.lex.NextToken()\n}", "func (p *parser) next() token {\n\tif p.peekCount > 0 {\n\t\tp.peekCount--\n\t} else {\n\t\tp.token[0], _ = p.lex.nextToken()\n\t}\n\treturn p.token[p.peekCount]\n}", "func (p *parser) next() token {\n\tvar tok token\n\tif p.lookAheadTok != nil {\n\t\ttok = *p.lookAheadTok\n\t\tp.lookAheadTok = nil\n\t} else {\n\t\ttok = p.lex.nextToken()\n\t}\n\treturn tok\n}", "func (p *Parser) nextToken() {\n\tp.prevToken = p.curToken\n\tp.curToken = p.peekToken\n\tp.peekToken = p.l.NextToken()\n}", "func (p *parser) tokenNext() tree.Token {\n\ttok := p.token()\n\tp.next()\n\treturn tok\n}", "func (f *tokenFormat) nextToken(customVerbs []string) (token, error) {\n\tfor {\n\t\tr, _, err := f.stream.ReadRune()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch r {\n\t\tcase ' ':\n\t\t\treturn spaceToken{}, nil\n\t\tcase ':':\n\t\t\treturn f.readAction(customVerbs)\n\t\tdefault:\n\t\t\treturn f.readLiteral(r)\n\t\t}\n\t}\n}", "func (lex *Lexer) Next() {\n\tdefer func() {\n\t\tif lex.debug {\n\t\t\t_, file, line, ok := runtime.Caller(2)\n\t\t\tif ok {\n\t\t\t\tlog.Printf(\n\t\t\t\t\t\"[DEBUG] Text=[%s], Token=[%v], Pos=[%s] called from %s:%d\\n\",\n\t\t\t\t\tlex.Text,\n\t\t\t\t\tlex.Token,\n\t\t\t\t\tlex.Pos,\n\t\t\t\t\tfilepath.Base(file),\n\t\t\t\t\tline,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar err error\n\tlex.Token, lex.Text, lex.Pos, err = lex.scanner.Scan()\n\tlex.RawText = lex.scanner.LastScanRaw()\n\tif err != nil {\n\t\tlex.scanErr = err\n\t\tlex.Error(lex, err)\n\t}\n}", "func (z *Tokenizer) Next() Token {\n\tz.Scan()\n\treturn z.tok\n}", "func (p *parser) next() {\n\tif p.look != nil {\n\t\t// Consume stored state.\n\t\tp.tokenstate = *p.look\n\t\tp.look = nil\n\t\treturn\n\t}\n\n\tp.off, p.tok, p.lit = p.scanner.Scan()\n\n\tp.pre = nil\n\t// Skip over prefix tokens, accumulating them in p.pre.\n\tfor p.tok.IsPrefix() {\n\t\tp.pre = append(p.pre, tree.Prefix{Type: p.tok, Bytes: p.lit})\n\t\tp.off, p.tok, p.lit = p.scanner.Scan()\n\t}\n}", "func (t *Tree) next() token {\n\tif t.peekCount > 0 {\n\t\tt.peekCount--\n\t} else {\n\t\tt.token[0] = t.lex.nextToken()\n\t}\n\treturn t.token[t.peekCount]\n}", "func (ts *TokenScanner) next() Token {\n\tif ts.i >= len(ts.tokens) {\n\t\treturn Token{NIL, \"<nil>\"}\n\t}\n\n\t// Hack due to lack of ++i\n\tdefer func() { ts.i++ }()\n\n\treturn ts.tokens[ts.i]\n}", "func (p *Parser) nextToken() {\n\tp.tok = p.nextTok\n\tp.nextTok = p.l.NextToken()\n}", "func (p *Parser) Next() (t Token, err error) {\n\tif p.err != nil {\n\t\treturn nil, p.err\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tp.err = err\n\t\t}\n\t}()\n\n\tp.t = nil\n\n\tstate := (*Parser).start\n\n\tfor {\n\t\tr, _, err := p.r.ReadRune()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tp.err = err\n\t\t\t\tr = '\\n'\n\t\t\t} else {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tif r == '\\n' {\n\t\t\tp.line++\n\t\t\tp.pos = 0\n\t\t} else {\n\t\t\tp.pos++\n\t\t}\n\n\t\tnewState, err := state(p, r)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tp.last = state\n\t\tstate = newState\n\n\t\tif (state == nil) || (p.err != nil) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif (p.err != nil) && (p.t == nil) {\n\t\treturn nil, p.err\n\t}\n\n\treturn p.t, nil\n}", "func (p *Parser) next() {\n\tif p.offset+1 == len(p.source) {\n\t\tp.offset = len(p.source)\n\t\tp.word = ast.Word{token.EOF, \"\"}\n\t\treturn\n\t}\n\n\tp.offset++\n\tp.word = p.source[p.offset]\n\n\t// During parsing Parser ommit comments. Comment will be added\n\t// during printing the tree.\n\tif p.word.Token == token.COMMENT {\n\t\tp.next()\n\t}\n}", "func (z *Tokenizer) Next() Token {\n\tmark := z.pos\n\tt := z.consumeAToken()\n\tt.parent = z\n\tt.startPos = mark\n\tt.endPos = z.pos\n\treturn t\n}", "func (l *Lexer) Next() Token {\nrestart:\n\tl.tokenLine = l.line\n\tl.tokenOffset = l.offset\n\n\tstate := tmStateMap[l.State]\n\tfor state >= 0 {\n\t\tvar ch int\n\t\tif uint(l.ch) < tmRuneClassLen {\n\t\t\tch = int(tmRuneClass[l.ch])\n\t\t} else if l.ch < 0 {\n\t\t\tstate = int(tmLexerAction[state*tmNumClasses])\n\t\t\tcontinue\n\t\t} else {\n\t\t\tch = 1\n\t\t}\n\t\tstate = int(tmLexerAction[state*tmNumClasses+ch])\n\t\tif state > tmFirstRule {\n\t\t\tif l.ch == '\\n' {\n\t\t\t\tl.line++\n\t\t\t}\n\n\t\t\t// Scan the next character.\n\t\t\t// Note: the following code is inlined to avoid performance implications.\n\t\t\tl.offset = l.scanOffset\n\t\t\tif l.offset < len(l.source) {\n\t\t\t\tr, w := rune(l.source[l.offset]), 1\n\t\t\t\tif r >= 0x80 {\n\t\t\t\t\t// not ASCII\n\t\t\t\t\tr, w = utf8.DecodeRuneInString(l.source[l.offset:])\n\t\t\t\t}\n\t\t\t\tl.scanOffset += w\n\t\t\t\tl.ch = r\n\t\t\t} else {\n\t\t\t\tl.ch = -1 // EOI\n\t\t\t}\n\t\t}\n\t}\n\n\trule := tmFirstRule - state\n\n\ttoken := tmToken[rule]\n\tspace := false\n\tswitch rule {\n\tcase 0:\n\t\tif l.offset == l.tokenOffset {\n\t\t\tl.rewind(l.scanOffset)\n\t\t}\n\tcase 2: // invalid_token: /\\x00/\n\t\t{\n\t\t\tl.invalidTokenClass = InvalidTokenNullCharInCode\n\t\t}\n\tcase 3: // whitespace: /[\\n\\r\\t\\f\\v ]+/\n\t\tspace = true\n\tcase 4: // EnterBlockComment: /\\(\\*/\n\t\tspace = true\n\t\t{\n\t\t\tl.enterBlockComment()\n\t\t}\n\tcase 5: // invalid_token: /\\*\\)/\n\t\t{\n\t\t\tl.invalidTokenClass = InvalidTokenUnmatchedBlockComment\n\t\t}\n\tcase 6: // invalid_token: /{eoi}/\n\t\t{\n\t\t\tl.State = StateInitial\n\t\t\tl.invalidTokenClass = InvalidTokenEoiInComment\n\t\t}\n\tcase 7: // ExitBlockComment: /\\*\\)/\n\t\tspace = true\n\t\t{\n\t\t\tl.exitBlockComment()\n\t\t}\n\tcase 8: // BlockComment: /[^\\(\\)\\*]+|[\\*\\(\\)]/\n\t\tspace = true\n\tcase 9: // LineComment: /\\-\\-.*/\n\t\tspace = true\n\tcase 14: // invalid_token: /\"({strRune}*\\x00{strRune}*)+\"/\n\t\t{\n\t\t\tl.invalidTokenClass = InvalidTokenNullCharInString\n\t\t}\n\tcase 15: // invalid_token: /\"({strRune}*\\\\\\x00{strRune}*)+\"/\n\t\t{\n\t\t\tl.invalidTokenClass = InvalidTokenEscapedNullCharInString\n\t\t}\n\tcase 16: // invalid_token: /\"{strRune}*{eoi}/\n\t\t{\n\t\t\tl.invalidTokenClass = InvalidTokenEoiInString\n\t\t}\n\t}\n\tif space {\n\t\tgoto restart\n\t}\n\treturn token\n}", "func (s *Scanner) next() *Token {\n\tfor {\n\t\tr := s.read()\n\t\tswitch {\n\t\tcase r == '@':\n\t\t\treturn mkToken(tokAt, \"@\")\n\t\tcase isSpace(r):\n\t\tcase isIdentifierStart(r):\n\t\t\treturn s.alphanum(tokIdentifier, r)\n\t\tcase isDigit(r):\n\t\t\treturn s.number(r)\n\t\tcase isPunctuator(r):\n\t\t\treturn s.punctuator(r)\n\t\t}\n\t}\n}", "func (p *Parser) next0() {\n\t// Because of one-token look-ahead, print the previous token\n\t// when tracing as it provides a more readable output. The\n\t// very first token (!p.pos.IsValid()) is not initialized\n\t// (it is token.ILLEGAL), so don't print it .\n\tif p.trace && p.pos.IsValid() {\n\t\ts := p.tok.String()\n\t\tswitch {\n\t\tcase p.tok.IsLiteral():\n\t\t\tp.printTrace(s, p.lit)\n\t\tcase p.tok.IsOperator(), p.tok.IsKeyword():\n\t\t\tp.printTrace(\"\\\"\" + s + \"\\\"\")\n\t\tdefault:\n\t\t\tp.printTrace(s)\n\t\t}\n\t}\n\n\tp.pos, p.tok, p.lit = p.lexer.Lex()\n}", "func (s *cssTokenizer) Next() *Token {\n\tif s.index >= len(s.tokens) {\n\t\treturn nil\n\t}\n\tret := s.tokens[s.index]\n\ts.index++\n\treturn ret\n}", "func (p *parser) next() {\n\tp.leadComment = nil\n\tp.lineComment = nil\n//\tprev := p.pos\n\tp.pos, p.tok, p.lit = p.scanner.Scan()\n}", "func (i *Interpreter) getNextToken() scanResult {\n\n\tvar r scanResult\n\n\tif i.Err != nil {\n\t\tr.err = i.Err\n\t\tr.t = errorT\n\t\treturn r\n\t}\n\n\tif !i.scanner.Scan() {\n\t\t// EOF\n\t\ti.Err = io.EOF\n\t\tr.err = i.Err\n\t\tr.t = errorT\n\t\treturn r\n\t}\n\n\tr.token = i.scanner.Text()\n\n\t// slurp comments if needed\n\tif r.token == \"(\" {\n\t\tfor r.token[len(r.token)-1:] != \")\" {\n\t\t\tif !i.scanner.Scan() {\n\t\t\t\tr.err = fmt.Errorf(\"unexpected unclosed comment : %s\", r.token)\n\t\t\t\tr.t = errorT\n\t\t\t\treturn r\n\t\t\t}\n\t\t\tr.token = i.scanner.Text()\n\t\t}\n\t\t// then tail-recurse,\n\t\t// you can have multiple successive comments ...\n\t\treturn i.getNextToken()\n\t}\n\n\t// try to decode token\n\tnfa := i.lookup(r.token)\n\tif i.Err == nil {\n\t\tr.v = 1 + nfa\n\t\tr.t = compoundT\n\t\tr.err = nil\n\t\treturn r\n\t}\n\n\t// so, token could not be decoded\n\t// reset error and try numbers ...\n\ti.Err = nil\n\tif num, err := strconv.ParseInt(r.token, i.getBase(), 64); err == nil {\n\t\tr.v = int(num)\n\t\tr.t = numberT\n\t\tr.err = nil\n\t\treturn r\n\t}\n\n\t// Token cannot be understood\n\tr.t = errorT\n\tr.err = fmt.Errorf(\"cannot understand the token : %s\", r.token)\n\treturn r\n\n}", "func parseNext(v rune, node **node) {\n\tv2 := string(v)\n\n\tswitch v2 {\n\tcase \"[\":\n\t\tif checkName() {\n\t\t\taddNode(node, 1)\n\t\t}\n\tcase \"]\":\n\t\tif checkName() {\n\t\t\taddNode(node, 2)\n\t\t}\n\tcase \",\":\n\t\tif checkName() {\n\t\t\taddNode(node, 0)\n\t\t}\n\tdefault:\n\t\tif syntax.IsWordChar(v) {\n\t\t\tscan.name += string(v) // Accept only alphanumeric (No escapes)\n\t\t}\n\t}\n}", "func (lexto *LongLexto) Next() Token {\n\tif lexto.HasNext() {\n\t\tresult := lexto.tokens[lexto.current]\n\t\tlexto.current += 1\n\t\treturn result\n\t}\n\treturn Token{}\n}", "func (l *Lexer) Next() string {\n\tl.start = l.pos\n\tr := l.Peek()\n\tl.pos += l.width\n\treturn string(r)\n}", "func (p *parser) next0() {\n\t// Because of one-token look-ahead, print the previous token\n\t// when tracing as it provides a more readable output. The\n\t// very first token (!p.pos.IsValid()) is not initialized\n\t// (it is token.ILLEGAL), so don't print it.\n\tif p.trace && p.pos.IsValid() {\n\t\ts := p.tok.String()\n\t\tswitch {\n\t\tcase p.tok.IsLiteral():\n\t\t\tp.printTrace(s, p.lit)\n\t\tcase p.tok.IsStringLiteral():\n\t\t\tlit := p.lit\n\t\t\t// Simplify trace expression.\n\t\t\tif lit != \"\" {\n\t\t\t\tlit = `\"` + lit + `\"`\n\t\t\t}\n\t\t\tp.printTrace(s, lit)\n\t\tcase p.tok.IsOperator(), p.tok.IsCommand():\n\t\t\tp.printTrace(\"\\\"\" + s + \"\\\"\")\n\t\tdefault:\n\t\t\tp.printTrace(s)\n\t\t}\n\t}\n\n\tp.pos, p.tok, p.lit = p.scanner.Scan()\n}", "func (l *lexer) nextToken() token {\n\ttoken := <-l.tokens\n\tl.lastPos = token.pos\n\treturn token\n}", "func (p *Parser) next() {\n\tfor {\n\t\tp.tok = p.s.Scan()\n\n\t\t// skip whitespace\n\t\tif p.tok.Token != ItemWhitespace {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (l *lexer) nextToken() Token {\r\n\ttok := <-l.tokens\r\n\treturn tok\r\n}", "func (l *lexer) Next() *common.Token {\n\t// Pump some tokens onto the token stack\n\tfor l.s != nil && l.tokens.Len() == 0 {\n\t\t// Get a character from the scanner\n\t\tch := l.s.Next()\n\n\t\t// Handle EOF and error\n\t\tif ch.C == common.Err {\n\t\t\tl.pushErr(ch.Loc, ch.Val.(error))\n\t\t\tbreak\n\t\t} else if ch.C == common.EOF {\n\t\t\t// Warn about dangling pairs\n\t\t\tif l.pair.Len() > 0 {\n\t\t\t\tdangle := l.pair.Back().Value.(*common.Token)\n\t\t\t\tl.pushErr(dangle.Loc, common.ErrDanglingOpen(dangle))\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tl.pushTok(common.TokEOF, ch.Loc, nil)\n\t\t\tl.s = nil\n\t\t\tbreak\n\t\t}\n\n\t\t// Handle newlines and whitespace\n\t\tif ch.Class&common.CharNL != 0 && l.pair.Len() == 0 {\n\t\t\t// Generate a newline token\n\t\t\tl.pushTok(common.TokNewline, ch.Loc, nil)\n\t\t\tcontinue\n\t\t} else if ch.Class&common.CharWS != 0 {\n\t\t\t// Are we concerned about mixed spaces?\n\t\t\terrMixed := false\n\n\t\t\t// Set up the skipSpaces flags\n\t\t\tvar skip uint8\n\t\t\tif l.pair.Len() > 0 {\n\t\t\t\tskip = SkipNL\n\t\t\t} else {\n\t\t\t\tprevTok := l.lastTok()\n\t\t\t\tif prevTok == nil || prevTok.Sym == common.TokNewline {\n\t\t\t\t\tskip = SkipLeadFF\n\t\t\t\t\terrMixed = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Skip the whitespace\n\t\t\tmixed := l.skipSpaces(ch, skip)\n\n\t\t\t// Error out if it's mixed\n\t\t\tif errMixed && mixed {\n\t\t\t\tl.pushErr(ch.Loc, common.ErrMixedIndent)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Loop back around\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle backslash continuation\n\t\tif ch.C == '\\\\' {\n\t\t\t// Get next character and make sure it's\n\t\t\t// newline\n\t\t\tch = l.s.Next()\n\t\t\tif ch.C == common.Err {\n\t\t\t\t// Hmm, got an error\n\t\t\t\tl.pushErr(ch.Loc, ch.Val.(error))\n\t\t\t\tbreak\n\t\t\t} else if ch.C != '\\n' {\n\t\t\t\tl.pushErr(ch.Loc, common.ErrDanglingBackslash)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// OK, continue to the next character\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle the case of \".n\", where n is a decimal digit\n\t\tif ch.C == '.' {\n\t\t\tnext := l.s.Next()\n\t\t\tl.s.Push(next)\n\t\t\tif next.Class&common.CharDecDigit != 0 {\n\t\t\t\t// Suck in a number\n\t\t\t\trNumber(l).Recognize(ch)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Apply the correct recognizer\n\t\tif ch.Class&common.CharComment != 0 {\n\t\t\trComment(l).Recognize(ch)\n\t\t} else if ch.Class&common.CharDecDigit != 0 {\n\t\t\trNumber(l).Recognize(ch)\n\t\t} else if ch.Class&common.CharIDStart != 0 {\n\t\t\trIdent(l).Recognize(ch)\n\t\t} else if ch.Class&common.CharQuote != 0 {\n\t\t\trString(l).Recognize(ch)\n\t\t} else if ch.Class == 0 {\n\t\t\trOp(l).Recognize(ch)\n\t\t} else {\n\t\t\tl.pushErr(ch.Loc, common.ErrBadOp)\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If there are no tokens, return nil\n\tif l.tokens.Len() == 0 {\n\t\treturn nil\n\t}\n\n\t// Pop the first element off\n\telem := l.tokens.Front()\n\tl.tokens.Remove(elem)\n\n\t// Return the token, and save it so we know what we returned\n\t// last\n\tl.prevTok = elem.Value.(*common.Token)\n\treturn l.prevTok\n}", "func (s *javaTokenizer) Next() *Token {\n\tfor {\n\t\tch := s.scanner.Peek()\n\t\tif ch >= '0' && ch <= '9' {\n\t\t\ts.consumeNumericLiteral()\n\t\t\tcontinue\n\t\t} else if unicode.IsSpace(ch) {\n\t\t\t// consuming spaces\n\t\t\tfor unicode.IsSpace(ch) {\n\t\t\t\ts.scanner.Next()\n\t\t\t\tch = s.scanner.Peek()\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if ch == '\"' || ch == '\\'' {\n\t\t\ts.consumeStringLiteral(ch)\n\t\t\tcontinue\n\t\t}\n\n\t\tr := s.scanner.Scan()\n\t\tif r == scanner.EOF {\n\t\t\treturn nil\n\t\t}\n\t\tif r != scanner.Ident {\n\t\t\tcontinue\n\t\t}\n\t\ttext := s.scanner.TokenText()\n\t\tif s.isKeyword(text) {\n\t\t\t// consume package or import qualifiers\n\t\t\tif text == \"package\" || text == \"import\" {\n\t\t\t\tch = s.scanner.Next()\n\t\t\t\tfor ch >= 0 && ch != ';' {\n\t\t\t\t\tch = s.scanner.Next()\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tp := s.scanner.Pos()\n\t\treturn &Token{uint32(p.Offset - len([]byte(text))), p.Line, text}\n\t}\n}", "func (lx *Lexer) getNext() (tok Token, e error) {\n\tfor lx.hasNextRune() {\n\t\tp, e := lx.peekChar()\n\t\tlx.startPos = lx.pos\n\n\t\tif e != nil {\n\t\t\tpanic(\"End of file\")\n\t\t}\n\n\t\tswitch {\n\t\tcase IsWhitespace(p):\n\t\t\t// necessary for counting line number and tabs\n\t\t\tlx.whitespace()\n\t\t\tcontinue\n\t\t// case p == '/':\n\t\t// \tlx.comment()\n\t\tcase IsJavaLetter(p):\n\t\t\ttok = lx.identifier()\n\t\tcase IsDigit(p):\n\t\t\ttok = lx.numeralLiteral()\n\t\tcase p == '\\'':\n\t\t\ttok = lx.charLiteral()\n\t\tcase p == '\"':\n\t\t\ttok = lx.stringLiteral()\n\t\tcase IsSeparator(p):\n\t\t\ttok = lx.separator()\n\t\tcase IsOperatorStart(p):\n\t\t\ttok = lx.operator()\n\t\t}\n\n\t\tif tok.Type == Comment {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn tok, nil\n\t}\n\treturn Token{}, io.EOF\n}", "func (s *TokenStream) Next() Token {\n\treturn s.iter.Next()\n}", "func (m *ExpressionPager) Next() ql.Token {\n\tif m.peekCount > 0 {\n\t\tm.peekCount--\n\t} else {\n\t\tm.token[0] = m.lex.NextToken()\n\t}\n\treturn m.token[m.peekCount]\n}", "func (t *Tokenizer) Next() (tok Token, err error) {\n\tif t.lastToken == errorToken {\n\t\treturn nil, io.EOF\n\t}\n\n\ttok = nil\n\terr = nil\n\n\tif t.line == nil {\n\t\tt.lineno++\n\t\tt.offset = 1\n\t\tt.line, err = t.r.ReadBytes('\\n')\n\t\tif err != nil {\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\terr = nil\n\t\t\t} else {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(t.line) <= t.offset-1 {\n\t\tswitch t.lastToken {\n\t\tcase WordToken:\n\t\t\tt.lastToken = TerminatorToken\n\t\t\ttok = &terminatorToken{\n\t\t\t\tinfo: LineInfo{t.lineno, t.offset, t.line},\n\t\t\t\tskip: 0,\n\t\t\t}\n\t\t\treturn\n\n\t\tcase TerminatorToken, OutdentToken:\n\t\t\tif t.indentStack.Len() > 1 {\n\t\t\t\t// Ensure all indented blocks are closed.\n\t\t\t\t// Don't close the root block though.\n\n\t\t\t\tt.indentStack.Remove(t.indentStack.Back())\n\t\t\t\tt.lastToken = OutdentToken\n\t\t\t\ttok = &outdentToken{\n\t\t\t\t\tLineInfo{t.lineno, t.offset, t.line},\n\t\t\t\t\tt.indentStack.Back().Value.([]byte),\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\n\t\tt.lastToken = errorToken\n\t\treturn nil, io.EOF\n\t}\n\n\tswitch t.line[t.offset-1] {\n\tcase ' ', '\\t':\n\t\tt.offset++\n\t\treturn t.Next()\n\n\tcase '\\r':\n\t\tif t.offset == len(t.line) || t.line[t.offset] != '\\n' {\n\t\t\tt.lastToken = errorToken\n\t\t\terr = errorAtf(ErrCRLF, t.info(),\n\t\t\t\t\"found CR without matching LF\")\n\t\t\treturn\n\t\t}\n\n\t\tfallthrough\n\n\tcase '\\n':\n\t\tif t.lastToken == nilToken || t.lastToken == TerminatorToken {\n\t\t\tt.line = nil\n\t\t\treturn t.Next()\n\t\t}\n\n\t\tt.lastToken = TerminatorToken\n\t\ttok = &terminatorToken{\n\t\t\tinfo: LineInfo{t.lineno, t.offset, t.line},\n\t\t\tskip: 0,\n\t\t}\n\t\tt.line = nil\n\t\treturn\n\n\tcase '#':\n\t\tif t.lastToken == WordToken {\n\t\t\teol := len(t.line)\n\t\t\tif t.line[eol-1] == '\\n' && t.line[eol-2] == '\\r' {\n\t\t\t\teol--\n\t\t\t}\n\n\t\t\tt.lastToken = TerminatorToken\n\t\t\ttok = &terminatorToken{\n\t\t\t\tinfo: LineInfo{t.lineno, t.lastWordEnd, t.line},\n\t\t\t\tskip: eol - t.lastWordEnd,\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\ttok = &commentToken{LineInfo{\n\t\t\tt.lineno,\n\t\t\tt.offset,\n\t\t\tt.line,\n\t\t}}\n\t\tt.line = nil\n\t\treturn\n\n\tcase '{', '[':\n\t\tif t.lastToken != WordToken {\n\t\t\tt.lastToken = errorToken\n\t\t\tif t.line[t.offset-1] == '{' {\n\t\t\t\terr = errorAtf(ErrToken, t.info(),\n\t\t\t\t\t\"unexpected JSON object\")\n\t\t\t} else {\n\t\t\t\terr = errorAtf(ErrToken, t.info(),\n\t\t\t\t\t\"unexpected JSON array\")\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\treturn t.nextJSON()\n\n\tdefault:\n\t\tif t.lastToken == nilToken && t.offset != 1 {\n\t\t\tt.lastToken = errorToken\n\t\t\terr = errorAtf(ErrIndent, t.info(),\n\t\t\t\t\"first item must be unindented\")\n\t\t\treturn\n\t\t} else if t.lastToken == TerminatorToken {\n\t\t\tindent := t.line[:t.offset-1]\n\t\t\ttail := t.indentStack.Back()\n\t\t\ttailData := tail.Value.([]byte)\n\t\t\tif bytes.HasPrefix(indent, tailData) {\n\t\t\t\tif t.outdenting {\n\t\t\t\t\t// Didn't recognise indent!\n\t\t\t\t\tt.lastToken = errorToken\n\t\t\t\t\terr = errorAt(ErrOutdent, t.info())\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif len(indent) != len(tailData) {\n\t\t\t\t\t// More stuff in indent than tailData,\n\t\t\t\t\t// so we've indented.\n\t\t\t\t\tt.indentStack.PushBack(indent)\n\t\t\t\t\tt.lastToken = IndentToken\n\t\t\t\t\ttok = &indentToken{LineInfo{\n\t\t\t\t\t\tt.lineno, t.offset, t.line,\n\t\t\t\t\t}}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// indent & tailData are the same;\n\t\t\t\t// no indents or outdents,\n\t\t\t\t// so carry on with the word.\n\n\t\t\t} else if bytes.HasPrefix(tailData, indent) {\n\t\t\t\t// More stuff in tailData than indent,\n\t\t\t\t// so we've outdented.\n\n\t\t\t\tt.indentStack.Remove(tail)\n\t\t\t\ttail = t.indentStack.Back()\n\t\t\t\ttailData = tail.Value.([]byte)\n\t\t\t\tif !bytes.Equal(tailData, indent) {\n\t\t\t\t\tt.outdenting = true\n\t\t\t\t\treturn t.Next()\n\t\t\t\t}\n\n\t\t\t\tt.outdenting = false\n\t\t\t\tt.lastToken = OutdentToken\n\t\t\t\ttok = &outdentToken{\n\t\t\t\t\tLineInfo{t.lineno, t.offset, t.line},\n\t\t\t\t\ttailData,\n\t\t\t\t}\n\t\t\t\treturn\n\n\t\t\t} else {\n\t\t\t\t// Didn't recognise indent!\n\t\t\t\tt.lastToken = errorToken\n\t\t\t\terr = errorAt(ErrOutdent, t.info())\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\treturn t.nextWord()\n\t}\n}", "func (s *lexStream) nextToken(delim *charGroup) string {\r\n\tret := s.nextUntil(delim)\r\n\tif len(ret) == 0 {\r\n\t\tret = string(s.next())\r\n\t}\r\n\treturn ret\r\n}", "func (s *scanner) nextToken() tokenRef {\n\titem := <-s.items\n\ts.lastPos = item.pos\n\treturn item\n}", "func (l *ECMAScriptLexer) nextToken() antlr.Token {\n\tnext := l.NextToken()\n\n\tif next.GetChannel() == antlr.TokenDefaultChannel {\n\t\t// Keep track of the last token on the default channel.\n\t\tlastToken = next\n\t}\n\n\treturn next\n}", "func (s *scanner) Next() (token, error) {\n\treturn s.next()\n}", "func (stream *TokenStream) Next() (*Token, error) {\n\treturn stream.next()\n}", "func (p *Parser) advance() {\n\tp.previous = p.current\n\tfor {\n\t\tp.current = p.scanner.ScanToken()\n\t\tif p.current.Type != ERROR {\n\t\t\tbreak\n\t\t}\n\t\t// Report errors while scanning tokens\n\t\tp.raiseError(p.current, p.current.Literal)\n\t\tp.advance()\n\t}\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 (p *parser) next() item {\n\tif p.peekCount > 0 {\n\t\tp.peekCount--\n\t} else {\n\t\tt := p.lex.nextItem()\n\t\t// Skip comments.\n\t\tfor t.typ == itemComment {\n\t\t\tt = p.lex.nextItem()\n\t\t}\n\t\tp.token[0] = t\n\t}\n\tif p.token[p.peekCount].typ == itemError {\n\t\tp.errorf(\"%s\", p.token[p.peekCount].val)\n\t}\n\treturn p.token[p.peekCount]\n}", "func (p *parser) next() token {\n\tif len(p.backup) > 0 {\n\t\tt := p.backup[len(p.backup)-1]\n\t\tp.backup = p.backup[:len(p.backup)-1]\n\t\treturn t\n\t}\nSKIP_COMMENTS:\n\tt, ok := <-p.input\n\tif !ok {\n\t\treturn token{t_eof, \"eof\"}\n\t}\n\tif t.t == t_comment {\n\t\tgoto SKIP_COMMENTS\n\t}\n\treturn t\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 *lexStream) next() byte {\r\n\tret := s.peek()\r\n\ts.c++\r\n\tif ret == '\\n' {\r\n\t\ts.pos[len(s.pos)-1].line++\r\n\t}\r\n\treturn ret\r\n}", "func (p *Parser) Next() (textparse.Entry, error) {\n\tfor p.s.Scan() {\n\t\t// TODO(bwplotka): Assuming all line by line. If not do refetch like in previous version with more lines.\n\t\tline := p.s.Bytes()\n\n\t\tp.Parser = textparse.New(line, \"\") // use promtext format\n\t\tif et, err := p.Parser.Next(); err != io.EOF {\n\t\t\treturn et, err\n\t\t}\n\t\t// EOF from parser, continue scanning.\n\t}\n\tif err := p.s.Err(); err != nil {\n\t\treturn 0, err\n\t}\n\treturn 0, io.EOF\n}", "func (t *Tree) next() item {\n\tif t.peekCount > 0 {\n\t\tt.peekCount--\n\t} else {\n\t\tt.token[0] = t.lex.nextItem()\n\t}\n\treturn t.token[t.peekCount]\n}", "func (l *lexer) nextToken() token {\n\tvar tok token\n\n\tl.skipWhitespace()\n\n\tswitch l.ch {\n\tcase ',':\n\t\ttok = newToken(tokComma, l.ch)\n\tcase ':':\n\t\ttok = newToken(tokColon, l.ch)\n\tcase '{':\n\t\ttok = newToken(tokLBrace, l.ch)\n\tcase '}':\n\t\ttok = newToken(tokRBrace, l.ch)\n\tcase '[':\n\t\ttok = newToken(tokLBracket, l.ch)\n\tcase ']':\n\t\ttok = newToken(tokRBracket, l.ch)\n\tcase '\"':\n\t\ttok.Type = tokString\n\t\ttok.Literal = l.readString()\n\tcase '-':\n\t\ttok = newToken(tokMinus, l.ch)\n\tcase eof:\n\t\ttok.Literal = \"\"\n\t\ttok.Type = tokEOF\n\tdefault:\n\t\tif isLetter(l.ch) {\n\t\t\ttok.Literal = l.readKeyword()\n\t\t\ttok.Type = lookupKeyword(tok.Literal)\n\t\t\treturn tok\n\t\t} else if isDigit(l.ch) {\n\t\t\ttok.Literal = l.readNumber()\n\t\t\tif strings.Contains(tok.Literal, \".\") {\n\t\t\t\ttok.Type = tokFloat\n\t\t\t} else {\n\t\t\t\ttok.Type = tokInt\n\t\t\t}\n\t\t\treturn tok\n\t\t} else {\n\t\t\ttok = newToken(tokIllegal, l.ch)\n\t\t}\n\t}\n\n\tl.readChar()\n\n\treturn tok\n}", "func (parser *Parser) Next() (api.Call, error) {\n\tfor parser.scanner.Scan() {\n\t\tline := parser.scanner.Text()\n\t\tcall := parseCall(line)\n\t\tfmt.Printf(\"%#+v\\n\", call)\n\t\treturn call, nil\n\t}\n\n\tif err := parser.scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, io.EOF\n}", "func (l *lexer) next() (token, bool) {\n\tif l.currToken < len(l.tokens) {\n\t\tl.currToken++\n\t\treturn l.tokens[l.currToken-1], true\n\t} else {\n\t\treturn token{}, false\n\t}\n}", "func (p *parser) advance() lexer.Token {\n\tif !p.isAtEnd() {\n\t\tp.current++\n\t\treturn p.previous()\n\t} else {\n\t\treturn p.tokens[p.current]\n\t}\n}", "func (l *lexer) next() (r rune) {\n\tif l.position >= len(l.input) {\n\t\tl.width = 0\n\t\treturn eof\n\t}\n\n\tr, l.width = utf8.DecodeRuneInString(l.todo())\n\tl.position += l.width\n\treturn r\n}", "func (l *lexer) next() (r rune) {\n\tif l.position >= len(l.input) {\n\t\tl.width = 0\n\t\treturn eof\n\t}\n\n\tr, l.width = utf8.DecodeRuneInString(l.todo())\n\tl.position += l.width\n\treturn r\n}", "func (l *LexInner) Next() (char rune) {\n\tif l.Eof() {\n\t\tl.mark.width = 0\n\t\tchar = Eof\n\t\treturn Eof\n\t}\n\tchar, l.mark.width = utf8.DecodeRuneInString(l.input[l.mark.pos:])\n\tl.mark.pos += l.mark.width\n\tif char == '\\n' {\n\t\tl.mark.line++\n\t}\n\treturn char\n}", "func (lexer *Lexer) next() {\n lexer.current = lexer.source.ReadChar()\n if lexer.current == '\\n' {\n lexer.nextLine()\n } else {\n lexer.nextCol()\n }\n}", "func Next() {\n\tgo next()\n}", "func (t *Tokenizer) NextToken() (*Token, error) {\n\treturn t.scanStream()\n}", "func (lexer *Lexer) NextToken() token.Token {\n\tvar t token.Token\n\n\tlexer.skipWhitespace()\n\n\tswitch lexer.currentChar {\n\n\t// One-character bytes\n\tcase '(':\n\t\tt = newToken(token.LPAREN, lexer.currentChar)\n\tcase ')':\n\t\tt = newToken(token.RPAREN, lexer.currentChar)\n\tcase ',':\n\t\tt = newToken(token.COMMA, lexer.currentChar)\n\tcase '+':\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '=':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.PLUSEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tcase '+':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.INCREMENT,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tdefault:\n\t\t\tt = newToken(token.MINUS, lexer.currentChar)\n\t\t}\n\tcase '{':\n\t\tt = newToken(token.LBRACE, lexer.currentChar)\n\tcase '}':\n\t\tt = newToken(token.RBRACE, lexer.currentChar)\n\tcase '[':\n\t\tt = newToken(token.LBRACKET, lexer.currentChar)\n\tcase ']':\n\t\tt = newToken(token.RBRACKET, lexer.currentChar)\n\tcase '-':\n\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '>':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.OPENBLOCK,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\tcase '=':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.MINUSEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tcase '-':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.DECREMENT,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tdefault:\n\t\t\tt = newToken(token.MINUS, lexer.currentChar)\n\n\t\t}\n\n\tcase '/':\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '=':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.SLASHEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tdefault:\n\t\t\tt = newToken(token.SLASH, lexer.currentChar)\n\t\t}\n\tcase '*':\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '=':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.MULEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tdefault:\n\t\t\tt = newToken(token.ASTERISK, lexer.currentChar)\n\t\t}\n\tcase '<':\n\t\tif lexer.peekCharacter() == '=' {\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.LTEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\t} else {\n\t\t\tt = newToken(token.LT, lexer.currentChar)\n\t\t}\n\tcase '>':\n\t\tif lexer.peekCharacter() == '=' {\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.GTEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\t} else {\n\t\t\tt = newToken(token.GTEQ, lexer.currentChar)\n\t\t}\n\tcase ';':\n\t\tt = newToken(token.SEMICOLON, lexer.currentChar)\n\tcase ':':\n\t\tt = newToken(token.COLON, lexer.currentChar)\n\n\tcase '#':\n\t\tfor lexer.peekCharacter() != '\\n' && lexer.peekCharacter() != 0 {\n\t\t\tlexer.consumeChar()\n\t\t}\n\t\tlexer.skipWhitespace()\n\t\tlexer.consumeChar()\n\t\treturn lexer.NextToken()\n\n\t// EOF\n\tcase 0:\n\t\tt.Literal = \"\"\n\t\tt.Type = token.EOF\n\n\t// Multiple-character bytes\n\tcase '=':\n\t\tif lexer.peekCharacter() == '=' {\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.EQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\t} else {\n\t\t\tt = newToken(token.ASSIGN, lexer.currentChar)\n\t\t}\n\tcase '!':\n\t\tif lexer.peekCharacter() == '=' {\n\t\t\tcharacter := lexer.currentChar\n\n\t\t\tlexer.consumeChar()\n\t\t\tt = token.Token{\n\t\t\t\tType: token.NOT_EQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\t} else {\n\t\t\tt = newToken(token.BANG, lexer.currentChar)\n\t\t}\n\n\tcase '|':\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '|':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.OR,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\tdefault:\n\t\t\tt = newToken(token.ILLEGAL, lexer.currentChar)\n\n\t\t}\n\n\tcase '&':\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '&':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.AND,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\tdefault:\n\t\t\tt = newToken(token.ILLEGAL, lexer.currentChar)\n\n\t\t}\n\n\tcase '\"':\n\t\tt.Type = token.STRING\n\t\tt.Literal = lexer.readString()\n\n\tdefault:\n\t\tif util.IsLetter(lexer.currentChar) {\n\t\t\tt.Literal = lexer.consumeIdentifier()\n\t\t\tt.Type = token.LookupIdent(t.Literal)\n\t\t\treturn t\n\t\t} else if util.IsDigit(lexer.currentChar) {\n\t\t\tt.Literal = lexer.consumeInteger()\n\t\t\tt.Type = token.INT\n\t\t\treturn t\n\t\t} else {\n\t\t\tt = newToken(token.ILLEGAL, lexer.currentChar)\n\t\t}\n\t}\n\tlexer.consumeChar()\n\n\treturn t\n}", "func (p *parser) next() rune {\n\tif p.cur >= len(p.src) {\n\t\tp.length = 0\n\t\treturn eof\n\t}\n\tr, w := utf8.DecodeRune(p.src[p.cur:])\n\tp.length = w\n\tp.cur += p.length\n\t//p.pos.Colunm += p.length\n\treturn r\n}", "func (l *Lexer) NextToken() *Token {\n\treturn <-l.tokens\n}", "func nextToken(t []string) (string, []string) {\n\tif len(t) == 0 {\n\t\treturn \"\", t\n\t}\n\treturn t[0], t[1:]\n}", "func (lex *Lexer) NextToken() Token {\n\tfor {\n\t\tselect {\n\t\tcase item := <-lex.tokens:\n\t\t\treturn item\n\t\tdefault:\n\t\t\tlex.state = lex.state(lex)\n\t\t}\n\t}\n\tpanic(\"not reached\")\n}", "func (l *Lexer) NextToken() Token {\n\tfor {\n\t\tselect {\n\t\tcase tok := <-l.tokens:\n\t\t\treturn tok\n\t\tdefault:\n\t\t\tif l.state == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.state = l.state(l)\n\t\t}\n\t}\n}", "func (l *Lexer) next() rune {\n\tr, width := utf8.DecodeRuneInString(l.input[l.pos:])\n\tl.pos += width\n\t// log.Printf(\"[next] %s\", l.debugString())\n\treturn r\n}", "func (l *Lexer) NextToken() (t token.Token) {\n\tl.skipWhitespace()\n\ttyp := resolveTokenType(l.ch)\n\tt.Type = typ\n\tswitch typ {\n\tcase token.EOF:\n\t\tt.Literal = \"\"\n\tcase token.IDENT:\n\t\tif isLetter(l.ch) {\n\t\t\t// letters\n\t\t\tlit := l.readIdentifier()\n\t\t\ttyp = token.LookupIdent(lit)\n\t\t\tt = l.newToken(typ, lit)\n\t\t\treturn\n\t\t}\n\t\tif isDigit(l.ch) {\n\t\t\t// numbers\n\t\t\tlit := l.readNumber()\n\t\t\tt = l.newToken(token.INT, lit)\n\t\t\treturn\n\t\t}\n\n\t\tt = l.newTokenRune(token.ILLEGAL, l.ch)\n\tdefault:\n\t\tt = l.newTokenRune(typ, l.ch)\n\t}\n\tl.readChar() // set the pos to the next\n\treturn\n}", "func (p *Parser) advanceTokens() error {\n\tpeekToken, err := p.lex.NextToken(p.bracesAsString)\n\tif err != nil {\n\t\t// XXX: Add error reporting here\n\t\treturn err\n\t} else {\n\t\tp.curToken = p.peekToken\n\t\tp.peekToken = peekToken\n\t}\n\treturn nil\n}", "func (l *lexer) next() (r rune) {\n\tif l.pos >= len(l.input) {\n\t\tl.width = 0\n\t\treturn eof\n\t}\n\tr, l.width = utf8.DecodeRuneInString(l.input[l.pos:])\n\tl.pos += l.width\n\treturn r\n}", "func (l *lexer) next() (r rune) {\n\tif l.pos >= len(l.input) {\n\t\tl.width = 0\n\t\treturn eof\n\t}\n\tr, l.width = utf8.DecodeRuneInString(l.input[l.pos:])\n\tl.pos += l.width\n\treturn r\n}", "func (lx *Lexer) NextToken() token.Token {\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase tok := <-lx.tokens:\n\t\t\treturn tok\n\t\tdefault:\n\t\t\tif lx.state == nil {\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\t\tlx.state = lx.state(lx)\n\t\t}\n\t}\n\treturn token.Token{Type: token.EOF, Line: lx.line}\n}", "func (lx *Lexer) next() (r rune) {\n\tif lx.pos >= len(lx.input) {\n\t\tlx.width = 0\n\t\treturn eof\n\t}\n\tr, lx.width = utf8.DecodeRuneInString(lx.input[lx.pos:])\n\tlx.pos += lx.width\n\treturn r\n}", "func (p *parser) next() {\n\tp.leadComment = nil\n\tp.lineComment = nil\n\tprev := p.pos\n\tp.next0()\n\n\tif p.tok == token.TexComment {\n\t\tvar comment *ast.TexCommentGroup\n\t\tvar endLine int\n\n\t\tif p.file.Line(p.pos) == p.file.Line(prev) {\n\t\t\t// The comment is on same line as the previous token; it\n\t\t\t// cannot be a lead comment but may be a line comment.\n\t\t\tcomment, endLine = p.consumeCommentGroup(0)\n\t\t\tif p.file.Line(p.pos) != endLine || p.tok == token.EOF {\n\t\t\t\t// The next token is on a different line, thus\n\t\t\t\t// the last comment group is a line comment.\n\t\t\t\tp.lineComment = comment\n\t\t\t}\n\t\t}\n\n\t\t// consume successor comments, if any\n\t\tendLine = -1\n\t\tfor p.tok == token.TexComment {\n\t\t\tcomment, endLine = p.consumeCommentGroup(1)\n\t\t}\n\n\t\tif endLine+1 == p.file.Line(p.pos) {\n\t\t\t// The next token is following on the line immediately after the\n\t\t\t// comment group, thus the last comment group is a lead comment.\n\t\t\tp.leadComment = comment\n\t\t}\n\t}\n}", "func (l *Lexer) NextToken() Token {\n\tvar tok Token\n\n\t//Skips comments and whitespace\n\tl.skip()\n\n\tswitch l.ch {\n\tcase '+':\n\t\ttok = newToken(PLUS, l.ch)\n\tcase '-':\n\t\ttok = newToken(MINUS, l.ch)\n\tcase '/':\n\t\ttok = newToken(DIV, l.ch)\n\tcase '*':\n\t\ttok = newToken(MUL, l.ch)\n\tcase '(':\n\t\ttok = newToken(LPAREN, l.ch)\n\tcase ')':\n\t\ttok = newToken(RPAREN, l.ch)\n\tcase '<':\n\t\tif l.peekChar() == '=' {\n\t\t\ttok.Literal = \"<=\"\n\t\t\ttok.Type = LEQUAL\n\t\t\tl.readChar() //Otherwise it will get an extra =\n\t\t} else {\n\t\t\ttok = newToken(LTHEN, l.ch)\n\t\t}\n\tcase '>':\n\t\tif l.peekChar() == '=' {\n\t\t\ttok.Literal = \">=\"\n\t\t\ttok.Type = GEQUAL\n\t\t\tl.readChar() //Otherwise it will get an extra =\n\t\t} else {\n\t\t\ttok = newToken(GTHEN, l.ch)\n\t\t}\n\tcase '=':\n\t\ttok = newToken(EQUAL, l.ch)\n\tcase 0: //EOF as defined in readChar()\n\t\ttok.Literal = \"\"\n\t\ttok.Type = EOF\n\tdefault:\n\t\tif isLetter(l.ch) {\n\t\t\ttok.Literal = l.readIdentifier()\n\t\t\ttok.Type = IDENT\n\t\t\treturn tok //return instantly because readChar has been executed in readIdentifier()\n\t\t} else if isDigit(l.ch) {\n\t\t\ttok.Type = NUMBER\n\t\t\ttok.Literal = l.readNumber()\n\t\t\treturn tok ////return instantly because readChar has been executed in readNumber()\n\t\t}\n\t\ttok = newToken(ILLEGAL, l.ch)\n\t}\n\n\tl.readChar()\n\treturn tok\n}", "func GetNextToken() {\n var cmpValue uint64;\n GetNextTokenRaw();\n\n // Convert identifier to keyworded tokens\n if tok.id == TOKEN_IDENTIFIER {\n cmpValue = libgogo.StringCompare(\"if\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_IF;\n }\n cmpValue = libgogo.StringCompare(\"else\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_ELSE;\n }\n cmpValue = libgogo.StringCompare(\"for\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_FOR;\n }\n cmpValue = libgogo.StringCompare(\"type\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_TYPE;\n }\n cmpValue = libgogo.StringCompare(\"const\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_CONST;\n }\n cmpValue = libgogo.StringCompare(\"var\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_VAR;\n }\n cmpValue = libgogo.StringCompare(\"struct\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_STRUCT;\n }\n cmpValue = libgogo.StringCompare(\"return\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_RETURN;\n }\n cmpValue = libgogo.StringCompare(\"func\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_FUNC;\n }\n cmpValue = libgogo.StringCompare(\"import\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_IMPORT;\n }\n cmpValue = libgogo.StringCompare(\"package\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_PACKAGE;\n }\n cmpValue = libgogo.StringCompare(\"break\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_BREAK;\n }\n cmpValue = libgogo.StringCompare(\"continue\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_CONTINUE;\n }\n }\n\n tok.nextToken = 0;\n}", "func (x *exprLex) next() rune {\n\tif x.peek != eof {\n\t\tr := x.peek\n\t\tx.peek = eof\n\t\treturn r\n\t}\n\tif len(x.line) == 0 {\n\t\treturn eof\n\t}\n\tc, size := utf8.DecodeRune(x.line)\n\tx.line = x.line[size:]\n\tif c == utf8.RuneError && size == 1 {\n\t\tlog.Print(\"invalid utf8\")\n\t\treturn x.next()\n\t}\n\treturn c\n}", "func (l *Lexer) NextToken() token.Token {\n\tvar tok token.Token\n\n\tl.skipWhitespace()\n\tl.skipComment()\n\tl.skipWhitespace()\n\n\tswitch l.ch {\n\tcase '\"':\n\t\tkind, literal := l.readString()\n\t\ttok = l.newToken(kind, literal)\n\tcase '+':\n\t\tif l.peekChar() == '+' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CONCAT, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == '.' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.FPLUS, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == ':' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CPLUS, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.PLUS, string(l.ch))\n\t\t}\n\tcase '-':\n\t\tif l.peekChar() == '>' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.RARROW, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == '.' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.FMINUS, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == ':' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CMINUS, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.MINUS, string(l.ch))\n\t\t}\n\tcase '(':\n\t\ttok = l.newToken(token.LPAREN, string(l.ch))\n\tcase ')':\n\t\ttok = l.newToken(token.RPAREN, string(l.ch))\n\tcase '{':\n\t\ttok = l.newToken(token.LBRACKET, string(l.ch))\n\tcase '}':\n\t\ttok = l.newToken(token.RBRACKET, string(l.ch))\n\tcase '*':\n\t\tif l.peekChar() == '.' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.FTIMES, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == ':' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CTIMES, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.TIMES, string(l.ch))\n\t\t}\n\n\tcase '/':\n\t\tif l.peekChar() == '.' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.FDIVIDE, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == ':' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CDIVIDE, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.DIVIDE, string(l.ch))\n\t\t}\n\n\tcase '^':\n\t\ttok = l.newToken(token.TOPOW, string(l.ch))\n\tcase '=':\n\t\ttok = l.newToken(token.EQUALS, string(l.ch))\n\tcase '%':\n\t\ttok = l.newToken(token.MODULO, string(l.ch))\n\tcase '@':\n\t\ttok = l.newToken(token.AT, string(l.ch))\n\tcase '.':\n\t\ttok = l.newToken(token.ACCESS, string(l.ch))\n\tcase ',':\n\t\ttok = l.newToken(token.COMMA, string(l.ch))\n\tcase '$':\n\t\ttok = l.newToken(token.DOLLAR, string(l.ch))\n\tcase '!':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.DIFFERS, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.NOT, string(l.ch))\n\t\t}\n\tcase '&':\n\t\tif l.peekChar() == '&' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.LAND, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.ILLEGAL, string(l.ch))\n\t\t}\n\tcase '|':\n\t\tif l.peekChar() == '|' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.OR, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.ILLEGAL, string(l.ch))\n\t\t}\n\tcase ':':\n\t\tif l.peekChar() == ':' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CONS, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.ANNOT, string(l.ch))\n\t\t}\n\tcase '<':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\tif l.peekChar() == '<' {\n\t\t\t\tch2 := l.ch\n\t\t\t\tl.readChar()\n\t\t\t\ttok = l.newToken(token.COMPOSE, string(ch)+string(ch2)+string(l.ch))\n\t\t\t} else {\n\t\t\t\ttok = l.newToken(token.LESSEQ, string(ch)+string(l.ch))\n\t\t\t}\n\t\t} else {\n\t\t\ttok = l.newToken(token.LESS, string(l.ch))\n\n\t\t}\n\tcase '>':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\tif l.peekChar() == '>' {\n\t\t\t\tch2 := l.ch\n\t\t\t\tl.readChar()\n\t\t\t\ttok = l.newToken(token.PIPE, string(ch)+string(ch2)+string(l.ch))\n\t\t\t} else {\n\t\t\t\ttok = l.newToken(token.GREATEREQ, string(ch)+string(l.ch))\n\t\t\t}\n\t\t} else if l.peekChar() == '>' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.SEQUENCE, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.GREATER, string(l.ch))\n\n\t\t}\n\tcase ';':\n\t\ttok = l.newToken(token.SEMI, string(l.ch))\n\tcase 0:\n\t\ttok.Literal = \"\"\n\t\ttok.Type = token.EOF\n\n\t// Now the next token must either be and identifier, a number\n\t// Or an invalid token\n\tdefault:\n\t\tif isIdentifier(l.ch) {\n\t\t\tlit := l.readIdentifier()\n\t\t\ttok = l.newToken(token.LookupIdent(lit), lit)\n\t\t\treturn tok\n\t\t} else if isDigit(l.ch) {\n\t\t\tkind, value := l.readNumber(false)\n\t\t\ttok = l.newToken(kind, value)\n\t\t\treturn tok\n\t\t} else {\n\t\t\ttok = l.newToken(token.ILLEGAL, string(l.ch))\n\t\t}\n\t}\n\n\t// Advance by a character\n\tl.readChar()\n\treturn tok\n}", "func (x *langLex) next() rune {\n\tif x.peek != eof {\n\t\tr := x.peek\n\t\tx.peek = eof\n\t\treturn r\n\t}\n\tif len(x.line) == 0 {\n\t\treturn eof\n\t}\n\tc, size := utf8.DecodeRune(x.line)\n\tx.line = x.line[size:]\n\tif c == utf8.RuneError && size == 1 {\n\t\tlog.Print(\"invalid utf8\")\n\t\treturn x.next()\n\t}\n\treturn c\n}", "func (l *Lexer) NextToken() token.Token {\n\tvar tok token.Token\n\tl.skipWhiteSpace()\n\n\t// skip single-line comments\n\t// unless they are immediately followed by a number,\n\t// because our registers are \"#N\".\n\tif l.ch == rune('#') {\n\t\tif !isDigit(l.peekChar()) {\n\t\t\tl.skipComment()\n\t\t\treturn (l.NextToken())\n\t\t}\n\t}\n\n\tswitch l.ch {\n\tcase rune(','):\n\t\ttok = newToken(token.COMMA, l.ch)\n\tcase rune('\"'):\n\t\ttok.Type = token.STRING\n\t\ttok.Literal = l.readString()\n\tcase rune(':'):\n\t\ttok.Type = token.LABEL\n\t\ttok.Literal = l.readLabel()\n\tcase rune(0):\n\t\ttok.Type = token.EOF\n\t\ttok.Literal = \"\"\n\tdefault:\n\t\tif isDigit(l.ch) {\n\t\t\treturn l.readDecimal()\n\t\t} else {\n\t\t\ttok.Literal = l.readIdentifier()\n\t\t\ttok.Type = token.LookupIdentifier(tok.Literal)\n\t\t\treturn tok\n\t\t}\n\t}\n\tl.readChar()\n\treturn tok\n}", "func (l *Lexer) NextToken() token.Token {\n\tvar tok token.Token\n\n\tl.scanIgnoreWhiteSpace()\n\n\tswitch l.ch {\n\tcase '(':\n\t\ttok = newToken(token.LPAREN, l.ch)\n\tcase ')':\n\t\ttok = newToken(token.RPAREN, l.ch)\n\tcase ';':\n\t\tif l.peekChar() == ';' {\n\t\t\tch := l.ch\n\t\t\tl.scan()\n\t\t\tlit := string(ch) + string(l.ch)\n\t\t\ttok = token.Token{Type: token.EOI, Literal: lit}\n\t\t} else {\n\t\t\ttok = newToken(token.SEMICOLON, l.ch)\n\t\t}\n\tcase 0:\n\t\ttok.Literal = \"\"\n\t\ttok.Type = token.EOF\n\tcase '+':\n\t\ttok = newToken(token.PLUS, l.ch)\n\tcase '-':\n\t\ttok = newToken(token.MINUS, l.ch)\n\tcase '*':\n\t\ttok = newToken(token.ASTERISK, l.ch)\n\tcase '/':\n\t\ttok = newToken(token.SLASH, l.ch)\n\tdefault:\n\t\tif isLetter(l.ch) {\n\t\t\ttok.Literal = l.ScanIdent()\n\t\t\ttok.Type = token.LookupIdent(tok.Literal)\n\t\t\treturn tok\n\t\t} else if isDigit(l.ch) {\n\t\t\ttok.Literal = l.scanNumber()\n\t\t\tif strings.Contains(tok.Literal, \".\") {\n\t\t\t\ttok.Type = token.FLOAT_NUM\n\t\t\t} else {\n\t\t\t\ttok.Type = token.INT\n\t\t\t}\n\t\t\treturn tok\n\t\t} else {\n\t\t\ttok = newToken(token.ILLEGAL, l.ch)\n\t\t}\n\n\t}\n\n\tl.scan()\n\treturn tok\n\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 (l *Lexer) next() (rune rune) {\n\tif l.pos >= len(l.input) {\n\t\tl.width = 0\n\n\t\treturn eof\n\t}\n\trune, l.width = utf8.DecodeRuneInString(l.input[l.pos:])\n\tl.pos += l.width\n\n\treturn rune\n}", "func (p *DiceParser) consume() Token {\n\tif !p.isAtEnd() {\n\t\t// Advance the cursor and return whatever was before it.\n\t\tp.current += 1\n\t\treturn p.tokens[p.current-1]\n\t}\n\t// If we are at the end, then there's only one token left to consume.\n\treturn p.tokens[p.current]\n}", "func (lexer *MidiLexer) next() (finished bool, err error) {\n\n\t// Default for return values.\n\terr = nil\n\tfinished = false\n\n\t// The position in the file before the next lexing event happens.\n\t// Useful in some cases\n\tvar currentPosition int64\n\tcurrentPosition, err = lexer.input.Seek(0, 1)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// See comments for state values above.\n\tswitch lexer.state {\n\tcase ExpectHeader:\n\t\t{\n\t\t\t//fmt.Println(\"ExpectHeader\")\n\n\t\t\tvar chunkHeader ChunkHeader\n\t\t\tchunkHeader, err = parseChunkHeader(lexer.input)\n\t\t\tif chunkHeader.ChunkType != \"MThd\" {\n\t\t\t\terr = ExpectedMthd\n\n\t\t\t\t//fmt.Println(\"ChunkHeader error \", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar header HeaderData\n\t\t\theader, err = parseHeaderData(lexer.input)\n\n\t\t\tif err != nil {\n\t\t\t\t//fmt.Println(\"HeaderData error \", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlexer.callback.Began()\n\n\t\t\tlexer.callback.Header(header)\n\n\t\t\tlexer.state = ExpectChunk\n\n\t\t\treturn\n\t\t}\n\n\tcase ExpectChunk:\n\t\t{\n\t\t\t//fmt.Println(\"ExpectChunk\")\n\n\t\t\tvar chunkHeader ChunkHeader\n\t\t\tchunkHeader, err = parseChunkHeader(lexer.input)\n\n\t\t\t//fmt.Println(\"Got chunk header\", chunkHeader)\n\n\t\t\tif err != nil {\n\t\t\t\t// If we expect a chunk and we hit the end of the file, that's not so unexpected after all.\n\t\t\t\t// The file has to end some time, and this is the correct boundary upon which to end it.\n\t\t\t\tif err == UnexpectedEndOfFile {\n\t\t\t\t\tlexer.state = Done\n\n\t\t\t\t\t// TODO TEST\n\t\t\t\t\tlexer.callback.Finished()\n\n\t\t\t\t\tfinished = true\n\t\t\t\t\terr = nil\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t//fmt.Println(\"Chunk header error \", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlexer.callback.Track(chunkHeader)\n\t\t\tlexer.nextChunkHeader = int64(chunkHeader.Length) + currentPosition\n\n\t\t\t// If the header is of an unknown type, skip over it.\n\t\t\tif chunkHeader.ChunkType != \"MTrk\" {\n\t\t\t\tlexer.input.Seek(lexer.nextChunkHeader, 1)\n\n\t\t\t\t// Then we expect another chunk.\n\t\t\t\tlexer.state = ExpectChunk\n\t\t\t\tlexer.nextChunkHeader = 0\n\t\t\t} else {\n\t\t\t\t// We have a MTrk\n\t\t\t\tlexer.state = ExpectTrackEvent\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\tcase ExpectTrackEvent:\n\t\t{\n\t\t\t//fmt.Println(\"ExpectTrackEvent\")\n\n\t\t\t// Removed because there is an event to say 'end of chunk'.\n\t\t\t// TODO: investigate. Could put this back for error cases.\n\t\t\t// // If we're at the end of the chunk, change the state.\n\t\t\t// if lexer.nextChunkHeader != 0 {\n\n\t\t\t// \t// The chunk should end exactly on the chunk boundary, really.\n\t\t\t// \tif currentPosition == lexer.nextChunkHeader {\n\t\t\t// \t\tlexer.state = ExpectChunk\n\t\t\t// \t\treturn false, nil\n\t\t\t// \t} else if currentPosition > lexer.nextChunkHeader {\n\t\t\t// \t\t//fmt.Println(\"Chunk end error \", err)\n\t\t\t// \t\treturn false, BadSizeChunk\n\t\t\t// \t}\n\t\t\t// }\n\n\t\t\t// Time Delta\n\t\t\tvar time uint32\n\t\t\ttime, err = parseVarLength(lexer.input)\n\t\t\tif err != nil {\n\t\t\t\t//fmt.Println(\"Time delta error \", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Message type, Message Channel\n\t\t\tvar mType, channel uint8\n\t\t\tmType, channel, err = readStatusByte(lexer.input)\n\t\t\tvar process func(mType, channel uint8, repeat bool) (finished bool, err error)\n\t\t\tprocess = func(mType, channel uint8, repeat bool) (finished bool, err error) {\n\t\t\t\tvar firstArg uint8\n\t\t\t\tif repeat {\n\t\t\t\t\tfirstArg = ((mType & 0xf) << 4) | channel\n\t\t\t\t\tmType = lexer.preStatus\n\t\t\t\t\tchannel = lexer.preChannel\n\t\t\t\t}\n\n\t\t\t\t//fmt.Println(\"Track Event Type \", mType, channel, (mType<<4)+channel)\n\n\t\t\t\tswitch mType {\n\t\t\t\t// NoteOff\n\t\t\t\tcase 0x8, 0x9:\n\t\t\t\t\t{\n\t\t\t\t\t\tvar pitch, velocity uint8\n\t\t\t\t\t\tif repeat {\n\t\t\t\t\t\t\tpitch = firstArg\n\t\t\t\t\t\t\tvelocity, err = parseUint7(lexer.input)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpitch, velocity, err = parseTwoUint7(lexer.input)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t//fmt.Println(\"NoteOn error \", err)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif velocity == 0 {\n\t\t\t\t\t\t\tlexer.callback.NoteOff(channel, pitch, velocity, time)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlexer.callback.NoteOn(channel, pitch, velocity, time)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Polyphonic Key Pressure\n\t\t\t\tcase 0xA:\n\t\t\t\t\t{\n\t\t\t\t\t\tvar pitch, pressure uint8\n\t\t\t\t\t\tpitch, pressure, err = parseTwoUint7(lexer.input)\n\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\n\t\t\t\t\t\tlexer.callback.PolyphonicAfterTouch(channel, pitch, pressure, time)\n\t\t\t\t\t}\n\n\t\t\t\t\t// Control Change or Channel Mode Message\n\t\t\t\tcase 0xB:\n\t\t\t\t\t{\n\t\t\t\t\t\tvar controller, value uint8\n\t\t\t\t\t\tcontroller, value, err = parseTwoUint7(lexer.input)\n\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\n\t\t\t\t\t\t// TODO split this into ChannelMode for values [120, 127]?\n\t\t\t\t\t\t// TODO implement separate callbacks for each type of:\n\t\t\t\t\t\t// - All sound off\n\t\t\t\t\t\t// - Reset all controllers\n\t\t\t\t\t\t// - Local control\n\t\t\t\t\t\t// - All notes off\n\t\t\t\t\t\t// Only if required. http://www.midi.org/techspecs/midimessages.php\n\n\t\t\t\t\t\t// TODO TEST\n\t\t\t\t\t\tlexer.callback.ControlChange(channel, controller, value, time)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\t// Program Change\n\t\t\t\tcase 0xC:\n\t\t\t\t\t{\n\t\t\t\t\t\tvar program uint8\n\t\t\t\t\t\tprogram, err = parseUint7(lexer.input)\n\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\n\t\t\t\t\t\tlexer.callback.ProgramChange(channel, program, time)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\t// Channel Pressure\n\t\t\t\tcase 0xD:\n\t\t\t\t\t{\n\t\t\t\t\t\tvar value uint8\n\t\t\t\t\t\tvalue, err = parseUint7(lexer.input)\n\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\n\t\t\t\t\t\tlexer.callback.ChannelAfterTouch(channel, value, time)\n\t\t\t\t\t}\n\n\t\t\t\t\t// Pitch Wheel\n\t\t\t\tcase 0xE:\n\t\t\t\t\t{\n\t\t\t\t\t\t// The value is a signed int (relative to centre), and absoluteValue is the actual value in the file.\n\t\t\t\t\t\tvar value int16\n\t\t\t\t\t\tvar absoluteValue uint16\n\t\t\t\t\t\tvalue, absoluteValue, err = parsePitchWheelValue(lexer.input)\n\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\n\t\t\t\t\t\tlexer.callback.PitchWheel(channel, value, absoluteValue, time)\n\t\t\t\t\t}\n\n\t\t\t\t\t// System Common and System Real-Time / Meta\n\t\t\t\tcase 0xF:\n\t\t\t\t\t{\n\t\t\t\t\t\t// The 4-bit nibble called 'channel' isn't actually the channel in this case.\n\t\t\t\t\t\tswitch channel {\n\t\t\t\t\t\t// Meta-events\n\t\t\t\t\t\tcase 0xF:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar command uint8\n\t\t\t\t\t\t\t\tcommand, err = parseUint8(lexer.input)\n\n\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t//fmt.Println(\"SystemCommon/RealTime command:\", command)\n\n\t\t\t\t\t\t\t\t// TODO: If every one of these takes a length, then take this outside.\n\t\t\t\t\t\t\t\t// Will make for more more robust unknown types.\n\t\t\t\t\t\t\t\tswitch command {\n\n\t\t\t\t\t\t\t\t// Sequence number\n\t\t\t\t\t\t\t\tcase 0x00:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"seq no\")\n\t\t\t\t\t\t\t\t\t\tvar length uint8\n\t\t\t\t\t\t\t\t\t\tlength, err = parseUint8(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t// Zero length sequences allowed according to http://home.roadrunner.com/~jgglatt/tech/midifile/seq.htm\n\t\t\t\t\t\t\t\t\t\tif length == 0 {\n\t\t\t\t\t\t\t\t\t\t\tlexer.callback.SequenceNumber(channel, 0, false, time)\n\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t// Otherwise length will be 2 to hold the uint16.\n\t\t\t\t\t\t\t\t\t\tvar sequenceNumber uint16\n\t\t\t\t\t\t\t\t\t\tsequenceNumber, err = parseUint16(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.SequenceNumber(channel, sequenceNumber, true, time)\n\n\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Text event\n\t\t\t\t\t\t\t\tcase 0x01:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"Text\")\n\t\t\t\t\t\t\t\t\t\tvar text string\n\t\t\t\t\t\t\t\t\t\ttext, err = parseText(lexer.input)\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"text value\", text, err)\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.Text(channel, text, time)\n\n\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Copyright text event\n\t\t\t\t\t\t\t\tcase 0x02:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"Copyright\")\n\t\t\t\t\t\t\t\t\t\tvar text string\n\t\t\t\t\t\t\t\t\t\ttext, err = parseText(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.CopyrightText(channel, text, time)\n\n\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Sequence or track name\n\t\t\t\t\t\t\t\tcase 0x03:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar text string\n\t\t\t\t\t\t\t\t\t\ttext, err = parseText(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.SequenceName(channel, text, time)\n\n\t\t\t\t\t\t\t\t\t\treturn\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Track instrument name\n\t\t\t\t\t\t\t\tcase 0x04:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar text string\n\t\t\t\t\t\t\t\t\t\ttext, err = parseText(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.TrackInstrumentName(channel, text, time)\n\n\t\t\t\t\t\t\t\t\t\treturn\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Lyric text\n\t\t\t\t\t\t\t\tcase 0x05:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar text string\n\t\t\t\t\t\t\t\t\t\ttext, err = parseText(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.LyricText(channel, text, time)\n\n\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Marker text\n\t\t\t\t\t\t\t\tcase 0x06:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar text string\n\t\t\t\t\t\t\t\t\t\ttext, err = parseText(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.MarkerText(channel, text, time)\n\n\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Cue point text\n\t\t\t\t\t\t\t\tcase 0x07:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar text string\n\t\t\t\t\t\t\t\t\t\ttext, err = parseText(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.CuePointText(channel, text, time)\n\n\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t// Obsolete 'MIDI Channel'\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"MIDI Channel obsolete\")\n\t\t\t\t\t\t\t\t\t\tvar length uint32\n\t\t\t\t\t\t\t\t\t\tlength, err = parseVarLength(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif length != 1 {\n\t\t\t\t\t\t\t\t\t\t\terr = UnexpectedEventLengthError{\"Midi Channel Event expected length 1\"}\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t// This is the channel value.\n\t\t\t\t\t\t\t\t\t\t// Just forget this one.\n\t\t\t\t\t\t\t\t\t\t_, err = parseUint8(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tcase 0x21:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t// Obsolete 'MIDI Port'\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"MIDI PORT obsolete\")\n\t\t\t\t\t\t\t\t\t\tvar length uint32\n\t\t\t\t\t\t\t\t\t\tlength, err = parseVarLength(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif length != 1 {\n\t\t\t\t\t\t\t\t\t\t\terr = UnexpectedEventLengthError{\"MIDI Port Event expected length 1\"}\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t// This is the port value.\n\t\t\t\t\t\t\t\t\t\t// Just forget this one.\n\t\t\t\t\t\t\t\t\t\t_, err = parseUint8(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// End of track\n\t\t\t\t\t\t\t\tcase 0x2F:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar length uint32\n\t\t\t\t\t\t\t\t\t\tlength, err = parseVarLength(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif length != 0 {\n\t\t\t\t\t\t\t\t\t\t\terr = UnexpectedEventLengthError{\"EndOfTrack expected length 0\"}\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.EndOfTrack(channel, time)\n\n\t\t\t\t\t\t\t\t\t\t// Expect the next chunk event.\n\t\t\t\t\t\t\t\t\t\tlexer.state = ExpectChunk\n\n\t\t\t\t\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Set tempo\n\t\t\t\t\t\t\t\tcase 0x51:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t// TODO TEST\n\n\t\t\t\t\t\t\t\t\t\tvar length uint32\n\t\t\t\t\t\t\t\t\t\tlength, err = parseVarLength(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif length != 3 {\n\t\t\t\t\t\t\t\t\t\t\terr = UnexpectedEventLengthError{\"Tempo expected length 3\"}\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tvar microsecondsPerCrotchet uint32\n\t\t\t\t\t\t\t\t\t\tmicrosecondsPerCrotchet, err = parseUint24(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t// Also beats per minute\n\t\t\t\t\t\t\t\t\t\tvar bpm uint32\n\t\t\t\t\t\t\t\t\t\tbpm = 60000000 / microsecondsPerCrotchet\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.Tempo(bpm, microsecondsPerCrotchet, time)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Time signature\n\t\t\t\t\t\t\t\tcase 0x58:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar length uint32\n\t\t\t\t\t\t\t\t\t\tlength, err = parseVarLength(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif length != 4 {\n\t\t\t\t\t\t\t\t\t\t\terr = UnexpectedEventLengthError{\"TimeSignature expected length 4\"}\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t// TODO TEST\n\t\t\t\t\t\t\t\t\t\tvar numerator uint8\n\t\t\t\t\t\t\t\t\t\tnumerator, err = parseUint8(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tvar denomenator uint8\n\t\t\t\t\t\t\t\t\t\tdenomenator, err = parseUint8(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tvar clocksPerClick uint8\n\t\t\t\t\t\t\t\t\t\tclocksPerClick, err = parseUint8(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tvar demiSemiQuaverPerQuarter uint8\n\t\t\t\t\t\t\t\t\t\tdemiSemiQuaverPerQuarter, err = parseUint8(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"TimeSignature event\", numerator, denomenator, clocksPerClick, demiSemiQuaverPerQuarter, time)\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.TimeSignature(numerator, denomenator, clocksPerClick, demiSemiQuaverPerQuarter, time)\n\n\t\t\t\t\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Key signature\n\t\t\t\t\t\t\t\tcase 0x59:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t// TODO TEST\n\t\t\t\t\t\t\t\t\t\tvar length uint32\n\t\t\t\t\t\t\t\t\t\tvar sharpsOrFlats int8\n\t\t\t\t\t\t\t\t\t\tvar mode uint8\n\n\t\t\t\t\t\t\t\t\t\tlength, err = parseVarLength(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif length != 2 {\n\t\t\t\t\t\t\t\t\t\t\terr = UnexpectedEventLengthError{\"KeySignature expected length 2\"}\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t// Signed int, positive is sharps, negative is flats.\n\t\t\t\t\t\t\t\t\t\tsharpsOrFlats, err = parseInt8(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t// Mode is Major or Minor.\n\t\t\t\t\t\t\t\t\t\tmode, err = parseUint8(lexer.input)\n\n\t\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tkey, resultMode := keySignatureFromSharpsOrFlats(sharpsOrFlats, mode)\n\n\t\t\t\t\t\t\t\t\t\tlexer.callback.KeySignature(key, resultMode, sharpsOrFlats)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Sequencer specific info\n\t\t\t\t\t\t\t\tcase 0x7F:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"0x7F\")\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Timing clock\n\t\t\t\t\t\t\t\tcase 0xF8:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"0xF8\")\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Start current sequence\n\t\t\t\t\t\t\t\tcase 0xFA:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"0xFA\")\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Continue stopped sequence where left off\n\t\t\t\t\t\t\t\tcase 0xFB:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"0xFB\")\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Stop sequence\n\t\t\t\t\t\t\t\tcase 0xFc:\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//fmt.Println(\"0xFc\")\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t//fmt.Println(\"Unrecognised meta command\", command)\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\tdefault:\n\t\t\t\t\t\t\t//fmt.Println(\"Unrecognised message type\", mType)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//\n\t\t\t\t\t}\n\n\t\t\t\t\t// This covers all cases.\n\n\t\t\t\t\t// Now we need to see if we're at the end of a Track Data chunk.\n\t\t\t\tdefault:\n\t\t\t\t\t{\n\t\t\t\t\t\tif lexer.preStatus != 0 {\n\t\t\t\t\t\t\treturn process(mType, channel, true)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlexer.preStatus = mType\n\t\t\t\tlexer.preChannel = channel\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn process(mType, channel, false)\n\t\t}\n\n\tcase Done:\n\t\t{\n\t\t\t// The event that raised this will already have returned false to say it's stopped ticking.\n\t\t\t// Just keep returning false.\n\t\t\tfinished = true\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}", "func (l *Lexer) Next() rune {\n\tif l.b {\n\t\tl.b = false\n\t\treturn l.r\n\t}\n\tif l.r == EOF {\n\t\treturn EOF\n\t}\n\treturn l.next()\n}", "func (s *Scanner) next() {\n\tif s.rdOffset < len(s.src) {\n\t\ts.offset = s.rdOffset\n\t\tif s.ch == '\\n' {\n\t\t\ts.lineOffset = s.offset\n\t\t\ts.file.AddLine(s.offset)\n\t\t}\n\t\tr, w := rune(s.src[s.rdOffset]), 1\n\t\tswitch {\n\t\tcase r == 0:\n\t\t\ts.error(s.offset, \"illegal character NUL\")\n\t\tcase r >= utf8.RuneSelf:\n\t\t\t// not ASCII\n\t\t\tr, w = utf8.DecodeRune(s.src[s.rdOffset:])\n\t\t\tif r == utf8.RuneError && w == 1 {\n\t\t\t\ts.error(s.offset, \"illegal UTF-8 encoding\")\n\t\t\t} else if r == bom && s.offset > 0 {\n\t\t\t\ts.error(s.offset, \"illegal byte order mark\")\n\t\t\t}\n\t\t}\n\t\ts.rdOffset += w\n\t\ts.ch = r\n\t} else {\n\t\ts.offset = len(s.src)\n\t\tif s.ch == '\\n' {\n\t\t\ts.lineOffset = s.offset\n\t\t\ts.file.AddLine(s.offset)\n\t\t}\n\t\ts.ch = -1 // eof\n\t}\n}", "func (l *Lexer) Next() (r rune) {\n\tif l.pos >= l.length {\n\t\treturn l.read()\n\t}\n\n\tr, l.width = utf8.DecodeRune(l.buffer[l.pos:])\n\n\tl.pos += l.width\n\n\tif unicode.IsSpace(r) && r != '\\n' {\n\t\tl.Ignore()\n\t\treturn l.Next()\n\t}\n\n\treturn r\n}", "func (l *Lexer) Next() (i *Item) {\n\tfor {\n\t\tif head := l.dequeue(); head != nil {\n\t\t\treturn head\n\t\t}\n\t\tif l.state == nil {\n\t\t\treturn &Item{ItemEOF, l.start, \"\"}\n\t\t}\n\t\tl.state = l.state(l)\n\t}\n\tpanic(\"unreachable\")\n}", "func (l *Lexer) NextToken() *token.Token {\n\tl.skipNonTokens()\n\ttok := token.NewFromByte(l.ch)\n\tl.readChar()\n\treturn tok\n}", "func (l *lexer) next() rune {\n\tif int(l.pos) >= len(l.input) {\n\t\tl.width = 0\n\t\treturn eof\n\t}\n\tr, w := utf8.DecodeRuneInString(l.input[l.pos:])\n\tl.width = Pos(w)\n\tl.pos += l.width\n\tif r == '\\n' {\n\t\tl.file.AddLine(int(l.pos))\n\t}\n\treturn r\n}", "func (x *queryLex) next() rune {\n\tif x.peek != eof {\n\t\tr := x.peek\n\t\tx.peek = eof\n\t\treturn r\n\t}\n\tif len(x.line) == 0 {\n\t\treturn eof\n\t}\n\tc, size := utf8.DecodeRune(x.line)\n\tx.line = x.line[size:]\n\tif c == utf8.RuneError && size == 1 {\n\t\tlog.Print(\"invalid utf8\")\n\t\treturn x.next()\n\t}\n\treturn c\n}", "func (l *Lexer) NextToken() token.Token {\n\tvar tok token.Token\n\n\tl.skipWhitespace()\n\n\tswitch l.ch {\n\tcase '=':\n\t\ttok = token.New(token.ASSIGN, string(l.ch))\n\tcase ';':\n\t\ttok = token.New(token.SEMICOLON, string(l.ch))\n\tcase '(':\n\t\ttok = token.New(token.LPAREN, string(l.ch))\n\tcase ')':\n\t\ttok = token.New(token.RPAREN, string(l.ch))\n\tcase ',':\n\t\ttok = token.New(token.COMMA, string(l.ch))\n\tcase '+':\n\t\ttok = token.New(token.ADD, string(l.ch))\n\tcase '{':\n\t\ttok = token.New(token.LBRACE, string(l.ch))\n\tcase '}':\n\t\ttok = token.New(token.RBRACE, string(l.ch))\n\tcase 0:\n\t\ttok = token.New(token.EOF, \"\")\n\tdefault:\n\t\tif isLetter(l.ch) {\n\t\t\tliteral := l.readIdentifier()\n\t\t\ttok = token.New(string(token.LookupIdent(literal)), literal)\n\t\t\treturn tok\n\t\t} else if isDigit(l.ch) {\n\t\t\ttok = token.New(token.INT, l.readNumber())\n\t\t\treturn tok\n\t\t} else {\n\t\t\ttok = token.New(token.ILLEGAL, string(l.ch))\n\t\t\treturn tok\n\t\t}\n\t}\n\tl.readChar()\n\treturn tok\n}", "func (l *Lexer) NextToken() token.Token {\n\tvar tok token.Token\n\n\tl.skipWhitespace()\n\ttok.LineNo = l.lineNo\n\ttok.CharNo = l.charNo\n\n\tswitch l.ch {\n\n\tcase ';':\n\t\ttok = newToken(token.SEMICOLON, l.ch, l.charNo, l.lineNo)\n\tcase '.':\n\t\ttok = newToken(token.DOT, l.ch, l.charNo, l.lineNo)\n\tcase '(':\n\t\ttok = newToken(token.LPAREN, l.ch, l.charNo, l.lineNo)\n\tcase ')':\n\t\ttok = newToken(token.RPAREN, l.ch, l.charNo, l.lineNo)\n\tcase ',':\n\t\ttok = newToken(token.COMMA, l.ch, l.charNo, l.lineNo)\n\tcase '+':\n\t\ttok = newToken(token.PLUS, l.ch, l.charNo, l.lineNo)\n\tcase '{':\n\t\ttok = newToken(token.LBRACE, l.ch, l.charNo, l.lineNo)\n\tcase '}':\n\t\ttok = newToken(token.RBRACE, l.ch, l.charNo, l.lineNo)\n\tcase '-':\n\t\ttok = newToken(token.MINUS, l.ch, l.charNo, l.lineNo)\n\n\tcase '*':\n\t\ttok = newToken(token.ASTERISK, l.ch, l.charNo, l.lineNo)\n\tcase '/':\n\t\ttok = newToken(token.SLASH, l.ch, l.charNo, l.lineNo)\n\tcase '=':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.EQ, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.ASSIGN, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '!':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.NOT_EQ, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.BANG, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '<':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.LTE, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.LT, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '>':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.GTE, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.GT, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '\"':\n\t\ttok.Type = token.STRING\n\t\ttok.Literal = l.readString()\n\tcase ':':\n\t\ttok = newToken(token.COLON, l.ch, l.charNo, l.lineNo)\n\tcase '[':\n\t\ttok = newToken(token.LBRACKET, l.ch, l.charNo, l.lineNo)\n\tcase ']':\n\t\ttok = newToken(token.RBRACKET, l.ch, l.charNo, l.lineNo)\n\tcase 0:\n\t\ttok.Literal = \"\"\n\t\ttok.Type = token.EOF\n\tdefault:\n\t\tif isLetter(l.ch) {\n\t\t\ttok.Literal = l.readIdentifier()\n\t\t\ttok.Type = token.LookupIdent(tok.Literal)\n\t\t\treturn tok\n\t\t} else if isDigit(l.ch) {\n\t\t\ttok.Type, tok.Literal = l.readNumber()\n\t\t\treturn tok\n\t\t} else {\n\t\t\ttok = newToken(token.ILLEGAL, l.ch, l.charNo, l.lineNo)\n\t\t}\n\t}\n\tl.readChar()\n\treturn tok\n}", "func (p *ParserBase) Next() {\n\tp.newline = false\n\tp.Item = p.Lxr.Next()\n\tp.EndPos = int32(p.Item.Pos)\n\tfor {\n\t\tif p.Token == tok.Newline {\n\t\t\tif p.Lxr.AheadSkip(0).Token != tok.QMark {\n\t\t\t\tp.newline = true\n\t\t\t}\n\t\t} else if p.Token != tok.Comment && p.Token != tok.Whitespace {\n\t\t\tbreak\n\t\t}\n\t\tp.Item = p.Lxr.Next()\n\t}\n\tif p.EqToIs && p.Token == tok.Eq {\n\t\tp.Token = tok.Is\n\t}\n}", "func (p DiceParser) peek() Token {\n\treturn p.tokens[p.current]\n}", "func (l *lexer) next() rune {\r\n\tif int(l.pos) >= l.length {\r\n\t\tl.width = 0\r\n\t\treturn eof\r\n\t}\r\n\tr, w := utf8.DecodeRuneInString(l.input[l.pos:])\r\n\tl.width = Pos(w)\r\n\tl.pos += l.width\r\n\tif r == '\\n' {\r\n\t\tl.line++\r\n\t}\r\n\treturn r\r\n}", "func (p *parser) peek() token {\n\tif p.peekCount > 0 {\n\t\treturn p.token[p.peekCount-1]\n\t}\n\tp.peekCount = 1\n\tp.token[1] = p.token[0]\n\tp.token[0], _ = p.lex.nextToken()\n\treturn p.token[0]\n}" ]
[ "0.7589529", "0.7524865", "0.7380516", "0.73338383", "0.73338383", "0.72684634", "0.72526115", "0.72270924", "0.71557295", "0.71360236", "0.71148014", "0.71091104", "0.7095706", "0.70567477", "0.7050757", "0.7032534", "0.70102143", "0.7002279", "0.6942436", "0.6937876", "0.6881162", "0.68403935", "0.6828774", "0.6813196", "0.67003924", "0.6679654", "0.6677839", "0.66645163", "0.66555613", "0.6653368", "0.66463363", "0.6633754", "0.6629847", "0.6582079", "0.65590054", "0.6530425", "0.6507154", "0.64973736", "0.64937127", "0.64687353", "0.64675874", "0.6464898", "0.6458698", "0.6443327", "0.64146596", "0.6412801", "0.6409069", "0.63861823", "0.6381965", "0.6317612", "0.63158244", "0.6301159", "0.62762785", "0.6268954", "0.624811", "0.624697", "0.62296426", "0.62296426", "0.62214386", "0.6207765", "0.6164334", "0.616338", "0.6152286", "0.6147502", "0.614532", "0.6134852", "0.61339504", "0.6116213", "0.6083627", "0.605793", "0.6050434", "0.60497206", "0.60497206", "0.60415965", "0.60253084", "0.6007036", "0.6001501", "0.59993815", "0.59984726", "0.598957", "0.59894747", "0.5985584", "0.59784114", "0.5973845", "0.59619147", "0.5943587", "0.59294623", "0.5910169", "0.59051156", "0.5904073", "0.59024864", "0.5900869", "0.5900089", "0.5899703", "0.58801913", "0.5868495", "0.58532774", "0.58469135", "0.58366674", "0.5830829" ]
0.7241496
7
Peek will look at the next token without rolling the parser forward
func (p *Parser) Peek() token.Token { return p.peek }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (parser *Parser) peek() Token {\n\ttoken, _ := parser.scan()\n\tif token == WHITESPACE {\n\t\ttoken, _ = parser.scan()\n\t\tparser.unscan()\n\t}\n\tparser.unscan()\n\treturn token\n}", "func (p *parser) peek() token {\n\tif p.lookAheadTok != nil {\n\t\tpanic(\"cannot parser.peek(), lookAheadTok is in used\")\n\t}\n\ttok := p.lex.nextToken()\n\tp.lookAheadTok = &tok\n\treturn tok\n}", "func (p *parser) peek() lexer.Token {\n\treturn p.tokens[p.current]\n}", "func (p *parser) peek() token {\n\tif p.peekCount > 0 {\n\t\treturn p.token[p.peekCount-1]\n\t}\n\tp.peekCount = 1\n\tp.token[1] = p.token[0]\n\tp.token[0], _ = p.lex.nextToken()\n\treturn p.token[0]\n}", "func (p DiceParser) peek() Token {\n\treturn p.tokens[p.current]\n}", "func (s *TokenStream) Peek() Token {\n\treturn s.iter.Peek()\n}", "func (t *Tree) peek() token {\n\tif t.peekCount > 0 {\n\t\treturn t.token[t.peekCount-1]\n\t}\n\tt.peekCount = 1\n\tt.token[0] = t.lex.nextToken()\n\treturn t.token[0]\n}", "func (p *Parser) peek(cnt int) *Token {\n\tfor len(p.tokens) < cnt {\n\t\tp.tokens = append(p.tokens, p.lexer.NextToken())\n\t}\n\treturn p.tokens[cnt-1]\n}", "func (lex *Lexer) Peek() scanner.Token {\n\tlex.Next()\n\tdefer lex.UnNext()\n\treturn lex.Token\n}", "func (l *nonEmitingLexer) peek() rune {\n\trune := l.next()\n\tl.backup()\n\treturn rune\n}", "func (m *ExpressionPager) Peek() ql.Token {\n\n\tif m.peekCount > 0 {\n\t\t//u.Infof(\"peek: %v: len=%v\", m.peekCount, len(m.token))\n\t\treturn m.token[m.peekCount-1]\n\t}\n\tm.peekCount = 1\n\tm.token[0] = m.lex.NextToken()\n\t//u.Infof(\"peek: %v: len=%v %v\", m.peekCount, len(m.token), m.token[0])\n\treturn m.token[0]\n}", "func (pars *Parser) expectPeek(t lexer.TokenType) bool {\n\tif pars.peekTokenIs(t) {\n\t\tpars.nextToken()\n\t\treturn true\n\t}\n\treturn false\n}", "func (p *Parser) expectPeek(t tokentype.TokenType) bool {\n\tif p.peekTokenIs(t) {\n\t\tp.nextToken()\n\t\treturn true\n\t}\n\tp.AddError(\"expected next token to be %s, got %v\",\n\t\tt.Literal(), p.curToken.Literal)\n\treturn false\n}", "func (l *Lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *Lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (p *parser) peek() item {\n\tif p.peekCount > 0 {\n\t\treturn p.token[p.peekCount-1]\n\t}\n\tp.peekCount = 1\n\n\tt := p.lex.nextItem()\n\t// Skip comments.\n\tfor t.typ == itemComment {\n\t\tt = p.lex.nextItem()\n\t}\n\tp.token[0] = t\n\treturn p.token[0]\n}", "func (z *Tokenizer) peek() rune {\n\treturn z.peekAt(0)\n}", "func (p *parser) peek() string {\n\tif p.valid() {\n\t\treturn p.lines[p.idx]\n\t}\n\treturn \"\"\n}", "func (lex *Lexer) peek() rune {\n\tr := lex.next()\n\tlex.backup()\n\treturn r\n}", "func (lx *Lexer) peek() rune {\n\tr := lx.next()\n\tlx.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\r\n\tr := l.next()\r\n\tl.backup()\r\n\treturn r\r\n}", "func (lx *lexer) peek() rune {\r\n\tr := lx.next()\r\n\tlx.backup()\r\n\treturn r\r\n}", "func (s *lexStream) peek() byte {\r\n\tif s.c >= len(s.input) {\r\n\t\ts.pos[len(s.pos)-1].line = 0\r\n\t\treturn eof\r\n\t}\r\n\treturn s.input[s.c]\r\n}", "func (s *scanner) peek() rune {\n\tr := s.next()\n\ts.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (l *lexer) peek() rune {\n\tif l.isEOF() {\n\t\treturn eof\n\t}\n\tr := l.next()\n\tl.backup()\n\treturn r\n}", "func (p *Parser) expectPeek(t token.TokenType) bool {\n\t// It checks the type of peekToken, only if it's correct, it advances the\n\t// tokens by calling nextToken()\n\tif p.peekTokenIs(t) {\n\t\tp.nextToken()\n\t\treturn true\n\t}\n\n\tp.peekError(t)\n\treturn false\n}", "func (p *Parser) expectPeek(t lexer.TokenType) bool {\n\tif p.peekTokenIs(t) {\n\t\tp.advanceTokens()\n\t\treturn true\n\t} else {\n\t\tp.peekError(t)\n\t\treturn false\n\t}\n}", "func (p *Parser) peek() ast.Word {\n\ti := 1\n\n\tfor {\n\t\tif p.offset+i == len(p.source) {\n\t\t\treturn ast.Word{token.EOF, \"\"}\n\t\t}\n\t\tif p.source[p.offset+i].Token == token.COMMENT {\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\t\treturn p.source[p.offset+i]\n\t}\n\treturn ast.Word{token.EOF, \"\"}\n}", "func (t *Tree) peek() item {\n\tif t.peekCount > 0 {\n\t\treturn t.token[t.peekCount-1]\n\t}\n\tt.peekCount = 1\n\tt.token[0] = t.lex.nextItem()\n\treturn t.token[0]\n}", "func (p *parser) next() token {\n\tif p.peekCount > 0 {\n\t\tp.peekCount--\n\t} else {\n\t\tp.token[0], _ = p.lex.nextToken()\n\t}\n\treturn p.token[p.peekCount]\n}", "func (p *Parser) expectPeek(t token.Type) bool {\n\tif p.nextTokIs(t) {\n\t\tp.nextToken()\n\t\treturn true\n\t}\n\n\tp.peekError(t)\n\treturn false\n}", "func (l *reader) peek() rune {\n\trune := l.next()\n\tl.backup()\n\treturn rune\n}", "func (l *Lexer) peek() rune {\n\tr, _ := utf8.DecodeRuneInString(l.input[l.pos:])\n\t// log.Printf(\"[peek] %q\", r)\n\treturn r\n}", "func (l *Lexer) peek() rune {\n\trn, err := l.reader.Peek()\n\tif err != nil {\n\t\tl.reportError(fmt.Sprintf(\"Invalid '%s' character in source file\", string(rn)))\n\t}\n\n\treturn rn\n}", "func (l *Lexer) peek() rune {\n\tr, _ := utf8.DecodeRuneInString(l.input[l.pos:])\n\treturn r\n}", "func (s *Scanner) peek() rune {\n\tr := s.next()\n\ts.prev()\n\treturn r\n}", "func (m *minifier) peek() int {\n\tm.theLookahead = m.get()\n\treturn m.theLookahead\n}", "func (p *preprocessorImpl) Peek() tokenExpansion {\n\tfor p.currentToken == nil {\n\t\t// process any preprocessor directives\n\t\tp.processDirectives()\n\n\t\ttok := newTokenExpansion(p.lexer.Next())\n\t\tp.line, _ = tok.Info.Cst.Token().Cursor()\n\n\t\tif tok.Info.Token == nil {\n\t\t\tif len(p.ifStack) > 0 {\n\t\t\t\tp.err.Errorf(\"Unterminated #if directive at the end of file.\")\n\t\t\t}\n\t\t\tp.currentToken = &tok\n\t\t} else if !p.skipping() {\n\t\t\tp.currentToken = &tok\n\t\t}\n\t}\n\treturn *p.currentToken\n}", "func (l *StringLexer) Peek() (r rune) {\n\tr = l.Next()\n\tl.Backup()\n\treturn r\n}", "func (l *Lexer) Peek() rune {\n\tr := l.Next()\n\tl.Backup()\n\treturn r\n}", "func (l *Lexer) Peek() rune {\n\tr := l.Next()\n\tl.Backup()\n\treturn r\n}", "func peekToken(data []byte) json.Token {\n\ttok, _ := json.NewDecoder(bytes.NewReader(data)).Token()\n\treturn tok\n}", "func (z *Tokenizer) repeek() {\n\tby, err := z.r.Peek(3)\n\tif err != nil && err != io.EOF {\n\t\tpanic(err)\n\t}\n\tcopy(z.peek[:], by)\n\n\t// zero fill on EOF\n\ti := len(by)\n\tfor i < 3 {\n\t\tz.peek[i] = 0\n\t\ti++\n\t}\n}", "func (l *LexInner) Peek() rune {\n\tchar := l.Next()\n\tl.Back()\n\treturn char\n}", "func (l *Lexer) Peek() rune {\n\tr := l.Next()\n\n\tl.Backup()\n\treturn r\n}", "func (l *Lexer) Peek() rune {\n\tif l.b {\n\t\treturn l.r\n\t}\n\tif l.r == EOF {\n\t\treturn EOF\n\t}\n\tl.b = true\n\treturn l.next()\n}", "func (lexer *Lexer) peek() string {\n\tif lexer.curPos+1 >= len(lexer.source) {\n\t\treturn string(\"\\u0000\")\n\t} else {\n\t\treturn string(lexer.source[lexer.curPos+1])\n\t}\n}", "func (p *parametizer) peek() (byte, error) {\n\tif p.pos >= len(p.z) {\n\t\treturn 0, io.EOF\n\t}\n\treturn p.z[p.pos], nil\n}", "func (p *Parser) expectPeek(t token.Type) bool {\n\tif p.peek.Is(t) {\n\t\tp.next()\n\t\treturn true\n\t}\n\tp.peekError(t)\n\treturn false\n}", "func (p *parser) next() token {\n\tvar tok token\n\tif p.lookAheadTok != nil {\n\t\ttok = *p.lookAheadTok\n\t\tp.lookAheadTok = nil\n\t} else {\n\t\ttok = p.lex.nextToken()\n\t}\n\treturn tok\n}", "func peekNext(in *bufio.Reader) (rune, error) {\n\tif err := skipSpaces(in); err != nil {\n\t\treturn rune(0), err\n\t}\n\tr, _, err := in.ReadRune()\n\tif err != nil {\n\t\treturn rune(0), err\n\t}\n\tin.UnreadRune()\n\treturn r, nil\n}", "func (s *Scanner) peek() rune {\n\tif s.isAtEnd() {\n\t\treturn '\\000'\n\t}\n\tr, _ := utf8.DecodeRune(s.source[s.current:])\n\treturn r\n}", "func (s *Scanner) peekNext() rune {\n\tif s.current+1 >= len(s.source) {\n\t\treturn '\\000'\n\t}\n\t_, size := utf8.DecodeRune(s.source[s.current:])\n\tnextRune, _ := utf8.DecodeRune(s.source[s.current+size:])\n\treturn nextRune\n}", "func (l *LLk) Peek(k int) (*lexer.Token, error) {\n\tif k > l.k {\n\t\treturn nil, fmt.Errorf(\"grammar.LLk: cannot look ahead %v beyond defined %v\", k, l.k)\n\t}\n\tif k <= 0 {\n\t\treturn nil, fmt.Errorf(\"grammar.LLk: invalid look ahead value %v\", k)\n\t}\n\treturn &l.tkns[k], nil\n}", "func (t *Tree) peekNonSpace() (tok token) {\n\tfor {\n\t\ttok = t.next()\n\t\tif tok.typ != tokenSpace {\n\t\t\tbreak\n\t\t}\n\t}\n\tt.backup()\n\treturn tok\n}", "func (t *Tree) next() token {\n\tif t.peekCount > 0 {\n\t\tt.peekCount--\n\t} else {\n\t\tt.token[0] = t.lex.nextToken()\n\t}\n\treturn t.token[t.peekCount]\n}", "func (p *Parser) peekTokenIs(t tokentype.TokenType) bool {\n\treturn p.peekToken.Type == t\n}", "func (t *Tree) peekNonSpace() (token item) {\n\tfor {\n\t\ttoken = t.next()\n\t\tif token.typ != itemWhitespace {\n\t\t\tbreak\n\t\t}\n\t}\n\tt.backup()\n\treturn token\n}", "func (p *Parser) peekTokenIs(t token.TokenType) bool {\n\treturn p.peekToken.Type == t\n}", "func (s *Scanner) peek() rune {\n\tpeek, _, err := s.buf.ReadRune()\n\tif err != nil {\n\t\treturn eof\n\t}\n\n\ts.buf.UnreadRune()\n\treturn peek\n}", "func (l *Lexer) Peek() (r rune) {\n\tif l.pos >= len(l.Input) {\n\t\tl.width = 0\n\t\treturn 0\n\t}\n\tr, l.width = utf8.DecodeRuneInString(l.Input[l.pos:])\n\tif r == utf8.RuneError {\n\t\t// Treat bad unicode as EOF.\n\t\tl.width = 0\n\t\treturn 0\n\t}\n\treturn r\n}", "func (s *Scanner) peek(n int) rune {\n\tif len(s.peekRunes) >= n {\n\t\treturn s.peekRunes[n-1]\n\t}\n\n\tp := s.nextRune()\n\ts.peekRunes = append(s.peekRunes, p)\n\n\treturn p\n}", "func (pars *Parser) peekTokenIs(t lexer.TokenType) bool {\n\treturn pars.peekToken.Type == t\n}", "func (p *Parser) peekTokenIs(t lexer.TokenType) bool {\n\treturn p.peekToken.Type == t\n}", "func (l *Lexer) Peek() (rune, int) {\n\tc, n := l.Advance()\n\tl.Backup()\n\treturn c, n\n}", "func (p *parser) next() (t token) {\n\tp.fill()\n\tif len(p.buf) > 0 {\n\t\tt = p.buf[0]\n\t\tp.buf = p.buf[1:]\n\t}\n\tp.fill()\n\n\treturn\n}", "func (p *parser) next() {\n\tif p.look != nil {\n\t\t// Consume stored state.\n\t\tp.tokenstate = *p.look\n\t\tp.look = nil\n\t\treturn\n\t}\n\n\tp.off, p.tok, p.lit = p.scanner.Scan()\n\n\tp.pre = nil\n\t// Skip over prefix tokens, accumulating them in p.pre.\n\tfor p.tok.IsPrefix() {\n\t\tp.pre = append(p.pre, tree.Prefix{Type: p.tok, Bytes: p.lit})\n\t\tp.off, p.tok, p.lit = p.scanner.Scan()\n\t}\n}", "func (s *ss) peek(ok string) bool {\n\tr := s.getRune()\n\tif r != eof {\n\t\ts.UnreadRune()\n\t}\n\treturn indexRune(ok, r) >= 0\n}", "func (p *parser) peek(i ...int) rune {\n\tif len(i) == 0 {\n\t\tif p.cur >= len(p.src) {\n\t\t\treturn eof\n\t\t}\n\t\tr, _ := utf8.DecodeRune(p.src[p.cur:])\n\t\treturn r\n\t} else {\n\t\tif len(i) > 1 {\n\t\t\tpanic(\"no more than one arguments allowed\")\n\t\t}\n\t\tnth := i[0]\n\t\tpos := p.cur\n\t\tvar (\n\t\t\tr rune\n\t\t\tw int\n\t\t)\n\t\tfor k := 0; k < nth; k++ {\n\t\t\tr, w = utf8.DecodeRune(p.src[pos:])\n\t\t\tpos += w\n\t\t}\n\t\treturn r\n\t}\n}", "func (z *Tokenizer) peekAt(idx int) rune {\n\tif z.pos+idx > z.length {\n\t\treturn utf8.RuneError\n\t}\n\tidx += z.pos\n\tr, _ := utf8.DecodeRuneInString(z.input[idx:])\n\treturn r\n}", "func (p *parser) consume() {\n\tp.prev = p.next\n\tif p.next.k != lexKindEof {\n\t\tp.next = p.lex()\n\t}\n}", "func (rs *RuneScanner) Peek() rune {\n\tvar r rune\n\tif rs.inext < len(rs.runes) {\n\t\tr = rs.runes[rs.inext]\n\t} else {\n\t\tr = rs.Rune()\n\t\trs.Unrune()\n\t}\n\treturn r\n}", "func (r *reader) peek() byte {\n\tif r.eof() {\n\t\treturn 0\n\t}\n\treturn r.s[r.p.Offset]\n}", "func (s *Scanner) peek() (byte, error) {\n\tch, err := s.reader.Peek(1)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn ch[0], nil\n}", "func (lex *Lexer) PeekN(n int) scanner.Token {\n\tvar lasts [][]rune\n\tfor 0 < n {\n\t\tlex.Next()\n\t\tlasts = append(lasts, lex.RawText)\n\t\tn--\n\t}\n\ttoken := lex.Token\n\tfor i := len(lasts) - 1; 0 <= i; i-- {\n\t\tlex.UnNextTo(lasts[i])\n\t}\n\treturn token\n}", "func (p *Parser) consume(tokenType TokenType, err string) {\n\tif (p.current.Type == tokenType) {\n\t\tp.advance()\n\t\treturn\n\t}\n\tp.raiseError(p.current, err)\n}", "func (es *eeStack) peek() (v interface{}, t eeType) {\r\n\tt = es.peekType()\r\n\tv = t.peek(es)\r\n\treturn\r\n}", "func (p *Parser) next() *Token {\n\tif len(p.tokens) > 0 {\n\t\tt := p.tokens[0]\n\t\tp.tokens = p.tokens[1:]\n\t\treturn t\n\t}\n\treturn p.lexer.NextToken()\n}", "func (p *Parser) Consume(tok rune) error {\n if (p.Scanner.Token != tok) {\n return p.Error(fmt.Sprintf(\"Expected %s but found %s\",\n scanner.TokenString(tok), scanner.TokenString(p.Scanner.Token)))\n } else {\n p.Scanner.Scan()\n return nil\n }\n}", "func (pars *Parser) nextToken() {\n\tpars.thisToken = pars.peekToken\n\tpars.peekToken = pars.lex.NextToken()\n}", "func (s *Scanner) Peek() rune {\n\tr, _, _ := s.r.ReadRune()\n\tif r != eof {\n\t\t_ = s.r.UnreadRune()\n\t}\n\n\treturn r\n}", "func (p *Parser) nextToken() {\n\tp.curToken = p.peekToken\n\tp.peekToken = p.l.NextToken()\n}", "func (p *Parser) nextToken() {\n\tp.curToken = p.peekToken\n\tp.peekToken = p.l.NextToken()\n}", "func (l *Lexer) PeekNextTokenType() token.Type {\n\tif len(l.input)-1 > l.pos {\n\t\tch := l.input[l.pos]\n\t\treturn resolveTokenType(ch)\n\t}\n\treturn resolveTokenType(0) // EOF\n}", "func (l *Lexer) peekChar() byte {\n if l.readPosition >= len(l.input) {\n return 0\n } else {\n return l.input[l.readPosition]\n }\n}", "func (lx *Lexer) peekChar() (r rune, err error) {\n\tr, err = lx.runeGetter()\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// put it back on the queue\n\tlx.unicodeQueue.Queue(r)\n\treturn\n}", "func (w *RootWalker) peek() (*wrappedObj, error) {\n\tif w.Size() == 0 {\n\t\treturn nil, ErrEmptyInternalStack\n\t}\n\treturn w.stack[w.Size()-1], nil\n}" ]
[ "0.8098643", "0.80505794", "0.8001524", "0.7919769", "0.79038626", "0.7829674", "0.7595875", "0.7519973", "0.74746764", "0.74474275", "0.7429863", "0.741054", "0.7323536", "0.72951776", "0.72951776", "0.7285229", "0.7257971", "0.72551614", "0.7245528", "0.7237044", "0.72360635", "0.7177967", "0.7131328", "0.7130881", "0.71244097", "0.71244097", "0.71244097", "0.71244097", "0.71244097", "0.71244097", "0.71244097", "0.71244097", "0.71244097", "0.71244097", "0.71244097", "0.71244097", "0.71244097", "0.7113628", "0.7069103", "0.7059242", "0.7053985", "0.7053251", "0.70328295", "0.7027548", "0.70023316", "0.69740385", "0.6963406", "0.6937896", "0.6924961", "0.69237643", "0.69111884", "0.6908149", "0.68838656", "0.68838656", "0.6872213", "0.68678933", "0.6864756", "0.68554", "0.68410385", "0.68336475", "0.6815645", "0.68123424", "0.67620194", "0.6743457", "0.6724669", "0.6670688", "0.66448754", "0.6642481", "0.6634651", "0.6626179", "0.6623585", "0.65914166", "0.65869975", "0.65830666", "0.65803504", "0.65544057", "0.6548428", "0.65360653", "0.6523574", "0.64949435", "0.6487081", "0.64535093", "0.644478", "0.6364831", "0.6347399", "0.6337325", "0.6322921", "0.6313949", "0.6313517", "0.6296941", "0.6295292", "0.62695205", "0.62622243", "0.62492955", "0.6233517", "0.6233517", "0.6231853", "0.6220641", "0.6201212", "0.61375153" ]
0.75338626
7
Token will look at the current token
func (p *Parser) Token() token.Token { return p.curr }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *VppToken) GetToken()(*string) {\n return m.token\n}", "func (t jsonToken) Token() (tok Token) {\n\ttok.strBuilder.WriteString(t.Value)\n\ttok.Position = t.Position\n\ttok.Type = t.Type\n\ttok.Sub = t.Sub\n\treturn\n}", "func (obj *tokenSection) Token() RawToken {\n\treturn obj.token\n}", "func (m *TokenBase) Token() *token32 {\n\treturn m.token\n}", "func (op Op) Token() token.Token {\n\treturn opMap[op]\n}", "func (s *Scanner) current() *Token {\n\treturn s.tokbuf\n}", "func GetToken() string {\n\treturn tokenString\n}", "func (obj *instruction) Token() token.Token {\n\treturn obj.tok\n}", "func (t *TemplateInvokeNode) GetToken() *token.Token {\n\treturn t.Token\n}", "func (l *lexer) nextToken() Token {\r\n\ttok := <-l.tokens\r\n\treturn tok\r\n}", "func (z *Tokenizer) Token() Token {\n\treturn z.tok\n}", "func (l *LLk) Current() *lexer.Token {\n\treturn &l.tkns[0]\n}", "func (f *tokenFormat) nextToken(customVerbs []string) (token, error) {\n\tfor {\n\t\tr, _, err := f.stream.ReadRune()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch r {\n\t\tcase ' ':\n\t\t\treturn spaceToken{}, nil\n\t\tcase ':':\n\t\t\treturn f.readAction(customVerbs)\n\t\tdefault:\n\t\t\treturn f.readLiteral(r)\n\t\t}\n\t}\n}", "func (s *Scanner) Token() *Token {\n\treturn s.token\n}", "func token(name string) lex.Action {\n\treturn func(s *lex.Scanner, m *machines.Match) (interface{}, error) {\n\t\treturn s.Token(TokenIds[name], string(m.Bytes), m), nil\n\t}\n}", "func token(name string) lex.Action {\n\treturn func(s *lex.Scanner, m *machines.Match) (interface{}, error) {\n\t\treturn s.Token(TokenIds[name], string(m.Bytes), m), nil\n\t}\n}", "func (stream *TokenStream) Token() *Token {\n\treturn stream.token\n}", "func (l *lexer) nextToken() token {\n\ttoken := <-l.tokens\n\tl.lastPos = token.pos\n\treturn token\n}", "func (c *configuration) Token(restConfig *RestConfig) Token {\n\tif restConfig != nil {\n\t\treturn Token(restConfig.Config.BearerToken)\n\t}\n\treturn \"\"\n}", "func (o *Venda) GetToken() string {\n\tif o == nil || o.Token.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Token.Get()\n}", "func (o SourceCodeTokenOutput) Token() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SourceCodeToken) pulumi.StringOutput { return v.Token }).(pulumi.StringOutput)\n}", "func (pars *Parser) nextToken() {\n\tpars.thisToken = pars.peekToken\n\tpars.peekToken = pars.lex.NextToken()\n}", "func (c *ClusterConnectionInfoResolver) Token() string {\n\treturn c.token\n}", "func (p *ProtoParserAndFramer) Token(m []byte) (rainslib.Token, error) {\n\ttoken := rainslib.Token{}\n\tmessage, err := capnp.Unmarshal(m)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\tmsg, err := proto.ReadRootRainsMessage(message)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\n\ttok, err := msg.Token()\n\tif err != nil {\n\t\tlog.Warn(\"Could not decode token\", \"error\", err)\n\t\treturn token, err\n\t}\n\tif len(tok) != 16 {\n\t\tlog.Warn(\"Length of token is not 16\", \"token\", tok, \"length\", len(tok))\n\t\treturn token, errors.New(\"Length of token is not 16\")\n\t}\n\n\tcopy(token[:], tok)\n\treturn token, nil\n}", "func (p *parser) token() tree.Token {\n\treturn tree.Token{\n\t\tType: p.tok,\n\t\tPrefix: p.pre,\n\t\tOffset: p.off,\n\t\tBytes: p.lit,\n\t}\n}", "func (s *Server) CurrentToken() (token string, err error) {\n\ts.tokenLock.RLock()\n\tif s.config.Clock().Now().Before(s.tokenExpireTime) {\n\t\tdefer s.tokenLock.RUnlock()\n\t\treturn s.token, nil\n\t}\n\n\ts.tokenLock.RUnlock()\n\n\tbuf := make([]byte, tokenByteSize)\n\tif _, err = rand.Read(buf); err != nil {\n\t\treturn \"\", err\n\t}\n\ttoken = base64.URLEncoding.EncodeToString(buf)\n\n\ts.tokenLock.Lock()\n\tdefer s.tokenLock.Unlock()\n\n\tif s.config.Clock().Now().Before(s.tokenExpireTime) {\n\t\treturn s.token, nil\n\t}\n\n\ts.token = token\n\ts.tokenExpireTime = s.config.Clock().Now().Add(tokenValidTime)\n\n\treturn token, nil\n}", "func (p *parser) tokenNext() tree.Token {\n\ttok := p.token()\n\tp.next()\n\treturn tok\n}", "func (a assign) Token() token.Token {\n\treturn a.t\n}", "func Token(c *cli.Context) {\n\tconfigPath := c.GlobalString(\"config\")\n\n\tconfig, err := parseConfig(configPath)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error parsing the config : %s\", err)\n\t\treturn\n\t}\n\n\tfmt.Print(string(authtoken.Token(config.HTTP.Login, config.HTTP.Password, config.HTTP.Salt)))\n}", "func (o PipelineTriggerOutput) Token() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PipelineTrigger) pulumi.StringOutput { return v.Token }).(pulumi.StringOutput)\n}", "func (d *Decoder) Token() (Token, error) {\n\treturn nil, nil\n}", "func (p *Parser) nextToken() {\n\tp.tok = p.nextTok\n\tp.nextTok = p.l.NextToken()\n}", "func (pars *Parser) curTokenIs(t lexer.TokenType) bool {\n\treturn pars.thisToken.Type == t\n}", "func (p *Parser) nextToken() {\n\tp.curToken = p.peekToken\n\tp.peekToken = p.l.NextToken()\n}", "func (p *Parser) nextToken() {\n\tp.curToken = p.peekToken\n\tp.peekToken = p.l.NextToken()\n}", "func (rd *Reader) Token(init rune) (string, error) {\n\tvar b strings.Builder\n\tif init != -1 {\n\t\tb.WriteRune(init)\n\t}\n\n\tfor {\n\t\tr, err := rd.NextRune()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn b.String(), err\n\t\t}\n\n\t\tif rd.IsTerminal(r) {\n\t\t\trd.Unread(r)\n\t\t\tbreak\n\t\t}\n\n\t\tb.WriteRune(r)\n\t}\n\n\treturn b.String(), nil\n}", "func (s *reuseTokenSource) Token() (*Token, error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.t.Valid() {\n\t\treturn s.t, nil\n\t}\n\tt, err := s.new.Token()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.t = t\n\treturn t, nil\n}", "func (o RegistryTaskSourceTriggerAuthenticationOutput) Token() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RegistryTaskSourceTriggerAuthentication) string { return v.Token }).(pulumi.StringOutput)\n}", "func (s *Service) Token(str string) string {\n\ts.h.Reset()\n\tfmt.Fprintf(s.h, \"%s%s\", str, strconv.Itoa(time.Now().Nanosecond()))\n\treturn fmt.Sprintf(\"%x\", s.h.Sum(nil))\n}", "func (m *SessionMutation) Token() (r string, exists bool) {\n\tv := m.token\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (d *Decoder) Token() (Token, error) {\n\ttok := <-d.tokChan\n\tif tok == nil {\n\t\treturn tok, d.err\n\t}\n\treturn tok, nil\n}", "func (p *Parser) nextToken() {\n\tp.prevToken = p.curToken\n\tp.curToken = p.peekToken\n\tp.peekToken = p.l.NextToken()\n}", "func Token() gin.HandlerFunc {\r\n\treturn func(c *gin.Context) {\r\n\t\tsession := sessions.Default(c)\r\n\t\tUserID := session.Get(\"UserID\")\r\n\t\tIsLeader := session.Get(\"IsLeader\")\r\n\r\n\t\tfmt.Println(\"UserID, IsLeader\", UserID, IsLeader)\r\n\t\tif UserID == nil {\r\n\t\t\tstate := string([]byte(c.Request.URL.Path)[1:])\r\n\t\t\tc.Redirect(http.StatusFound, \"/login?state=\"+state)\r\n\t\t\tc.Abort()\r\n\t\t} else {\r\n\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\t\t\tc.Next()\r\n\t\t}\r\n\t}\r\n}", "func (r *FlatJsonReader) token() (json.Token, error) {\n for {\n t, err := r.d.Token()\n if err != nil {\n return nil, errors.Wrap(err, \"cannot get token\")\n }\n switch t.(type) {\n case json.Delim:\n default:\n return t, nil\n }\n }\n}", "func (p *Parser) curTokenIs(t tokentype.TokenType) bool {\n\treturn p.curToken.Type == t\n}", "func (parser *Parser) match(kind tokenKind) (*token, error) {\n\tcurrToken := parser.currToken\n\n\t// If the current token is not a match, return the token for\n\t// error reporting purposes. Do not consume the token.\n\tif currToken.kind != kind {\n\t\treturn currToken, fmt.Errorf(`Unexpected token - found: \"%s\", expected: \"%s\"`,\n\t\t\tcurrToken.kind.ToString(), kind.ToString())\n\t}\n\n\ttoken, err := parser.lexer.nextToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparser.currToken = token\n\n\treturn currToken, nil\n}", "func (r *RedisDL) GetToken() string {\n\treturn r.currentToken\n}", "func (o RegistryTaskSourceTriggerAuthenticationPtrOutput) Token() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *RegistryTaskSourceTriggerAuthentication) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Token\n\t}).(pulumi.StringPtrOutput)\n}", "func (p *Session) Token() (token []byte) {\n\ttoken, _ = p.socket.Token()\n\treturn\n}", "func (n *noop) Token(opts ...TokenOption) (*Token, error) {\n\treturn &Token{}, nil\n}", "func (a *ActionNode) GetToken() *token.Token {\n\treturn a.Token\n}", "func (conf *OnboardingConfig) Token() (string, error) {\n\ttoken, err := utils.TryReadValueAsFile(conf.TokenValue)\n\tif err != nil {\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\n\treturn token, nil\n}", "func debugToken(tok *Token) {\n libgogo.PrintString(\"---------------------\\n\");\n libgogo.PrintString(\"Token Id: \");\n libgogo.PrintNumber(tok.id);\n libgogo.PrintString(\"\\n\");\n if (tok.id == TOKEN_IDENTIFIER) || (tok.id == TOKEN_STRING) {\n libgogo.PrintString(\"Stored string: \");\n libgogo.PrintString(tok.strValue);\n libgogo.PrintString(\"\\n\");\n }\n if tok.id == TOKEN_INTEGER {\n libgogo.PrintString(\"Stored integer: \");\n libgogo.PrintNumber(tok.intValue);\n libgogo.PrintString(\"\\n\");\n }\n}", "func (_Token *TokenCallerSession) Token() (common.Address, error) {\n\treturn _Token.Contract.Token(&_Token.CallOpts)\n}", "func (cfg Config) GetToken() (token string) {\n\treturn cfg.Token\n}", "func (r *Tokens) Token() (xml.Token, error) {\n\tif len(*r) == 0 {\n\t\treturn nil, io.EOF\n\t}\n\n\tvar t xml.Token\n\tt, *r = (*r)[0], (*r)[1:]\n\treturn t, nil\n}", "func (s *lexStream) nextToken(delim *charGroup) string {\r\n\tret := s.nextUntil(delim)\r\n\tif len(ret) == 0 {\r\n\t\tret = string(s.next())\r\n\t}\r\n\treturn ret\r\n}", "func (p *Parser) curTokenIs(t token.TokenType) bool {\n\treturn p.curToken.Type == t\n}", "func (src *tokenProvider) token() (string, error) {\n\ttoken, err := src.tokenSource.Token()\n\tif err != nil {\n\t\treturn \"\", errors.New(\"fcm: failed to generate Bearer token\")\n\t}\n\treturn token.AccessToken, nil\n}", "func (p *Parser) curTokenIs(t lexer.TokenType) bool {\n\treturn p.curToken.Type == t\n}", "func (lex *Lexer) NextToken() Token {\n\tfor {\n\t\tselect {\n\t\tcase item := <-lex.tokens:\n\t\t\treturn item\n\t\tdefault:\n\t\t\tlex.state = lex.state(lex)\n\t\t}\n\t}\n\tpanic(\"not reached\")\n}", "func (c *instance) Token(call TokenCall) error {\n\to := bind.NewKeyedTransactor(c.key)\n\n\t// gateway redirect to private chain\n\tclient, err := ethclient.Dial(config.ETHAddr())\n\tif err != nil {\n\t\treturn err\n\t}\n\tinstance, err := token.NewDhToken(c.tokenAddr, client)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn call(instance, o)\n}", "func (l *Lexer) NextToken() *Token {\n\treturn <-l.tokens\n}", "func (s *scanner) nextToken() tokenRef {\n\titem := <-s.items\n\ts.lastPos = item.pos\n\treturn item\n}", "func (_Token *TokenSession) Token() (common.Address, error) {\n\treturn _Token.Contract.Token(&_Token.CallOpts)\n}", "func (m *VppToken) SetToken(value *string)() {\n m.token = value\n}", "func (p *parser) next() token {\n\tvar tok token\n\tif p.lookAheadTok != nil {\n\t\ttok = *p.lookAheadTok\n\t\tp.lookAheadTok = nil\n\t} else {\n\t\ttok = p.lex.nextToken()\n\t}\n\treturn tok\n}", "func (c *Conn) Token() string {\n\ta := c.headers.Get(\"Authorization\")\n\tif len(a) < 7 {\n\t\treturn \"\"\n\t}\n\treturn a[7:]\n}", "func (fts ErroringTokenSource) Token() (*oauth2.Token, error) {\n\treturn nil, errors.New(\"intentional error\")\n}", "func (_Token *TokenCaller) Token(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _Token.contract.Call(opts, out, \"token\")\n\treturn *ret0, err\n}", "func (p *Parser) classifyToken(token *lexer.Token, hint *grammar.ParserHint) int {\n\t//util.DumpObject(hint, \"classifyToken(): hint = \")\n\t// No need to classify if we already have\n\tif token.Type != tokens.TOKEN_NULL {\n\t\t//fmt.Printf(\"classifyToken(): returning existing token type\\n\")\n\t\treturn token.Type\n\t}\n\tif p.stack.Cur().allowNextWordReserved {\n\t\tp.stack.Cur().allowNextWordReserved = false\n\t\tfor _, rule := range rules.ReservedRules {\n\t\t\t// TODO: check for:\n\t\t\t// * previous tokens match AfterTokens (-1 is wildcard), for in/do after case/for\n\t\t\tif token.Value == rule.Pattern {\n\t\t\t\treturn rule.TokenType\n\t\t\t}\n\t\t}\n\t}\n\tNAME_RE := regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]+$`)\n\tASSIGNMENT_RE := regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]+=`)\n\tfor _, hintTokenType := range hint.TokenTypes {\n\t\tswitch hintTokenType {\n\t\tcase tokens.TOKEN_NAME:\n\t\t\tif NAME_RE.MatchString(token.Value) {\n\t\t\t\treturn tokens.TOKEN_NAME\n\t\t\t}\n\t\tcase tokens.TOKEN_ASSIGNMENT_WORD:\n\t\t\t//fmt.Printf(\"classifyToken(): checking '%s' for ASSIGNMENT_WORD\\n\", token.Value)\n\t\t\tif ASSIGNMENT_RE.MatchString(token.Value) {\n\t\t\t\treturn tokens.TOKEN_ASSIGNMENT_WORD\n\t\t\t}\n\t\t}\n\t}\n\t// Fallback to generic WORD token type\n\treturn tokens.TOKEN_WORD\n}", "func Token() (string, error) {\n\treturn generate(32)\n}", "func GetNextToken() {\n var cmpValue uint64;\n GetNextTokenRaw();\n\n // Convert identifier to keyworded tokens\n if tok.id == TOKEN_IDENTIFIER {\n cmpValue = libgogo.StringCompare(\"if\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_IF;\n }\n cmpValue = libgogo.StringCompare(\"else\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_ELSE;\n }\n cmpValue = libgogo.StringCompare(\"for\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_FOR;\n }\n cmpValue = libgogo.StringCompare(\"type\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_TYPE;\n }\n cmpValue = libgogo.StringCompare(\"const\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_CONST;\n }\n cmpValue = libgogo.StringCompare(\"var\",tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_VAR;\n }\n cmpValue = libgogo.StringCompare(\"struct\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_STRUCT;\n }\n cmpValue = libgogo.StringCompare(\"return\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_RETURN;\n }\n cmpValue = libgogo.StringCompare(\"func\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_FUNC;\n }\n cmpValue = libgogo.StringCompare(\"import\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_IMPORT;\n }\n cmpValue = libgogo.StringCompare(\"package\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_PACKAGE;\n }\n cmpValue = libgogo.StringCompare(\"break\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_BREAK;\n }\n cmpValue = libgogo.StringCompare(\"continue\", tok.strValue);\n if cmpValue == 0 {\n tok.id = TOKEN_CONTINUE;\n }\n }\n\n tok.nextToken = 0;\n}", "func (t *tokenSource) Token() (*oauth2.Token, error) {\n\treturn t.token, nil\n}", "func (t *tokenSource) Token() (*oauth2.Token, error) {\n\treturn t.token, nil\n}", "func (s *Scanner) next() *Token {\n\tfor {\n\t\tr := s.read()\n\t\tswitch {\n\t\tcase r == '@':\n\t\t\treturn mkToken(tokAt, \"@\")\n\t\tcase isSpace(r):\n\t\tcase isIdentifierStart(r):\n\t\t\treturn s.alphanum(tokIdentifier, r)\n\t\tcase isDigit(r):\n\t\t\treturn s.number(r)\n\t\tcase isPunctuator(r):\n\t\t\treturn s.punctuator(r)\n\t\t}\n\t}\n}", "func GetToken(c *gin.Context) {\n\tcode = c.Query(\"code\")\n\t//fmt.Println(\"code: \" + code)\n\tTokenRequest(code, c)\n}", "func (r *RotatingTokens) GetToken() (string, error) {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tif r.lastAccessed >= len(r.keys) {\n\t\tr.lastAccessed = 0\n\t}\n\tif len(r.keys) == 0 {\n\t\treturn \"\", fmt.Errorf(\"no tokens\")\n\t}\n\tkey := r.keys[r.lastAccessed]\n\tr.lastAccessed++\n\treturn key, nil\n}", "func (l *Lexer) NextToken() token.Token {\n\tvar tok token.Token\n\n\tl.skipWhitespace()\n\ttok.LineNo = l.lineNo\n\ttok.CharNo = l.charNo\n\n\tswitch l.ch {\n\n\tcase ';':\n\t\ttok = newToken(token.SEMICOLON, l.ch, l.charNo, l.lineNo)\n\tcase '.':\n\t\ttok = newToken(token.DOT, l.ch, l.charNo, l.lineNo)\n\tcase '(':\n\t\ttok = newToken(token.LPAREN, l.ch, l.charNo, l.lineNo)\n\tcase ')':\n\t\ttok = newToken(token.RPAREN, l.ch, l.charNo, l.lineNo)\n\tcase ',':\n\t\ttok = newToken(token.COMMA, l.ch, l.charNo, l.lineNo)\n\tcase '+':\n\t\ttok = newToken(token.PLUS, l.ch, l.charNo, l.lineNo)\n\tcase '{':\n\t\ttok = newToken(token.LBRACE, l.ch, l.charNo, l.lineNo)\n\tcase '}':\n\t\ttok = newToken(token.RBRACE, l.ch, l.charNo, l.lineNo)\n\tcase '-':\n\t\ttok = newToken(token.MINUS, l.ch, l.charNo, l.lineNo)\n\n\tcase '*':\n\t\ttok = newToken(token.ASTERISK, l.ch, l.charNo, l.lineNo)\n\tcase '/':\n\t\ttok = newToken(token.SLASH, l.ch, l.charNo, l.lineNo)\n\tcase '=':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.EQ, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.ASSIGN, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '!':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.NOT_EQ, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.BANG, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '<':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.LTE, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.LT, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '>':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.GTE, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.GT, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '\"':\n\t\ttok.Type = token.STRING\n\t\ttok.Literal = l.readString()\n\tcase ':':\n\t\ttok = newToken(token.COLON, l.ch, l.charNo, l.lineNo)\n\tcase '[':\n\t\ttok = newToken(token.LBRACKET, l.ch, l.charNo, l.lineNo)\n\tcase ']':\n\t\ttok = newToken(token.RBRACKET, l.ch, l.charNo, l.lineNo)\n\tcase 0:\n\t\ttok.Literal = \"\"\n\t\ttok.Type = token.EOF\n\tdefault:\n\t\tif isLetter(l.ch) {\n\t\t\ttok.Literal = l.readIdentifier()\n\t\t\ttok.Type = token.LookupIdent(tok.Literal)\n\t\t\treturn tok\n\t\t} else if isDigit(l.ch) {\n\t\t\ttok.Type, tok.Literal = l.readNumber()\n\t\t\treturn tok\n\t\t} else {\n\t\t\ttok = newToken(token.ILLEGAL, l.ch, l.charNo, l.lineNo)\n\t\t}\n\t}\n\tl.readChar()\n\treturn tok\n}", "func (tok *Tokenizer) RequestToken(user string) bool {\n\ttok.lock.Lock();\n\tdefer tok.lock.Unlock();\n\tif(tok.availableTokens > 0) {\n\t\tfmt.Println(\"Assigning a token for user : \" + user);\n\t\ttok.availableTokens--;\n\t\ttok.currentUsers[user] = true;\n\t\treturn true;\n\t} \n\tfmt.Println(\"No available tokens! Denying request for user \" + user);\n\treturn false;\n}", "func (c *Client) Token() string {\n\tc.modifyLock.RLock()\n\tdefer c.modifyLock.RUnlock()\n\treturn c.token\n}", "func (l *lexer) nextToken() token {\n\tvar tok token\n\n\tl.skipWhitespace()\n\n\tswitch l.ch {\n\tcase ',':\n\t\ttok = newToken(tokComma, l.ch)\n\tcase ':':\n\t\ttok = newToken(tokColon, l.ch)\n\tcase '{':\n\t\ttok = newToken(tokLBrace, l.ch)\n\tcase '}':\n\t\ttok = newToken(tokRBrace, l.ch)\n\tcase '[':\n\t\ttok = newToken(tokLBracket, l.ch)\n\tcase ']':\n\t\ttok = newToken(tokRBracket, l.ch)\n\tcase '\"':\n\t\ttok.Type = tokString\n\t\ttok.Literal = l.readString()\n\tcase '-':\n\t\ttok = newToken(tokMinus, l.ch)\n\tcase eof:\n\t\ttok.Literal = \"\"\n\t\ttok.Type = tokEOF\n\tdefault:\n\t\tif isLetter(l.ch) {\n\t\t\ttok.Literal = l.readKeyword()\n\t\t\ttok.Type = lookupKeyword(tok.Literal)\n\t\t\treturn tok\n\t\t} else if isDigit(l.ch) {\n\t\t\ttok.Literal = l.readNumber()\n\t\t\tif strings.Contains(tok.Literal, \".\") {\n\t\t\t\ttok.Type = tokFloat\n\t\t\t} else {\n\t\t\t\ttok.Type = tokInt\n\t\t\t}\n\t\t\treturn tok\n\t\t} else {\n\t\t\ttok = newToken(tokIllegal, l.ch)\n\t\t}\n\t}\n\n\tl.readChar()\n\n\treturn tok\n}", "func (t *tokenReplacer) Token() (tok *oauth2.Token, err error) {\n\tdefer func() {\n\t\t// If the AccessToken field changes, cache the new token.\n\t\tif tok != nil && (t.lastTok == nil || tok.AccessToken != t.lastTok.AccessToken) {\n\t\t\tif err := writeToken(tok); err != nil {\n\t\t\t\tlog.Printf(\"cannot cache authentication: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\ttok, err = t.ts.Token()\n\tif err == nil {\n\t\treturn\n\t}\n\ttok, err = t.tsr.Token()\n\tif err == nil {\n\t\tt.ts = oauthConfig.TokenSource(context.Background(), tok)\n\t}\n\treturn\n}", "func (r ApiIntrospectOAuth2TokenRequest) Token(token string) ApiIntrospectOAuth2TokenRequest {\n\tr.token = &token\n\treturn r\n}", "func (s *HTTPServer) parseToken(req *http.Request, token *string) {\n\ts.parseTokenInternal(req, token, true)\n}", "func Token(g *gin.Context) {\n\tlog.Println(\"token\")\n\tclientIdStr, ok := g.GetQuery(\"client_id\")\n\tif !ok {\n\t\tg.JSON(400, \"error\")\n\t\treturn\n\t}\n\n\tclientId, err := strconv.Atoi(clientIdStr)\n\tif err != nil {\n\t\tg.JSON(400, \"error\")\n\t\treturn\n\t}\n\n\t// 需要验证 secret id\n\t// ...\n\n\tauthCode := g.Query(\"auth\")\n\tif store[clientId].AuthCode != authCode {\n\t\tg.JSON(400, \"error\")\n\t\treturn\n\t}\n\n\ttoken := \"this.\" + authCode + \".test\"\n\n\tg.JSON(200, token)\n}", "func (p *parser) peek() lexer.Token {\n\treturn p.tokens[p.current]\n}", "func SetToken(newtoken string) string {\n\tToken = newtoken\n\treturn Token\n}", "func (s *Slice) Token() token.Type {\n\treturn s.basic.Token()\n}", "func (p GsGameLogonPacket) Token() string {\n\treturn hex.EncodeToString(p[1:7])\n}", "func (_FinalizableCrowdsaleImpl *FinalizableCrowdsaleImplSession) Token() (common.Address, error) {\n\treturn _FinalizableCrowdsaleImpl.Contract.Token(&_FinalizableCrowdsaleImpl.CallOpts)\n}", "func (i *Interpreter) getNextToken() scanResult {\n\n\tvar r scanResult\n\n\tif i.Err != nil {\n\t\tr.err = i.Err\n\t\tr.t = errorT\n\t\treturn r\n\t}\n\n\tif !i.scanner.Scan() {\n\t\t// EOF\n\t\ti.Err = io.EOF\n\t\tr.err = i.Err\n\t\tr.t = errorT\n\t\treturn r\n\t}\n\n\tr.token = i.scanner.Text()\n\n\t// slurp comments if needed\n\tif r.token == \"(\" {\n\t\tfor r.token[len(r.token)-1:] != \")\" {\n\t\t\tif !i.scanner.Scan() {\n\t\t\t\tr.err = fmt.Errorf(\"unexpected unclosed comment : %s\", r.token)\n\t\t\t\tr.t = errorT\n\t\t\t\treturn r\n\t\t\t}\n\t\t\tr.token = i.scanner.Text()\n\t\t}\n\t\t// then tail-recurse,\n\t\t// you can have multiple successive comments ...\n\t\treturn i.getNextToken()\n\t}\n\n\t// try to decode token\n\tnfa := i.lookup(r.token)\n\tif i.Err == nil {\n\t\tr.v = 1 + nfa\n\t\tr.t = compoundT\n\t\tr.err = nil\n\t\treturn r\n\t}\n\n\t// so, token could not be decoded\n\t// reset error and try numbers ...\n\ti.Err = nil\n\tif num, err := strconv.ParseInt(r.token, i.getBase(), 64); err == nil {\n\t\tr.v = int(num)\n\t\tr.t = numberT\n\t\tr.err = nil\n\t\treturn r\n\t}\n\n\t// Token cannot be understood\n\tr.t = errorT\n\tr.err = fmt.Errorf(\"cannot understand the token : %s\", r.token)\n\treturn r\n\n}", "func (_FinalizableCrowdsaleImpl *FinalizableCrowdsaleImplCallerSession) Token() (common.Address, error) {\n\treturn _FinalizableCrowdsaleImpl.Contract.Token(&_FinalizableCrowdsaleImpl.CallOpts)\n}", "func (s *Scanner) TokenText() string {\n\treturn string(s.src[s.Position.Offset:s.srcPos.Offset])\n}", "func (t *Tokenizer) NextToken() (*Token, error) {\n\treturn t.scanStream()\n}", "func (z *Tokenizer) Next() Token {\n\tz.Scan()\n\treturn z.tok\n}", "func (mt *mockTokenBuilder) Token() zmssvctoken.Token {\n\tt := &mockToken{}\n\tt.valueFunc = mt.valueFunc\n\treturn t\n}", "func parseToken(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tevent := ssas.Event{Op: \"ParseToken\"}\n\t\tauthHeader := r.Header.Get(\"Authorization\")\n\t\tif authHeader == \"\" {\n\t\t\tevent.Help = \"no authorization header found\"\n\t\t\tssas.AuthorizationFailure(event)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tauthRegexp := regexp.MustCompile(`^Bearer (\\S+)$`)\n\t\tauthSubmatches := authRegexp.FindStringSubmatch(authHeader)\n\t\tif len(authSubmatches) < 2 {\n\t\t\tevent.Help = \"invalid Authorization header value\"\n\t\t\tssas.AuthorizationFailure(event)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\ttokenString := authSubmatches[1]\n\t\ttoken, err := server.VerifyToken(tokenString)\n\t\tif err != nil {\n\t\t\tevent.Help = fmt.Sprintf(\"unable to decode authorization header value; %s\", err)\n\t\t\tssas.AuthorizationFailure(event)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tvar rd ssas.AuthRegData\n\t\tif rd, err = readRegData(r); err != nil {\n\t\t\trd = ssas.AuthRegData{}\n\t\t}\n\n\t\tif claims, ok := token.Claims.(*service.CommonClaims); ok && token.Valid {\n\t\t\trd.AllowedGroupIDs = claims.GroupIDs\n\t\t\trd.OktaID = claims.OktaID\n\t\t}\n\t\tctx := context.WithValue(r.Context(), \"ts\", tokenString)\n\t\tctx = context.WithValue(ctx, \"rd\", rd)\n\t\tservice.LogEntrySetField(r, \"rd\", rd)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}", "func (c *Client) Token() string {\n\treturn c.token\n}", "func (tokenValidator *tokenValidator) validToken(tokenManager tokenManager, token string) (bool, error) {\n\tcorrectToken, err := tokenManager.getToken()\n\tif err != nil {\n\t\tklog.Error(err)\n\t\treturn false, err\n\t}\n\n\treturn token == correctToken, nil\n}" ]
[ "0.71517646", "0.69445807", "0.69423914", "0.69060665", "0.6875628", "0.68362564", "0.6813639", "0.6795291", "0.6773583", "0.67608863", "0.67586327", "0.671923", "0.6635157", "0.6618294", "0.66162235", "0.66162235", "0.66159034", "0.66046107", "0.65750414", "0.6566827", "0.6553702", "0.65471226", "0.6512225", "0.6504776", "0.65032816", "0.6500665", "0.64882416", "0.6474835", "0.64525044", "0.6439815", "0.6432283", "0.64239526", "0.6422822", "0.64012", "0.64012", "0.63986033", "0.6397599", "0.63726723", "0.6367822", "0.6358807", "0.6356489", "0.63480747", "0.63371825", "0.63283527", "0.63189816", "0.62976027", "0.6279494", "0.62681127", "0.6267933", "0.62528324", "0.6246726", "0.6245512", "0.6239277", "0.6235216", "0.62323284", "0.62291735", "0.6224877", "0.62082946", "0.61986405", "0.61926514", "0.61729074", "0.61664563", "0.6128475", "0.612787", "0.6127234", "0.61141443", "0.6094002", "0.60918635", "0.60839367", "0.6081894", "0.60763437", "0.60681695", "0.6065999", "0.60640705", "0.60640705", "0.6058789", "0.6057647", "0.6054643", "0.60406595", "0.60360295", "0.6034838", "0.60313165", "0.60207105", "0.6019665", "0.6018709", "0.6015633", "0.6010407", "0.60068446", "0.5999428", "0.5994994", "0.59931517", "0.59906614", "0.598593", "0.59831893", "0.5979759", "0.5974802", "0.597143", "0.59662795", "0.59586143", "0.59554523" ]
0.6990417
1
XXX_OneofFuncs is for the internal use of the proto package.
func (*WriteReq) 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{}) { return _WriteReq_OneofMarshaler, _WriteReq_OneofUnmarshaler, _WriteReq_OneofSizer, []interface{}{ (*WriteReq_Name)(nil), (*WriteReq_Blob)(nil), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*EncapVal) 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 _EncapVal_OneofMarshaler, _EncapVal_OneofUnmarshaler, _EncapVal_OneofSizer, []interface{}{\n\t\t(*EncapVal_VlanId)(nil),\n\t\t(*EncapVal_MPLSTag)(nil),\n\t\t(*EncapVal_Vnid)(nil),\n\t\t(*EncapVal_QinQ)(nil),\n\t}\n}", "func (*FlowL4Info) 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 _FlowL4Info_OneofMarshaler, _FlowL4Info_OneofUnmarshaler, _FlowL4Info_OneofSizer, []interface{}{\n\t\t(*FlowL4Info_TcpUdpInfo)(nil),\n\t\t(*FlowL4Info_IcmpInfo)(nil),\n\t}\n}", "func (*Msg) 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 _Msg_OneofMarshaler, _Msg_OneofUnmarshaler, _Msg_OneofSizer, []interface{}{\n\t\t(*Msg_Request)(nil),\n\t\t(*Msg_Preprepare)(nil),\n\t\t(*Msg_Prepare)(nil),\n\t\t(*Msg_Commit)(nil),\n\t\t(*Msg_ViewChange)(nil),\n\t\t(*Msg_NewView)(nil),\n\t\t(*Msg_Checkpoint)(nil),\n\t\t(*Msg_Hello)(nil),\n\t}\n}", "func (*RuleL4Match) 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 _RuleL4Match_OneofMarshaler, _RuleL4Match_OneofUnmarshaler, _RuleL4Match_OneofSizer, []interface{}{\n\t\t(*RuleL4Match_Ports)(nil),\n\t\t(*RuleL4Match_TypeCode)(nil),\n\t}\n}", "func (*Example) 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 _Example_OneofMarshaler, _Example_OneofUnmarshaler, _Example_OneofSizer, []interface{}{\n\t\t(*Example_ImagePayload)(nil),\n\t\t(*Example_TextPayload)(nil),\n\t\t(*Example_VideoPayload)(nil),\n\t\t(*Example_AudioPayload)(nil),\n\t}\n}", "func (*Metric) 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 _Metric_OneofMarshaler, _Metric_OneofUnmarshaler, _Metric_OneofSizer, []interface{}{\n\t\t(*Metric_StringData)(nil),\n\t\t(*Metric_Float32Data)(nil),\n\t\t(*Metric_Float64Data)(nil),\n\t\t(*Metric_Int32Data)(nil),\n\t\t(*Metric_Int64Data)(nil),\n\t\t(*Metric_BytesData)(nil),\n\t\t(*Metric_BoolData)(nil),\n\t\t(*Metric_Uint32Data)(nil),\n\t\t(*Metric_Uint64Data)(nil),\n\t}\n}", "func (*Interface) 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 _Interface_OneofMarshaler, _Interface_OneofUnmarshaler, _Interface_OneofSizer, []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}\n}", "func (*Metadata) 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 _Metadata_OneofMarshaler, _Metadata_OneofUnmarshaler, _Metadata_OneofSizer, []interface{}{\n\t\t(*Metadata_DevAddrPrefix)(nil),\n\t\t(*Metadata_AppId)(nil),\n\t\t(*Metadata_AppEui)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []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 (*Message) 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 _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Chunk)(nil),\n\t\t(*Message_Status)(nil),\n\t}\n}", "func (*Message) 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 _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_OpenPayload)(nil),\n\t\t(*Message_ClosePayload)(nil),\n\t\t(*Message_DataPayload)(nil),\n\t}\n}", "func (*BMRPCRequest) 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 _BMRPCRequest_OneofMarshaler, _BMRPCRequest_OneofUnmarshaler, _BMRPCRequest_OneofSizer, []interface{}{\n\t\t(*BMRPCRequest_Newaddress)(nil),\n\t\t(*BMRPCRequest_Help)(nil),\n\t\t(*BMRPCRequest_Listaddresses)(nil),\n\t}\n}", "func (*Interface) 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 _Interface_OneofMarshaler, _Interface_OneofUnmarshaler, _Interface_OneofSizer, []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}\n}", "func (*OpenStatusUpdate) 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 _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) 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 _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) 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 _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*StatTable) 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 _StatTable_OneofMarshaler, _StatTable_OneofUnmarshaler, _StatTable_OneofSizer, []interface{}{\n\t\t(*StatTable_PodGroup_)(nil),\n\t}\n}", "func (*Bitmessage) 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 _Bitmessage_OneofMarshaler, _Bitmessage_OneofUnmarshaler, _Bitmessage_OneofSizer, []interface{}{\n\t\t(*Bitmessage_Text)(nil),\n\t}\n}", "func (*RunnerMsg) 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 _RunnerMsg_OneofMarshaler, _RunnerMsg_OneofUnmarshaler, _RunnerMsg_OneofSizer, []interface{}{\n\t\t(*RunnerMsg_Acknowledged)(nil),\n\t\t(*RunnerMsg_ResultStart)(nil),\n\t\t(*RunnerMsg_Data)(nil),\n\t\t(*RunnerMsg_Finished)(nil),\n\t}\n}", "func (*DiscoveryInfo) 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 _DiscoveryInfo_OneofMarshaler, _DiscoveryInfo_OneofUnmarshaler, _DiscoveryInfo_OneofSizer, []interface{}{\n\t\t(*DiscoveryInfo_Inflated)(nil),\n\t\t(*DiscoveryInfo_BlobAdded)(nil),\n\t\t(*DiscoveryInfo_BlobRemoved)(nil),\n\t}\n}", "func (*Event) 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 _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Read_)(nil),\n\t\t(*Event_Write_)(nil),\n\t}\n}", "func (*OpenStatusUpdate) 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 _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) 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 _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) 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 _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) 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 _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*TwoOneofs) 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 _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []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_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 _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []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_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 _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []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_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 _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []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_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 _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []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_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 _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []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 (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Signin)(nil),\n\t\t(*Message_Chatmsg)(nil),\n\t}\n}", "func (*LoggingPayloadData) 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 _LoggingPayloadData_OneofMarshaler, _LoggingPayloadData_OneofUnmarshaler, _LoggingPayloadData_OneofSizer, []interface{}{\n\t\t(*LoggingPayloadData_Msg)(nil),\n\t\t(*LoggingPayloadData_Raw)(nil),\n\t}\n}", "func (*EvalRequest) 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 _EvalRequest_OneofMarshaler, _EvalRequest_OneofUnmarshaler, _EvalRequest_OneofSizer, []interface{}{\n\t\t(*EvalRequest_ParsedExpr)(nil),\n\t\t(*EvalRequest_CheckedExpr)(nil),\n\t}\n}", "func (*Header) 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 _Header_OneofMarshaler, _Header_OneofUnmarshaler, _Header_OneofSizer, []interface{}{\n\t\t(*Header_Version)(nil),\n\t\t(*Header_SourceType)(nil),\n\t\t(*Header_EventType)(nil),\n\t}\n}", "func (*ReadModifyWriteRule) 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 _ReadModifyWriteRule_OneofMarshaler, _ReadModifyWriteRule_OneofUnmarshaler, _ReadModifyWriteRule_OneofSizer, []interface{}{\n\t\t(*ReadModifyWriteRule_AppendValue)(nil),\n\t\t(*ReadModifyWriteRule_IncrementAmount)(nil),\n\t}\n}", "func (*BitmessageRPC) 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 _BitmessageRPC_OneofMarshaler, _BitmessageRPC_OneofUnmarshaler, _BitmessageRPC_OneofSizer, []interface{}{\n\t\t(*BitmessageRPC_Request)(nil),\n\t\t(*BitmessageRPC_Reply)(nil),\n\t\t(*BitmessageRPC_Push)(nil),\n\t}\n}", "func (*SetConfigRequest_Entry) 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 _SetConfigRequest_Entry_OneofMarshaler, _SetConfigRequest_Entry_OneofUnmarshaler, _SetConfigRequest_Entry_OneofSizer, []interface{}{\n\t\t(*SetConfigRequest_Entry_ValueStr)(nil),\n\t\t(*SetConfigRequest_Entry_ValueInt32)(nil),\n\t\t(*SetConfigRequest_Entry_ValueBool)(nil),\n\t}\n}", "func (*HealthCheck_Payload) 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 _HealthCheck_Payload_OneofMarshaler, _HealthCheck_Payload_OneofUnmarshaler, _HealthCheck_Payload_OneofSizer, []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*FlowKey) 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 _FlowKey_OneofMarshaler, _FlowKey_OneofUnmarshaler, _FlowKey_OneofSizer, []interface{}{\n\t\t(*FlowKey_IPFlowKey)(nil),\n\t\t(*FlowKey_MACFlowKey)(nil),\n\t}\n}", "func (*LeafStat) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _LeafStat_OneofMarshaler, _LeafStat_OneofUnmarshaler, _LeafStat_OneofSizer, []interface{}{\n\t\t(*LeafStat_Classification)(nil),\n\t\t(*LeafStat_Regression)(nil),\n\t}\n}", "func (*Metadata) 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 _Metadata_OneofMarshaler, _Metadata_OneofUnmarshaler, _Metadata_OneofSizer, []interface{}{\n\t\t(*Metadata_GatewayID)(nil),\n\t\t(*Metadata_DevAddrPrefix)(nil),\n\t\t(*Metadata_AppID)(nil),\n\t\t(*Metadata_AppEUI)(nil),\n\t}\n}", "func (*BitcoinRules) 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 _BitcoinRules_OneofMarshaler, _BitcoinRules_OneofUnmarshaler, _BitcoinRules_OneofSizer, []interface{}{\n\t\t(*BitcoinRules_Address)(nil),\n\t\t(*BitcoinRules_String_)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) 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 _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) 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 _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) 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 _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) 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 _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*TriggerMessage) 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 _TriggerMessage_OneofMarshaler, _TriggerMessage_OneofUnmarshaler, _TriggerMessage_OneofSizer, []interface{}{\n\t\t(*TriggerMessage_Topic)(nil),\n\t\t(*TriggerMessage_Type)(nil),\n\t\t(*TriggerMessage_Event)(nil),\n\t\t(*TriggerMessage_BodyBytes)(nil),\n\t\t(*TriggerMessage_Offset)(nil),\n\t\t(*TriggerMessage_Extensions)(nil),\n\t\t(*TriggerMessage_Uuid)(nil),\n\t\t(*TriggerMessage_Bid)(nil),\n\t}\n}", "func (*Params) 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 _Params_OneofMarshaler, _Params_OneofUnmarshaler, _Params_OneofSizer, []interface{}{\n\t\t(*Params_AppCredentials)(nil),\n\t\t(*Params_ApiKey)(nil),\n\t\t(*Params_ServiceAccountPath)(nil),\n\t}\n}", "func (*Component) 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 _Component_OneofMarshaler, _Component_OneofUnmarshaler, _Component_OneofSizer, []interface{}{\n\t\t(*Component_AppengineModule)(nil),\n\t\t(*Component_GkePod)(nil),\n\t}\n}", "func (*Event) 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 _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Register)(nil),\n\t\t(*Event_Block)(nil),\n\t\t(*Event_ChaincodeEvent)(nil),\n\t\t(*Event_Rejection)(nil),\n\t\t(*Event_Unregister)(nil),\n\t}\n}", "func (*Event) 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 _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Register)(nil),\n\t\t(*Event_Block)(nil),\n\t\t(*Event_ChaincodeEvent)(nil),\n\t\t(*Event_Rejection)(nil),\n\t\t(*Event_Unregister)(nil),\n\t}\n}", "func (*StateKey) 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 _StateKey_OneofMarshaler, _StateKey_OneofUnmarshaler, _StateKey_OneofSizer, []interface{}{\n\t\t(*StateKey_Runner_)(nil),\n\t\t(*StateKey_MultimapSideInput_)(nil),\n\t\t(*StateKey_BagUserState_)(nil),\n\t}\n}", "func (*StateKey) 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 _StateKey_OneofMarshaler, _StateKey_OneofUnmarshaler, _StateKey_OneofSizer, []interface{}{\n\t\t(*StateKey_Runner_)(nil),\n\t\t(*StateKey_MultimapSideInput_)(nil),\n\t\t(*StateKey_BagUserState_)(nil),\n\t}\n}", "func (*InternalRequest) 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 _InternalRequest_OneofMarshaler, _InternalRequest_OneofUnmarshaler, _InternalRequest_OneofSizer, []interface{}{\n\t\t(*InternalRequest_PutReq)(nil),\n\t\t(*InternalRequest_GetReq)(nil),\n\t\t(*InternalRequest_DeleteReq)(nil),\n\t}\n}", "func (*Message) 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 _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Transfer)(nil),\n\t\t(*Message_Account)(nil),\n\t}\n}", "func (*VideoAdInfo) 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 _VideoAdInfo_OneofMarshaler, _VideoAdInfo_OneofUnmarshaler, _VideoAdInfo_OneofSizer, []interface{}{\n\t\t(*VideoAdInfo_InStream)(nil),\n\t}\n}", "func (*TapEvent) 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 _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*TapEvent) 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 _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*TapEvent) 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 _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*UploadBinaryRequest) 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 _UploadBinaryRequest_OneofMarshaler, _UploadBinaryRequest_OneofUnmarshaler, _UploadBinaryRequest_OneofSizer, []interface{}{\n\t\t(*UploadBinaryRequest_Key_)(nil),\n\t\t(*UploadBinaryRequest_Chunk_)(nil),\n\t}\n}", "func (*Metric) 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 _Metric_OneofMarshaler, _Metric_OneofUnmarshaler, _Metric_OneofSizer, []interface{}{\n\t\t(*Metric_I64)(nil),\n\t\t(*Metric_U64)(nil),\n\t\t(*Metric_F64)(nil),\n\t\t(*Metric_String_)(nil),\n\t\t(*Metric_Bool)(nil),\n\t\t(*Metric_Duration)(nil),\n\t}\n}", "func (*SendBitmessageRequest) 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 _SendBitmessageRequest_OneofMarshaler, _SendBitmessageRequest_OneofUnmarshaler, _SendBitmessageRequest_OneofSizer, []interface{}{\n\t\t(*SendBitmessageRequest_Text)(nil),\n\t}\n}", "func (*Service) 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 _Service_OneofMarshaler, _Service_OneofUnmarshaler, _Service_OneofSizer, []interface{}{\n\t\t(*Service_DstPort)(nil),\n\t\t(*Service_IcmpMsgType)(nil),\n\t}\n}", "func (*Event) 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 _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Error)(nil),\n\t\t(*Event_Progress)(nil),\n\t\t(*Event_Match)(nil),\n\t\t(*Event_Pagination)(nil),\n\t}\n}", "func (*Config) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Config_OneofMarshaler, _Config_OneofUnmarshaler, _Config_OneofSizer, []interface{}{\n\t\t(*Config_Custom)(nil),\n\t\t(*Config_Random)(nil),\n\t\t(*Config_Fixed)(nil),\n\t}\n}", "func (*FetchRequest) 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 _FetchRequest_OneofMarshaler, _FetchRequest_OneofUnmarshaler, _FetchRequest_OneofSizer, []interface{}{\n\t\t(*FetchRequest_TagMatchers)(nil),\n\t}\n}", "func (*Wrapper) 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 _Wrapper_OneofMarshaler, _Wrapper_OneofUnmarshaler, _Wrapper_OneofSizer, []interface{}{\n\t\t(*Wrapper_Source)(nil),\n\t\t(*Wrapper_GherkinDocument)(nil),\n\t\t(*Wrapper_Pickle)(nil),\n\t\t(*Wrapper_Attachment)(nil),\n\t\t(*Wrapper_TestCaseStarted)(nil),\n\t\t(*Wrapper_TestStepStarted)(nil),\n\t\t(*Wrapper_TestStepFinished)(nil),\n\t\t(*Wrapper_TestCaseFinished)(nil),\n\t\t(*Wrapper_TestHookStarted)(nil),\n\t\t(*Wrapper_TestHookFinished)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Bigint)(nil),\n\t\t(*Message_EcGroupElement)(nil),\n\t\t(*Message_Status)(nil),\n\t\t(*Message_PedersenFirst)(nil),\n\t\t(*Message_PedersenDecommitment)(nil),\n\t\t(*Message_SchnorrProofData)(nil),\n\t\t(*Message_SchnorrProofRandomData)(nil),\n\t\t(*Message_SchnorrEcProofRandomData)(nil),\n\t\t(*Message_PseudonymsysCaCertificate)(nil),\n\t\t(*Message_PseudonymsysNymGenProofRandomData)(nil),\n\t\t(*Message_PseudonymsysIssueProofRandomData)(nil),\n\t\t(*Message_DoubleBigint)(nil),\n\t\t(*Message_PseudonymsysTransferCredentialData)(nil),\n\t\t(*Message_PseudonymsysCaCertificateEc)(nil),\n\t\t(*Message_PseudonymsysNymGenProofRandomDataEc)(nil),\n\t\t(*Message_PseudonymsysIssueProofRandomDataEc)(nil),\n\t\t(*Message_PseudonymsysTransferCredentialDataEc)(nil),\n\t\t(*Message_SessionKey)(nil),\n\t}\n}", "func (*StateRequest) 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 _StateRequest_OneofMarshaler, _StateRequest_OneofUnmarshaler, _StateRequest_OneofSizer, []interface{}{\n\t\t(*StateRequest_Get)(nil),\n\t\t(*StateRequest_Append)(nil),\n\t\t(*StateRequest_Clear)(nil),\n\t}\n}", "func (*StateRequest) 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 _StateRequest_OneofMarshaler, _StateRequest_OneofUnmarshaler, _StateRequest_OneofSizer, []interface{}{\n\t\t(*StateRequest_Get)(nil),\n\t\t(*StateRequest_Append)(nil),\n\t\t(*StateRequest_Clear)(nil),\n\t}\n}", "func (*Event) 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 _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_ResourceHeader)(nil),\n\t\t(*Event_CertAuthority)(nil),\n\t\t(*Event_StaticTokens)(nil),\n\t\t(*Event_ProvisionToken)(nil),\n\t\t(*Event_ClusterName)(nil),\n\t\t(*Event_ClusterConfig)(nil),\n\t\t(*Event_User)(nil),\n\t\t(*Event_Role)(nil),\n\t\t(*Event_Namespace)(nil),\n\t\t(*Event_Server)(nil),\n\t\t(*Event_ReverseTunnel)(nil),\n\t\t(*Event_TunnelConnection)(nil),\n\t\t(*Event_AccessRequest)(nil),\n\t}\n}", "func (*NetworkAddress) 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 _NetworkAddress_OneofMarshaler, _NetworkAddress_OneofUnmarshaler, _NetworkAddress_OneofSizer, []interface{}{\n\t\t(*NetworkAddress_Ipv4Address)(nil),\n\t\t(*NetworkAddress_Ipv6Address)(nil),\n\t\t(*NetworkAddress_LocalAddress)(nil),\n\t}\n}", "func (*NetworkAddress) 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 _NetworkAddress_OneofMarshaler, _NetworkAddress_OneofUnmarshaler, _NetworkAddress_OneofSizer, []interface{}{\n\t\t(*NetworkAddress_Ipv4Address)(nil),\n\t\t(*NetworkAddress_Ipv6Address)(nil),\n\t\t(*NetworkAddress_LocalAddress)(nil),\n\t}\n}", "func (*RPC) 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 _RPC_OneofMarshaler, _RPC_OneofUnmarshaler, _RPC_OneofSizer, []interface{}{\n\t\t(*RPC_Args)(nil),\n\t\t(*RPC_ByteArgs)(nil),\n\t}\n}", "func (*FeeUpdateRequest) 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 _FeeUpdateRequest_OneofMarshaler, _FeeUpdateRequest_OneofUnmarshaler, _FeeUpdateRequest_OneofSizer, []interface{}{\n\t\t(*FeeUpdateRequest_Global)(nil),\n\t\t(*FeeUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*FeeUpdateRequest) 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 _FeeUpdateRequest_OneofMarshaler, _FeeUpdateRequest_OneofUnmarshaler, _FeeUpdateRequest_OneofSizer, []interface{}{\n\t\t(*FeeUpdateRequest_Global)(nil),\n\t\t(*FeeUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*ServiceSpec) 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 _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*ServiceSpec) 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 _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*ServiceSpec) 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 _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*TestUTF8) 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 _TestUTF8_OneofMarshaler, _TestUTF8_OneofUnmarshaler, _TestUTF8_OneofSizer, []interface{}{\n\t\t(*TestUTF8_Field)(nil),\n\t}\n}", "func (*TestUTF8) 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 _TestUTF8_OneofMarshaler, _TestUTF8_OneofUnmarshaler, _TestUTF8_OneofSizer, []interface{}{\n\t\t(*TestUTF8_Field)(nil),\n\t}\n}", "func (*Eos) 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 _Eos_OneofMarshaler, _Eos_OneofUnmarshaler, _Eos_OneofSizer, []interface{}{\n\t\t(*Eos_GrpcStatusCode)(nil),\n\t\t(*Eos_ResetErrorCode)(nil),\n\t}\n}", "func (*Eos) 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 _Eos_OneofMarshaler, _Eos_OneofUnmarshaler, _Eos_OneofSizer, []interface{}{\n\t\t(*Eos_GrpcStatusCode)(nil),\n\t\t(*Eos_ResetErrorCode)(nil),\n\t}\n}", "func (*RecordKey) 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 _RecordKey_OneofMarshaler, _RecordKey_OneofUnmarshaler, _RecordKey_OneofSizer, []interface{}{\n\t\t(*RecordKey_DatastoreKey)(nil),\n\t\t(*RecordKey_BigQueryKey)(nil),\n\t}\n}", "func (*WatchRequest) 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 _WatchRequest_OneofMarshaler, _WatchRequest_OneofUnmarshaler, _WatchRequest_OneofSizer, []interface{}{\n\t\t(*WatchRequest_CreateRequest)(nil),\n\t\t(*WatchRequest_CancelRequest)(nil),\n\t}\n}", "func (*Node) 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 _Node_OneofMarshaler, _Node_OneofUnmarshaler, _Node_OneofSizer, []interface{}{\n\t\t(*Node_Src)(nil),\n\t\t(*Node_Snk)(nil),\n\t\t(*Node_ContentHash)(nil),\n\t}\n}", "func (*FeedMapping) 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 _FeedMapping_OneofMarshaler, _FeedMapping_OneofUnmarshaler, _FeedMapping_OneofSizer, []interface{}{\n\t\t(*FeedMapping_PlaceholderType)(nil),\n\t\t(*FeedMapping_CriterionType)(nil),\n\t}\n}", "func (*Virtual) 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 _Virtual_OneofMarshaler, _Virtual_OneofUnmarshaler, _Virtual_OneofSizer, []interface{}{\n\t\t(*Virtual_Genesis)(nil),\n\t\t(*Virtual_Child)(nil),\n\t\t(*Virtual_Jet)(nil),\n\t\t(*Virtual_IncomingRequest)(nil),\n\t\t(*Virtual_OutgoingRequest)(nil),\n\t\t(*Virtual_Result)(nil),\n\t\t(*Virtual_Type)(nil),\n\t\t(*Virtual_Code)(nil),\n\t\t(*Virtual_Activate)(nil),\n\t\t(*Virtual_Amend)(nil),\n\t\t(*Virtual_Deactivate)(nil),\n\t\t(*Virtual_PendingFilament)(nil),\n\t}\n}", "func (*CloseStatusUpdate) 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 _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) 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 _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) 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 _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) 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 _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) 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 _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) 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 _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) 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 _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*PrintKVRequest) 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 _PrintKVRequest_OneofMarshaler, _PrintKVRequest_OneofUnmarshaler, _PrintKVRequest_OneofSizer, []interface{}{\n\t\t(*PrintKVRequest_ValueString)(nil),\n\t\t(*PrintKVRequest_ValueInt)(nil),\n\t}\n}", "func (*ChannelEventUpdate) 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 _ChannelEventUpdate_OneofMarshaler, _ChannelEventUpdate_OneofUnmarshaler, _ChannelEventUpdate_OneofSizer, []interface{}{\n\t\t(*ChannelEventUpdate_OpenChannel)(nil),\n\t\t(*ChannelEventUpdate_ClosedChannel)(nil),\n\t\t(*ChannelEventUpdate_ActiveChannel)(nil),\n\t\t(*ChannelEventUpdate_InactiveChannel)(nil),\n\t}\n}", "func (*ChannelEventUpdate) 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 _ChannelEventUpdate_OneofMarshaler, _ChannelEventUpdate_OneofUnmarshaler, _ChannelEventUpdate_OneofSizer, []interface{}{\n\t\t(*ChannelEventUpdate_OpenChannel)(nil),\n\t\t(*ChannelEventUpdate_ClosedChannel)(nil),\n\t\t(*ChannelEventUpdate_ActiveChannel)(nil),\n\t\t(*ChannelEventUpdate_InactiveChannel)(nil),\n\t}\n}", "func (*ChannelEventUpdate) 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 _ChannelEventUpdate_OneofMarshaler, _ChannelEventUpdate_OneofUnmarshaler, _ChannelEventUpdate_OneofSizer, []interface{}{\n\t\t(*ChannelEventUpdate_OpenChannel)(nil),\n\t\t(*ChannelEventUpdate_ClosedChannel)(nil),\n\t\t(*ChannelEventUpdate_ActiveChannel)(nil),\n\t\t(*ChannelEventUpdate_InactiveChannel)(nil),\n\t}\n}" ]
[ "0.8907106", "0.890579", "0.8891233", "0.88697135", "0.8868073", "0.8863467", "0.8863115", "0.8862988", "0.886209", "0.8861827", "0.8859999", "0.88558704", "0.88540995", "0.88527775", "0.88527775", "0.88527775", "0.88480514", "0.8847366", "0.8844595", "0.8841944", "0.8837193", "0.88370156", "0.88370156", "0.88370156", "0.88370156", "0.8835452", "0.8835452", "0.8835452", "0.8835452", "0.8835452", "0.8835452", "0.88341135", "0.88305503", "0.8830491", "0.8830415", "0.8830316", "0.8829064", "0.88287365", "0.8827809", "0.8824382", "0.8824265", "0.8823733", "0.88221323", "0.88188404", "0.88188404", "0.88188404", "0.88188404", "0.8814617", "0.8813053", "0.8811626", "0.88105947", "0.88105947", "0.880831", "0.880831", "0.88082665", "0.8808227", "0.8805944", "0.8805914", "0.8805914", "0.8805914", "0.88056016", "0.88042617", "0.88038075", "0.88034934", "0.88032365", "0.8802399", "0.880174", "0.87993646", "0.8799361", "0.87975067", "0.87975067", "0.8795369", "0.8795032", "0.8795032", "0.8792591", "0.8791414", "0.8791414", "0.8791351", "0.8791351", "0.8791351", "0.87900233", "0.87900233", "0.8788791", "0.8788791", "0.8788189", "0.8787607", "0.87870103", "0.8787005", "0.8786366", "0.87856686", "0.87856686", "0.87856686", "0.87856686", "0.8785405", "0.8785405", "0.8785405", "0.8784138", "0.87823385", "0.87823385", "0.87823385" ]
0.88448733
18
NewAzureAccountsClient creates an instance of the AzureAccountsClient client.
func NewAzureAccountsClient(endpoint string) AzureAccountsClient { return AzureAccountsClient{New(endpoint)} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewAccountsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AccountsClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".AccountsClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &AccountsClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func NewAccountsClient(ctx context.Context, log *logrus.Entry, subscriptionID string, authorizer autorest.Authorizer) AccountsClient {\n\tclient := storage.NewAccountsClient(subscriptionID)\n\tsetupClient(ctx, log, \"storage.AccountsClient\", &client.Client, authorizer)\n\n\treturn &accountsClient{\n\t\tAccountsClient: client,\n\t}\n}", "func NewAzureServicesClient(subscriptionID string) (*services.AzureClients, error) {\n\tauthorizer, err := auth.NewAuthorizerFromEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tazureComputeClient := compute.NewService(subscriptionID)\n\tazureComputeClient.SetAuthorizer(authorizer)\n\tazureResourceManagementClient := resources.NewService(subscriptionID)\n\tazureResourceManagementClient.SetAuthorizer(authorizer)\n\tazureNetworkClient := network.NewService(subscriptionID)\n\tazureNetworkClient.SetAuthorizer(authorizer)\n\treturn &services.AzureClients{\n\t\tCompute: azureComputeClient,\n\t\tResourcemanagement: azureResourceManagementClient,\n\t\tNetwork: azureNetworkClient,\n\t}, nil\n}", "func NewClient(azAuth *azure.Authentication, extraUserAgent string) (*Client, error) {\n\tif azAuth == nil {\n\t\treturn nil, fmt.Errorf(\"Authentication is not supplied for the Azure client\")\n\t}\n\n\tuserAgent := []string{defaultUserAgent}\n\tif extraUserAgent != \"\" {\n\t\tuserAgent = append(userAgent, extraUserAgent)\n\t}\n\n\tclient, err := azure.NewClient(azAuth, baseURI, userAgent)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Creating Azure client failed: %v\", err)\n\t}\n\n\tauthorizer, err := auth.NewClientCredentialsConfig(azAuth.ClientID, azAuth.ClientSecret, azAuth.TenantID).Authorizer()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsc := network.NewSubnetsClient(azAuth.SubscriptionID)\n\tsc.Authorizer = authorizer\n\n\treturn &Client{\n\t\tsc: sc,\n\t\thc: client.HTTPClient,\n\t\tauth: azAuth,\n\t}, nil\n}", "func NewClient(opts *cli.Options) (*servicebus.Namespace, error) {\n\tc, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(opts.Azure.ConnectionString))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to create new azure service bus client\")\n\t}\n\treturn c, nil\n}", "func newClient(auth azure.Authorizer) *azureClient {\n\tc := newPrivateZonesClient(auth.SubscriptionID(), auth.BaseURI(), auth.Authorizer())\n\tv := newVirtualNetworkLinksClient(auth.SubscriptionID(), auth.BaseURI(), auth.Authorizer())\n\tr := newRecordSetsClient(auth.SubscriptionID(), auth.BaseURI(), auth.Authorizer())\n\treturn &azureClient{c, v, r}\n}", "func NewAccountClient(subscriptionID string) AccountClient {\n return NewAccountClientWithBaseURI(DefaultBaseURI, subscriptionID)\n}", "func newClient(auth azure.Authorizer) *azureClient {\n\treturn &azureClient{\n\t\tscalesetvms: newVirtualMachineScaleSetVMsClient(auth.SubscriptionID(), auth.BaseURI(), auth.Authorizer()),\n\t}\n}", "func NewClient(apiVersion ApiVersion, tenantId string) Client {\n\treturn Client{\n\t\tEndpoint: environments.AadGraphGlobal.Endpoint,\n\t\tApiVersion: apiVersion,\n\t\tTenantId: tenantId,\n\t\thttpClient: http.DefaultClient,\n\t}\n}", "func NewAzure(svc hermes.Service) *azure {\n\treturn &azure{svc}\n}", "func NewAccountClient() *AccountClient {\n\tclient := resty.New()\n\tclient.SetDebug(false)\n\t// Try getting Accounts API base URL from env var\n\tapiURL := os.Getenv(\"API_ADDR\")\n\tif apiURL == \"\" {\n\t\tapiURL = defaultBaseURL\n\t}\n\tclient.SetHostURL(apiURL)\n\t// Setting global error struct that maps to Form3's error response\n\tclient.SetError(&Error{})\n\n\treturn &AccountClient{client: client}\n}", "func NewClient(configMode string) (client AzureClient) {\n\tvar configload Config\n\tif configMode == \"metadata\" {\n\t\tconfigload = LoadConfig()\n\t} else if configMode == \"environment\" {\n\t\tconfigload = EnvLoadConfig()\n\t} else {\n\t\tlog.Print(\"Invalid config Mode\")\n\t}\n\n\tclient = AzureClient{\n\t\tconfigload,\n\t\tGetVMClient(configload),\n\t\tGetNicClient(configload),\n\t\tGetLbClient(configload),\n\t}\n\treturn\n}", "func newClient(auth azure.Authorizer) *azureClient {\n\tc := newResourceHealthClient(auth.SubscriptionID(), auth.BaseURI(), auth.Authorizer())\n\treturn &azureClient{c}\n}", "func initAzureClient() azure.UsageExplorer {\n\texplorer := azure.NewUsageExplorer()\n\treturn explorer\n}", "func NewApplicationsClient(ctx context.Context, log *logrus.Entry, tenantID string, authorizer autorest.Authorizer) ApplicationsClient {\n\tclient := graphrbac.NewApplicationsClient(tenantID)\n\tazureclient.SetupClient(ctx, log, \"graphrbac.ApplicationsClient\", &client.Client, authorizer)\n\n\treturn &applicationsClient{\n\t\tApplicationsClient: client,\n\t}\n}", "func NewClient(vaultURL string, credential azcore.TokenCredential, options *ClientOptions) (*Client, error) {\n\tif options == nil {\n\t\toptions = &ClientOptions{}\n\t}\n\tauthPolicy := internal.NewKeyVaultChallengePolicy(\n\t\tcredential,\n\t\t&internal.KeyVaultChallengePolicyOptions{\n\t\t\tDisableChallengeResourceVerification: options.DisableChallengeResourceVerification,\n\t\t},\n\t)\n\tazcoreClient, err := azcore.NewClient(\"rbac.Client\", ainternal.Version, runtime.PipelineOptions{PerRetry: []policy.Policy{authPolicy}}, &options.ClientOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{endpoint: vaultURL, internal: azcoreClient}, nil\n}", "func NewClient(clientName, moduleVersion string, cred azcore.TokenCredential, options *ClientOptions) (*Client, error) {\n\tpkg, err := shared.ExtractPackageName(clientName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif options == nil {\n\t\toptions = &ClientOptions{}\n\t}\n\n\tif !options.Telemetry.Disabled {\n\t\tif err := shared.ValidateModVer(moduleVersion); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint\n\tif c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {\n\t\tep = c.Endpoint\n\t}\n\tpl, err := armruntime.NewPipeline(pkg, moduleVersion, cred, runtime.PipelineOptions{}, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttr := options.TracingProvider.NewTracer(clientName, moduleVersion)\n\treturn &Client{ep: ep, pl: pl, tr: tr}, nil\n}", "func NewRestorableDatabaseAccountsClient(con *armcore.Connection, subscriptionID string) *RestorableDatabaseAccountsClient {\n\treturn &RestorableDatabaseAccountsClient{con: con, subscriptionID: subscriptionID}\n}", "func NewModelsAzureCredentials() *ModelsAzureCredentials {\n\tthis := ModelsAzureCredentials{}\n\treturn &this\n}", "func NewClient(options *Options) (*DefaultClient, error) {\n\tcredential, err := options.Credential()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// This configures the client to use the default retry policy. The default policy uses exponential backoff with\n\t// maxRetries = 4. If this behavior needs to be changed, add the Retry member to azblob.PipelineOptions. For\n\t// more information on azure retry policies see https://pkg.go.dev/github.com/Azure/azure-storage-blob-go/azblob#RetryOptions\n\t//\n\t// Example (this is not the default):\n\t//\tRetryOptions{\n\t//\t\tPolicy: RetryPolicyExponential, // Use exponential backoff as opposed to linear\n\t//\t\tMaxTries: 3, // Try at most 3 times to perform the operation (set to 1 to disable retries)\n\t//\t\tTryTimeout: time.Second * 3, // Maximum time allowed for any single try\n\t//\t\tRetryDelay: time.Second * 1, // Backoff amount for each retry (exponential or linear)\n\t//\t\tMaxRetryDelay: time.Second * 3, // Max delay between retries\n\t//\t}\n\tpl := azblob.NewPipeline(credential, azblob.PipelineOptions{})\n\n\treturn &DefaultClient{pl}, nil\n}", "func NewAppsClient(azureRegion AzureRegions) AppsClient {\n\treturn AppsClient{New(azureRegion)}\n}", "func NewAccountClientWithBaseURI(baseURI string, subscriptionID string) AccountClient {\n return AccountClient{ NewWithBaseURI(baseURI, subscriptionID)}\n }", "func NewAzureCLICredential(options *AzureCLICredentialOptions) (*AzureCLICredential, error) {\n\tcp := AzureCLICredentialOptions{}\n\tif options != nil {\n\t\tcp = *options\n\t}\n\tcp.init()\n\tc := AzureCLICredential{tokenProvider: cp.tokenProvider}\n\tc.s = newSyncer(credNameAzureCLI, cp.TenantID, cp.AdditionallyAllowedTenants, c.requestToken, c.requestToken)\n\treturn &c, nil\n}", "func NewClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*Client, error) {\n\tcl, err := arm.NewClient(moduleName+\".Client\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &Client{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func New(c rest.Interface) *AgonesV1Client {\n\treturn &AgonesV1Client{c}\n}", "func NewClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*Client, error) {\n\tif options == nil {\n\t\toptions = &arm.ClientOptions{}\n\t}\n\tep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint\n\tif c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {\n\t\tep = c.Endpoint\n\t}\n\tpl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &Client{\n\t\tsubscriptionID: subscriptionID,\n\t\thost: ep,\n\t\tpl: pl,\n\t}\n\treturn client, nil\n}", "func NewClient(endpointUrl string, cred azcore.TokenCredential, options *ClientOptions) (*Client, error) {\n\tif options == nil {\n\t\toptions = &ClientOptions{}\n\t}\n\n\tgenOptions := options.toConnectionOptions()\n\n\ttokenScope, err := getDefaultScope(endpointUrl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsyncTokenPolicy := newSyncTokenPolicy()\n\tgenOptions.PerRetryPolicies = append(\n\t\tgenOptions.PerRetryPolicies,\n\t\truntime.NewBearerTokenPolicy(cred, []string{tokenScope}, nil),\n\t\tsyncTokenPolicy,\n\t)\n\n\tpl := runtime.NewPipeline(moduleName, moduleVersion, runtime.PipelineOptions{}, genOptions)\n\treturn &Client{\n\t\tappConfigClient: generated.NewAzureAppConfigurationClient(endpointUrl, nil, pl),\n\t\tsyncTokenPolicy: syncTokenPolicy,\n\t}, nil\n}", "func CreateAzureCloudCredentials(rancherClient *rancher.Client) (*cloudcredentials.CloudCredential, error) {\n\tvar azureCredentialConfig cloudcredentials.AzureCredentialConfig\n\tconfig.LoadConfig(cloudcredentials.AzureCredentialConfigurationFileKey, &azureCredentialConfig)\n\n\tcloudCredential := cloudcredentials.CloudCredential{\n\t\tName: azureCloudCredNameBase,\n\t\tAzureCredentialConfig: &azureCredentialConfig,\n\t}\n\n\tresp := &cloudcredentials.CloudCredential{}\n\terr := rancherClient.Management.APIBaseClient.Ops.DoCreate(management.CloudCredentialType, cloudCredential, resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func NewSpatialAnchorsAccountsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SpatialAnchorsAccountsClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".SpatialAnchorsAccountsClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &SpatialAnchorsAccountsClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func NewTierAzure(name, accountName, accountKey, bucket string, options ...AzureOptions) (*TierConfig, error) {\n\tif name == \"\" {\n\t\treturn nil, ErrTierNameEmpty\n\t}\n\n\taz := &TierAzure{\n\t\tAccountName: accountName,\n\t\tAccountKey: accountKey,\n\t\tBucket: bucket,\n\t\t// Defaults\n\t\tEndpoint: \"http://blob.core.windows.net\",\n\t\tPrefix: \"\",\n\t\tRegion: \"\",\n\t\tStorageClass: \"\",\n\t}\n\n\tfor _, option := range options {\n\t\terr := option(az)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &TierConfig{\n\t\tVersion: TierConfigV1,\n\t\tType: Azure,\n\t\tName: name,\n\t\tAzure: az,\n\t}, nil\n}", "func NewClient(subscriptionID string, authorizer autorest.Authorizer) Client {\n\treturn NewClientWithBaseURI(DefaultBaseURI, subscriptionID, authorizer)\n}", "func NewAzureClientWithClientSecret(env azure.Environment, subscriptionID, tenantID, clientID, clientSecret string) (armhelper.ACSEngineClient, error) {\n\toauthConfig, tenantID, err := getOAuthConfig(env, subscriptionID, tenantID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tarmSpt, err := adal.NewServicePrincipalToken(*oauthConfig, clientID, clientSecret, env.ServiceManagementEndpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgraphSpt, err := adal.NewServicePrincipalToken(*oauthConfig, clientID, clientSecret, env.GraphEndpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgraphSpt.Refresh()\n\n\treturn getClient(env, subscriptionID, tenantID, armSpt, graphSpt), nil\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tclient := &Client{\n\t\tClient: *httpClient,\n\t\tUserAgent: \"Akamai-Open-Edgegrid-golang/\" + libraryVersion +\n\t\t\t\" golang/\" + strings.TrimPrefix(runtime.Version(), \"go\"),\n\t}\n\n\treturn client\n}", "func NewClient() *Client {\n\tu := getVaultAddr()\n\tauth := getAuthStrategy()\n\treturn &Client{u, auth, \"\", nil}\n}", "func NewAgentPoolsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AgentPoolsClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".AgentPoolsClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &AgentPoolsClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func NewAgentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AgentsClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".AgentsClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &AgentsClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func NewCloudServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudServicesClient, error) {\n\tif options == nil {\n\t\toptions = &arm.ClientOptions{}\n\t}\n\tep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint\n\tif c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {\n\t\tep = c.Endpoint\n\t}\n\tpl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &CloudServicesClient{\n\t\tsubscriptionID: subscriptionID,\n\t\thost: ep,\n\t\tpl: pl,\n\t}\n\treturn client, nil\n}", "func NewDatasetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DatasetsClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".DatasetsClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &DatasetsClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func NewAvailabilitySetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) *AvailabilitySetsClient {\n\tcp := arm.ClientOptions{}\n\tif options != nil {\n\t\tcp = *options\n\t}\n\tif len(cp.Host) == 0 {\n\t\tcp.Host = arm.AzurePublicCloud\n\t}\n\treturn &AvailabilitySetsClient{subscriptionID: subscriptionID, ep: string(cp.Host), pl: armruntime.NewPipeline(module, version, credential, &cp)}\n}", "func NewUsersClient(tenantId string) *UsersClient {\n\treturn &UsersClient{\n\t\tBaseClient: base.NewClient(base.VersionBeta, tenantId),\n\t}\n}", "func NewSubAccountClient(client *rest.Client) (*SubAccountClient, error) {\n\treturn &SubAccountClient{\n\t\tclient: client,\n\t}, nil\n}", "func (a *Client) ListAzureAccounts(params *ListAzureAccountsParams, opts ...ClientOption) (*ListAzureAccountsOK, *ListAzureAccountsMultiStatus, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListAzureAccountsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"ListAzureAccounts\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/kubernetes-protection/entities/accounts/azure/v1\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListAzureAccountsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tswitch value := result.(type) {\n\tcase *ListAzureAccountsOK:\n\t\treturn value, nil, nil\n\tcase *ListAzureAccountsMultiStatus:\n\t\treturn nil, value, nil\n\t}\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 kubernetes_protection: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func NewClient(vaultURL string, credential azcore.TokenCredential, options *ClientOptions) (*Client, error) {\n\tif options == nil {\n\t\toptions = &ClientOptions{}\n\t}\n\tauthPolicy := internal.NewKeyVaultChallengePolicy(\n\t\tcredential,\n\t\t&internal.KeyVaultChallengePolicyOptions{\n\t\t\tDisableChallengeResourceVerification: options.DisableChallengeResourceVerification,\n\t\t},\n\t)\n\tazcoreClient, err := azcore.NewClient(\"azcertificates.Client\", version, runtime.PipelineOptions{PerRetry: []policy.Policy{authPolicy}}, &options.ClientOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{endpoint: vaultURL, internal: azcoreClient}, nil\n}", "func (client Client) StorageAccounts() storage.AccountsClient {\n\tif client.accounts == nil {\n\t\tclnt := storage.NewAccountsClientWithBaseURI(client.baseURI, client.subscriptionID)\n\t\tclnt.Authorizer = client.Authorizer\n\t\tclnt.RequestInspector = client.RequestInspector\n\t\tclnt.ResponseInspector = client.ResponseInspector\n\t\tclient.accounts = &clnt\t\t\n\t}\t\n\treturn *client.accounts\n}", "func NewVirtualMachinesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachinesClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".VirtualMachinesClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &VirtualMachinesClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func NewModelsAzureCredentialsWithDefaults() *ModelsAzureCredentials {\n\tthis := ModelsAzureCredentials{}\n\treturn &this\n}", "func InitAzureKubeAuth(portalProxy interfaces.PortalProxy) KubeAuthProvider {\n\treturn &AzureKubeAuth{*InitCertKubeAuth(portalProxy)}\n}", "func NewClient(acls *gitacls.ACLs) Client {\n\treturn &implementation{acls: acls}\n}", "func NewClient() (*VaultClient, error) {\n\tclient, err := vault.NewClient(nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create secrets client\")\n\t}\n\n\treturn &VaultClient{client: client}, nil\n}", "func New(c rest.Interface) *KudzuV1alpha1Client {\n\treturn &KudzuV1alpha1Client{c}\n}", "func NewAzureProvisioner() (*AzureProvisioner, error) {\n\n\tclient, err := auth.NewAuthorizerFromEnvironment()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &AzureProvisioner{\n\t\tclient: client,\n\t}, nil\n}", "func NewClient(address string) (KubeClient, error) {\n\t// create tls client\n\tcacertFile := \"/var/run/secrets/kubernetes.io/serviceaccount/ca.crt\"\n\tcapem, err := ioutil.ReadFile(cacertFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcacert := x509.NewCertPool()\n\tif !cacert.AppendCertsFromPEM(capem) {\n\t\treturn nil, fmt.Errorf(\"unable to load certificate authority\")\n\t}\n\tconfig := &tls.Config{RootCAs: cacert}\n\ttransport := &http.Transport{TLSClientConfig: config}\n\n\t// read token\n\tclient := &http.Client{Transport: transport}\n\ttokenFile := \"/var/run/secrets/kubernetes.io/serviceaccount/token\"\n\ttoken, err := ioutil.ReadFile(tokenFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &realKubeClient{client, address, string(token)}, nil\n}", "func NewAzureProvider(p *Provider) (*AzureProvider, error) {\n\tctx := context.Background()\n\tif p.ProviderURL == \"\" {\n\t\tp.ProviderURL = defaultAzureProviderURL\n\t}\n\tvar err error\n\tp.provider, err = oidc.NewProvider(ctx, p.ProviderURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(p.Scopes) == 0 {\n\t\tp.Scopes = []string{oidc.ScopeOpenID, \"profile\", \"email\", \"offline_access\", \"Group.Read.All\"}\n\t}\n\tp.verifier = p.provider.Verifier(&oidc.Config{ClientID: p.ClientID})\n\tp.oauth = &oauth2.Config{\n\t\tClientID: p.ClientID,\n\t\tClientSecret: p.ClientSecret,\n\t\tEndpoint: p.provider.Endpoint(),\n\t\tRedirectURL: p.RedirectURL.String(),\n\t\tScopes: p.Scopes,\n\t}\n\n\tazureProvider := &AzureProvider{\n\t\tProvider: p,\n\t}\n\t// azure has a \"end session endpoint\"\n\tvar claims struct {\n\t\tRevokeURL string `json:\"end_session_endpoint\"`\n\t}\n\tif err := p.provider.Claims(&claims); err != nil {\n\t\treturn nil, err\n\t}\n\tazureProvider.RevokeURL, err = url.Parse(claims.RevokeURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn azureProvider, nil\n}", "func NewAzureProvider(p *ProviderData) *AzureProvider {\n\tp.ProviderName = \"Azure\"\n\n\tif p.ProfileURL == nil || p.ProfileURL.String() == \"\" {\n\t\tp.ProfileURL = &url.URL{\n\t\t\tScheme: \"https\",\n\t\t\tHost: \"graph.windows.net\",\n\t\t\tPath: \"/me\",\n\t\t\tRawQuery: \"api-version=1.6\",\n\t\t}\n\t}\n\tif p.ProtectedResource == nil || p.ProtectedResource.String() == \"\" {\n\t\tp.ProtectedResource = &url.URL{\n\t\t\tScheme: \"https\",\n\t\t\tHost: \"graph.windows.net\",\n\t\t}\n\t}\n\tif p.Scope == \"\" {\n\t\tp.Scope = \"openid\"\n\t}\n\n\treturn &AzureProvider{ProviderData: p}\n}", "func NewClient(username string, password string) *Client {\n\tbaseURL, _ := url.Parse(DefaultBaseURL)\n\tc := &Client{HTTP: &http.Client{}, BaseURL: baseURL}\n token, _ := c.GetToken(username, password)\n c.Token = token\n ActiveClient = c\n\treturn c\n}", "func New(tenantServiceURL string, authToken string) Client {\n\tlogger := log.WithFields(\n\t\tlog.Fields{\n\t\t\t\"component\": \"tenant\",\n\t\t\t\"url\": tenantServiceURL,\n\t\t},\n\t)\n\n\treturn Client{\n\t\tauthToken: authToken,\n\t\ttenantServiceURL: tenantServiceURL,\n\t\tclient: util.HTTPClient(),\n\t\tlogger: logger,\n\t}\n}", "func newRecordSetsClient(subscriptionID string, baseURI string, authorizer autorest.Authorizer) privatedns.RecordSetsClient {\n\trecordsClient := privatedns.NewRecordSetsClientWithBaseURI(baseURI, subscriptionID)\n\tazure.SetAutoRestClientDefaults(&recordsClient.Client, authorizer)\n\treturn recordsClient\n}", "func NewClient(apiKey string, apiSecret string, apiBackend razorpay.Backend) *Client {\n\treturn &Client{razorpay.NewClient(apiKey, apiSecret, apiBackend)}\n}", "func NewClient(apiKey string, apiSecret string, apiBackend razorpay.Backend) *Client {\n\treturn &Client{razorpay.NewClient(apiKey, apiSecret, apiBackend)}\n}", "func NewClient(apiKey string, apiSecret string, apiBackend razorpay.Backend) *Client {\n\treturn &Client{razorpay.NewClient(apiKey, apiSecret, apiBackend)}\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\tbaseURL, err := url.Parse(baseURL)\n\tc := &Client{client: httpClient, BaseURL: baseURL, err: err}\n\tc.common.client = c\n\tc.Teams = (*TeamsService)(&c.common)\n\tc.Invitations = (*InvitationsService)(&c.common)\n\treturn c\n}", "func NewTriggersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TriggersClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".TriggersClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &TriggersClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func New(opts *Options) (*API, error) {\n\tconf := management.DefaultConfig()\n\tconf.APIVersion = \"2015-04-01\"\n\n\tif opts.ManagementURL != \"\" {\n\t\tconf.ManagementURL = opts.ManagementURL\n\t}\n\n\tif opts.StorageEndpointSuffix == \"\" {\n\t\topts.StorageEndpointSuffix = storage.DefaultBaseURL\n\t}\n\n\tprofiles, err := internalAuth.ReadAzureProfile(opts.AzureProfile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't read Azure profile: %v\", err)\n\t}\n\n\tsubOpts := profiles.SubscriptionOptions(opts.AzureSubscription)\n\tif subOpts == nil {\n\t\treturn nil, fmt.Errorf(\"Azure subscription named %q doesn't exist in %q\", opts.AzureSubscription, opts.AzureProfile)\n\t}\n\n\tif os.Getenv(\"AZURE_AUTH_LOCATION\") == \"\" {\n\t\tif opts.AzureAuthLocation == \"\" {\n\t\t\tuser, err := user.Current()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\topts.AzureAuthLocation = filepath.Join(user.HomeDir, internalAuth.AzureAuthPath)\n\t\t}\n\t\t// TODO: Move to Flight once built to allow proper unsetting\n\t\tos.Setenv(\"AZURE_AUTH_LOCATION\", opts.AzureAuthLocation)\n\t}\n\n\tif opts.SubscriptionID == \"\" {\n\t\topts.SubscriptionID = subOpts.SubscriptionID\n\t}\n\n\tif opts.SubscriptionName == \"\" {\n\t\topts.SubscriptionName = subOpts.SubscriptionName\n\t}\n\n\tif opts.ManagementURL == \"\" {\n\t\topts.ManagementURL = subOpts.ManagementURL\n\t}\n\n\tif opts.ManagementCertificate == nil {\n\t\topts.ManagementCertificate = subOpts.ManagementCertificate\n\t}\n\n\tif opts.StorageEndpointSuffix == \"\" {\n\t\topts.StorageEndpointSuffix = subOpts.StorageEndpointSuffix\n\t}\n\n\tclient, err := management.NewClientFromConfig(opts.SubscriptionID, opts.ManagementCertificate, conf)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create azure client: %v\", err)\n\t}\n\n\tapi := &API{\n\t\tclient: client,\n\t\topts: opts,\n\t}\n\n\terr = api.resolveImage()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to resolve image: %v\", err)\n\t}\n\n\treturn api, nil\n}", "func NewAzureProvider(p *ProviderData) *AzureProvider {\n\tp.setProviderDefaults(providerDefaults{\n\t\tname: azureProviderName,\n\t\tloginURL: azureDefaultLoginURL,\n\t\tredeemURL: azureDefaultRedeemURL,\n\t\tprofileURL: azureDefaultProfileURL,\n\t\tvalidateURL: nil,\n\t\tscope: azureDefaultScope,\n\t})\n\n\tif p.ProtectedResource == nil || p.ProtectedResource.String() == \"\" {\n\t\tp.ProtectedResource = azureDefaultProtectResourceURL\n\t}\n\tif p.ValidateURL == nil || p.ValidateURL.String() == \"\" {\n\t\tp.ValidateURL = p.ProfileURL\n\t}\n\n\treturn &AzureProvider{\n\t\tProviderData: p,\n\t\tTenant: \"common\",\n\t}\n}", "func NewClient(httpClient *http.Client) (*Client, error) {\n\tif httpClient == nil {\n\t\thttpClient = &http.Client{}\n\t}\n\tb, err := url.Parse(baseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := &Client{client: httpClient, BaseURL: b}\n\tc.PriceHistory = &PriceHistoryService{client: c}\n\tc.Account = &AccountsService{client: c}\n\tc.MarketHours = &MarketHoursService{client: c}\n\tc.Quotes = &QuotesService{client: c}\n\tc.Instrument = &InstrumentService{client: c}\n\tc.Chains = &ChainsService{client: c}\n\tc.Mover = &MoverService{client: c}\n\tc.TransactionHistory = &TransactionHistoryService{client: c}\n\tc.User = &UserService{client: c}\n\tc.Watchlist = &WatchlistService{client: c}\n\n\treturn c, nil\n}", "func New() *Accounts {\n\treturn &Accounts{\n\t\tdata: make(map[string]*Account),\n\t}\n}", "func New(client *client.Client, properties ClientProperties) *Client {\n\treturn &Client{\n\t\tclient: client,\n\n\t\taccountSid: properties.AccountSid,\n\t\tcountryCode: properties.CountryCode,\n\t}\n}", "func NewClustersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) *ClustersClient {\n\tcp := arm.ClientOptions{}\n\tif options != nil {\n\t\tcp = *options\n\t}\n\tif len(cp.Host) == 0 {\n\t\tcp.Host = arm.AzurePublicCloud\n\t}\n\treturn &ClustersClient{subscriptionID: subscriptionID, ep: string(cp.Host), pl: armruntime.NewPipeline(module, version, credential, &cp)}\n}", "func NewOktaClient() *OktaClient {\n\tmyclient := &OktaClient{}\n\n\tif os.Getenv(\"OKTA_CLIENT_ORGURL\") == \"\" {\n\t\tlog.Fatal(\"Must set environment variable OKTA_CLIENT_ORGURL (ie: https://example.okta.com)\")\n\t}\n\tif os.Getenv(\"OKTA_CLIENT_TOKEN\") == \"\" {\n\t\tlog.Fatal(\"Must set API token as environment variable OKTA_CLIENT_TOKEN\")\n\t}\n\n\toktaDomain := os.Getenv(\"OKTA_CLIENT_ORGURL\")\n\tapiToken := os.Getenv(\"OKTA_CLIENT_TOKEN\")\n\n\tconfig := okta.NewConfig().WithOrgUrl(oktaDomain).WithToken(apiToken)\n\n\tmyclient.Client = okta.NewClient(config, nil, nil)\n\treturn myclient\n}", "func NewClient(options ClientOptions) (*Client, error) {\n\tc := &Client{\n\t\thttpClient: &http.Client{},\n\t\toptions: options,\n\t}\n\terr := c.login()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"login failed, %s\", err)\n\t}\n\treturn c, nil\n}", "func NewClient(baseURL *url.URL, token string, httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tc := &Client{client: httpClient, BaseURL: baseURL, token: token}\n\tc.Dashboards = NewDashboardsService(c)\n\tc.Datasources = NewDatasourcesService(c)\n\n\treturn c\n}", "func newVirtualNetworkLinksClient(subscriptionID string, baseURI string, authorizer autorest.Authorizer) privatedns.VirtualNetworkLinksClient {\n\tlinksClient := privatedns.NewVirtualNetworkLinksClientWithBaseURI(baseURI, subscriptionID)\n\tazure.SetAutoRestClientDefaults(&linksClient.Client, authorizer)\n\treturn linksClient\n}", "func NewClient(httpClient *http.Client, address, token string, logger Logger) *Client {\n\treturn &Client{httpClient, address, token, logger}\n}", "func NewClient(httpClient *http.Client, username string, password string, atlantisURL string) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\treturn &Client{\n\t\tHTTPClient: httpClient,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tBaseURL: BaseURL,\n\t\tAtlantisURL: atlantisURL,\n\t}\n}", "func NewClient(kubeconfig, configContext string) (*Client, error) {\n\tconfig, err := defaultRestConfig(kubeconfig, configContext)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trestClient, err := rest.RESTClientFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{config, restClient}, nil\n}", "func NewClient(kubeconfig, configContext string) (*Client, error) {\n\tconfig, err := defaultRestConfig(kubeconfig, configContext)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trestClient, err := rest.RESTClientFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{config, restClient}, nil\n}", "func NewClient(options Options) *Client {\n\treturn &Client{Options: options}\n}", "func NewClient(\n\thost string,\n\tapplicationName string,\n\toptions ...Option,\n) (*Client, error) {\n\tc := &Client{\n\t\thost: host,\n\t\tapplicationName: applicationName,\n\t}\n\n\tfor _, o := range options {\n\t\terr := o(c)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"client.NewClient failed to apply option: %s\", err)\n\t\t}\n\t}\n\n\treturn c, nil\n}", "func New(c rest.Interface) *ServicebrokerV1alpha1Client {\n\treturn &ServicebrokerV1alpha1Client{c}\n}", "func NewActionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ActionsClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".ActionsClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &ActionsClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func NewClient(accessToken string) *api.Client {\n\treturn api.NewClient(accessToken)\n}", "func NewApplicationClient(credential azcore.TokenCredential, options *arm.ClientOptions) *ApplicationClient {\n\tcp := arm.ClientOptions{}\n\tif options != nil {\n\t\tcp = *options\n\t}\n\tif len(cp.Host) == 0 {\n\t\tcp.Host = arm.AzurePublicCloud\n\t}\n\treturn &ApplicationClient{ep: string(cp.Host), pl: armruntime.NewPipeline(module, version, credential, &cp)}\n}", "func NewTablesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TablesClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".TablesClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &TablesClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func NewAccountService(client *binarylane.Client) AccountService {\n\treturn &accountService{\n\t\tclient: client,\n\t}\n}", "func NewClient(cfg clients.Config, hc *http.Client) (Client, error) {\n\treturn clients.NewClient(cfg, hc)\n}", "func NewClient(cfg clients.Config, hc *http.Client) (Client, error) {\n\treturn clients.NewClient(cfg, hc)\n}", "func NewClient(ctx context.Context, config *ClientConfig, httpClient auth.HTTPClient) Client {\n\tif httpClient != nil {\n\t\treturn &serviceManagerClient{Context: ctx, Config: config, HTTPClient: httpClient}\n\t}\n\tccConfig := &clientcredentials.Config{\n\t\tClientID: config.ClientID,\n\t\tClientSecret: config.ClientSecret,\n\t\tTokenURL: config.TokenURL + tokenURLSuffix,\n\t\tAuthStyle: oauth2.AuthStyleInParams,\n\t}\n\n\tauthClient := auth.NewAuthClient(ccConfig, config.SSLDisabled)\n\treturn &serviceManagerClient{Context: ctx, Config: config, HTTPClient: authClient}\n}", "func NewAzureInfoer(config Config, logger cloudinfo.Logger) (*AzureInfoer, error) {\n\tvar authorizer autorest.Authorizer\n\tif config.ClientID != \"\" && config.ClientSecret != \"\" && config.TenantID != \"\" {\n\t\tcredentialsConfig := auth.NewClientCredentialsConfig(config.ClientID, config.ClientSecret, config.TenantID)\n\t\ta, err := credentialsConfig.Authorizer()\n\t\tif err != nil {\n\t\t\treturn nil, emperror.Wrap(err, \"failed to build authorizer\")\n\t\t}\n\n\t\tauthorizer = a\n\t}\n\n\tif authorizer == nil {\n\t\ta, err := auth.NewAuthorizerFromEnvironment()\n\t\tauthorizer = a\n\t\tif err != nil { // Failed to create authorizer from environment, try from file\n\t\t\ta, err := auth.NewAuthorizerFromFile(azure.PublicCloud.ResourceManagerEndpoint)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to get authorizer from both env and file\")\n\t\t\t}\n\n\t\t\tauthorizer = a\n\t\t}\n\t}\n\n\tsClient := subscriptions.NewClient()\n\tsClient.Authorizer = authorizer\n\n\trcClient := commerce.NewRateCardClient(config.SubscriptionID)\n\trcClient.Authorizer = authorizer\n\n\tskusClient := skus.NewResourceSkusClient(config.SubscriptionID)\n\tskusClient.Authorizer = authorizer\n\n\tprovidersClient := resources.NewProvidersClient(config.SubscriptionID)\n\tprovidersClient.Authorizer = authorizer\n\n\tcontainerServiceClient := containerservice.NewContainerServicesClient(config.SubscriptionID)\n\tcontainerServiceClient.Authorizer = authorizer\n\n\treturn &AzureInfoer{\n\t\tsubscriptionId: config.SubscriptionID,\n\t\tsubscriptionsClient: sClient,\n\t\tskusClient: skusClient,\n\t\trateCardClient: rcClient,\n\t\tprovidersClient: providersClient,\n\t\tcontainerSvcClient: &containerServiceClient,\n\t\tlog: logger,\n\t}, nil\n}", "func NewClient(meta *metadata.Client, acc string) *http.Client {\n\treturn &http.Client{\n\t\tTransport: newRoundTripper(meta, acc),\n\t}\n}", "func NewGuestAgentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GuestAgentsClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".GuestAgentsClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &GuestAgentsClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func NewClient(options Options) *Client {\n\tif options.Timeout.String() == \"\" {\n\t\toptions.Timeout = 30 * time.Second\n\t}\n\n\tteamsClient := &Client{\n\t\thttpClient: &http.Client{\n\t\t\tTimeout: options.Timeout,\n\t\t},\n\t\toptions: &options,\n\t}\n\n\treturn teamsClient\n}", "func ExampleBotsClient_Create() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armbotservice.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewBotsClient().Create(ctx, \"OneResourceGroupName\", \"samplebotname\", armbotservice.Bot{\n\t\tEtag: to.Ptr(\"etag1\"),\n\t\tKind: to.Ptr(armbotservice.KindSdk),\n\t\tLocation: to.Ptr(\"West US\"),\n\t\tSKU: &armbotservice.SKU{\n\t\t\tName: to.Ptr(armbotservice.SKUNameS1),\n\t\t},\n\t\tTags: map[string]*string{\n\t\t\t\"tag1\": to.Ptr(\"value1\"),\n\t\t\t\"tag2\": to.Ptr(\"value2\"),\n\t\t},\n\t\tProperties: &armbotservice.BotProperties{\n\t\t\tDescription: to.Ptr(\"The description of the bot\"),\n\t\t\tCmekKeyVaultURL: to.Ptr(\"https://myCmekKey\"),\n\t\t\tDeveloperAppInsightKey: to.Ptr(\"appinsightskey\"),\n\t\t\tDeveloperAppInsightsAPIKey: to.Ptr(\"appinsightsapikey\"),\n\t\t\tDeveloperAppInsightsApplicationID: to.Ptr(\"appinsightsappid\"),\n\t\t\tDisableLocalAuth: to.Ptr(true),\n\t\t\tDisplayName: to.Ptr(\"The Name of the bot\"),\n\t\t\tEndpoint: to.Ptr(\"http://mybot.coffee\"),\n\t\t\tIconURL: to.Ptr(\"http://myicon\"),\n\t\t\tIsCmekEnabled: to.Ptr(true),\n\t\t\tLuisAppIDs: []*string{\n\t\t\t\tto.Ptr(\"luisappid1\"),\n\t\t\t\tto.Ptr(\"luisappid2\")},\n\t\t\tLuisKey: to.Ptr(\"luiskey\"),\n\t\t\tMsaAppID: to.Ptr(\"exampleappid\"),\n\t\t\tMsaAppMSIResourceID: to.Ptr(\"/subscriptions/foo/resourcegroups/bar/providers/microsoft.managedidentity/userassignedidentities/sampleId\"),\n\t\t\tMsaAppTenantID: to.Ptr(\"exampleapptenantid\"),\n\t\t\tMsaAppType: to.Ptr(armbotservice.MsaAppTypeUserAssignedMSI),\n\t\t\tPublicNetworkAccess: to.Ptr(armbotservice.PublicNetworkAccessEnabled),\n\t\t\tSchemaTransformationVersion: to.Ptr(\"1.0\"),\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Bot = armbotservice.Bot{\n\t// \tName: to.Ptr(\"samplebotname\"),\n\t// \tType: to.Ptr(\"Microsoft.BotService/botServices\"),\n\t// \tEtag: to.Ptr(\"etag1\"),\n\t// \tID: to.Ptr(\"/subscriptions/subscription-id/resourceGroups/OneResourceGroupName/providers/Microsoft.BotService/botServices/samplebotname\"),\n\t// \tKind: to.Ptr(armbotservice.KindSdk),\n\t// \tLocation: to.Ptr(\"West US\"),\n\t// \tTags: map[string]*string{\n\t// \t\t\"tag1\": to.Ptr(\"value1\"),\n\t// \t\t\"tag2\": to.Ptr(\"value2\"),\n\t// \t},\n\t// \tProperties: &armbotservice.BotProperties{\n\t// \t\tDescription: to.Ptr(\"The description of the bot\"),\n\t// \t\tCmekKeyVaultURL: to.Ptr(\"https://myCmekKey\"),\n\t// \t\tConfiguredChannels: []*string{\n\t// \t\t\tto.Ptr(\"facebook\"),\n\t// \t\t\tto.Ptr(\"groupme\")},\n\t// \t\t\tDeveloperAppInsightKey: to.Ptr(\"appinsightskey\"),\n\t// \t\t\tDeveloperAppInsightsApplicationID: to.Ptr(\"appinsightsappid\"),\n\t// \t\t\tDisableLocalAuth: to.Ptr(true),\n\t// \t\t\tDisplayName: to.Ptr(\"The Name of the bot\"),\n\t// \t\t\tEnabledChannels: []*string{\n\t// \t\t\t\tto.Ptr(\"facebook\")},\n\t// \t\t\t\tEndpoint: to.Ptr(\"http://mybot.coffee\"),\n\t// \t\t\t\tEndpointVersion: to.Ptr(\"version\"),\n\t// \t\t\t\tIconURL: to.Ptr(\"http://myicon\"),\n\t// \t\t\t\tIsCmekEnabled: to.Ptr(true),\n\t// \t\t\t\tLuisAppIDs: []*string{\n\t// \t\t\t\t\tto.Ptr(\"luisappid1\"),\n\t// \t\t\t\t\tto.Ptr(\"luisappid2\")},\n\t// \t\t\t\t\tMsaAppID: to.Ptr(\"msaappid\"),\n\t// \t\t\t\t\tMsaAppMSIResourceID: to.Ptr(\"/subscriptions/foo/resourcegroups/bar/providers/microsoft.managedidentity/userassignedidentities/sampleId\"),\n\t// \t\t\t\t\tMsaAppTenantID: to.Ptr(\"msaapptenantid\"),\n\t// \t\t\t\t\tMsaAppType: to.Ptr(armbotservice.MsaAppTypeUserAssignedMSI),\n\t// \t\t\t\t\tPublicNetworkAccess: to.Ptr(armbotservice.PublicNetworkAccessEnabled),\n\t// \t\t\t\t\tSchemaTransformationVersion: to.Ptr(\"1.0\"),\n\t// \t\t\t\t},\n\t// \t\t\t}\n}", "func NewMockAzureCloud(location string) *MockAzureCloud {\n\treturn &MockAzureCloud{\n\t\tLocation: location,\n\t\tResourceGroupsClient: &MockResourceGroupsClient{\n\t\t\tRGs: map[string]resources.Group{},\n\t\t},\n\t\tVirtualNetworksClient: &MockVirtualNetworksClient{\n\t\t\tVNets: map[string]network.VirtualNetwork{},\n\t\t},\n\t\tSubnetsClient: &MockSubnetsClient{\n\t\t\tSubnets: map[string]network.Subnet{},\n\t\t},\n\t\tRouteTablesClient: &MockRouteTablesClient{\n\t\t\tRTs: map[string]network.RouteTable{},\n\t\t},\n\t\tNetworkSecurityGroupsClient: &MockNetworkSecurityGroupsClient{\n\t\t\tNSGs: map[string]network.SecurityGroup{},\n\t\t},\n\t\tApplicationSecurityGroupsClient: &MockApplicationSecurityGroupsClient{\n\t\t\tASGs: map[string]network.ApplicationSecurityGroup{},\n\t\t},\n\t\tVMScaleSetsClient: &MockVMScaleSetsClient{\n\t\t\tVMSSes: map[string]compute.VirtualMachineScaleSet{},\n\t\t},\n\t\tVMScaleSetVMsClient: &MockVMScaleSetVMsClient{\n\t\t\tVMs: map[string]compute.VirtualMachineScaleSetVM{},\n\t\t},\n\t\tDisksClient: &MockDisksClient{\n\t\t\tDisks: map[string]compute.Disk{},\n\t\t},\n\t\tRoleAssignmentsClient: &MockRoleAssignmentsClient{\n\t\t\tRAs: map[string]authz.RoleAssignment{},\n\t\t},\n\t\tNetworkInterfacesClient: &MockNetworkInterfacesClient{\n\t\t\tNIs: map[string]network.Interface{},\n\t\t},\n\t\tLoadBalancersClient: &MockLoadBalancersClient{\n\t\t\tLBs: map[string]network.LoadBalancer{},\n\t\t},\n\t\tPublicIPAddressesClient: &MockPublicIPAddressesClient{\n\t\t\tPubIPs: map[string]network.PublicIPAddress{},\n\t\t},\n\t\tNatGatewaysClient: &MockNatGatewaysClient{\n\t\t\tNGWs: map[string]network.NatGateway{},\n\t\t},\n\t}\n}", "func New(idpAccount *cfg.IDPAccount) (*Client, error) {\n\n\ttr := provider.NewDefaultTransport(idpAccount.SkipVerify)\n\n\tclient, err := provider.NewHTTPClient(tr, provider.BuildHttpClientOpts(idpAccount))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error building http client\")\n\t}\n\n\t// assign a response validator to ensure all responses are either success or a redirect\n\t// this is to avoid have explicit checks for every single response\n\tclient.CheckResponseStatus = provider.SuccessOrRedirectResponseValidator\n\n\t// add cookie jar to keep track of cookies during okta login flow\n\tjar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error building cookie jar\")\n\t}\n\tclient.Jar = jar\n\n\tdisableSessions := idpAccount.DisableSessions\n\trememberDevice := !idpAccount.DisableRememberDevice\n\n\tif idpAccount.DisableSessions { // if user disabled sessions, also dont remember device\n\t\trememberDevice = false\n\t}\n\n\t// Debug the disableSessions and rememberDevice values\n\tlogger.Debugf(\"okta | disableSessions: %v\", disableSessions)\n\tlogger.Debugf(\"okta | rememberDevice: %v\", rememberDevice)\n\n\treturn &Client{\n\t\tclient: client,\n\t\tmfa: idpAccount.MFA,\n\t\ttargetURL: idpAccount.TargetURL,\n\t\tdisableSessions: disableSessions,\n\t\trememberDevice: rememberDevice,\n\t}, nil\n}", "func New(c rest.Interface) *LekvaV1Client {\n\treturn &LekvaV1Client{c}\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = &http.Client{}\n\t}\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\n\tc := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}\n\tc.common.client = c\n\tc.Datasets = (*DatasetsService)(&c.common)\n\tc.Streams = (*StreamsService)(&c.common)\n\tc.Users = (*UsersService)(&c.common)\n\tc.Groups = (*GroupsService)(&c.common)\n\tc.Pages = (*PagesService)(&c.common)\n\tc.Logs = (*ActivityLogsService)(&c.common)\n\tc.Accounts = (*AccountsService)(&c.common)\n\n\treturn c\n}", "func NewFactoriesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FactoriesClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".FactoriesClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &FactoriesClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func New(c rest.Interface) *ZdyfapiV1alpha1Client {\n\treturn &ZdyfapiV1alpha1Client{c}\n}", "func NewClient(c *Config) *Client {\n\treturn &Client{\n\t\tBaseURL: BaseURLV1,\n\t\tUname: c.Username,\n\t\tPword: c.Password,\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: time.Minute,\n\t\t},\n\t}\n}", "func NewAzureProviders(options *types.Options) ([]*customTemplateAzureBlob, error) {\n\tproviders := []*customTemplateAzureBlob{}\n\tif options.AzureContainerName != \"\" && !options.AzureTemplateDisableDownload {\n\t\t// Establish a connection to Azure and build a client object with which to download templates from Azure Blob Storage\n\t\tazClient, err := getAzureBlobClient(options.AzureTenantID, options.AzureClientID, options.AzureClientSecret, options.AzureServiceURL)\n\t\tif err != nil {\n\t\t\treturn nil, errorutil.NewWithErr(err).Msgf(\"Error establishing Azure Blob client for %s\", options.AzureContainerName)\n\t\t}\n\n\t\t// Create a new Azure Blob Storage container object\n\t\tazTemplateContainer := &customTemplateAzureBlob{\n\t\t\tazureBlobClient: azClient,\n\t\t\tcontainerName: options.AzureContainerName,\n\t\t}\n\n\t\t// Add the Azure Blob Storage container object to the list of custom templates\n\t\tproviders = append(providers, azTemplateContainer)\n\t}\n\treturn providers, nil\n}" ]
[ "0.734695", "0.7332698", "0.6740265", "0.6499215", "0.636416", "0.6299267", "0.62756824", "0.61970305", "0.599469", "0.5988111", "0.5970805", "0.58722574", "0.5838493", "0.58318853", "0.5827103", "0.575781", "0.5738369", "0.57283914", "0.5709558", "0.56532186", "0.56343085", "0.5594885", "0.55818754", "0.5576807", "0.5544125", "0.5530099", "0.55159473", "0.5482331", "0.54802954", "0.54431796", "0.5409255", "0.5377004", "0.5339324", "0.53341997", "0.53313065", "0.5322588", "0.5306312", "0.52948135", "0.5289536", "0.52853036", "0.52701795", "0.5269495", "0.52593166", "0.52542895", "0.5244147", "0.5225317", "0.5221167", "0.5201641", "0.519406", "0.51858985", "0.51568115", "0.5152009", "0.5134234", "0.51334035", "0.5126493", "0.51184756", "0.5117449", "0.51158535", "0.51158535", "0.51158535", "0.511074", "0.5109745", "0.5104499", "0.50845265", "0.5074978", "0.5072972", "0.50571424", "0.5052275", "0.50443965", "0.5039029", "0.50338024", "0.50322944", "0.50285745", "0.5026671", "0.5015845", "0.5015845", "0.501216", "0.50086623", "0.49979186", "0.49957287", "0.49933746", "0.4991184", "0.49873385", "0.49862802", "0.49860772", "0.49860772", "0.49820086", "0.49771577", "0.49769866", "0.4976125", "0.4971503", "0.49693215", "0.4965436", "0.4962944", "0.49629095", "0.49622846", "0.4948739", "0.49477118", "0.4945954", "0.4944559" ]
0.82849646
0
AssignToApp assigns an azure account to the application. Parameters: appID the application ID. azureAccountInfoObject the azure account information object.
func (client AzureAccountsClient) AssignToApp(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (result OperationStatus, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/AzureAccountsClient.AssignToApp") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: azureAccountInfoObject, Constraints: []validation.Constraint{{Target: "azureAccountInfoObject", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "azureAccountInfoObject.AzureSubscriptionID", Name: validation.Null, Rule: true, Chain: nil}, {Target: "azureAccountInfoObject.ResourceGroup", Name: validation.Null, Rule: true, Chain: nil}, {Target: "azureAccountInfoObject.AccountName", Name: validation.Null, Rule: true, Chain: nil}, }}}}}); err != nil { return result, validation.NewError("authoring.AzureAccountsClient", "AssignToApp", err.Error()) } req, err := client.AssignToAppPreparer(ctx, appID, azureAccountInfoObject) if err != nil { err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "AssignToApp", nil, "Failure preparing request") return } resp, err := client.AssignToAppSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "AssignToApp", resp, "Failure sending request") return } result, err = client.AssignToAppResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "AssignToApp", resp, "Failure responding to request") } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AzureAccountsClient) AssignToAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\tif azureAccountInfoObject != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(azureAccountInfoObject))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AzureAccountsClient) AssignToAppSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (m *ApplicationResource) AssignUserToApplication(ctx context.Context, appId string, body AppUser) (*AppUser, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/users\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"POST\", url, body)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar appUser *AppUser\n\n\tresp, err := rq.Do(ctx, req, &appUser)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn appUser, resp, nil\n}", "func (client AzureAccountsClient) AssignToAppResponder(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.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (adm *AdminClient) SetAppInfo(appName string, appVersion string) {\n\t// if app name and version is not set, we do not a new user\n\t// agent.\n\tif appName != \"\" && appVersion != \"\" {\n\t\tadm.appInfo.appName = appName\n\t\tadm.appInfo.appVersion = appVersion\n\t}\n}", "func (client AzureAccountsClient) RemoveFromApp(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (result OperationStatus, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.RemoveFromApp\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: azureAccountInfoObject,\n\t\t\tConstraints: []validation.Constraint{{Target: \"azureAccountInfoObject\", Name: validation.Null, Rule: false,\n\t\t\t\tChain: []validation.Constraint{{Target: \"azureAccountInfoObject.AzureSubscriptionID\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.ResourceGroup\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.AccountName\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t}}}}}); err != nil {\n\t\treturn result, validation.NewError(\"authoring.AzureAccountsClient\", \"RemoveFromApp\", err.Error())\n\t}\n\n\treq, err := client.RemoveFromAppPreparer(ctx, appID, azureAccountInfoObject)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.RemoveFromAppSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.RemoveFromAppResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (a *AzureCLI) CreateApp(appDisplayName string) error {\n\tc := fmt.Sprintf(\"az ad app create --display-name '%s' --available-to-other-tenants true --homepage %s --reply-urls %s\",\n\t\tappDisplayName, viper.GetString(\"app.url\"), viper.GetString(\"app.url\"))\n\t_, err := ExecuteCmd(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Client) AddUserToApp(email string, name string, secret string, cpf string) (*http.Response, error) {\n\tpath := fmt.Sprintf(\"/management/%v/users/%v?includeRoles='readonly'\", string(c.APPKey.Buffer()), strings.TrimSuffix(email, \"\\n\"))\n\tcomment, _ := json.Marshal(userComment{TotpSecret: secret, Status: \"enabled\", CPF: cpf})\n\tuser := userData{FullName: name, Comment: string(comment)}\n\tdata, _ := json.Marshal(user)\n\n\treturn c.Put(path, bytes.NewBuffer(data))\n}", "func (client *Client) AttachAppPolicyToIdentity(request *AttachAppPolicyToIdentityRequest) (_result *AttachAppPolicyToIdentityResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &AttachAppPolicyToIdentityResponse{}\n\t_body, _err := client.AttachAppPolicyToIdentityWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (c Client) CreateApplication(name string, email string, accounts string, cloudProviders string, instancePort string, description string) (types.TaskRef, error) {\n var taskRef types.TaskRef\n var jobs []types.Job\n\n a := strings.Split(accounts, \",\")\n\n for _, account := range a {\n jobs = append(jobs, types.Job {\n Type: \"createApplication\",\n Account: account,\n User: \"\",\n Application: types.CreateApplication {\n Name: name,\n Description: description,\n Accounts: accounts,\n CloudProviders: cloudProviders,\n Email: email,\n InstancePort: instancePort,\n },\n })\n }\n\n task := types.Task {\n Application: name,\n Description: \"Create Application: \" + name,\n Job : jobs,\n }\n\n resp, err := c.post(\"/applications/\" + name + \"/tasks\", task)\n defer ensureReaderClosed(resp)\n if err != nil {\n return taskRef, err\n }\n\n err = json.NewDecoder(resp.body).Decode(&taskRef)\n return taskRef, err\n}", "func (client *Client) CreateAppInfo(request *CreateAppInfoRequest) (_result *CreateAppInfoResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &CreateAppInfoResponse{}\n\t_body, _err := client.CreateAppInfoWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (c *RollbarAPIClient) AssignTeamToProject(teamID, projectID int) error {\n\tl := log.With().\n\t\tInt(\"teamID\", teamID).\n\t\tInt(\"projectID\", projectID).\n\t\tLogger()\n\tl.Debug().Msg(\"Assigning team to project\")\n\tresp, err := c.Resty.R().\n\t\tSetPathParams(map[string]string{\n\t\t\t\"teamID\": strconv.Itoa(teamID),\n\t\t\t\"projectID\": strconv.Itoa(projectID),\n\t\t}).\n\t\tSetError(ErrorResult{}).\n\t\tPut(c.BaseURL + pathTeamProject)\n\tif err != nil {\n\t\tl.Err(err).Msg(\"Error assigning team to project\")\n\t\treturn err\n\t}\n\terr = errorFromResponse(resp)\n\tif err != nil {\n\t\tl.Err(err).Msg(\"Error assigning team to project\")\n\t\treturn err\n\t}\n\tl.Debug().Msg(\"Successfully assigned team to project\")\n\treturn nil\n}", "func (api API) CreateApp(name, engine string) (app AppBundle, err error) {\n\n\tbearer, err := api.Authenticator.GetToken(\"code:all\")\n\tif err != nil {\n\t\treturn\n\t}\n\tpath := api.Authenticator.GetHostPath() + api.DesignAutomationPath\n\tapp, err = createApp(path, name, engine, bearer.AccessToken)\n\n\tapp.authenticator = api.Authenticator\n\tapp.path = path\n\tapp.name = name\n\tapp.uploadURL = api.UploadAppURL\n\n\t//WARNING: when an AppBundle is created, it is assigned an '$LATEST' alias\n\t// but this alias is not usable and if no other alias is created for this\n\t// appBundle, then the alias listing will fail.\n\t// Thus I decided to autoasign a \"default\" alias upon app creation\n\tgo app.CreateAlias(\"default\", 1)\n\n\treturn\n}", "func (client *Client) AttachAppPolicyToIdentityWithOptions(request *AttachAppPolicyToIdentityRequest, runtime *util.RuntimeOptions) (_result *AttachAppPolicyToIdentityResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AppId)) {\n\t\tquery[\"AppId\"] = request.AppId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.IdentityName)) {\n\t\tquery[\"IdentityName\"] = request.IdentityName\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.IdentityType)) {\n\t\tquery[\"IdentityType\"] = request.IdentityType\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.PolicyNames)) {\n\t\tquery[\"PolicyNames\"] = request.PolicyNames\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"AttachAppPolicyToIdentity\"),\n\t\tVersion: tea.String(\"2017-03-21\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &AttachAppPolicyToIdentityResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (cli *OpsGenieAlertV2Client) Assign(req alertsv2.AssignAlertRequest) (*AsyncRequestResponse, error) {\n\treturn cli.sendAsyncPostRequest(&req)\n}", "func (c *Client) AssociateSerialsToApp(appID string, serials []string) (*ManageVPPLicensesByAdamIdSrv, error) {\n\toptions := ManageVPPLicensesByAdamIdSrvOptions{\n\t\tAssociateSerialNumbers: serials,\n\t}\n\n\tresponse, err := c.ManageVPPLicensesByAdamIdSrv(appID, options)\n\treturn &response, err\n}", "func (tc TeresaClient) CreateApp(name string, scale int64, teamID int64) (app *models.App, err error) {\n\tparams := apps.NewCreateAppParams()\n\tparams.TeamID = teamID\n\tparams.WithBody(&models.App{Name: &name, Scale: &scale})\n\tr, err := tc.teresa.Apps.CreateApp(params, tc.apiKeyAuthFunc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Payload, nil\n}", "func (_PermInterface *PermInterfaceTransactor) AssignAccountRole(opts *bind.TransactOpts, _account common.Address, _orgId string, _roleId string) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"assignAccountRole\", _account, _orgId, _roleId)\n}", "func (c *RollbarAPIClient) AssignUserToTeam(teamID, userID int) error {\n\tl := log.With().Int(\"userID\", userID).Int(\"teamID\", teamID).Logger()\n\tl.Debug().Msg(\"Assigning user to team\")\n\tresp, err := c.Resty.R().\n\t\tSetPathParams(map[string]string{\n\t\t\t\"teamID\": strconv.Itoa(teamID),\n\t\t\t\"userID\": strconv.Itoa(userID),\n\t\t}).\n\t\tSetError(ErrorResult{}).\n\t\tPut(c.BaseURL + pathTeamUser)\n\tif err != nil {\n\t\tl.Err(err).Msg(\"Error assigning user to team\")\n\t\treturn err\n\t}\n\terr = errorFromResponse(resp)\n\tif err != nil {\n\t\t// API returns status `403 Forbidden` on invalid user to team assignment\n\t\t// https://github.com/rollbar/terraform-provider-rollbar/issues/66\n\t\tif resp.StatusCode() == http.StatusForbidden {\n\t\t\tl.Err(err).Msg(\"Team or user not found\")\n\t\t\treturn ErrNotFound\n\t\t}\n\t\tl.Err(err).Msg(\"Error assigning user to team\")\n\t\treturn err\n\t}\n\tl.Debug().Msg(\"Successfully assigned user to team\")\n\treturn nil\n}", "func (o *GetAppsAppCallsCallParams) SetApp(app string) {\n\to.App = app\n}", "func Transfer(c *deis.Client, appID string, username string) error {\n\tu := fmt.Sprintf(\"/v2/apps/%s/\", appID)\n\n\treq := api.AppUpdateRequest{Owner: username}\n\tbody, err := json.Marshal(req)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := c.Request(\"POST\", u, body)\n\tif err == nil {\n\t\tres.Body.Close()\n\t}\n\treturn err\n}", "func activateAppUser(token string) api.Response {\n\tvar err = auth.ActivateAppUser(token)\n\tif err != nil {\n\t\treturn api.BadRequest(err)\n\t}\n\n\treturn api.PlainTextResponse(http.StatusCreated, \"Account is now active\")\n}", "func (client *Client) CreateAppInfoWithOptions(request *CreateAppInfoRequest, runtime *util.RuntimeOptions) (_result *CreateAppInfoResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AppName)) {\n\t\tquery[\"AppName\"] = request.AppName\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.Description)) {\n\t\tquery[\"Description\"] = request.Description\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"CreateAppInfo\"),\n\t\tVersion: tea.String(\"2017-03-21\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &CreateAppInfoResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (t *TeamsService) AssignProject(teamID, projectID int) (*TeamProjectAssocResponse, *simpleresty.Response, error) {\n\tvar result *TeamProjectAssocResponse\n\turlStr := t.client.http.RequestURL(\"/team/%d/project/%d\", teamID, projectID)\n\n\t// Set the correct authentication header\n\tt.client.setAuthTokenHeader(t.client.accountAccessToken)\n\n\t// Execute the request\n\tresponse, getErr := t.client.http.Put(urlStr, &result, nil)\n\n\treturn result, response, getErr\n}", "func (d *DB) CreateApp(ctx context.Context, name string, claims ScopeClaims) (*App, error) {\n\tlog := logger.FromContext(ctx)\n\n\tif d.verbose {\n\t\tlog.Log(\n\t\t\t\"msg\", \"creating app\",\n\t\t\t\"name\", name,\n\t\t\t\"claims\", claims,\n\t\t)\n\t}\n\n\tif !areKnownClaims(claims) {\n\t\treturn nil, errors.New(\"invalid scope claims\")\n\t}\n\n\tb, err := randomBytes(keyLength)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get random bytes when creating app\")\n\t}\n\n\tuid, err := randomUID(10)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create random UID when creating app\")\n\t}\n\n\tapp := &App{\n\t\tUID: uid,\n\t\tName: name,\n\t\tHash: fmt.Sprintf(\"%x\", b),\n\t\tRoles: claims,\n\t\tKey: fmt.Sprintf(\"%s-%x\", uid, b),\n\t}\n\n\ttx, err := d.DB.Beginx()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create transaction to save app\")\n\t}\n\n\tsql := `INSERT INTO applications\n\t\t(uid, app_name, key_hash, scope)\n\tVALUES (:uid, :app_name, crypt(:key_hash, gen_salt('bf', 5)), :scope)`\n\n\tsql, args, err := tx.BindNamed(sql, app)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn nil, errors.Wrap(err, \"failed to bind named query\")\n\t}\n\n\t_, err = tx.Exec(sql, args...)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\tif pqErr, ok := err.(*pq.Error); ok {\n\t\t\tif pqErr.Code == pqUniqueViolation {\n\t\t\t\treturn nil, errors.New(\"duplicate application name error. an application with this name is already registered\")\n\t\t\t}\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"failed to execute query\")\n\t}\n\n\treturn app, tx.Commit()\n}", "func (c *RestClient) CreateApp(name string, memory int) (string, error) {\n\t// Ensure that app name is unique for this user. We do this as\n\t// unfortunately the server doesn't enforce it.\n\tapps, err := c.ListApps()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor _, app := range apps {\n\t\tif app.Name == name {\n\t\t\treturn \"\", fmt.Errorf(\"App by that name (%s) already exists\", name)\n\t\t}\n\t}\n\n\t// The CC requires that a POST on /apps sends, at minimum, these\n\t// fields. The values for framework/runtime doesn't matter for our\n\t// purpose (they will get overwritten by a subsequent app push).\n\tcreateArgs := map[string]interface{}{\n\t\t\"name\": name,\n\t\t\"space_guid\": c.Space,\n\t\t\"memory\": memory,\n\t}\n\n\tvar resp struct {\n\t\tMetadata struct {\n\t\t\tGUID string\n\t\t}\n\t}\n\terr = c.MakeRequest(\"POST\", \"/v2/apps\", createArgs, &resp)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif resp.Metadata.GUID == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Missing App GUID from CC\")\n\t}\n\n\treturn resp.Metadata.GUID, nil\n}", "func (m *ApplicationResource) CreateApplication(ctx context.Context, body App, qp *query.Params) (App, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps\")\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(\"POST\", url, body)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tapplication := body\n\n\tresp, err := rq.Do(ctx, req, &application)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn application, resp, nil\n}", "func (a *API) CreateApplication(app Application, appEUI *lorawan.EUI64) error {\n\tif err := CreateApplication(a.ctx.DB, app); err != nil {\n\t\treturn err\n\t}\n\t*appEUI = app.AppEUI\n\treturn nil\n}", "func (m *Application) SetAppId(value *string)() {\n m.appId = value\n}", "func (c *Client) CreateApp(user, name string) (*App, error) {\n\tlog.Printf(\"[INFO] creating application %s/%s\", user, name)\n\n\tbody, err := json.Marshal(&appWrapper{&App{\n\t\tUser: user,\n\t\tName: name,\n\t}})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tendpoint := \"/api/v1/vagrant/applications\"\n\trequest, err := c.Request(\"POST\", endpoint, &RequestOptions{\n\t\tBody: bytes.NewReader(body),\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := checkResp(c.HTTPClient.Do(request))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar app App\n\tif err := decodeJSON(response, &app); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &app, nil\n}", "func CallAssign() MapAssignReply {\n\n\targs := MapAssignArgs{}\n\n\targs.TASKID = taskId\n\n\treply := MapAssignReply{}\n\n\tcall(\"Master.AssignTask\", &args, &reply)\n\n\t// fmt.Println(reply)\n\n\treturn reply\n}", "func (account *Account) CreateOAuthApplication(name string, redirectURI string) (*just.Status, error) {\n\tvar changes = struct {\n\t\tAuthToken string `json:\"authToken\"`\n\t\tUserName string `json:\"user_name\"`\n\t\tApp struct {\n\t\t\tName string `json:\"app_name\"`\n\t\t\tRedirectURI string `json:\"app_redirect_uri\"`\n\t\t} `json:\"app\"`\n\t}{}\n\n\tchanges.AuthToken = account.AuthToken\n\tchanges.UserName = account.UserName\n\tchanges.App.Name = name\n\tchanges.App.RedirectURI = redirectURI\n\n\tdst, err := json.Marshal(&changes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar args f.Args\n\targs.Add(\"authToken\", account.AuthToken)\n\n\turl := fmt.Sprintf(APIEndpoint, fmt.Sprint(\"oauthapps/\", account.UserName))\n\tresp, err := just.POST(dst, url, &args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn just.FixStatus(resp), nil\n}", "func (_PermInterface *PermInterfaceTransactorSession) AssignAccountRole(_account common.Address, _orgId string, _roleId string) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AssignAccountRole(&_PermInterface.TransactOpts, _account, _orgId, _roleId)\n}", "func (actor Actor) CreateApplicationInSpace(app Application, spaceGUID string) (Application, Warnings, error) {\n\tcreatedApp, warnings, err := actor.CloudControllerClient.CreateApplication(\n\t\tccv3.Application{\n\t\t\tLifecycleType: app.LifecycleType,\n\t\t\tLifecycleBuildpacks: app.LifecycleBuildpacks,\n\t\t\tStackName: app.StackName,\n\t\t\tName: app.Name,\n\t\t\tRelationships: ccv3.Relationships{\n\t\t\t\tconstant.RelationshipTypeSpace: ccv3.Relationship{GUID: spaceGUID},\n\t\t\t},\n\t\t})\n\n\tif err != nil {\n\t\tif _, ok := err.(ccerror.NameNotUniqueInSpaceError); ok {\n\t\t\treturn Application{}, Warnings(warnings), actionerror.ApplicationAlreadyExistsError{Name: app.Name}\n\t\t}\n\t\treturn Application{}, Warnings(warnings), err\n\t}\n\n\treturn actor.convertCCToActorApplication(createdApp), Warnings(warnings), nil\n}", "func (o *DeeplinkApp) SetAppleAppEntitlementId(v string) {\n\to.AppleAppEntitlementId = &v\n}", "func assignVolunteerToTeam(c *gin.Context) {\n\tidentifier := c.Params.ByName(\"identifier\")\n\n\tvar ve VolunteerEmail\n\t//Validates json\n\tif err := c.BindJSON(&ve); err != nil {\n\t\tcreateBadRequestResponse(c, err)\n\t\treturn\n\t}\n\temail := ve.VolunteerEmail\n\n\t//Gets VolunteerEmail from database\n\terr := db.Raw(getCfgString(cSelectVolunteerEmail), ve.VolunteerEmail, identifier).Find(&ve).Error\n\tif err == nil {\n\t\tcreateStatusConflictResponse(c)\n\t\treturn\n\t}\n\n\t//Gets Team from database\n\tvar tm Team\n\tif err := db.Where(\"identifier = ?\", identifier).First(&tm).Error; err != nil {\n\t\tcreateInternalErrorResponse(c)\n\t\treturn\n\t}\n\n\t//Writes VolunterEmail to the database\n\tve = VolunteerEmail{tm.ID, email}\n\tif err := db.Create(&ve).Error; err != nil {\n\t\tcreateInternalErrorResponse(c)\n\t\treturn\n\t}\n\tc.JSON(200, ve)\n\n}", "func (c *Client) CreateApp(ctx context.Context, params *CreateAppInput, optFns ...func(*Options)) (*CreateAppOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateAppInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateApp\", params, optFns, c.addOperationCreateAppMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateAppOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (_PermInterface *PermInterfaceSession) AssignAccountRole(_account common.Address, _orgId string, _roleId string) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AssignAccountRole(&_PermInterface.TransactOpts, _account, _orgId, _roleId)\n}", "func InitTaskManagerApp(a TaskManagerApp) {\n\ttaskManagerApp = a\n}", "func (r *Resolver) CreateApp(ctx context.Context, args struct {\n\tName string\n\tIcon string\n\tIntro string\n\tURL string\n}) (*AppResolver, error) {\n\ttoken := ctx.Value(meta.KeyTokenPayload).(*pb.TokenPayload)\n\tacl := utils.NewACL(token, meta.SrvSelf)\n\tif !acl.Check() {\n\t\treturn nil, meta.ErrAccessDenied\n\t}\n\n\tservice := ctx.Value(meta.KeyService).(*client.MicroClient)\n\tres, err := service.SelfApp.Create(ctx, &selfPb.AppModify{\n\t\tVisitor: acl.Visitor(),\n\t\tName: args.Name,\n\t\tIcon: args.Icon,\n\t\tIntro: args.Intro,\n\t\tURL: args.URL,\n\t})\n\tif err != nil {\n\t\treturn nil, utils.MicroError(err)\n\t}\n\treturn &AppResolver{ctx, acl, res}, nil\n}", "func (o *User) SetAppRoleAssignments(v []AppRoleAssignment) {\n\to.AppRoleAssignments = v\n}", "func (m *AppVulnerabilityTask) SetAppName(value *string)() {\n err := m.GetBackingStore().Set(\"appName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m memberUsecase) AssignToProject(ctx context.Context, memberID models.UUID, projectID models.UUID) error {\n\treturn m.memberRepos.AssignToProject(ctx, memberID, projectID)\n}", "func LookupApp(ctx *pulumi.Context, args *LookupAppArgs, opts ...pulumi.InvokeOption) (*LookupAppResult, error) {\n\tvar rv LookupAppResult\n\terr := ctx.Invoke(\"azure-native:iotcentral/v20180901:getApp\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func (k Keeper) SetApplication(ctx sdk.Context, application types.Application) {\n\tstore := ctx.KVStore(k.storeKey)\n\tbz := types.MustMarshalApplication(k.cdc, application)\n\tstore.Set(types.KeyForAppByAllApps(application.Address), bz)\n\tctx.Logger().Info(\"Setting App on Main Store \" + application.Address.String())\n\n}", "func (c Client) addAppToMerchant(merchantID string, appID string) error {\n\tdata := []byte(fmt.Sprintf(`{\"appId\":\"%s\"}`, appID))\n\tpath := fmt.Sprintf(\"/merchants/%s/apps\", merchantID)\n\treq, err := http.NewRequest(\"POST\", c.getURL(path), bytes.NewBuffer(data))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.executeRequestAndMarshal(req, nil)\n}", "func (m *ServicePrincipalRiskDetection) SetAppId(value *string)() {\n err := m.GetBackingStore().Set(\"appId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (client AzureAccountsClient) RemoveFromAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\tif azureAccountInfoObject != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(azureAccountInfoObject))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (_PermInterface *PermInterfaceTransactor) AssignAdminRole(opts *bind.TransactOpts, _orgId string, _account common.Address, _roleId string) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"assignAdminRole\", _orgId, _account, _roleId)\n}", "func (m *UserResource) AddApplicationTargetToAppAdminRoleForUser(ctx context.Context, userId string, roleId string, appName string, applicationId string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/users/%v/roles/%v/targets/catalog/apps/%v/%v\", userId, roleId, appName, applicationId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"PUT\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func (o OpenSignal) CreateAnApp(app App) (App, error) {\n\tstrResponse := App{}\n\n\tres, body, errs := o.Client.Post(createApp).\n\t\tSend(app).\n\t\tSet(\"Authorization\", \"Basic \"+o.AuthKey).\n\t\tEndStruct(&strResponse)\n\terr := catch(res, body)\n\tif err == nil {\n\t\tfor _, e := range errs {\n\t\t\tif e != nil {\n\t\t\t\terr = e\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn strResponse, err\n}", "func (s *AppServerV3) SetApp(app Application) error {\n\tappV3, ok := app.(*AppV3)\n\tif !ok {\n\t\treturn trace.BadParameter(\"expected *AppV3, got %T\", app)\n\t}\n\ts.Spec.App = appV3\n\treturn nil\n}", "func (details *UserAssignedIdentityDetails) AssignProperties_To_UserAssignedIdentityDetails(destination *v20220301s.UserAssignedIdentityDetails) error {\n\t// Clone the existing property bag\n\tpropertyBag := genruntime.NewPropertyBag(details.PropertyBag)\n\n\t// Reference\n\tdestination.Reference = details.Reference.Copy()\n\n\t// Update the property bag\n\tif len(propertyBag) > 0 {\n\t\tdestination.PropertyBag = propertyBag\n\t} else {\n\t\tdestination.PropertyBag = nil\n\t}\n\n\t// Invoke the augmentConversionForUserAssignedIdentityDetails interface (if implemented) to customize the conversion\n\tvar detailsAsAny any = details\n\tif augmentedDetails, ok := detailsAsAny.(augmentConversionForUserAssignedIdentityDetails); ok {\n\t\terr := augmentedDetails.AssignPropertiesTo(destination)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"calling augmented AssignPropertiesTo() for conversion\")\n\t\t}\n\t}\n\n\t// No error\n\treturn nil\n}", "func (o *GetClientConfigV1ConfigByNameParams) SetApp(app *string) {\n\to.App = app\n}", "func (_PermInterface *PermInterfaceTransactorSession) AssignAdminRole(_orgId string, _account common.Address, _roleId string) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AssignAdminRole(&_PermInterface.TransactOpts, _orgId, _account, _roleId)\n}", "func (m *User) SetAppRoleAssignments(value []AppRoleAssignmentable)() {\n m.appRoleAssignments = value\n}", "func (p *Proxy) InstallApp(in Incoming, cc apps.Context, appID apps.AppID, deployType apps.DeployType, trusted bool, secret string) (*apps.App, string, error) {\n\tconf, _, log := p.conf.Basic()\n\tlog = log.With(\"app_id\", appID)\n\tm, err := p.store.Manifest.Get(appID)\n\tif err != nil {\n\t\treturn nil, \"\", errors.Wrap(err, \"failed to find manifest to install app\")\n\t}\n\tif !m.SupportsDeploy(deployType) {\n\t\treturn nil, \"\", errors.Errorf(\"app does not support %s deployment\", deployType)\n\t}\n\terr = CanDeploy(p, deployType)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tapp, err := p.store.App.Get(appID)\n\tif err != nil {\n\t\tif !errors.Is(err, utils.ErrNotFound) {\n\t\t\treturn nil, \"\", errors.Wrap(err, \"failed looking for existing app\")\n\t\t}\n\t\tapp = &apps.App{}\n\t}\n\n\tapp.DeployType = deployType\n\tapp.Manifest = *m\n\tif app.Disabled {\n\t\tapp.Disabled = false\n\t}\n\tapp.GrantedPermissions = m.RequestedPermissions\n\tapp.GrantedLocations = m.RequestedLocations\n\tif secret != \"\" {\n\t\tapp.Secret = secret\n\t}\n\n\tif app.GrantedPermissions.Contains(apps.PermissionRemoteWebhooks) {\n\t\tapp.WebhookSecret = model.NewId()\n\t}\n\n\ticon, err := p.getAppIcon(*app)\n\tif err != nil {\n\t\treturn nil, \"\", errors.Wrap(err, \"failed get bot icon\")\n\t}\n\tif icon != nil {\n\t\tdefer icon.Close()\n\t}\n\n\t// See if the app is inaaccessible. Call its ping path with nothing\n\t// expanded, ignore 404 errors coming back and consider everything else a\n\t// \"success\".\n\t//\n\t// Note that this check is often ineffective, but \"the best we can do\"\n\t// before we start the diffcult-to-revert install process.\n\t_, err = p.callApp(in, *app, apps.CallRequest{\n\t\tCall: apps.DefaultPing,\n\t\tContext: cc,\n\t})\n\tif err != nil && errors.Cause(err) != utils.ErrNotFound {\n\t\treturn nil, \"\", errors.Wrapf(err, \"failed to install, %s path is not accessible\", apps.DefaultPing.Path)\n\t}\n\n\tasAdmin, err := p.getAdminClient(in)\n\tif err != nil {\n\t\treturn nil, \"\", errors.Wrap(err, \"failed to get an admin HTTP client\")\n\t}\n\terr = p.ensureBot(asAdmin, log, app, icon)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tif app.GrantedPermissions.Contains(apps.PermissionActAsUser) {\n\t\tvar oAuthApp *model.OAuthApp\n\t\toAuthApp, err = p.ensureOAuthApp(asAdmin, log, conf, *app, trusted, in.ActingUserID)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tapp.MattermostOAuth2.ClientID = oAuthApp.Id\n\t\tapp.MattermostOAuth2.ClientSecret = oAuthApp.ClientSecret\n\t\tapp.Trusted = trusted\n\t}\n\n\terr = p.store.App.Save(*app)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tmessage := fmt.Sprintf(\"Installed %s.\", app.DisplayName)\n\tif app.OnInstall != nil {\n\t\tcresp := p.call(in, *app, *app.OnInstall, &cc)\n\t\tif cresp.Type == apps.CallResponseTypeError {\n\t\t\t// TODO: should fail and roll back.\n\t\t\tlog.WithError(cresp).Warnf(\"Installed %s, despite on_install failure.\", app.AppID)\n\t\t\tmessage = fmt.Sprintf(\"Installed %s, despite on_install failure: %s\", app.AppID, cresp.Error())\n\t\t} else if cresp.Markdown != \"\" {\n\t\t\tmessage += \"\\n\\n\" + cresp.Markdown\n\t\t}\n\t} else if len(app.GrantedLocations) > 0 {\n\t\t// Make sure the app's binding call is accessible.\n\t\tcresp := p.call(in, *app, app.Bindings.WithDefault(apps.DefaultBindings), &cc)\n\t\tif cresp.Type == apps.CallResponseTypeError {\n\t\t\t// TODO: should fail and roll back.\n\t\t\tlog.WithError(cresp).Warnf(\"Installed %s, despite bindings failure.\", app.AppID)\n\t\t\tmessage = fmt.Sprintf(\"Installed %s despite bindings failure: %s\", app.AppID, cresp.Error())\n\t\t}\n\t}\n\n\tp.conf.Telemetry().TrackInstall(string(app.AppID), string(app.DeployType))\n\n\tp.dispatchRefreshBindingsEvent(in.ActingUserID)\n\n\tlog.Infof(message)\n\treturn app, message, nil\n}", "func CreateApplication(iq IQ, name, id, organizationID string) (string, error) {\n\tif name == \"\" || id == \"\" || organizationID == \"\" {\n\t\treturn \"\", fmt.Errorf(\"cannot create application with empty values\")\n\t}\n\n\tdoError := func(err error) (string, error) {\n\t\treturn \"\", fmt.Errorf(\"application '%s' not created: %v\", name, err)\n\t}\n\n\trequest, err := json.Marshal(iqNewAppRequest{Name: name, PublicID: id, OrganizationID: organizationID})\n\tif err != nil {\n\t\treturn doError(err)\n\t}\n\n\tbody, _, err := iq.Post(restApplication, bytes.NewBuffer(request))\n\tif err != nil {\n\t\treturn doError(err)\n\t}\n\n\tvar resp Application\n\tif err = json.Unmarshal(body, &resp); err != nil {\n\t\treturn doError(err)\n\t}\n\n\treturn resp.ID, nil\n}", "func deployApp(c Client, log utils.Logger, pd *DeployData, params DeployAppParams) (*DeployAppResult, error) {\n\tout := DeployAppResult{\n\t\tManifest: *pd.Manifest,\n\t}\n\n\terr := deployS3StaticAssets(c, log, pd, params, &out)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"can't save manifest fo the app %s to S3\", pd.Manifest.AppID)\n\t}\n\n\terr = deployLambdaFunctions(c, log, pd, params, &out)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"can't deploy functions of the app - %s\", pd.Manifest.AppID)\n\t}\n\n\terr = deployS3Manifest(c, log, pd, params, &out)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"can't save manifest fo the app %s to S3\", pd.Manifest.AppID)\n\t}\n\n\treturn &out, nil\n}", "func (m *ApplicationResource) ActivateApplication(ctx context.Context, appId string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/lifecycle/activate\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func (details *UserAssignedIdentityDetails) AssignProperties_To_UserAssignedIdentityDetails(destination *v20201201s.UserAssignedIdentityDetails) error {\n\t// Create a new property bag\n\tpropertyBag := genruntime.NewPropertyBag()\n\n\t// Reference\n\tdestination.Reference = details.Reference.Copy()\n\n\t// Update the property bag\n\tif len(propertyBag) > 0 {\n\t\tdestination.PropertyBag = propertyBag\n\t} else {\n\t\tdestination.PropertyBag = nil\n\t}\n\n\t// No error\n\treturn nil\n}", "func (application *VirtualApplication) AssignProperties_To_VirtualApplication(destination *v20220301s.VirtualApplication) error {\n\t// Clone the existing property bag\n\tpropertyBag := genruntime.NewPropertyBag(application.PropertyBag)\n\n\t// PhysicalPath\n\tdestination.PhysicalPath = genruntime.ClonePointerToString(application.PhysicalPath)\n\n\t// PreloadEnabled\n\tif application.PreloadEnabled != nil {\n\t\tpreloadEnabled := *application.PreloadEnabled\n\t\tdestination.PreloadEnabled = &preloadEnabled\n\t} else {\n\t\tdestination.PreloadEnabled = nil\n\t}\n\n\t// VirtualDirectories\n\tif application.VirtualDirectories != nil {\n\t\tvirtualDirectoryList := make([]v20220301s.VirtualDirectory, len(application.VirtualDirectories))\n\t\tfor virtualDirectoryIndex, virtualDirectoryItem := range application.VirtualDirectories {\n\t\t\t// Shadow the loop variable to avoid aliasing\n\t\t\tvirtualDirectoryItem := virtualDirectoryItem\n\t\t\tvar virtualDirectory v20220301s.VirtualDirectory\n\t\t\terr := virtualDirectoryItem.AssignProperties_To_VirtualDirectory(&virtualDirectory)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"calling AssignProperties_To_VirtualDirectory() to populate field VirtualDirectories\")\n\t\t\t}\n\t\t\tvirtualDirectoryList[virtualDirectoryIndex] = virtualDirectory\n\t\t}\n\t\tdestination.VirtualDirectories = virtualDirectoryList\n\t} else {\n\t\tdestination.VirtualDirectories = nil\n\t}\n\n\t// VirtualPath\n\tdestination.VirtualPath = genruntime.ClonePointerToString(application.VirtualPath)\n\n\t// Update the property bag\n\tif len(propertyBag) > 0 {\n\t\tdestination.PropertyBag = propertyBag\n\t} else {\n\t\tdestination.PropertyBag = nil\n\t}\n\n\t// Invoke the augmentConversionForVirtualApplication interface (if implemented) to customize the conversion\n\tvar applicationAsAny any = application\n\tif augmentedApplication, ok := applicationAsAny.(augmentConversionForVirtualApplication); ok {\n\t\terr := augmentedApplication.AssignPropertiesTo(destination)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"calling augmented AssignPropertiesTo() for conversion\")\n\t\t}\n\t}\n\n\t// No error\n\treturn nil\n}", "func (r *RepoStruct) SetApp(appRelName, appName string) (updated *bool, _ error) {\n\tif err := r.initApp(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tupdated = new(bool)\n\tif v, found := r.Apps[appRelName]; !found || (found && v != appName) {\n\t\t*updated = true\n\t}\n\tr.Apps[appRelName] = appName\n\n\tif set, err := r.SetInternalRelApp(appRelName, appName); set == nil {\n\t\treturn set, err\n\t}\n\treturn\n}", "func (t *Tracker) SetAppId(appId string) {\n\tt.AppId = appId\n}", "func CreateApp(a *App, units uint) error {\n\tif units == 0 {\n\t\treturn &ValidationError{Message: \"Cannot create app with 0 units.\"}\n\t}\n\tif !a.isValid() {\n\t\tmsg := \"Invalid app name, your app should have at most 63 \" +\n\t\t\t\"characters, containing only lower case letters or numbers, \" +\n\t\t\t\"starting with a letter.\"\n\t\treturn &ValidationError{Message: msg}\n\t}\n\tactions := []action{\n\t\tnew(insertApp),\n\t\tnew(createBucketIam),\n\t\tnew(createRepository),\n\t\tnew(provisionApp),\n\t}\n\treturn execute(a, actions, units)\n}", "func (details *UserAssignedIdentityDetails) AssignProperties_To_UserAssignedIdentityDetails(destination *v20210515s.UserAssignedIdentityDetails) error {\n\t// Create a new property bag\n\tpropertyBag := genruntime.NewPropertyBag()\n\n\t// Reference\n\tdestination.Reference = details.Reference.Copy()\n\n\t// Update the property bag\n\tif len(propertyBag) > 0 {\n\t\tdestination.PropertyBag = propertyBag\n\t} else {\n\t\tdestination.PropertyBag = nil\n\t}\n\n\t// No error\n\treturn nil\n}", "func (psc *PartitionSchedulingContext) AddSchedulingApplication(schedulingApp *SchedulingApplication) error {\n psc.lock.Lock()\n defer psc.lock.Unlock()\n\n // Add to applications\n appId := schedulingApp.ApplicationInfo.ApplicationId\n if psc.applications[appId] != nil {\n return fmt.Errorf(\"adding application %s to partition %s, but application already existed\", appId, psc.Name)\n }\n\n psc.applications[appId] = schedulingApp\n\n // Put app under queue\n schedulingQueue := psc.queues[schedulingApp.ApplicationInfo.QueueName]\n if schedulingQueue == nil {\n return fmt.Errorf(\"failed to find queue %s for application %s\", schedulingApp.ApplicationInfo.QueueName, appId)\n }\n schedulingApp.queue = schedulingQueue\n schedulingQueue.AddSchedulingApplication(schedulingApp)\n\n return nil\n}", "func (_PermInterface *PermInterfaceSession) AssignAdminRole(_orgId string, _account common.Address, _roleId string) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AssignAdminRole(&_PermInterface.TransactOpts, _orgId, _account, _roleId)\n}", "func (m *ApplicationSignInDetailedSummary) SetAppId(value *string)() {\n err := m.GetBackingStore().Set(\"appId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (i *IAM) createAIBObject(namespace, aibName, aiName string) runtime.Object {\n\t// Create an AIB object and assign attributes using input parameters\n\taib := aibv1.AzureIdentityBinding{}\n\n\taib.TypeMeta.Kind = \"AzureIdentityBinding\"\n\taib.TypeMeta.APIVersion = \"aadpodidentity.k8s.io/v1\"\n\taib.ObjectMeta.Namespace = namespace\n\taib.ObjectMeta.Name = aibName\n\taib.Spec.AzureIdentity = aiName\n\taib.Spec.Selector = i.azureIdentitySelector\n\n\t// Copy into a runtime.Object which is required for the api request\n\truntimeAib := aib.DeepCopyObject()\n\n\treturn runtimeAib\n}", "func (m *ApplicationResource) CreateApplicationGroupAssignment(ctx context.Context, appId string, groupId string, body ApplicationGroupAssignment) (*ApplicationGroupAssignment, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/groups/%v\", appId, groupId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"PUT\", url, body)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar applicationGroupAssignment *ApplicationGroupAssignment\n\n\tresp, err := rq.Do(ctx, req, &applicationGroupAssignment)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn applicationGroupAssignment, resp, nil\n}", "func SetAppName(name string) {\n\tappName = name\n}", "func (as *AppStorage) CreateApp(app model.AppData) (model.AppData, error) {\n\tres, ok := app.(*AppData)\n\tif !ok || res == nil {\n\t\treturn nil, model.ErrorWrongDataFormat\n\t}\n\tresult, err := as.addNewApp(res)\n\treturn result, err\n}", "func (o *DeeplinkApp) GetAppleAppEntitlementId() string {\n\tif o == nil || o.AppleAppEntitlementId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.AppleAppEntitlementId\n}", "func (o *RegenerateDeployKeyParams) SetAppName(appName string) {\n\to.AppName = appName\n}", "func NewApp(ctx *pulumi.Context,\n\tname string, args *AppArgs, opts ...pulumi.ResourceOption) (*App, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.AppType == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'AppType'\")\n\t}\n\tif args.DomainId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'DomainId'\")\n\t}\n\tif args.UserProfileName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'UserProfileName'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource App\n\terr := ctx.RegisterResource(\"aws-native:sagemaker:App\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (m *Group) SetAppRoleAssignments(value []AppRoleAssignmentable)() {\n m.appRoleAssignments = value\n}", "func (resource *ResourcesData) PushApplication(venAppName, spaceGUID string, parsedArguments *arguments.ParserArguments, v2Resources v2.Resources) error {\n\n\tui.Say(\"create application %s\", parsedArguments.AppName)\n\terr := resource.CreateApp(parsedArguments)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tui.Say(\"generate manifest without routes...\")\n\n\tui.Say(\"apply manifest file\")\n\terr = resource.AssignAppManifest(parsedArguments.NoRouteManifestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tui.Say(\"push application\")\n\terr = resource.PushApp(parsedArguments)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tui.Say(\"set health-check with type: %s for application %s\", parsedArguments.HealthCheckType, parsedArguments.AppName)\n\terr = resource.SetHealthCheck(parsedArguments.AppName, parsedArguments.HealthCheckType, parsedArguments.HealthCheckHTTPEndpoint, parsedArguments.InvocationTimeout, parsedArguments.Process)\n\tif err != nil {\n\t\treturn err\n\t}\n\tui.Ok()\n\n\treturn nil\n}", "func (c *applicationOperator) createApp(app *v1alpha1.HelmApplication, iconData string) (*v1alpha1.HelmApplication, error) {\n\texists, err := c.getHelmAppByName(app.GetWorkspace(), app.GetTrueName())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif exists != nil {\n\t\treturn nil, appItemExists\n\t}\n\tif strings.HasPrefix(iconData, \"http://\") || strings.HasPrefix(iconData, \"https://\") {\n\t\tapp.Spec.Icon = iconData\n\t} else if len(iconData) != 0 {\n\t\t// save icon attachment\n\t\ticonId := idutils.GetUuid(v1alpha1.HelmAttachmentPrefix)\n\t\tdecodeString, err := base64.StdEncoding.DecodeString(iconData)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"decodeString icon failed, error: %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\terr = c.backingStoreClient.Upload(iconId, iconId, bytes.NewBuffer(decodeString), len(iconData))\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"save icon attachment failed, error: %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tapp.Spec.Icon = iconId\n\t}\n\n\tapp, err = c.appClient.Create(context.TODO(), app, metav1.CreateOptions{})\n\treturn app, err\n}", "func NewAppleEnrollmentProfileAssignment()(*AppleEnrollmentProfileAssignment) {\n m := &AppleEnrollmentProfileAssignment{\n Entity: *NewEntity(),\n }\n return m\n}", "func (o *MicrosoftGraphAppIdentity) SetAppId(v string) {\n\to.AppId = &v\n}", "func (details *UserAssignedIdentityDetails) AssignProperties_To_UserAssignedIdentityDetails(destination *v1beta20220501s.UserAssignedIdentityDetails) error {\n\t// Create a new property bag\n\tpropertyBag := genruntime.NewPropertyBag()\n\n\t// Reference\n\tdestination.Reference = details.Reference.Copy()\n\n\t// Update the property bag\n\tif len(propertyBag) > 0 {\n\t\tdestination.PropertyBag = propertyBag\n\t} else {\n\t\tdestination.PropertyBag = nil\n\t}\n\n\t// No error\n\treturn nil\n}", "func CreateApp(\n\tctx context.Context,\n\tt *testing.T,\n\tf *framework.Framework,\n\tcleanupOpts *framework.CleanupOptions,\n\tnamespacedName types.NamespacedName,\n\tmatchLabels map[string]string,\n) appsv1.Deployment {\n\tt.Logf(\"Creating Deployment mock object '%#v'...\", namespacedName)\n\tns := namespacedName.Namespace\n\tappName := namespacedName.Name\n\n\td := mocks.DeploymentMock(ns, appName, matchLabels)\n\trequire.NoError(t, f.Client.Create(ctx, &d, cleanupOpts))\n\n\t// waiting for application deployment to reach one replica\n\tt.Log(\"Waiting for application deployment reach one replica...\")\n\trequire.NoError(\n\t\tt,\n\t\te2eutil.WaitForDeployment(t, f.KubeClient, ns, appName, 1, retryInterval, timeout),\n\t)\n\n\t// retrieveing deployment, to inspect its contents\n\tt.Logf(\"Reading application deployment '%s'\", appName)\n\trequire.NoError(t, f.Client.Get(ctx, namespacedName, &d))\n\n\treturn d\n}", "func (dal *DalNavElement) AssignToRole(ctx context.Context, tx *sql.Tx,\n\telementID, roleId string,\n) error {\n\trecord := goqu.Record{\n\t\tCoreNavElementRole.NerRoleID: elementID,\n\t\tCoreNavElementRole.NerNavElementID: roleId,\n\t}\n\tins := NewInsert(T.CoreNavElementRole).Rows(record)\n\t_, err := DoInsert(ctx, tx, ins)\n\tif err != nil {\n\t\tDebugErr(ctx, err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o AppOutput) AppArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *App) pulumi.StringOutput { return v.AppArn }).(pulumi.StringOutput)\n}", "func RegisterApp(appName, nodeURL, serverURL string) error {\n\tappBind := &types.InstanceBindings{\n\t\tNode: nodeURL,\n\t\tServer: serverURL,\n\t}\n\tappBindingJSON, err := json.Marshal(appBind)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = client.HSet(ApplicationKey, appName, appBindingJSON).Result()\n\treturn err\n}", "func (p *Pvr) InstallApplication(app *AppData) (err error) {\n\n\tapp.SquashFile = SQUASH_FILE\n\tappManifest, err := p.GetApplicationManifest(app.Appname)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttargetApp := *app\n\ttargetManifest := appManifest\n\tif appManifest.Base != \"\" {\n\t\ttargetManifest, err = p.GetApplicationManifest(appManifest.Base)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttargetApp.Appmanifest = targetManifest\n\t\ttargetApp.Appname = appManifest.Base\n\t\ttargetApp.Base = \"\"\n\t}\n\n\tdockerName := targetManifest.DockerName\n\trepoDigest := targetManifest.DockerDigest\n\n\ttargetApp.From = repoDigest\n\tif targetApp.Source == \"remote\" && !strings.Contains(repoDigest, \"@\") {\n\t\ttargetApp.From = dockerName + \"@\" + repoDigest\n\t}\n\n\tswitch targetApp.SourceType {\n\tcase models.SourceTypeDocker:\n\t\terr = InstallDockerApp(p, &targetApp, targetManifest)\n\tcase models.SourceTypeRootFs:\n\t\terr = InstallRootFsApp(p, &targetApp, targetManifest)\n\tcase models.SourceTypePvr:\n\t\terr = InstallPVApp(p, &targetApp, targetManifest)\n\tdefault:\n\t\treturn fmt.Errorf(\"type %s not supported yet\", models.SourceTypePvr)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if we have ovl digest we go for it ...\n\tif appManifest.DockerOvlDigest != \"\" || appManifest.Base != \"\" {\n\t\tappManifest, err = p.GetApplicationManifest(app.Appname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tapp.SquashFile = SQUASH_OVL_FILE\n\n\t\trepoDigest = appManifest.DockerOvlDigest\n\t\tapp.From = repoDigest\n\t\tif app.Source == \"remote\" && !strings.Contains(repoDigest, \"@\") {\n\t\t\tapp.From = dockerName + \"@\" + repoDigest\n\t\t}\n\n\t\tswitch app.SourceType {\n\t\tcase models.SourceTypeDocker:\n\t\t\terr = InstallDockerApp(p, app, appManifest)\n\t\tcase models.SourceTypeRootFs:\n\t\t\terr = InstallRootFsApp(p, app, appManifest)\n\t\tcase models.SourceTypePvr:\n\t\t\terr = InstallPVApp(p, app, appManifest)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"type %s not supported yet\", models.SourceTypePvr)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdiff, err := p.Diff()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// skip updating dm if nothing changed really ...\n\tif diff != nil && len(*diff) == 2 {\n\t\treturn nil\n\t}\n\n\tif appManifest.DmEnabled != nil {\n\t\terr = p.DmCVerityApply(app.Appname)\n\t}\n\n\treturn err\n}", "func (m *AndroidManagedStoreApp) SetAppIdentifier(value *string)() {\n err := m.GetBackingStore().Set(\"appIdentifier\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *AssignPostRequestBody) SetMobileAppAssignments(value []iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.MobileAppAssignmentable)() {\n m.mobileAppAssignments = value\n}", "func (s *Service) CreateAppid(appid string) error {\n\treturn s.d.CreateAppid(context.Background(), appid)\n}", "func (tc TeresaClient) GetAppInfo(teamName, appName string) (appInfo AppInfo) {\n\tme, err := tc.Me()\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to get user information: %s\", err)\n\t}\n\tif len(me.Teams) > 1 && teamName == \"\" {\n\t\tlog.Fatalln(\"User is in more than one team and provided none\")\n\t}\n\tfor _, t := range me.Teams {\n\t\tif teamName == \"\" || *t.Name == teamName {\n\t\t\tappInfo.TeamID = t.ID\n\t\t\tfor _, a := range t.Apps {\n\t\t\t\tif *a.Name == appName {\n\t\t\t\t\tappInfo.AppID = a.ID\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tif appInfo.TeamID == 0 || appInfo.AppID == 0 {\n\t\tlog.Fatalf(\"Invalid Team [%s] or App [%s]\\n\", teamName, appName)\n\t}\n\treturn\n}", "func (r a) Assign(company string, team string, engagement string, params map[string]string) (*http.Response, []byte) {\n return r.client.Put(\"/otask/v1/tasks/companies/\" + company + \"/teams/\" + team + \"/engagements/\" + engagement + \"/tasks\", params)\n}", "func (m *EducationAssignment) SetAssignTo(value EducationAssignmentRecipientable)() {\n m.assignTo = value\n}", "func (client AppsClient) Add(ctx context.Context, applicationCreateObject ApplicationCreateObject) (result UUID, err error) {\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: applicationCreateObject,\n\t\t\tConstraints: []validation.Constraint{{Target: \"applicationCreateObject.Culture\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t{Target: \"applicationCreateObject.Name\", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"programmatic.AppsClient\", \"Add\", err.Error())\n\t}\n\n\treq, err := client.AddPreparer(ctx, applicationCreateObject)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.AppsClient\", \"Add\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.AddSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.AppsClient\", \"Add\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.AddResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.AppsClient\", \"Add\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (mr *MockprojectDeployerMockRecorder) AddAppToProject(project, appName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddAppToProject\", reflect.TypeOf((*MockprojectDeployer)(nil).AddAppToProject), project, appName)\n}", "func CallAssignMapTask() MapTaskData {\n\treply := MapTaskData{}\n\n\tif ok := call(\"Master.AssignMapTask\", \"\", &reply); !ok {\n\t\tlog.Fatalln(\"Error running map task\")\n\t}\n\treturn reply\n}", "func (lgtv *Client) SubscribeApp(h func(AppInfo)) error {\n\treturn lgtv.subscribe(uriAppGet, func(payload json.RawMessage) {\n\t\tp := AppInfo{}\n\t\tif err := json.Unmarshal(payload, &p); err != nil {\n\t\t\tlog.Printf(\"Could not unmarshal app info update \\\"%s\\\": %s\", string(payload), err)\n\t\t} else {\n\t\t\th(p)\n\t\t}\n\t})\n}", "func AppCreate(ctx *Context, name string, typ DeviceType) (*Application, error) {\n\th := authHeader(ctx.Config.AuthToken)\n\turi := ctx.Config.APIEndpoint(\"application\")\n\tdata := make(map[string]interface{})\n\tdata[\"app_name\"] = name\n\tdata[\"device_type\"] = typ.String()\n\tbody, err := marhsalReader(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := doJSON(ctx, \"POST\", uri, h, nil, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trst := &Application{}\n\terr = json.Unmarshal(b, rst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rst, nil\n}", "func CreateApp(env env.Project, appJson, appDir, appName, vendorDir, constraints string) error {\n\treturn doCreate(env, appJson, appDir, appName, vendorDir, constraints)\n}", "func (d *InMemoryTaskDB) AssignId(_ context.Context, t *types.Task) error {\n\tif t.Id != \"\" {\n\t\treturn fmt.Errorf(\"Task Id already assigned: %v\", t.Id)\n\t}\n\tt.Id = uuid.New().String()\n\treturn nil\n}" ]
[ "0.6451236", "0.6322245", "0.6296271", "0.5685041", "0.53162926", "0.52507275", "0.52359843", "0.49754086", "0.4878812", "0.48281038", "0.4737655", "0.46844086", "0.46481755", "0.45860133", "0.45652634", "0.45574507", "0.4554541", "0.4484046", "0.44671705", "0.44337445", "0.43990424", "0.4391265", "0.43887058", "0.43754384", "0.43517426", "0.4342779", "0.4322251", "0.43153942", "0.43087822", "0.4293081", "0.42808712", "0.4261233", "0.4251742", "0.42423534", "0.42411193", "0.42394122", "0.42191595", "0.42189747", "0.4215711", "0.42067513", "0.42045298", "0.42033046", "0.41986597", "0.41933677", "0.4191826", "0.4168371", "0.4159993", "0.4158814", "0.41579294", "0.41272476", "0.41271448", "0.41233525", "0.4117354", "0.4114934", "0.41089246", "0.4107625", "0.41041142", "0.4098695", "0.40961134", "0.4093658", "0.4093247", "0.4092982", "0.40898916", "0.40872425", "0.40866584", "0.4083632", "0.4081243", "0.40740383", "0.40721315", "0.40706873", "0.4068066", "0.40670824", "0.4065532", "0.40611356", "0.40601698", "0.4051752", "0.40476122", "0.40441254", "0.4040064", "0.40386114", "0.40137917", "0.401196", "0.4001974", "0.39863896", "0.3985777", "0.39843026", "0.39732918", "0.3970619", "0.3961757", "0.3956202", "0.3947629", "0.3941641", "0.39323622", "0.39268884", "0.3926474", "0.39252722", "0.3919221", "0.39149272", "0.3911373", "0.39113477" ]
0.8379583
0
AssignToAppPreparer prepares the AssignToApp request.
func (client AzureAccountsClient) AssignToAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) { urlParameters := map[string]interface{}{ "Endpoint": client.Endpoint, } pathParameters := map[string]interface{}{ "appId": autorest.Encode("path", appID), } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithCustomBaseURL("{Endpoint}/luis/api/v2.0", urlParameters), autorest.WithPathParameters("/apps/{appId}/azureaccounts", pathParameters)) if azureAccountInfoObject != nil { preparer = autorest.DecoratePreparer(preparer, autorest.WithJSON(azureAccountInfoObject)) } return preparer.Prepare((&http.Request{}).WithContext(ctx)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client ManagementClient) GetAppsPreparer(hostName string, filter string, top *int32, selectParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostName\": autorest.Encode(\"path\", hostName),\n\t}\n\n\tconst APIVersion = \"2015-01-14-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Intune/locations/{hostName}/apps\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client AppsClient) AddPreparer(ctx context.Context, applicationCreateObject ApplicationCreateObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/apps/\"),\n\t\tautorest.WithJSON(applicationCreateObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (alr AppListResult) appListResultPreparer() (*http.Request, error) {\n\tif alr.NextLink == nil || len(to.String(alr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(alr.NextLink)))\n}", "func (client AzureAccountsClient) AssignToAppSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AzureAccountsClient) AssignToAppResponder(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.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client AppsClient) PublishPreparer(ctx context.Context, appID uuid.UUID, applicationPublishObject ApplicationPublishObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/publish\", pathParameters),\n\t\tautorest.WithJSON(applicationPublishObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppsClient) UpdatePreparer(ctx context.Context, appID uuid.UUID, applicationUpdateObject ApplicationUpdateObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPut(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}\", pathParameters),\n\t\tautorest.WithJSON(applicationUpdateObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func PrepareApp(env env.Project, options *PrepareOptions) error {\n\treturn doPrepare(env, options)\n}", "func (client AppListResult) AppListResultPreparer() (*http.Request, error) {\r\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\r\n\t\treturn nil, nil\r\n\t}\r\n\treturn autorest.Prepare(&http.Request{},\r\n\t\tautorest.AsJSON(),\r\n\t\tautorest.AsGet(),\r\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\r\n}", "func (client AppsClient) ImportPreparer(ctx context.Context, luisApp LuisApp, appName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tqueryParameters := map[string]interface{}{}\n\tif len(appName) > 0 {\n\t\tqueryParameters[\"appName\"] = autorest.Encode(\"query\", appName)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/apps/import\"),\n\t\tautorest.WithJSON(luisApp),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func prepareApp(p *stage1commontypes.Pod, ra *schema.RuntimeApp) (*preparedApp, error) {\n\tpa := preparedApp{\n\t\tapp: ra,\n\t\tenv: ra.App.Environment,\n\t\tnoNewPrivileges: getAppNoNewPrivileges(ra.App.Isolators),\n\t}\n\tvar err error\n\n\t// Determine numeric uid and gid\n\tu, g, err := parseUserGroup(p, ra)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(errors.New(\"unable to determine app's uid and gid\"), err)\n\t}\n\tif u < 0 || g < 0 {\n\t\treturn nil, errors.New(\"Invalid uid or gid\")\n\t}\n\tpa.uid = uint32(u)\n\tpa.gid = uint32(g)\n\n\t// Set some rkt-provided environment variables\n\tpa.env.Set(\"AC_APP_NAME\", ra.Name.String())\n\tif p.MetadataServiceURL != \"\" {\n\t\tpa.env.Set(\"AC_METADATA_URL\", p.MetadataServiceURL)\n\t}\n\n\t// Determine capability set\n\tpa.capabilities, err = getAppCapabilities(ra.App.Isolators)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(errors.New(\"unable to construct capabilities\"), err)\n\t}\n\n\t// Determine mounts\n\tcfd := ConvertedFromDocker(p.Images[ra.Name.String()])\n\tpa.mounts, err = GenerateMounts(ra, p.Manifest.Volumes, cfd)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(errors.New(\"unable to compute mounts\"), err)\n\t}\n\n\t// Compute resources\n\tpa.resources, err = computeAppResources(ra.App.Isolators)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(errors.New(\"unable to compute resources\"), err)\n\t}\n\n\t// Protect kernel tunables by default\n\tif !p.InsecureOptions.DisablePaths {\n\t\tpa.roPaths = append(pa.roPaths, protectKernelROPaths...)\n\t\tpa.hiddenPaths = append(pa.hiddenDirs, protectKernelHiddenPaths...)\n\t\tpa.hiddenDirs = append(pa.hiddenDirs, protectKernelHiddenDirs...)\n\t}\n\n\t// Seccomp\n\tif !p.InsecureOptions.DisableSeccomp {\n\t\tpa.seccomp, err = generateSeccompFilter(p, &pa)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif pa.seccomp != nil && pa.seccomp.forceNoNewPrivileges {\n\t\t\tpa.noNewPrivileges = true\n\t\t}\n\t}\n\n\t// Write the systemd-sysusers config file\n\tif err := generateSysusers(p, pa.app, int(pa.uid), int(pa.gid), &p.UidRange); err != nil {\n\t\treturn nil, errwrap.Wrapf(\"unable to generate sysusers file\", err)\n\t}\n\n\treturn &pa, nil\n}", "func (client ApplicationsClient) AddOwnerPreparer(ctx context.Context, applicationObjectID string, parameters AddOwnerParameters) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}/$links/owners\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AzureAccountsClient) RemoveFromAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\tif azureAccountInfoObject != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(azureAccountInfoObject))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (aclr AppCollectionListResult) appCollectionListResultPreparer() (*http.Request, error) {\n\tif aclr.NextLink == nil || len(to.String(aclr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(aclr.NextLink)))\n}", "func (client ApplicationsClient) CreatePreparer(ctx context.Context, parameters ApplicationCreateParameters) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\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.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DeploymentsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}\", pathParameters),\n\t\tautorest.WithJSON(deploymentResource),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppCollectionListResult) AppCollectionListResultPreparer() (*http.Request, error) {\r\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\r\n\t\treturn nil, nil\r\n\t}\r\n\treturn autorest.Prepare(&http.Request{},\r\n\t\tautorest.AsJSON(),\r\n\t\tautorest.AsGet(),\r\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\r\n}", "func (client ApplicationsClient) PatchPreparer(ctx context.Context, applicationObjectID string, parameters ApplicationUpdateParameters) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppsClient) GetPreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ApplicationsClient) GetPreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AzureAccountsClient) GetAssignedPreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AzureAccountsClient) AssignToApp(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (result OperationStatus, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.AssignToApp\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: azureAccountInfoObject,\n\t\t\tConstraints: []validation.Constraint{{Target: \"azureAccountInfoObject\", Name: validation.Null, Rule: false,\n\t\t\t\tChain: []validation.Constraint{{Target: \"azureAccountInfoObject.AzureSubscriptionID\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.ResourceGroup\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.AccountName\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t}}}}}); err != nil {\n\t\treturn result, validation.NewError(\"authoring.AzureAccountsClient\", \"AssignToApp\", err.Error())\n\t}\n\n\treq, err := client.AssignToAppPreparer(ctx, appID, azureAccountInfoObject)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.AssignToAppSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.AssignToAppResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (m *EmbeddedSIMActivationCodePoolsEmbeddedSIMActivationCodePoolItemRequestBuilder) Assign()(*EmbeddedSIMActivationCodePoolsItemAssignRequestBuilder) {\n return NewEmbeddedSIMActivationCodePoolsItemAssignRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (client ManagementClient) GetMAMUserFlaggedEnrolledAppsPreparer(hostName string, userName string, filter string, top *int32, selectParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostName\": autorest.Encode(\"path\", hostName),\n\t\t\"userName\": autorest.Encode(\"path\", userName),\n\t}\n\n\tconst APIVersion = \"2015-01-14-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Intune/locations/{hostName}/flaggedUsers/{userName}/flaggedEnrolledApps\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (alr AssignmentListResult) assignmentListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !alr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(alr.NextLink)))\n}", "func (ral RegistrationAssignmentList) registrationAssignmentListPreparer(ctx context.Context) (*http.Request, error) {\n\tif !ral.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(ral.NextLink)))\n}", "func (client ApplicationsClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\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\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *UnifiedRoleAssignmentScheduleRequest) SetAppScope(value AppScopeable)() {\n m.appScope = value\n}", "func (client JobClient) ApprovePreparer(ctx context.Context, resourceGroupName string, accountName string, jobName string, body *JobUserActionDescription) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"jobName\": jobName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPost(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/jobs/{jobName}/approve\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n if body != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(body))\n }\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client DeploymentsClient) StartPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/start\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *DeviceConfigurationItemRequestBuilder) Assign()(*i4cd13eb5be3949210a98b3e74a48e803b388b1057dc5b76fa296250220177115.AssignRequestBuilder) {\n return i4cd13eb5be3949210a98b3e74a48e803b388b1057dc5b76fa296250220177115.NewAssignRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (client DeploymentsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, version []string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif version != nil && len(version) > 0 {\n\t\tqueryParameters[\"version\"] = version\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppsClient) ListPreparer(ctx context.Context, skip *int32, take *int32) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tqueryParameters := map[string]interface{}{}\n\tif skip != nil {\n\t\tqueryParameters[\"skip\"] = autorest.Encode(\"query\", *skip)\n\t} else {\n\t\tqueryParameters[\"skip\"] = autorest.Encode(\"query\", 0)\n\t}\n\tif take != nil {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", *take)\n\t} else {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", 100)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/apps/\"),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *EducationAssignmentItemRequestBuilder) SetUpResourcesFolder()(*ic8a76de5ffb5d6e2de378abe7f4341d25a11d4ea88cad7b35c31b72f63d17e7a.SetUpResourcesFolderRequestBuilder) {\n return ic8a76de5ffb5d6e2de378abe7f4341d25a11d4ea88cad7b35c31b72f63d17e7a.NewSetUpResourcesFolderRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (client ApplicationsClient) ListOwnersPreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}/owners\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DeploymentsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPut(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}\", pathParameters),\n\t\tautorest.WithJSON(deploymentResource),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DeploymentsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ModelClient) AddIntentPreparer(ctx context.Context, appID uuid.UUID, versionID string, intentCreateObject ModelCreateObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/intents\", pathParameters),\n\t\tautorest.WithJSON(intentCreateObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *EntitlementManagementRoleAssignmentSchedulesUnifiedRoleAssignmentScheduleItemRequestBuilder) AppScope()(*EntitlementManagementRoleAssignmentSchedulesItemAppScopeRequestBuilder) {\n return NewEntitlementManagementRoleAssignmentSchedulesItemAppScopeRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (m *IntentsDeviceManagementIntentItemRequestBuilder) Assign()(*IntentsItemAssignRequestBuilder) {\n return NewIntentsItemAssignRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func PrepareApp() {\n\tdir.SetChangePermission(!DryRun)\n\tif DryRun {\n\t\tlogger.Verbose = true\n\t}\n}", "func (c *jsiiProxy_CfnApp) Prepare() {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"prepare\",\n\t\tnil, // no parameters\n\t)\n}", "func (m *ManagedEBooksManagedEBookItemRequestBuilder) Assign()(*ManagedEBooksItemAssignRequestBuilder) {\n return NewManagedEBooksItemAssignRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (client AppsClient) UpdateSettingsPreparer(ctx context.Context, appID uuid.UUID, applicationSettingUpdateObject ApplicationSettingUpdateObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPut(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/settings\", pathParameters),\n\t\tautorest.WithJSON(applicationSettingUpdateObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *ApplicationResource) AssignUserToApplication(ctx context.Context, appId string, body AppUser) (*AppUser, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/users\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"POST\", url, body)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar appUser *AppUser\n\n\tresp, err := rq.Do(ctx, req, &appUser)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn appUser, resp, nil\n}", "func (client AppsClient) DeletePreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client RoleAssignmentScheduleRequestsClient) CreatePreparer(ctx context.Context, scope string, roleAssignmentScheduleRequestName string, parameters RoleAssignmentScheduleRequest) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"roleAssignmentScheduleRequestName\": autorest.Encode(\"path\", roleAssignmentScheduleRequestName),\n\t\t\"scope\": scope,\n\t}\n\n\tconst APIVersion = \"2020-10-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tparameters.ID = nil\n\tparameters.Name = nil\n\tparameters.Type = nil\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(\"/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppsClient) GetSettingsPreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/settings\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DeploymentsClient) RestartPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/restart\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *EnterpriseAppsItemRoleAssignmentsUnifiedRoleAssignmentItemRequestBuilder) AppScope()(*EnterpriseAppsItemRoleAssignmentsItemAppScopeRequestBuilder) {\n return NewEnterpriseAppsItemRoleAssignmentsItemAppScopeRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (client ModelClient) AddPrebuiltPreparer(ctx context.Context, appID uuid.UUID, versionID string, prebuiltExtractorNames []string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/prebuilts\", pathParameters),\n\t\tautorest.WithJSON(prebuiltExtractorNames))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func NewMobileAppAssignmentItemRequestBuilderInternal(pathParameters map[string]string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*MobileAppAssignmentItemRequestBuilder) {\n m := &MobileAppAssignmentItemRequestBuilder{\n }\n m.urlTemplate = \"{+baseurl}/deviceAppManagement/mobileApps/{mobileApp%2Did}/assignments/{mobileAppAssignment%2Did}{?%24select,%24expand}\";\n urlTplParams := make(map[string]string)\n for idx, item := range pathParameters {\n urlTplParams[idx] = item\n }\n m.pathParameters = urlTplParams;\n m.requestAdapter = requestAdapter;\n return m\n}", "func (rmpalr RoleManagementPolicyAssignmentListResult) roleManagementPolicyAssignmentListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !rmpalr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(rmpalr.NextLink)))\n}", "func (m *VirtualEndpointUserSettingsCloudPcUserSettingItemRequestBuilder) Assign()(*VirtualEndpointUserSettingsItemAssignRequestBuilder) {\n return NewVirtualEndpointUserSettingsItemAssignRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (client ModelClient) UpdateIntentPreparer(ctx context.Context, appID uuid.UUID, versionID string, intentID uuid.UUID, modelUpdateObject ModelUpdateObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"intentId\": autorest.Encode(\"path\", intentID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPut(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/intents/{intentId}\", pathParameters),\n\t\tautorest.WithJSON(modelUpdateObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ModelClient) AddCustomPrebuiltIntentPreparer(ctx context.Context, appID uuid.UUID, versionID string, prebuiltDomainModelCreateObject PrebuiltDomainModelCreateObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/customprebuiltintents\", pathParameters),\n\t\tautorest.WithJSON(prebuiltDomainModelCreateObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client MSIXPackagesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, hostPoolName string, msixPackageFullName string, msixPackage *MSIXPackagePatch) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostPoolName\": autorest.Encode(\"path\", hostPoolName),\n\t\t\"msixPackageFullName\": autorest.Encode(\"path\", msixPackageFullName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-09-21-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages/{msixPackageFullName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\tif msixPackage != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(msixPackage))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (rpoc ResourceProviderOperationCollection) resourceProviderOperationCollectionPreparer(ctx context.Context) (*http.Request, error) {\n\tif !rpoc.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(rpoc.NextLink)))\n}", "func (client DeploymentsClient) EnableRemoteDebuggingPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, remoteDebuggingPayload *RemoteDebuggingPayload) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/enableRemoteDebugging\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\tif remoteDebuggingPayload != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(remoteDebuggingPayload))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (rnr *Runner) Preparer(l logger.Logger) (preparer.Preparer, error) {\n\n\t// NOTE: We have a good generic preparer so we'll provide that here\n\n\tl.Debug(\"** Preparer **\")\n\n\t// Return the existing preparer if we already have one\n\tif rnr.Prepare != nil {\n\t\tl.Debug(\"Returning existing preparer\")\n\t\treturn rnr.Prepare, nil\n\t}\n\n\tl.Debug(\"Creating new preparer\")\n\n\tp, err := prepare.NewPrepare(l)\n\tif err != nil {\n\t\tl.Warn(\"Failed new prepare >%v<\", err)\n\t\treturn nil, err\n\t}\n\n\tdb, err := rnr.Store.GetDb()\n\tif err != nil {\n\t\tl.Warn(\"Failed getting database handle >%v<\", err)\n\t\treturn nil, err\n\t}\n\n\terr = p.Init(db)\n\tif err != nil {\n\t\tl.Warn(\"Failed preparer init >%v<\", err)\n\t\treturn nil, err\n\t}\n\n\trnr.Prepare = p\n\n\treturn p, nil\n}", "func (r *ResourceRequestReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\t// generate the predicate to filter just the ResourceRequest created by the remote cluster checking crdReplicator labels\n\tp, err := predicate.LabelSelectorPredicate(crdreplicator.ReplicatedResourcesLabelSelector)\n\tif err != nil {\n\t\tklog.Error(err)\n\t\treturn err\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&discoveryv1alpha1.ResourceRequest{}, builder.WithPredicates(p)).\n\t\tOwns(&sharingv1alpha1.ResourceOffer{}).\n\t\tComplete(r)\n}", "func (cmc ConsortiumMemberCollection) consortiumMemberCollectionPreparer(ctx context.Context) (*http.Request, error) {\n\tif !cmc.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(cmc.NextLink)))\n}", "func (ralr RoleAssignmentListResult) roleAssignmentListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !ralr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(ralr.NextLink)))\n}", "func (client ApplicationsClient) DeletePreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func setupPreparers(fixture consultest.Fixture) {\n\tfor _, node := range testNodes {\n\t\tkey := fmt.Sprintf(\"reality/%s/p2-preparer\", node)\n\t\tfixture.SetKV(key, []byte(testPreparerManifest))\n\t}\n}", "func (m *AppConsentApprovalRoute) SetAppConsentRequests(value []AppConsentRequestable)() {\n m.appConsentRequests = value\n}", "func (client ServicesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}\", pathParameters),\n\t\tautorest.WithJSON(resource),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (e *jsiiProxy_EcsApplication) Prepare() {\n\t_jsii_.InvokeVoid(\n\t\te,\n\t\t\"prepare\",\n\t\tnil, // no parameters\n\t)\n}", "func AddToRequest(app *App) server.PreHandlerFunc {\n\treturn func(req *http.Request) *http.Request {\n\t\tnewCtx := With(req.Context(), app)\n\t\treturn req.Clone(newCtx)\n\t}\n}", "func (client ContainerAppsRevisionsClient) ActivateRevisionPreparer(ctx context.Context, resourceGroupName string, containerAppName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"containerAppName\": autorest.Encode(\"path\", containerAppName),\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2021-03-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/containerApps/{containerAppName}/revisions/{name}/activate\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AccountClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, body AccountResourcePatchDescription) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPatch(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}\",pathParameters),\nautorest.WithJSON(body),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (c *jsiiProxy_CfnApplication) Prepare() {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"prepare\",\n\t\tnil, // no parameters\n\t)\n}", "func (c *jsiiProxy_CfnApplication) Prepare() {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"prepare\",\n\t\tnil, // no parameters\n\t)\n}", "func (s *Server) ensureApp(ctx context.Context, wroute *models.RouteWrapper, method string) error {\n\tapp, err := s.Datastore.GetApp(ctx, wroute.Route.AppName)\n\tif err != nil && err != models.ErrAppsNotFound {\n\t\treturn err\n\t} else if app == nil {\n\t\t// Create a new application\n\t\tnewapp := &models.App{Name: wroute.Route.AppName}\n\t\tif err = newapp.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = s.FireBeforeAppCreate(ctx, newapp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = s.Datastore.InsertApp(ctx, newapp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = s.FireAfterAppCreate(ctx, newapp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\treturn nil\n}", "func (client ModelClient) ListPrebuiltEntitiesPreparer(ctx context.Context, appID uuid.UUID, versionID string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/listprebuilts\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (cplr ComputePolicyListResult) computePolicyListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif cplr.NextLink == nil || len(to.String(cplr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(cplr.NextLink)))\n}", "func Prepare(deployment DeploymentOptions) (PrepareResult, error) {\n\tif deployment.IsCloud() {\n\t\treturn PrepareResult{}, fmt.Errorf(\"prepare is not supported with %s target\", deployment.Target.Type())\n\t}\n\tsessionURL, err := deployment.url(\"/application/v2/tenant/default/session\")\n\tif err != nil {\n\t\treturn PrepareResult{}, err\n\t}\n\tresult, err := uploadApplicationPackage(sessionURL, deployment)\n\tif err != nil {\n\t\treturn PrepareResult{}, err\n\t}\n\tprepareURL, err := deployment.url(fmt.Sprintf(\"/application/v2/tenant/default/session/%d/prepared\", result.ID))\n\tif err != nil {\n\t\treturn PrepareResult{}, err\n\t}\n\treq, err := http.NewRequest(\"PUT\", prepareURL.String(), nil)\n\tif err != nil {\n\t\treturn PrepareResult{}, err\n\t}\n\tserviceDescription := \"Deploy service\"\n\tresponse, err := deployment.HTTPClient.Do(req, time.Second*30)\n\tif err != nil {\n\t\treturn PrepareResult{}, err\n\t}\n\tdefer response.Body.Close()\n\tif err := checkResponse(req, response, serviceDescription); err != nil {\n\t\treturn PrepareResult{}, err\n\t}\n\treturn result, nil\n}", "func (cr *cmdRunner) prep(req storage.ScmPrepareRequest, scanRes *storage.ScmScanResponse) (resp *storage.ScmPrepareResponse, err error) {\n\tstate := scanRes.State\n\tresp = &storage.ScmPrepareResponse{State: state}\n\n\tcr.log.Debugf(\"scm backend prep: state %q\", state)\n\n\tif err = cr.deleteGoals(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Handle unspecified NrNamespacesPerSocket in request.\n\tif req.NrNamespacesPerSocket == 0 {\n\t\treq.NrNamespacesPerSocket = minNrNssPerSocket\n\t}\n\n\tswitch state {\n\tcase storage.ScmStateNotInterleaved:\n\t\t// Non-interleaved AppDirect memory mode is unsupported.\n\t\terr = storage.FaultScmNotInterleaved\n\tcase storage.ScmStateNoRegions:\n\t\t// No regions exist, create interleaved AppDirect PMem regions.\n\t\tif err = cr.createRegions(); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tresp.RebootRequired = true\n\tcase storage.ScmStateFreeCapacity:\n\t\t// Regions exist but no namespaces, create block devices on PMem regions.\n\t\tresp.Namespaces, err = cr.createNamespaces(req.NrNamespacesPerSocket)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tresp.State = storage.ScmStateNoFreeCapacity\n\tcase storage.ScmStateNoFreeCapacity:\n\t\t// Regions and namespaces exist so sanity check number of namespaces matches the\n\t\t// number requested before returning details.\n\t\tvar regionFreeBytes []uint64\n\t\tregionFreeBytes, err = cr.getRegionFreeSpace()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tnrRegions := uint(len(regionFreeBytes))\n\t\tnrNamespaces := uint(len(scanRes.Namespaces))\n\n\t\t// Assume 1:1 mapping between region and NUMA node.\n\t\tif (nrRegions * req.NrNamespacesPerSocket) != nrNamespaces {\n\t\t\terr = storage.FaultScmNamespacesNrMismatch(req.NrNamespacesPerSocket,\n\t\t\t\tnrRegions, nrNamespaces)\n\t\t\tbreak\n\t\t}\n\t\tresp.Namespaces = scanRes.Namespaces\n\tdefault:\n\t\terr = errors.Errorf(\"unhandled scm state %q\", state)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (dpmlr DataPolicyManifestListResult) dataPolicyManifestListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !dpmlr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(dpmlr.NextLink)))\n}", "func (client DeploymentsClient) DisableRemoteDebuggingPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/disableRemoteDebugging\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func NewAssignmentPoliciesRequestBuilderInternal(pathParameters map[string]string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*AssignmentPoliciesRequestBuilder) {\n m := &AssignmentPoliciesRequestBuilder{\n }\n m.urlTemplate = \"{+baseurl}/identityGovernance/entitlementManagement/assignmentPolicies{?%24top,%24skip,%24search,%24filter,%24count,%24orderby,%24select,%24expand}\";\n urlTplParams := make(map[string]string)\n for idx, item := range pathParameters {\n urlTplParams[idx] = item\n }\n m.pathParameters = urlTplParams;\n m.requestAdapter = requestAdapter;\n return m\n}", "func (client AccountQuotaPolicyClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, policyName string, body AccountQuotaPolicyResourcePatchDescription) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"policyName\": policyName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPatch(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/accountQuotaPolicies/{policyName}\",pathParameters),\nautorest.WithJSON(body),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func InitTaskManagerApp(a TaskManagerApp) {\n\ttaskManagerApp = a\n}", "func NewEntitlementManagementAccessPackageAssignmentPoliciesRequestBuilderInternal(pathParameters map[string]string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*EntitlementManagementAccessPackageAssignmentPoliciesRequestBuilder) {\n m := &EntitlementManagementAccessPackageAssignmentPoliciesRequestBuilder{\n BaseRequestBuilder: *i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.NewBaseRequestBuilder(requestAdapter, \"{+baseurl}/identityGovernance/entitlementManagement/accessPackageAssignmentPolicies{?%24top,%24skip,%24search,%24filter,%24count,%24orderby,%24select,%24expand}\", pathParameters),\n }\n return m\n}", "func (client JobClient) SuspendPreparer(ctx context.Context, resourceGroupName string, accountName string, jobName string, body *JobUserActionDescription) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"jobName\": jobName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPost(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/jobs/{jobName}/suspend\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n if body != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(body))\n }\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (rasrlr RoleAssignmentScheduleRequestListResult) roleAssignmentScheduleRequestListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !rasrlr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(rasrlr.NextLink)))\n}", "func (me *XsdGoPkgHasElem_AssignQualificationRequestsequenceTxsdRequestRequestschema_AssignQualificationRequest_TAssignQualificationRequest_) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_AssignQualificationRequestsequenceTxsdRequestRequestschema_AssignQualificationRequest_TAssignQualificationRequest_; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.AssignQualificationRequest.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (client ListApplicationsResult) ListApplicationsResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (me *XsdGoPkgHasElems_AssignQualificationRequestsequenceRequestschema_AssignQualificationRequest_TAssignQualificationRequest_) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_AssignQualificationRequestsequenceRequestschema_AssignQualificationRequest_TAssignQualificationRequest_; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfor _, x := range me.AssignQualificationRequests {\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func NewMobileAppAssignmentItemRequestBuilder(rawUrl string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*MobileAppAssignmentItemRequestBuilder) {\n urlParams := make(map[string]string)\n urlParams[\"request-raw-url\"] = rawUrl\n return NewMobileAppAssignmentItemRequestBuilderInternal(urlParams, requestAdapter)\n}", "func (client DatabasesClient) ImportPreparer(resourceGroupName string, serverName string, parameters ImportRequest, cancel <-chan struct{}) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\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.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/import\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{Cancel: cancel})\n}", "func NewAppPreviewSetsAppPreviewsReplaceToManyRelationshipRequest(server string, id string, body AppPreviewSetsAppPreviewsReplaceToManyRelationshipJSONRequestBody) (*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 NewAppPreviewSetsAppPreviewsReplaceToManyRelationshipRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func (client AppsClient) ListAvailableCustomPrebuiltDomainsPreparer(ctx context.Context) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/apps/customprebuiltdomains\"))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client NodeResources) NodeResourcesPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (itlr ImportTaskListResult) importTaskListResultPreparer() (*http.Request, error) {\n\tif itlr.NextLink == nil || len(to.String(itlr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(itlr.NextLink)))\n}", "func NewItemAppConsentRequestsForApprovalItemUserConsentRequestsFilterByCurrentUserWithOnRequestBuilderInternal(pathParameters map[string]string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter, on *string)(*ItemAppConsentRequestsForApprovalItemUserConsentRequestsFilterByCurrentUserWithOnRequestBuilder) {\n m := &ItemAppConsentRequestsForApprovalItemUserConsentRequestsFilterByCurrentUserWithOnRequestBuilder{\n BaseRequestBuilder: *i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.NewBaseRequestBuilder(requestAdapter, \"{+baseurl}/users/{user%2Did}/appConsentRequestsForApproval/{appConsentRequest%2Did}/userConsentRequests/filterByCurrentUser(on='{on}'){?%24top,%24skip,%24search,%24filter,%24count,%24select,%24orderby}\", pathParameters),\n }\n if on != nil {\n m.BaseRequestBuilder.PathParameters[\"on\"] = *on\n }\n return m\n}", "func (client RoleAssignmentScheduleRequestsClient) ListForScopePreparer(ctx context.Context, scope string, filter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"scope\": scope,\n\t}\n\n\tconst APIVersion = \"2020-10-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppsClient) AddCustomPrebuiltDomainPreparer(ctx context.Context, prebuiltDomainCreateObject PrebuiltDomainCreateObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/apps/customprebuiltdomains\"),\n\t\tautorest.WithJSON(prebuiltDomainCreateObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ApplicationsClient) RemoveOwnerPreparer(ctx context.Context, applicationObjectID string, ownerObjectID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"ownerObjectId\": autorest.Encode(\"path\", ownerObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}/$links/owners/{ownerObjectId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (sm *Statemgr) OnIPAMPolicyCreateReq(nodeID string, objinfo *netproto.IPAMPolicy) error {\n\treturn nil\n}" ]
[ "0.593061", "0.59178853", "0.5887742", "0.5838368", "0.57673186", "0.57636875", "0.57515496", "0.57268244", "0.5694454", "0.5670612", "0.56097984", "0.5607709", "0.5550994", "0.5442835", "0.5400823", "0.5300256", "0.52975756", "0.5269028", "0.52530587", "0.52349305", "0.5231144", "0.52110136", "0.5197281", "0.5190388", "0.5101419", "0.509549", "0.50933254", "0.50783706", "0.50534576", "0.5046231", "0.49333632", "0.49161118", "0.4907997", "0.48743355", "0.4856986", "0.48299658", "0.48295373", "0.48122275", "0.4805948", "0.47850156", "0.47430137", "0.47366676", "0.4710297", "0.4689748", "0.46769303", "0.46716213", "0.46430415", "0.46384555", "0.46284857", "0.46022132", "0.45950842", "0.4587417", "0.45834157", "0.45811749", "0.45752662", "0.4572377", "0.45705202", "0.45689052", "0.45687595", "0.4558791", "0.45585713", "0.4548917", "0.45481303", "0.4534433", "0.4534351", "0.4523781", "0.45091245", "0.45067933", "0.44787374", "0.4462498", "0.44520256", "0.44464552", "0.44464552", "0.44453543", "0.44443667", "0.44276986", "0.44264114", "0.44245595", "0.44223708", "0.44195208", "0.44119272", "0.4401364", "0.43995643", "0.43937215", "0.43906677", "0.43875855", "0.43867677", "0.4384718", "0.43831158", "0.43799442", "0.43714708", "0.43685403", "0.43652815", "0.43625638", "0.43615758", "0.43520093", "0.4349639", "0.43415883", "0.43383813", "0.43349597" ]
0.80483973
0
AssignToAppSender sends the AssignToApp request. The method will close the http.Response Body if it receives an error.
func (client AzureAccountsClient) AssignToAppSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AzureAccountsClient) AssignToAppResponder(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.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client AzureAccountsClient) AssignToApp(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (result OperationStatus, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.AssignToApp\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: azureAccountInfoObject,\n\t\t\tConstraints: []validation.Constraint{{Target: \"azureAccountInfoObject\", Name: validation.Null, Rule: false,\n\t\t\t\tChain: []validation.Constraint{{Target: \"azureAccountInfoObject.AzureSubscriptionID\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.ResourceGroup\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.AccountName\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t}}}}}); err != nil {\n\t\treturn result, validation.NewError(\"authoring.AzureAccountsClient\", \"AssignToApp\", err.Error())\n\t}\n\n\treq, err := client.AssignToAppPreparer(ctx, appID, azureAccountInfoObject)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.AssignToAppSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.AssignToAppResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (m *ApplicationResource) AssignUserToApplication(ctx context.Context, appId string, body AppUser) (*AppUser, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/users\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"POST\", url, body)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar appUser *AppUser\n\n\tresp, err := rq.Do(ctx, req, &appUser)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn appUser, resp, nil\n}", "func (client AzureAccountsClient) AssignToAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\tif azureAccountInfoObject != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(azureAccountInfoObject))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (r CreateAppRequest) Send(ctx context.Context) (*CreateAppResponse, 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 := &CreateAppResponse{\n\t\tCreateAppOutput: r.Request.Data.(*CreateAppOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (r CreateAppRequest) Send(ctx context.Context) (*CreateAppOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*CreateAppOutput), nil\n}", "func (r CreateAppRequest) Send(ctx context.Context) (*CreateAppOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*CreateAppOutput), nil\n}", "func (cli *OpsGenieAlertV2Client) Assign(req alertsv2.AssignAlertRequest) (*AsyncRequestResponse, error) {\n\treturn cli.sendAsyncPostRequest(&req)\n}", "func (client ApplicationsClient) AddOwnerSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AppsClient) UpdateSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AppsClient) PublishSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (r LaunchAppRequest) Send(ctx context.Context) (*LaunchAppResponse, 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 := &LaunchAppResponse{\n\t\tLaunchAppOutput: r.Request.Data.(*LaunchAppOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (client ApplicationsClient) CreateSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AzureAccountsClient) RemoveFromAppSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AppsClient) AddSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (r UpdateAppRequest) Send(ctx context.Context) (*UpdateAppOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*UpdateAppOutput), nil\n}", "func (r UpdateAppRequest) Send(ctx context.Context) (*UpdateAppOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*UpdateAppOutput), nil\n}", "func (r LaunchAppRequest) Send(ctx context.Context) (*LaunchAppOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*LaunchAppOutput), nil\n}", "func (client ManagementClient) GetAppsSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client,\n\t\treq,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ApplicationsClient) PatchSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client MSIXPackagesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func Transfer(c *deis.Client, appID string, username string) error {\n\tu := fmt.Sprintf(\"/v2/apps/%s/\", appID)\n\n\treq := api.AppUpdateRequest{Owner: username}\n\tbody, err := json.Marshal(req)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := c.Request(\"POST\", u, body)\n\tif err == nil {\n\t\tres.Body.Close()\n\t}\n\treturn err\n}", "func (c *Connection) SendApp(ctx context.Context, messageCommand pvdata.PVByte, payload interface{}) error {\n\tc.encoderMu.Lock()\n\tdefer c.encoderMu.Unlock()\n\tdefer c.flush()\n\tvar bytes []byte\n\tif b, ok := payload.([]byte); ok {\n\t\tbytes = b\n\t} else {\n\t\tvar err error\n\t\tbytes, err = c.encodePayload(payload)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tflags := proto.FLAG_MSG_APP | c.Direction\n\tif c.encoderState.ByteOrder == binary.BigEndian {\n\t\tflags |= proto.FLAG_BO_BE\n\t}\n\th := proto.PVAccessHeader{\n\t\tVersion: c.Version,\n\t\tFlags: flags,\n\t\tMessageCommand: messageCommand,\n\t\tPayloadSize: pvdata.PVInt(len(bytes)),\n\t}\n\tl := ctxlog.L(ctx).WithFields(ctxlog.Fields{\n\t\t\"command\": messageCommand,\n\t\t\"payload_size\": len(bytes),\n\t})\n\tl.Debug(\"sending app message\")\n\tl.Tracef(\"app message body = %x\", bytes)\n\tif err := h.PVEncode(c.encoderState); err != nil {\n\t\treturn err\n\t}\n\t_, err := c.encoderState.Buf.Write(bytes)\n\treturn err\n}", "func (c *EpinioClient) Push(ctx context.Context, params PushParams) error {\n\tname := params.Name\n\tsource := params.Path\n\n\tappRef := models.AppRef{Name: name, Org: c.Config.Org}\n\tlog := c.Log.\n\t\tWithName(\"Push\").\n\t\tWithValues(\"Name\", appRef.Name,\n\t\t\t\"Namespace\", appRef.Org,\n\t\t\t\"Sources\", source)\n\tlog.Info(\"start\")\n\tdefer log.Info(\"return\")\n\tdetails := log.V(1) // NOTE: Increment of level, not absolute. Visible via TRACE_LEVEL=2\n\n\tsourceToShow := source\n\tif params.GitRev != \"\" {\n\t\tsourceToShow = fmt.Sprintf(\"%s @ %s\", sourceToShow, params.GitRev)\n\t}\n\n\tmsg := c.ui.Note().\n\t\tWithStringValue(\"Name\", appRef.Name).\n\t\tWithStringValue(\"Sources\", sourceToShow).\n\t\tWithStringValue(\"Namespace\", appRef.Org)\n\n\tif err := c.TargetOk(); err != nil {\n\t\treturn err\n\t}\n\n\tif len(params.Configuration.Services) > 0 {\n\t\tmsg = msg.WithStringValue(\"Services:\",\n\t\t\tstrings.Join(params.Configuration.Services, \", \"))\n\t}\n\n\tmsg.Msg(\"About to push an application with given name and sources into the specified namespace\")\n\n\tc.ui.Exclamation().\n\t\tTimeout(duration.UserAbort()).\n\t\tMsg(\"Hit Enter to continue or Ctrl+C to abort (deployment will continue automatically in 5 seconds)\")\n\n\tdetails.Info(\"validate app name\")\n\terrorMsgs := validation.IsDNS1123Subdomain(appRef.Name)\n\tif len(errorMsgs) > 0 {\n\t\treturn fmt.Errorf(\"%s: %s\", \"app name incorrect\", strings.Join(errorMsgs, \"\\n\"))\n\t}\n\n\tc.ui.Normal().Msg(\"Create the application resource ...\")\n\n\trequest := models.ApplicationCreateRequest{\n\t\tName: appRef.Name,\n\t\tConfiguration: params.Configuration,\n\t}\n\n\t_, err := c.API.AppCreate(\n\t\trequest,\n\t\tappRef.Org,\n\t\tfunc(response *http.Response, _ []byte, err error) error {\n\t\t\tif response.StatusCode == http.StatusConflict {\n\t\t\t\tdetails.WithValues(\"response\", response).Info(\"app exists conflict\")\n\t\t\t\tc.ui.Normal().Msg(\"Application exists, updating ...\")\n\n\t\t\t\t_, err := c.API.AppUpdate(params.Configuration, appRef.Org, appRef.Name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar blobUID string\n\tif params.GitRev == \"\" && params.Docker == \"\" {\n\t\tc.ui.Normal().Msg(\"Collecting the application sources ...\")\n\n\t\ttmpDir, tarball, err := helpers.Tar(source)\n\t\tdefer func() {\n\t\t\tif tmpDir != \"\" {\n\t\t\t\t_ = os.RemoveAll(tmpDir)\n\t\t\t}\n\t\t}()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.ui.Normal().Msg(\"Uploading application code ...\")\n\n\t\tdetails.Info(\"upload code\")\n\t\tupload, err := c.API.AppUpload(appRef.Org, appRef.Name, tarball)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.V(3).Info(\"upload response\", \"response\", upload)\n\n\t\tblobUID = upload.BlobUID\n\n\t} else if params.GitRev != \"\" {\n\t\tc.ui.Normal().Msg(\"Importing the application sources from Git ...\")\n\n\t\tgitRef := models.GitRef{\n\t\t\tURL: source,\n\t\t\tRevision: params.GitRev,\n\t\t}\n\t\tresponse, err := c.API.AppImportGit(appRef, gitRef)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"importing git remote\")\n\t\t}\n\t\tblobUID = response.BlobUID\n\t}\n\n\tstageID := \"\"\n\tvar stageResponse *models.StageResponse\n\tif params.Docker == \"\" {\n\t\tc.ui.Normal().Msg(\"Staging application via docker image ...\")\n\n\t\treq := models.StageRequest{\n\t\t\tApp: appRef,\n\t\t\tBlobUID: blobUID,\n\t\t\tBuilderImage: params.BuilderImage,\n\t\t}\n\t\tdetails.Info(\"staging code\", \"Blob\", blobUID)\n\t\tstageResponse, err = c.API.AppStage(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tstageID = stageResponse.Stage.ID\n\t\tlog.V(3).Info(\"stage response\", \"response\", stageResponse)\n\n\t\tdetails.Info(\"start tailing logs\", \"StageID\", stageResponse.Stage.ID)\n\t\terr = c.stageLogs(details, appRef, stageResponse.Stage.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tc.ui.Normal().Msg(\"Deploying application ...\")\n\tdeployRequest := models.DeployRequest{\n\t\tApp: appRef,\n\t}\n\t// If docker param is specified, then we just take it into ImageURL\n\t// If not, we take the one from the staging response\n\tif params.Docker != \"\" {\n\t\tdeployRequest.ImageURL = params.Docker\n\t} else {\n\t\tdeployRequest.ImageURL = stageResponse.ImageURL\n\t\tdeployRequest.Stage = models.StageRef{ID: stageID}\n\t}\n\n\tdeployResponse, err := c.API.AppDeploy(deployRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdetails.Info(\"wait for application resources\")\n\terr = c.waitForApp(appRef)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"waiting for app failed\")\n\t}\n\n\tc.ui.Success().\n\t\tWithStringValue(\"Name\", appRef.Name).\n\t\tWithStringValue(\"Namespace\", appRef.Org).\n\t\tWithStringValue(\"Route\", fmt.Sprintf(\"https://%s\", deployResponse.Route)).\n\t\tWithStringValue(\"Builder Image\", params.BuilderImage).\n\t\tMsg(\"App is online.\")\n\n\treturn nil\n}", "func sendResponse(w http.ResponseWriter, statusCode int, message string) {\n\tw.WriteHeader(statusCode)\n\tjson.NewEncoder(w).Encode(appResponse{Message: message})\n}", "func (p *Proxy) InstallApp(in Incoming, cc apps.Context, appID apps.AppID, deployType apps.DeployType, trusted bool, secret string) (*apps.App, string, error) {\n\tconf, _, log := p.conf.Basic()\n\tlog = log.With(\"app_id\", appID)\n\tm, err := p.store.Manifest.Get(appID)\n\tif err != nil {\n\t\treturn nil, \"\", errors.Wrap(err, \"failed to find manifest to install app\")\n\t}\n\tif !m.SupportsDeploy(deployType) {\n\t\treturn nil, \"\", errors.Errorf(\"app does not support %s deployment\", deployType)\n\t}\n\terr = CanDeploy(p, deployType)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tapp, err := p.store.App.Get(appID)\n\tif err != nil {\n\t\tif !errors.Is(err, utils.ErrNotFound) {\n\t\t\treturn nil, \"\", errors.Wrap(err, \"failed looking for existing app\")\n\t\t}\n\t\tapp = &apps.App{}\n\t}\n\n\tapp.DeployType = deployType\n\tapp.Manifest = *m\n\tif app.Disabled {\n\t\tapp.Disabled = false\n\t}\n\tapp.GrantedPermissions = m.RequestedPermissions\n\tapp.GrantedLocations = m.RequestedLocations\n\tif secret != \"\" {\n\t\tapp.Secret = secret\n\t}\n\n\tif app.GrantedPermissions.Contains(apps.PermissionRemoteWebhooks) {\n\t\tapp.WebhookSecret = model.NewId()\n\t}\n\n\ticon, err := p.getAppIcon(*app)\n\tif err != nil {\n\t\treturn nil, \"\", errors.Wrap(err, \"failed get bot icon\")\n\t}\n\tif icon != nil {\n\t\tdefer icon.Close()\n\t}\n\n\t// See if the app is inaaccessible. Call its ping path with nothing\n\t// expanded, ignore 404 errors coming back and consider everything else a\n\t// \"success\".\n\t//\n\t// Note that this check is often ineffective, but \"the best we can do\"\n\t// before we start the diffcult-to-revert install process.\n\t_, err = p.callApp(in, *app, apps.CallRequest{\n\t\tCall: apps.DefaultPing,\n\t\tContext: cc,\n\t})\n\tif err != nil && errors.Cause(err) != utils.ErrNotFound {\n\t\treturn nil, \"\", errors.Wrapf(err, \"failed to install, %s path is not accessible\", apps.DefaultPing.Path)\n\t}\n\n\tasAdmin, err := p.getAdminClient(in)\n\tif err != nil {\n\t\treturn nil, \"\", errors.Wrap(err, \"failed to get an admin HTTP client\")\n\t}\n\terr = p.ensureBot(asAdmin, log, app, icon)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tif app.GrantedPermissions.Contains(apps.PermissionActAsUser) {\n\t\tvar oAuthApp *model.OAuthApp\n\t\toAuthApp, err = p.ensureOAuthApp(asAdmin, log, conf, *app, trusted, in.ActingUserID)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tapp.MattermostOAuth2.ClientID = oAuthApp.Id\n\t\tapp.MattermostOAuth2.ClientSecret = oAuthApp.ClientSecret\n\t\tapp.Trusted = trusted\n\t}\n\n\terr = p.store.App.Save(*app)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tmessage := fmt.Sprintf(\"Installed %s.\", app.DisplayName)\n\tif app.OnInstall != nil {\n\t\tcresp := p.call(in, *app, *app.OnInstall, &cc)\n\t\tif cresp.Type == apps.CallResponseTypeError {\n\t\t\t// TODO: should fail and roll back.\n\t\t\tlog.WithError(cresp).Warnf(\"Installed %s, despite on_install failure.\", app.AppID)\n\t\t\tmessage = fmt.Sprintf(\"Installed %s, despite on_install failure: %s\", app.AppID, cresp.Error())\n\t\t} else if cresp.Markdown != \"\" {\n\t\t\tmessage += \"\\n\\n\" + cresp.Markdown\n\t\t}\n\t} else if len(app.GrantedLocations) > 0 {\n\t\t// Make sure the app's binding call is accessible.\n\t\tcresp := p.call(in, *app, app.Bindings.WithDefault(apps.DefaultBindings), &cc)\n\t\tif cresp.Type == apps.CallResponseTypeError {\n\t\t\t// TODO: should fail and roll back.\n\t\t\tlog.WithError(cresp).Warnf(\"Installed %s, despite bindings failure.\", app.AppID)\n\t\t\tmessage = fmt.Sprintf(\"Installed %s despite bindings failure: %s\", app.AppID, cresp.Error())\n\t\t}\n\t}\n\n\tp.conf.Telemetry().TrackInstall(string(app.AppID), string(app.DeployType))\n\n\tp.dispatchRefreshBindingsEvent(in.ActingUserID)\n\n\tlog.Infof(message)\n\treturn app, message, nil\n}", "func (m *IntentsDeviceManagementIntentItemRequestBuilder) Assign()(*IntentsItemAssignRequestBuilder) {\n return NewIntentsItemAssignRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (client JobClient) ApproveSender(req *http.Request) (future JobApproveFuture, 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 (a *appHandler) CreateApp(w http.ResponseWriter, r *http.Request) {\n\tvar app model.App\n\terr := json.NewDecoder(r.Body).Decode(&app)\n\tif err != nil {\n\t\ta.httpUtil.WriteJSONBadRequestResponse(w, err)\n\t\treturn\n\t}\n\n\t// TODO : Create\n\n\tjsonR, err := json.Marshal(app)\n\tif err != nil {\n\t\ta.httpUtil.WriteJSONInternalServerErrorResponse(w, err)\n\t}\n\n\ta.httpUtil.WriteJSONSuccessResponse(w, jsonR)\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 (client RoleAssignmentScheduleRequestsClient) CreateSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (m *EmbeddedSIMActivationCodePoolsEmbeddedSIMActivationCodePoolItemRequestBuilder) Assign()(*EmbeddedSIMActivationCodePoolsItemAssignRequestBuilder) {\n return NewEmbeddedSIMActivationCodePoolsItemAssignRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (obj *Global) AllowCreateApp(ctx context.Context) (bool, error) {\n\tresult := &struct {\n\t\tReturn bool `json:\"qReturn\"`\n\t}{}\n\terr := obj.RPC(ctx, \"AllowCreateApp\", result)\n\treturn result.Return, err\n}", "func (o OpenSignal) UpdateAnApp(app App) (App, error) {\n\tstrResponse := App{}\n\n\tURL := f(updateAnApp, app.ID)\n\tres, body, errs := o.Client.Put(URL).\n\t\tSend(app).\n\t\tSet(\"Authorization\", \"Basic \"+o.AuthKey).\n\t\tEndStruct(&strResponse)\n\terr := catch(res, body)\n\tif err == nil {\n\t\tfor _, e := range errs {\n\t\t\tif e != nil {\n\t\t\t\terr = e\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn strResponse, err\n}", "func (m *ManagedEBooksManagedEBookItemRequestBuilder) Assign()(*ManagedEBooksItemAssignRequestBuilder) {\n return NewManagedEBooksItemAssignRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (r a) Assign(company string, team string, engagement string, params map[string]string) (*http.Response, []byte) {\n return r.client.Put(\"/otask/v1/tasks/companies/\" + company + \"/teams/\" + team + \"/engagements/\" + engagement + \"/tasks\", params)\n}", "func (m *TestFixClient) ToApp(msg *fix.Message, sID fix.SessionID) error {\n\tif !m.OmitLogMessages {\n\t\tlog.Printf(\"[FIX %s] MockFix.ToApp (outgoing): %s\", m.name, fixString(msg))\n\t}\n\ts := m.Sessions[sID.String()]\n\tseq, err := msg.Header.GetInt(34)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Sent[seq] = strings.Replace(msg.String(), string(0x1), \"|\", -1)\n\treturn nil\n}", "func (s *server) Create(ctx context.Context, body *pb.RequestBody) (*pb.ResponseBody, error) {\n\tlanguage := body.GetLanguage()\n\tapp := &types.ApplicationConfig{}\n\n\terr := json.Unmarshal(body.GetData(), app)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser, err := mongo.FetchSingleUser(body.GetOwner())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmaxCount := configs.ServiceConfig.AppMaker.AppLimit\n\trateCount := configs.ServiceConfig.RateLimit\n\ttimeInterval := configs.ServiceConfig.RateInterval\n\tif !user.IsAdmin() && maxCount >= 0 {\n\t\trateLimitCount := mongo.CountInstanceInTimeFrame(body.GetOwner(), mongo.AppInstance, timeInterval)\n\t\ttotalCount := mongo.CountInstancesByUser(body.GetOwner(), mongo.AppInstance)\n\t\tif totalCount < maxCount {\n\t\t\tif rateLimitCount >= rateCount && rateCount >= 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"cannot deploy more than %d app instances in %d hours\", rateCount, timeInterval)\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"cannot deploy more than %d app instances\", maxCount)\n\t\t}\n\t}\n\n\tapp.SetLanguage(language)\n\tapp.SetOwner(body.GetOwner())\n\tapp.SetInstanceType(mongo.AppInstance)\n\tapp.SetHostIP(utils.HostIP)\n\tapp.SetNameServers(configs.GasperConfig.DNSServers)\n\tapp.SetDateTime()\n\n\tgendnsNameServers, _ := redis.FetchServiceInstances(types.GenDNS)\n\tfor _, nameServer := range gendnsNameServers {\n\t\tif strings.Contains(nameServer, \":\") {\n\t\t\tapp.AddNameServers(strings.Split(nameServer, \":\")[0])\n\t\t} else {\n\t\t\tutils.LogError(\"AppMaker-Controller-1\", fmt.Errorf(\"GenDNS instance %s is of invalid format\", nameServer))\n\t\t}\n\t}\n\n\tif pipeline[language] == nil {\n\t\treturn nil, fmt.Errorf(\"language `%s` is not supported\", language)\n\t}\n\tresErr := pipeline[language].create(app)\n\tif resErr != nil {\n\t\tif resErr.Message() != \"repository already exists\" && resErr.Message() != \"container already exists\" {\n\t\t\tgo diskCleanup(app.GetName())\n\t\t}\n\t\treturn nil, fmt.Errorf(resErr.Error())\n\t}\n\n\tsshEntrypointIP := configs.ServiceConfig.GenSSH.EntrypointIP\n\tif len(sshEntrypointIP) == 0 {\n\t\tsshEntrypointIP = utils.HostIP\n\t}\n\tapp.SetSSHCmd(configs.ServiceConfig.GenSSH.Port, app.GetName(), sshEntrypointIP)\n\n\tapp.SetAppURL(fmt.Sprintf(\"%s.%s.%s\", app.GetName(), cloudflare.ApplicationInstance, configs.GasperConfig.Domain))\n\n\tif configs.CloudflareConfig.PlugIn {\n\t\tresp, err := cloudflare.CreateApplicationRecord(app.GetName())\n\t\tif err != nil {\n\t\t\tgo diskCleanup(app.GetName())\n\t\t\treturn nil, err\n\t\t}\n\t\tapp.SetCloudflareID(resp.Result.ID)\n\t\tapp.SetPublicIP(configs.CloudflareConfig.PublicIP)\n\t}\n\n\terr = mongo.UpsertInstance(\n\t\ttypes.M{\n\t\t\tmongo.NameKey: app.GetName(),\n\t\t\tmongo.InstanceTypeKey: mongo.AppInstance,\n\t\t}, app)\n\n\tif err != nil && err != mongo.ErrNoDocuments {\n\t\tgo diskCleanup(app.GetName())\n\t\tgo stateCleanup(app.GetName())\n\t\treturn nil, err\n\t}\n\n\terr = redis.RegisterApp(\n\t\tapp.GetName(),\n\t\tfmt.Sprintf(\"%s:%d\", utils.HostIP, configs.ServiceConfig.AppMaker.Port),\n\t\tfmt.Sprintf(\"%s:%d\", utils.HostIP, app.GetContainerPort()),\n\t)\n\n\tif err != nil {\n\t\tgo diskCleanup(app.GetName())\n\t\tgo stateCleanup(app.GetName())\n\t\treturn nil, err\n\t}\n\n\terr = redis.IncrementServiceLoad(\n\t\tServiceName,\n\t\tfmt.Sprintf(\"%s:%d\", utils.HostIP, configs.ServiceConfig.AppMaker.Port),\n\t)\n\n\tif err != nil {\n\t\tgo diskCleanup(app.GetName())\n\t\tgo stateCleanup(app.GetName())\n\t\treturn nil, err\n\t}\n\n\tapp.SetSuccess(true)\n\n\tresponse, err := json.Marshal(app)\n\treturn &pb.ResponseBody{Data: response}, err\n}", "func (adm *AdminClient) SetAppInfo(appName string, appVersion string) {\n\t// if app name and version is not set, we do not a new user\n\t// agent.\n\tif appName != \"\" && appVersion != \"\" {\n\t\tadm.appInfo.appName = appName\n\t\tadm.appInfo.appVersion = appVersion\n\t}\n}", "func (c *Client) AddUserToApp(email string, name string, secret string, cpf string) (*http.Response, error) {\n\tpath := fmt.Sprintf(\"/management/%v/users/%v?includeRoles='readonly'\", string(c.APPKey.Buffer()), strings.TrimSuffix(email, \"\\n\"))\n\tcomment, _ := json.Marshal(userComment{TotpSecret: secret, Status: \"enabled\", CPF: cpf})\n\tuser := userData{FullName: name, Comment: string(comment)}\n\tdata, _ := json.Marshal(user)\n\n\treturn c.Put(path, bytes.NewBuffer(data))\n}", "func (client AppsClient) ImportSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (r *RPC) PasterAPP(c context.Context, arg *model.ArgPaster, res *model.Paster) (err error) {\n\tvar rs *model.Paster\n\tif rs, err = r.s.PasterAPP(c, arg.Platform, arg.AdType, arg.Aid, arg.TypeId, arg.Buvid); err == nil {\n\t\t*res = *rs\n\t}\n\treturn\n}", "func CallAssign() MapAssignReply {\n\n\targs := MapAssignArgs{}\n\n\targs.TASKID = taskId\n\n\treply := MapAssignReply{}\n\n\tcall(\"Master.AssignTask\", &args, &reply)\n\n\t// fmt.Println(reply)\n\n\treturn reply\n}", "func (o OpenSignal) CreateAnApp(app App) (App, error) {\n\tstrResponse := App{}\n\n\tres, body, errs := o.Client.Post(createApp).\n\t\tSend(app).\n\t\tSet(\"Authorization\", \"Basic \"+o.AuthKey).\n\t\tEndStruct(&strResponse)\n\terr := catch(res, body)\n\tif err == nil {\n\t\tfor _, e := range errs {\n\t\t\tif e != nil {\n\t\t\t\terr = e\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn strResponse, err\n}", "func (client Client) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req)\n}", "func (t *Handler) sendEmail(teamUsername, teamUserAuthority, teamAuthority, teamOwnerNamespace, teamName, teamChildNamespace, subject string) {\n\tuser, err := t.edgenetClientset.AppsV1alpha().Users(fmt.Sprintf(\"authority-%s\", teamUserAuthority)).Get(teamUsername, metav1.GetOptions{})\n\tif err == nil && user.Status.Active && user.Status.AUP {\n\t\t// Set the HTML template variables\n\t\tcontentData := mailer.ResourceAllocationData{}\n\t\tcontentData.CommonData.Authority = teamUserAuthority\n\t\tcontentData.CommonData.Username = teamUsername\n\t\tcontentData.CommonData.Name = fmt.Sprintf(\"%s %s\", user.Spec.FirstName, user.Spec.LastName)\n\t\tcontentData.CommonData.Email = []string{user.Spec.Email}\n\t\tcontentData.Authority = teamAuthority\n\t\tcontentData.Name = teamName\n\t\tcontentData.OwnerNamespace = teamOwnerNamespace\n\t\tcontentData.ChildNamespace = teamChildNamespace\n\t\tmailer.Send(subject, contentData)\n\t}\n}", "func DeployApp(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tstatus := params[\"status\"]\n\tlog.Printf(\"Params: %s\\n\", params)\n\n\tclientset, err := getConfig()\n\tif err != nil {\n\t\tlog.Fatalln(\"failed to get the config:\", err)\n\t}\n\n\tdeploymentsClient := clientset.AppsV1().Deployments(namespace)\n\n\tdeploymentName := params[\"app\"] + \"-deployment\"\n\n\tlist, err := deploymentsClient.List(metav1.ListOptions{})\n\tif err != nil {\n\t\tlog.Fatalln(\"failed to get deployments:\", err)\n\t}\n\n\tcontainers := []apiv1.Container{createContainer(params[\"app\"], repository+\"/\"+params[\"app\"]+appversion)}\n\n\tif status == \"true\" {\n\t\tfor _, d := range list.Items {\n\t\t\tif d.Name == deploymentName && *d.Spec.Replicas > 0 {\n\t\t\t\tlog.Printf(\"Deployment already running: %s\\n\", deploymentName)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tnodeLabel(params[\"node\"], \"app\", params[\"app\"], \"add\")\n\n\t\tdeployment := &appsv1.Deployment{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: deploymentName,\n\t\t\t},\n\t\t\tSpec: appsv1.DeploymentSpec{\n\t\t\t\tReplicas: int32Ptr(1),\n\t\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\t\"app\": params[\"app\"],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tTemplate: apiv1.PodTemplateSpec{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\t\"app\": params[\"app\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tSpec: apiv1.PodSpec{\n\t\t\t\t\t\tContainers: containers,\n\t\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\t\t\"app\": params[\"app\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tVolumes: []apiv1.Volume{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: \"mem\",\n\t\t\t\t\t\t\t\tVolumeSource: apiv1.VolumeSource{\n\t\t\t\t\t\t\t\t\tHostPath: &apiv1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\t\tPath: \"/dev/mem\",\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\t{\n\t\t\t\t\t\t\t\tName: \"gpiomem\",\n\t\t\t\t\t\t\t\tVolumeSource: apiv1.VolumeSource{\n\t\t\t\t\t\t\t\t\tHostPath: &apiv1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\t\tPath: \"/dev/gpiomem\",\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\t// Create Deployment\n\t\tfmt.Println(\"Creating deployment...\")\n\t\tresult, err := deploymentsClient.Create(deployment)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Printf(\"Created deployment %q.\\n\", result.GetObjectMeta().GetName())\n\n\t} else {\n\n\t\tnodeLabel(params[\"node\"], \"app\", params[\"app\"], \"del\")\n\n\t\tfmt.Println(\"Deleting deployment...\")\n\t\tdeletePolicy := metav1.DeletePropagationForeground\n\t\tif err := deploymentsClient.Delete(deploymentName, &metav1.DeleteOptions{\n\t\t\tPropagationPolicy: &deletePolicy,\n\t\t}); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(\"Deleted deployment.\")\n\t}\n\n}", "func (client MSIXPackagesClient) UpdateSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (m *UnifiedRoleAssignmentScheduleRequest) SetAppScope(value AppScopeable)() {\n m.appScope = value\n}", "func (o *GetClientConfigV1ConfigByNameParams) SetApp(app *string) {\n\to.App = app\n}", "func (r *RepoStruct) SetApp(appRelName, appName string) (updated *bool, _ error) {\n\tif err := r.initApp(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tupdated = new(bool)\n\tif v, found := r.Apps[appRelName]; !found || (found && v != appName) {\n\t\t*updated = true\n\t}\n\tr.Apps[appRelName] = appName\n\n\tif set, err := r.SetInternalRelApp(appRelName, appName); set == nil {\n\t\treturn set, err\n\t}\n\treturn\n}", "func (client HTTPSuccessClient) Patch202Sender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (m *AssignPostRequestBody) SetMobileAppAssignments(value []iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.MobileAppAssignmentable)() {\n m.mobileAppAssignments = value\n}", "func (r GetAppRequest) Send(ctx context.Context) (*GetAppOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*GetAppOutput), nil\n}", "func (r GetAppRequest) Send(ctx context.Context) (*GetAppOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*GetAppOutput), nil\n}", "func (client ModelClient) UpdateIntentSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (resource *ResourcesData) PushApplication(venAppName, spaceGUID string, parsedArguments *arguments.ParserArguments, v2Resources v2.Resources) error {\n\n\tui.Say(\"create application %s\", parsedArguments.AppName)\n\terr := resource.CreateApp(parsedArguments)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tui.Say(\"generate manifest without routes...\")\n\n\tui.Say(\"apply manifest file\")\n\terr = resource.AssignAppManifest(parsedArguments.NoRouteManifestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tui.Say(\"push application\")\n\terr = resource.PushApp(parsedArguments)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tui.Say(\"set health-check with type: %s for application %s\", parsedArguments.HealthCheckType, parsedArguments.AppName)\n\terr = resource.SetHealthCheck(parsedArguments.AppName, parsedArguments.HealthCheckType, parsedArguments.HealthCheckHTTPEndpoint, parsedArguments.InvocationTimeout, parsedArguments.Process)\n\tif err != nil {\n\t\treturn err\n\t}\n\tui.Ok()\n\n\treturn nil\n}", "func (appHandler *ApplicationApiHandler) Application(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := ps.ByName(\"id\")\n\tidint, err := strconv.Atoi(id)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tapp, err := appHandler.appService.Application(idint)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tresponse, err := json.Marshal(app)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\t_, err = w.Write(response)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\n}", "func (m *ApplicationResource) ActivateApplication(ctx context.Context, appId string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/lifecycle/activate\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func (client HTTPSuccessClient) Post202Sender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (a *app) SendHello() error {\n\thelloDetails := make(map[string]interface{})\n\thelloDetails[\"authid\"] = a.getAuthID()\n\thelloDetails[\"authmethods\"] = a.getAuthMethods()\n\n\t// Duct tape for js demo\n\t// if Fabric == FabricProduction && c.app.token == \"\" {\n\t// Info(\"No token found on production. Attempting to auth from scratch\")\n\n\t// if token, err := tokenLogin(c.app.agent); err != nil {\n\t// return err\n\t// } else {\n\t// c.app.token = token\n\t// }\n\t// }\n\n\tmsg := hello{\n\t\tRealm: a.agent,\n\t\tDetails: helloDetails,\n\t}\n\n\treturn a.Send(&msg)\n}", "func sendToManager(c *Client, data []byte) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = r.(error)\n\t\t}\n\t}()\n\n\tc.send <- data\n\treturn\n}", "func (m *AppVulnerabilityTask) SetAppName(value *string)() {\n err := m.GetBackingStore().Set(\"appName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *applicationUsecaseImpl) Deploy(ctx context.Context, app *model.Application, req apisv1.ApplicationDeployRequest) (*apisv1.ApplicationDeployResponse, error) {\n\t// TODO: rollback to handle all the error case\n\t// step1: Render oam application\n\tversion := utils.GenerateVersion(\"\")\n\toamApp, err := c.renderOAMApplication(ctx, app, req.WorkflowName, version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfigByte, _ := yaml.Marshal(oamApp)\n\n\tworkflow, err := c.workflowUsecase.GetWorkflow(ctx, app, oamApp.Annotations[oam.AnnotationWorkflowName])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// step2: check and create deploy event\n\tif !req.Force {\n\t\tvar lastVersion = model.ApplicationRevision{\n\t\t\tAppPrimaryKey: app.PrimaryKey(),\n\t\t\tEnvName: workflow.EnvName,\n\t\t}\n\t\tlist, err := c.ds.List(ctx, &lastVersion, &datastore.ListOptions{\n\t\t\tPageSize: 1, Page: 1, SortBy: []datastore.SortOption{{Key: \"createTime\", Order: datastore.SortOrderDescending}}})\n\t\tif err != nil && !errors.Is(err, datastore.ErrRecordNotExist) {\n\t\t\tlog.Logger.Errorf(\"query app latest revision failure %s\", err.Error())\n\t\t\treturn nil, bcode.ErrDeployConflict\n\t\t}\n\t\tif len(list) > 0 && list[0].(*model.ApplicationRevision).Status != model.RevisionStatusComplete {\n\t\t\tlog.Logger.Warnf(\"last app revision can not complete %s/%s\", list[0].(*model.ApplicationRevision).AppPrimaryKey, list[0].(*model.ApplicationRevision).Version)\n\t\t\treturn nil, bcode.ErrDeployConflict\n\t\t}\n\t}\n\n\tvar appRevision = &model.ApplicationRevision{\n\t\tAppPrimaryKey: app.PrimaryKey(),\n\t\tVersion: version,\n\t\tApplyAppConfig: string(configByte),\n\t\tStatus: model.RevisionStatusInit,\n\t\t// TODO: Get user information from ctx and assign a value.\n\t\tDeployUser: \"\",\n\t\tNote: req.Note,\n\t\tTriggerType: req.TriggerType,\n\t\tWorkflowName: oamApp.Annotations[oam.AnnotationWorkflowName],\n\t\tEnvName: workflow.EnvName,\n\t}\n\n\tif err := c.ds.Add(ctx, appRevision); err != nil {\n\t\treturn nil, err\n\t}\n\t// step3: check and create namespace\n\tvar namespace corev1.Namespace\n\tif err := c.kubeClient.Get(ctx, types.NamespacedName{Name: oamApp.Namespace}, &namespace); apierrors.IsNotFound(err) {\n\t\tnamespace.Name = oamApp.Namespace\n\t\tif err := c.kubeClient.Create(ctx, &namespace); err != nil {\n\t\t\tlog.Logger.Errorf(\"auto create namespace failure %s\", err.Error())\n\t\t\treturn nil, bcode.ErrCreateNamespace\n\t\t}\n\t}\n\t// step4: apply to controller cluster\n\terr = c.apply.Apply(ctx, oamApp)\n\tif err != nil {\n\t\tappRevision.Status = model.RevisionStatusFail\n\t\tappRevision.Reason = err.Error()\n\t\tif err := c.ds.Put(ctx, appRevision); err != nil {\n\t\t\tlog.Logger.Warnf(\"update deploy event failure %s\", err.Error())\n\t\t}\n\n\t\tlog.Logger.Errorf(\"deploy app %s failure %s\", app.PrimaryKey(), err.Error())\n\t\treturn nil, bcode.ErrDeployApplyFail\n\t}\n\n\t// step5: create workflow record\n\tif err := c.workflowUsecase.CreateWorkflowRecord(ctx, app, oamApp, workflow); err != nil {\n\t\tlog.Logger.Warnf(\"create workflow record failure %s\", err.Error())\n\t}\n\n\t// step6: update app revision status\n\tappRevision.Status = model.RevisionStatusRunning\n\tif err := c.ds.Put(ctx, appRevision); err != nil {\n\t\tlog.Logger.Warnf(\"update app revision failure %s\", err.Error())\n\t}\n\n\treturn &apisv1.ApplicationDeployResponse{\n\t\tApplicationRevisionBase: apisv1.ApplicationRevisionBase{\n\t\t\tVersion: appRevision.Version,\n\t\t\tStatus: appRevision.Status,\n\t\t\tReason: appRevision.Reason,\n\t\t\tDeployUser: appRevision.DeployUser,\n\t\t\tNote: appRevision.Note,\n\t\t\tTriggerType: appRevision.TriggerType,\n\t\t},\n\t}, nil\n}", "func (client HTTPSuccessClient) Put202Sender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func AppPush(tokenList []string, msg string, extraInfo map[string]string, time int64) {\n\tlog.Debug(\"calling rpc.IOSPush\")\n\tRpcClientD.ApplePush(context.Background(), &pb.ApplePushRequest{Message: msg, ExtraInfo: extraInfo, Time: time, DeviceToken: tokenList})\n}", "func (client ViewsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (m *DeviceConfigurationItemRequestBuilder) Assign()(*i4cd13eb5be3949210a98b3e74a48e803b388b1057dc5b76fa296250220177115.AssignRequestBuilder) {\n return i4cd13eb5be3949210a98b3e74a48e803b388b1057dc5b76fa296250220177115.NewAssignRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (client ModelClient) AddIntentSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (a *Application) AddSubmitApplicationActivity(supplierID string, supplierName string, clientID string, clientName string, auctionID string, auctionNumber string) (stream.Activity, error) {\n\thelper := NewHelper(a.telemetryClient)\n\n\tsupplierData, _ := helper.createJSONMarshal(supplierID, supplierName, \"supplier\")\n\tauctionData, _ := helper.createJSONMarshal(auctionID, auctionNumber, \"auction\")\n\n\tassignmentRepository, settingsRepository := a.createAssignmentAndSettingsRepository()\n\tassignments, _ := assignmentRepository.GetEmployerAssignmentsByAuctionID(auctionID)\n\n\tif assignmentRepository.IsApprovedAuctionStatus(auctionID) {\n\t\tfor _, assignment := range assignments {\n\t\t\tuserID := strings.ToLower(assignment.UserID)\n\t\t\tsettings, _ := settingsRepository.GetSettingsByClientID(userID)\n\n\t\t\tif settings.Applications {\n\t\t\t\tverb := \"apply\"\n\t\t\t\tobject := fmt.Sprintf(\"auction:%s\", auctionID)\n\t\t\t\tcontent := fmt.Sprintf(\"Congratulations, Agency %s applied to your Auction #%s (Competitive).\", supplierData, auctionData)\n\t\t\t\tcategory := \"Application\"\n\t\t\t\tsubcategory := map[string]string{\n\t\t\t\t\t\"type\": \"Application\",\n\t\t\t\t\t\"status\": \"Pending\",\n\t\t\t\t}\n\n\t\t\t\ta.sendNotificationToEmployer(userID, verb, object, supplierID, content, category, subcategory)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn stream.Activity{}, nil\n}", "func (m *Application) SetAppId(value *string)() {\n m.appId = value\n}", "func (m *VirtualEndpointUserSettingsCloudPcUserSettingItemRequestBuilder) Assign()(*VirtualEndpointUserSettingsItemAssignRequestBuilder) {\n return NewVirtualEndpointUserSettingsItemAssignRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (wa *WalletsAddresses) Assign(payload *WalletAddressesPayload) (*WalletAddressData, *ApiError, error) {\n\tresult := new(WalletAddressesResult)\n\tpayloadJSON, err := ffjson.Marshal(payload)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tapiErr, err := wa.client.call(\"walletAddresses\", \"assign\", payloadJSON, result)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn &result.Data, apiErr, nil\n\n}", "func (a AppsApi) AppsPost(body AppWrapper) (*AppWrapper, *APIResponse, error) {\n\n\tvar localVarHttpMethod = strings.ToUpper(\"Post\")\n\t// create path and map variables\n\tlocalVarPath := a.Configuration.BasePath + \"/apps\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := make(map[string]string)\n\tvar localVarPostBody interface{}\n\tvar localVarFileName string\n\tvar localVarFileBytes []byte\n\t// add default headers if any\n\tfor key := range a.Configuration.DefaultHeader {\n\t\tlocalVarHeaderParams[key] = a.Configuration.DefaultHeader[key]\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 := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tvar successPayload = new(AppWrapper)\n\tlocalVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\n\tvar localVarURL, _ = url.Parse(localVarPath)\n\tlocalVarURL.RawQuery = localVarQueryParams.Encode()\n\tvar localVarAPIResponse = &APIResponse{Operation: \"AppsPost\", Method: localVarHttpMethod, RequestURL: localVarURL.String()}\n\tif localVarHttpResponse != nil {\n\t\tlocalVarAPIResponse.Response = localVarHttpResponse.RawResponse\n\t\tlocalVarAPIResponse.Payload = localVarHttpResponse.Body()\n\t}\n\n\tif err != nil {\n\t\treturn successPayload, localVarAPIResponse, err\n\t}\n\terr = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)\n\treturn successPayload, localVarAPIResponse, err\n}", "func doAssign(be pb.BackendClient) {\n\n\tfor {\n\t\tmatch := <-matches\n\t\tids := []string{}\n\t\tfor _, t := range match.Tickets {\n\t\t\tids = append(ids, t.Id)\n\t\t}\n\n\t\treq := &pb.AssignTicketsRequest{\n\t\t\tTicketIds: ids,\n\t\t\tAssignment: &pb.Assignment{\n\t\t\t\tConnection: fmt.Sprintf(\"%d.%d.%d.%d:2222\", rand.Intn(256), rand.Intn(256), rand.Intn(256), rand.Intn(256)),\n\t\t\t},\n\t\t}\n\n\t\tif _, err := be.AssignTickets(context.Background(), req); err != nil {\n\t\t\terrMsg := fmt.Sprintf(\"failed to assign tickets: %w\", err)\n\t\t\terrRead, ok := errMap.Load(errMsg)\n\t\t\tif !ok {\n\t\t\t\terrRead = 0\n\t\t\t}\n\t\t\terrMap.Store(errMsg, errRead.(int)+1)\n\t\t}\n\n\t\tatomic.AddUint64(&assigned, uint64(len(ids)))\n\t\tfor _, id := range ids {\n\t\t\tdeleteIds <- id\n\t\t}\n\t}\n}", "func (m *AssignPostRequestBody) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetMobileAppAssignments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMobileAppAssignments())\n err := writer.WriteCollectionOfObjectValues(\"mobileAppAssignments\", cast)\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 (s *Server) CreateAppSession(ctx context.Context, req services.CreateAppSessionRequest, user services.User, checker services.AccessChecker) (services.WebSession, error) {\n\tif !modules.GetModules().Features().App {\n\t\treturn nil, trace.AccessDenied(\n\t\t\t\"this Teleport cluster doesn't support application access, please contact the cluster administrator\")\n\t}\n\n\t// Check that a matching parent web session exists in the backend.\n\tparentSession, err := s.GetWebSession(ctx, types.GetWebSessionRequest{\n\t\tUser: req.Username,\n\t\tSessionID: req.ParentSession,\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// Don't let the TTL of the child certificate go longer than the parent.\n\tttl := checker.AdjustSessionTTL(parentSession.GetExpiryTime().Sub(s.clock.Now()))\n\n\t// Create certificate for this session.\n\tprivateKey, publicKey, err := s.GetNewKeyPairFromPool()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tcerts, err := s.generateUserCert(certRequest{\n\t\tuser: user,\n\t\tpublicKey: publicKey,\n\t\tchecker: checker,\n\t\tttl: ttl,\n\t\t// Set the login to be a random string. Application certificates are never\n\t\t// used to log into servers but SSH certificate generation code requires a\n\t\t// principal be in the certificate.\n\t\ttraits: wrappers.Traits(map[string][]string{\n\t\t\tteleport.TraitLogins: {uuid.New()},\n\t\t}),\n\t\t// Only allow this certificate to be used for applications.\n\t\tusage: []string{teleport.UsageAppsOnly},\n\t\t// Add in the application routing information.\n\t\tappSessionID: uuid.New(),\n\t\tappPublicAddr: req.PublicAddr,\n\t\tappClusterName: req.ClusterName,\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// Create services.WebSession for this session.\n\tsessionID, err := utils.CryptoRandomHex(SessionTokenBytes)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tsession := services.NewWebSession(sessionID, services.KindWebSession, services.KindAppSession, services.WebSessionSpecV2{\n\t\tUser: req.Username,\n\t\tPriv: privateKey,\n\t\tPub: certs.ssh,\n\t\tTLSCert: certs.tls,\n\t\tExpires: s.clock.Now().Add(ttl),\n\t})\n\tif err = s.Identity.UpsertAppSession(ctx, session); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tlog.Debugf(\"Generated application web session for %v with TTL %v.\", req.Username, ttl)\n\n\treturn session, nil\n}", "func (o *GetAppsAppCallsCallParams) SetApp(app string) {\n\to.App = app\n}", "func (o *PostMultiNodeDeviceParams) SetAppcomps(appcomps *string) {\n\to.Appcomps = appcomps\n}", "func SendFeedback(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tvar r models.Review\n\n\tts := getToken(req)\n\tif ts == \"\" {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t_, err := authorize(\"employee\", ts, false)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tio.WriteString(w, err.Error())\n\t\treturn\n\t}\n\n\terr = json.NewDecoder(req.Body).Decode(&r)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\te, err := repo.GetEmployee(r.AuthorID)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tif b, i := toBReviewed(&e, &r); b {\n\t\terr = repo.AddReview(&r)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\te.Employees2Review[i] = e.Employees2Review[len(e.Employees2Review)-1]\n\t\te.Employees2Review = e.Employees2Review[:len(e.Employees2Review)-1]\n\n\t\terr = repo.UpdateEmployee(&e)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlog.Println(errors.New(\"Feedback does not match\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n}", "func (m *EducationAssignment) SetAssignTo(value EducationAssignmentRecipientable)() {\n m.assignTo = value\n}", "func (client RosettaNetProcessConfigurationsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (m *SecurityActionState) SetAppId(value *string)() {\n err := m.GetBackingStore().Set(\"appId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (r ListAppsRequest) Send(ctx context.Context) (*ListAppsResponse, 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 := &ListAppsResponse{\n\t\tListAppsOutput: r.Request.Data.(*ListAppsOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (c *AppsServices) Create(opt *AppsOpt) (interface{}, error) {\n\tu, err := url.Parse(c.client.BaseURL.String() + \"apps\")\n\tif err != nil {\n\t\treturn Success{}, err\n\t}\n\n\tb, err := EncodeBody(opt)\n\tif err != nil {\n\t\treturn Success{}, err\n\t}\n\n\tc.client.UseAuthKey = true\n\tresp, err := POST(u.String(), b, c.client)\n\tif err != nil {\n\t\treturn Success{}, err\n\t}\n\n\treturn resp, nil\n}", "func (s *AppServerV3) SetApp(app Application) error {\n\tappV3, ok := app.(*AppV3)\n\tif !ok {\n\t\treturn trace.BadParameter(\"expected *AppV3, got %T\", app)\n\t}\n\ts.Spec.App = appV3\n\treturn nil\n}", "func (client Client) CreateSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (p *Pvr) InstallApplication(app *AppData) (err error) {\n\n\tapp.SquashFile = SQUASH_FILE\n\tappManifest, err := p.GetApplicationManifest(app.Appname)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttargetApp := *app\n\ttargetManifest := appManifest\n\tif appManifest.Base != \"\" {\n\t\ttargetManifest, err = p.GetApplicationManifest(appManifest.Base)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttargetApp.Appmanifest = targetManifest\n\t\ttargetApp.Appname = appManifest.Base\n\t\ttargetApp.Base = \"\"\n\t}\n\n\tdockerName := targetManifest.DockerName\n\trepoDigest := targetManifest.DockerDigest\n\n\ttargetApp.From = repoDigest\n\tif targetApp.Source == \"remote\" && !strings.Contains(repoDigest, \"@\") {\n\t\ttargetApp.From = dockerName + \"@\" + repoDigest\n\t}\n\n\tswitch targetApp.SourceType {\n\tcase models.SourceTypeDocker:\n\t\terr = InstallDockerApp(p, &targetApp, targetManifest)\n\tcase models.SourceTypeRootFs:\n\t\terr = InstallRootFsApp(p, &targetApp, targetManifest)\n\tcase models.SourceTypePvr:\n\t\terr = InstallPVApp(p, &targetApp, targetManifest)\n\tdefault:\n\t\treturn fmt.Errorf(\"type %s not supported yet\", models.SourceTypePvr)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if we have ovl digest we go for it ...\n\tif appManifest.DockerOvlDigest != \"\" || appManifest.Base != \"\" {\n\t\tappManifest, err = p.GetApplicationManifest(app.Appname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tapp.SquashFile = SQUASH_OVL_FILE\n\n\t\trepoDigest = appManifest.DockerOvlDigest\n\t\tapp.From = repoDigest\n\t\tif app.Source == \"remote\" && !strings.Contains(repoDigest, \"@\") {\n\t\t\tapp.From = dockerName + \"@\" + repoDigest\n\t\t}\n\n\t\tswitch app.SourceType {\n\t\tcase models.SourceTypeDocker:\n\t\t\terr = InstallDockerApp(p, app, appManifest)\n\t\tcase models.SourceTypeRootFs:\n\t\t\terr = InstallRootFsApp(p, app, appManifest)\n\t\tcase models.SourceTypePvr:\n\t\t\terr = InstallPVApp(p, app, appManifest)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"type %s not supported yet\", models.SourceTypePvr)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdiff, err := p.Diff()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// skip updating dm if nothing changed really ...\n\tif diff != nil && len(*diff) == 2 {\n\t\treturn nil\n\t}\n\n\tif appManifest.DmEnabled != nil {\n\t\terr = p.DmCVerityApply(app.Appname)\n\t}\n\n\treturn err\n}", "func (sp *StackPackage) SetApp(app v1alpha1.AppMetadataSpec) {\n\tsp.Stack.Spec.AppMetadataSpec = app\n\tsp.appSet = true\n}", "func (m *AssignmentPoliciesRequestBuilder) Post(ctx context.Context, body iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.AccessPackageAssignmentPolicyable, requestConfiguration *AssignmentPoliciesRequestBuilderPostRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.AccessPackageAssignmentPolicyable, error) {\n requestInfo, err := m.CreatePostRequestInformation(ctx, body, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.SendAsync(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateAccessPackageAssignmentPolicyFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.AccessPackageAssignmentPolicyable), nil\n}", "func (response *Response) Send(to http.ResponseWriter) {\n\tdata, _ := json.Marshal(response)\n\tto.Header().Set(\"Content-Type\", \"application/json\")\n\tto.WriteHeader(response.Code)\n\tto.Write(data)\n}", "func (client AccountClient) CreateOrUpdateSender(req *http.Request) (future AccountCreateOrUpdateFuture, 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 (client ApplicationsClient) RemoveOwnerSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AccountClient) UpdateSender(req *http.Request) (future AccountUpdateFuture, 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 (m *MobileAppAssignmentItemRequestBuilder) Get(ctx context.Context, requestConfiguration *MobileAppAssignmentItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.MobileAppAssignmentable, error) {\n requestInfo, err := m.CreateGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.SendAsync(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateMobileAppAssignmentFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.MobileAppAssignmentable), nil\n}", "func SetAppName(name string) {\n\tappName = name\n}", "func (r *AlibabaEleFengniaoChainstoreRangesAPIRequest) SetAppId(_appId string) error {\n\tr._appId = _appId\n\tr.Set(\"app_id\", _appId)\n\treturn nil\n}", "func (m *ServicePrincipalRiskDetection) SetAppId(value *string)() {\n err := m.GetBackingStore().Set(\"appId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (client HTTPSuccessClient) Put201Sender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (c Client) createApp(body io.Reader) (*App, error) {\n\treq, err := http.NewRequest(\"POST\", c.getURL(\"/apps\"), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar marshalled map[string]*App\n\terr = c.executeRequestAndMarshal(req, &marshalled)\n\treturn marshalled[\"app\"], err\n}" ]
[ "0.6890221", "0.6337396", "0.58724403", "0.5694946", "0.5535855", "0.54211444", "0.54211444", "0.5383776", "0.5249452", "0.5220505", "0.5213725", "0.5158245", "0.5153737", "0.51290494", "0.51187915", "0.5055091", "0.5055091", "0.5023446", "0.49632743", "0.49520877", "0.49119952", "0.4903171", "0.49028128", "0.4831688", "0.48259902", "0.47990313", "0.4758929", "0.4750674", "0.47231913", "0.47176573", "0.47144186", "0.47034955", "0.46581963", "0.4652154", "0.46458802", "0.46373665", "0.46347064", "0.46315262", "0.46049494", "0.46005693", "0.4592118", "0.45886877", "0.45847657", "0.45819533", "0.45787087", "0.45740634", "0.45682213", "0.45680934", "0.45388934", "0.45371392", "0.45258537", "0.45173198", "0.45130262", "0.45107105", "0.45107105", "0.4503072", "0.45026264", "0.44878322", "0.44644415", "0.4464298", "0.44525957", "0.44431043", "0.4423571", "0.44193736", "0.44185242", "0.44159254", "0.4405165", "0.44034216", "0.43962032", "0.43884608", "0.43809378", "0.43791324", "0.43710923", "0.43527845", "0.4345945", "0.4341244", "0.4334909", "0.43334258", "0.4331123", "0.43260622", "0.43249908", "0.43240112", "0.43213502", "0.43180043", "0.43106666", "0.43088627", "0.43077055", "0.43062896", "0.43047848", "0.4302824", "0.42972606", "0.42941684", "0.4288982", "0.42829245", "0.42585796", "0.42568845", "0.424916", "0.42467615", "0.42390567", "0.42389783" ]
0.7702348
0
AssignToAppResponder handles the response to the AssignToApp request. The method always closes the http.Response Body.
func (client AzureAccountsClient) AssignToAppResponder(resp *http.Response) (result OperationStatus, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AzureAccountsClient) AssignToApp(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (result OperationStatus, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.AssignToApp\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: azureAccountInfoObject,\n\t\t\tConstraints: []validation.Constraint{{Target: \"azureAccountInfoObject\", Name: validation.Null, Rule: false,\n\t\t\t\tChain: []validation.Constraint{{Target: \"azureAccountInfoObject.AzureSubscriptionID\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.ResourceGroup\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.AccountName\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t}}}}}); err != nil {\n\t\treturn result, validation.NewError(\"authoring.AzureAccountsClient\", \"AssignToApp\", err.Error())\n\t}\n\n\treq, err := client.AssignToAppPreparer(ctx, appID, azureAccountInfoObject)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.AssignToAppSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.AssignToAppResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (client AzureAccountsClient) AssignToAppSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (appHandler *ApplicationApiHandler) Application(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := ps.ByName(\"id\")\n\tidint, err := strconv.Atoi(id)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tapp, err := appHandler.appService.Application(idint)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tresponse, err := json.Marshal(app)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\t_, err = w.Write(response)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\n}", "func (client AzureAccountsClient) RemoveFromAppResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client ApplicationsClient) CreateResponder(resp *http.Response) (result Application, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (a *appHandler) CreateApp(w http.ResponseWriter, r *http.Request) {\n\tvar app model.App\n\terr := json.NewDecoder(r.Body).Decode(&app)\n\tif err != nil {\n\t\ta.httpUtil.WriteJSONBadRequestResponse(w, err)\n\t\treturn\n\t}\n\n\t// TODO : Create\n\n\tjsonR, err := json.Marshal(app)\n\tif err != nil {\n\t\ta.httpUtil.WriteJSONInternalServerErrorResponse(w, err)\n\t}\n\n\ta.httpUtil.WriteJSONSuccessResponse(w, jsonR)\n}", "func (client AppsClient) UpdateResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (o *PartialUpdateAppOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tif err := producer.Produce(rw, o.Payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (client ManagementClient) GetAppsResponder(resp *http.Response) (result ApplicationCollection, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client JobClient) ApproveResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func CreateUpdateMessageAppResponse() (response *UpdateMessageAppResponse) {\n\tresponse = &UpdateMessageAppResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (o *GetAppsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (client ApplicationsClient) AddOwnerResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client DeploymentsClient) UpdateResponder(resp *http.Response) (result DeploymentResource, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client MSIXPackagesClient) UpdateResponder(resp *http.Response) (result MSIXPackage, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (o *PartialUpdateAppDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(o._statusCode)\n\tif o.Payload != nil {\n\t\tif err := producer.Produce(rw, o.Payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (client AppsClient) AddResponder(resp *http.Response) (result UUID, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func postAppHandler(w http.ResponseWriter, r *http.Request) {\n\n\tfmt.Printf(\"post app handler\")\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\t//handle error http.Error() for example\n\t\tpanic(err)\n\t}\n\tcommand := r.Form[\"command\"][0]\n\tfmt.Printf(\"COMMAND %v\\n\", command)\n\n\tvars := mux.Vars(r)\n\tappid := vars[\"appid\"]\n\tvar app App\n\terr = getApp(appid, &app)\n\tcheck(err)\n\n\tif command == \"start\" {\n\t\tvar result map[string]interface{}\n\t\tif deployApp(app) {\n\t\t\tresult = map[string]interface{}{\n\t\t\t\t\"message\": \"OK\",\n\t\t\t}\n\t\t} else {\n\t\t\tresult = map[string]interface{}{\n\t\t\t\t\"message\": \"error: unable to deploy app\",\n\t\t\t}\n\t\t}\n\t\trespondWithResult(w, result)\n\t} else if command == \"stop\" {\n\t\tvar result map[string]interface{}\n\t\tif stopApp(app) {\n\t\t\tresult = map[string]interface{}{\n\t\t\t\t\"message\": \"OK\",\n\t\t\t}\n\t\t} else {\n\t\t\tresult = map[string]interface{}{\n\t\t\t\t\"message\": \"error: unable to stop app\",\n\t\t\t}\n\t\t}\n\t\trespondWithResult(w, result)\n\t}\n}", "func AppHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tswitch r.URL.Path {\n\t\tcase \"/listallapps\":\n\t\t\tcmd := cmdFactory.NewAllApps()\n\t\t\tcmdRunner.Run(w, r, cmd)\n\n\t\tcase \"/stopinganapp\":\n\t\t\tcmd := cmdFactory.NewStop()\n\t\t\tcmdRunner.Run(w, r, cmd)\n\n\t\tcase \"/startinganapp\":\n\t\t\tcmd := cmdFactory.NewStart()\n\t\t\tcmdRunner.Run(w, r, cmd)\n\t\t}\n\t}\n}", "func (m *ApplicationResource) AssignUserToApplication(ctx context.Context, appId string, body AppUser) (*AppUser, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/users\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"POST\", url, body)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar appUser *AppUser\n\n\tresp, err := rq.Do(ctx, req, &appUser)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn appUser, resp, nil\n}", "func (client AzureAccountsClient) AssignToAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\tif azureAccountInfoObject != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(azureAccountInfoObject))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func upgAppRespInit(client clientApi.Client, hdlrs AgentHandlers, name string) {\n\tlog.Infof(\"upgAppRespInit called\")\n\tctx := &upgapprespctx{\n\t\tagentHdlrs: hdlrs,\n\t}\n\tupgrade.UpgAppRespMountKey(client, name, delphi.MountMode_ReadWriteMode)\n\tupgrade.UpgAppRespWatch(client, ctx)\n}", "func (p *AppsCreateOrUpdatePoller) FinalResponse(ctx context.Context) (AppsCreateOrUpdateResponse, error) {\n\trespType := AppsCreateOrUpdateResponse{}\n\tresp, err := p.pt.FinalResponse(ctx, &respType.AppResource)\n\tif err != nil {\n\t\treturn AppsCreateOrUpdateResponse{}, err\n\t}\n\trespType.RawResponse = resp\n\treturn respType, nil\n}", "func (h appHandler) getAppHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tprojectName := vars[\"project-name\"]\n\tcompositeAppName := vars[\"composite-app-name\"]\n\tcompositeAppVersion := vars[\"version\"]\n\tname := vars[\"app-name\"]\n\n\t// handle the get all apps case - return a list of only the json parts\n\tif len(name) == 0 {\n\t\tvar retList []moduleLib.App\n\n\t\tret, err := h.client.GetApps(projectName, compositeAppName, compositeAppVersion)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tfor _, app := range ret {\n\t\t\tretList = append(retList, moduleLib.App{Metadata: app.Metadata})\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\terr = json.NewEncoder(w).Encode(retList)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\treturn\n\t}\n\n\taccepted, _, err := mime.ParseMediaType(r.Header.Get(\"Accept\"))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusNotAcceptable)\n\t\treturn\n\t}\n\n\tvar retApp moduleLib.App\n\tvar retAppContent moduleLib.AppContent\n\n\tretApp, err = h.client.GetApp(name, projectName, compositeAppName, compositeAppVersion)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tretAppContent, err = h.client.GetAppContent(name, projectName, compositeAppName, compositeAppVersion)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tswitch accepted {\n\tcase \"multipart/form-data\":\n\t\tmpw := multipart.NewWriter(w)\n\t\tw.Header().Set(\"Content-Type\", mpw.FormDataContentType())\n\t\tw.WriteHeader(http.StatusOK)\n\t\tpw, err := mpw.CreatePart(textproto.MIMEHeader{\"Content-Type\": {\"application/json\"}, \"Content-Disposition\": {\"form-data; name=metadata\"}})\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tif err := json.NewEncoder(pw).Encode(retApp); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tpw, err = mpw.CreatePart(textproto.MIMEHeader{\"Content-Type\": {\"application/octet-stream\"}, \"Content-Disposition\": {\"form-data; name=file; filename=fileContent\"}})\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tfcBytes, err := base64.StdEncoding.DecodeString(retAppContent.FileContent)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\t_, err = pw.Write(fcBytes)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\tcase \"application/json\":\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\terr = json.NewEncoder(w).Encode(retApp)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\tcase \"application/octet-stream\":\n\t\tw.Header().Set(\"Content-Type\", \"application/octet-stream\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfcBytes, err := base64.StdEncoding.DecodeString(retAppContent.FileContent)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\t_, err = w.Write(fcBytes)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\thttp.Error(w, \"set Accept: multipart/form-data, application/json or application/octet-stream\", http.StatusMultipleChoices)\n\t\treturn\n\t}\n}", "func (r *RPC) PasterAPP(c context.Context, arg *model.ArgPaster, res *model.Paster) (err error) {\n\tvar rs *model.Paster\n\tif rs, err = r.s.PasterAPP(c, arg.Platform, arg.AdType, arg.Aid, arg.TypeId, arg.Buvid); err == nil {\n\t\t*res = *rs\n\t}\n\treturn\n}", "func (client HTTPSuccessClient) Post202Responder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func (o *CancelLaunchOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (c *applicationUsecaseImpl) Deploy(ctx context.Context, app *model.Application, req apisv1.ApplicationDeployRequest) (*apisv1.ApplicationDeployResponse, error) {\n\t// TODO: rollback to handle all the error case\n\t// step1: Render oam application\n\tversion := utils.GenerateVersion(\"\")\n\toamApp, err := c.renderOAMApplication(ctx, app, req.WorkflowName, version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfigByte, _ := yaml.Marshal(oamApp)\n\n\tworkflow, err := c.workflowUsecase.GetWorkflow(ctx, app, oamApp.Annotations[oam.AnnotationWorkflowName])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// step2: check and create deploy event\n\tif !req.Force {\n\t\tvar lastVersion = model.ApplicationRevision{\n\t\t\tAppPrimaryKey: app.PrimaryKey(),\n\t\t\tEnvName: workflow.EnvName,\n\t\t}\n\t\tlist, err := c.ds.List(ctx, &lastVersion, &datastore.ListOptions{\n\t\t\tPageSize: 1, Page: 1, SortBy: []datastore.SortOption{{Key: \"createTime\", Order: datastore.SortOrderDescending}}})\n\t\tif err != nil && !errors.Is(err, datastore.ErrRecordNotExist) {\n\t\t\tlog.Logger.Errorf(\"query app latest revision failure %s\", err.Error())\n\t\t\treturn nil, bcode.ErrDeployConflict\n\t\t}\n\t\tif len(list) > 0 && list[0].(*model.ApplicationRevision).Status != model.RevisionStatusComplete {\n\t\t\tlog.Logger.Warnf(\"last app revision can not complete %s/%s\", list[0].(*model.ApplicationRevision).AppPrimaryKey, list[0].(*model.ApplicationRevision).Version)\n\t\t\treturn nil, bcode.ErrDeployConflict\n\t\t}\n\t}\n\n\tvar appRevision = &model.ApplicationRevision{\n\t\tAppPrimaryKey: app.PrimaryKey(),\n\t\tVersion: version,\n\t\tApplyAppConfig: string(configByte),\n\t\tStatus: model.RevisionStatusInit,\n\t\t// TODO: Get user information from ctx and assign a value.\n\t\tDeployUser: \"\",\n\t\tNote: req.Note,\n\t\tTriggerType: req.TriggerType,\n\t\tWorkflowName: oamApp.Annotations[oam.AnnotationWorkflowName],\n\t\tEnvName: workflow.EnvName,\n\t}\n\n\tif err := c.ds.Add(ctx, appRevision); err != nil {\n\t\treturn nil, err\n\t}\n\t// step3: check and create namespace\n\tvar namespace corev1.Namespace\n\tif err := c.kubeClient.Get(ctx, types.NamespacedName{Name: oamApp.Namespace}, &namespace); apierrors.IsNotFound(err) {\n\t\tnamespace.Name = oamApp.Namespace\n\t\tif err := c.kubeClient.Create(ctx, &namespace); err != nil {\n\t\t\tlog.Logger.Errorf(\"auto create namespace failure %s\", err.Error())\n\t\t\treturn nil, bcode.ErrCreateNamespace\n\t\t}\n\t}\n\t// step4: apply to controller cluster\n\terr = c.apply.Apply(ctx, oamApp)\n\tif err != nil {\n\t\tappRevision.Status = model.RevisionStatusFail\n\t\tappRevision.Reason = err.Error()\n\t\tif err := c.ds.Put(ctx, appRevision); err != nil {\n\t\t\tlog.Logger.Warnf(\"update deploy event failure %s\", err.Error())\n\t\t}\n\n\t\tlog.Logger.Errorf(\"deploy app %s failure %s\", app.PrimaryKey(), err.Error())\n\t\treturn nil, bcode.ErrDeployApplyFail\n\t}\n\n\t// step5: create workflow record\n\tif err := c.workflowUsecase.CreateWorkflowRecord(ctx, app, oamApp, workflow); err != nil {\n\t\tlog.Logger.Warnf(\"create workflow record failure %s\", err.Error())\n\t}\n\n\t// step6: update app revision status\n\tappRevision.Status = model.RevisionStatusRunning\n\tif err := c.ds.Put(ctx, appRevision); err != nil {\n\t\tlog.Logger.Warnf(\"update app revision failure %s\", err.Error())\n\t}\n\n\treturn &apisv1.ApplicationDeployResponse{\n\t\tApplicationRevisionBase: apisv1.ApplicationRevisionBase{\n\t\t\tVersion: appRevision.Version,\n\t\t\tStatus: appRevision.Status,\n\t\t\tReason: appRevision.Reason,\n\t\t\tDeployUser: appRevision.DeployUser,\n\t\t\tNote: appRevision.Note,\n\t\t\tTriggerType: appRevision.TriggerType,\n\t\t},\n\t}, nil\n}", "func (client AppsClient) ListResponder(resp *http.Response) (result ListApplicationInfoResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client MSIXPackagesClient) CreateOrUpdateResponder(resp *http.Response) (result MSIXPackage, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (o *BookNewMedicalAppointmentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (client ApplicationsClient) PatchResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client JobClient) UpdateResponder(resp *http.Response) (result JobResourceDescription, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusCreated,http.StatusAccepted),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client ApplicationsClient) GetResponder(resp *http.Response) (result Application, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client AccountClient) UpdateResponder(resp *http.Response) (result AccountResourceDescription, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusCreated,http.StatusAccepted),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client AppsClient) GetResponder(resp *http.Response) (result ApplicationInfoResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (b *BaseHandler) setApp(a *App) {\n\tb.app = a\n}", "func (o OpenSignal) UpdateAnApp(app App) (App, error) {\n\tstrResponse := App{}\n\n\tURL := f(updateAnApp, app.ID)\n\tres, body, errs := o.Client.Put(URL).\n\t\tSend(app).\n\t\tSet(\"Authorization\", \"Basic \"+o.AuthKey).\n\t\tEndStruct(&strResponse)\n\terr := catch(res, body)\n\tif err == nil {\n\t\tfor _, e := range errs {\n\t\t\tif e != nil {\n\t\t\t\terr = e\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn strResponse, err\n}", "func (client appendBlobClient) sealResponder(resp pipeline.Response) (pipeline.Response, error) {\n\terr := validateResponse(resp, http.StatusOK)\n\tif resp == nil {\n\t\treturn nil, err\n\t}\n\tio.Copy(ioutil.Discard, resp.Response().Body)\n\tresp.Response().Body.Close()\n\treturn &AppendBlobSealResponse{rawResponse: resp.Response()}, err\n}", "func (o *StopAppAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(202)\n}", "func (a *OAuthAuthorizationsApiService) AuthorizationsOwnerSubjectidApplicationAppidDelete(ctx _context.Context, subjectid string, appid string) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/authorizations/owner/{subjectid}/application/{appid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"subjectid\"+\"}\", _neturl.QueryEscape(parameterToString(subjectid, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"appid\"+\"}\", _neturl.QueryEscape(parameterToString(appid, \"\")) , -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{}\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 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\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 localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (o *UpdateOfficeUserOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func DeployApp(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tstatus := params[\"status\"]\n\tlog.Printf(\"Params: %s\\n\", params)\n\n\tclientset, err := getConfig()\n\tif err != nil {\n\t\tlog.Fatalln(\"failed to get the config:\", err)\n\t}\n\n\tdeploymentsClient := clientset.AppsV1().Deployments(namespace)\n\n\tdeploymentName := params[\"app\"] + \"-deployment\"\n\n\tlist, err := deploymentsClient.List(metav1.ListOptions{})\n\tif err != nil {\n\t\tlog.Fatalln(\"failed to get deployments:\", err)\n\t}\n\n\tcontainers := []apiv1.Container{createContainer(params[\"app\"], repository+\"/\"+params[\"app\"]+appversion)}\n\n\tif status == \"true\" {\n\t\tfor _, d := range list.Items {\n\t\t\tif d.Name == deploymentName && *d.Spec.Replicas > 0 {\n\t\t\t\tlog.Printf(\"Deployment already running: %s\\n\", deploymentName)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tnodeLabel(params[\"node\"], \"app\", params[\"app\"], \"add\")\n\n\t\tdeployment := &appsv1.Deployment{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: deploymentName,\n\t\t\t},\n\t\t\tSpec: appsv1.DeploymentSpec{\n\t\t\t\tReplicas: int32Ptr(1),\n\t\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\t\"app\": params[\"app\"],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tTemplate: apiv1.PodTemplateSpec{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\t\"app\": params[\"app\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tSpec: apiv1.PodSpec{\n\t\t\t\t\t\tContainers: containers,\n\t\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\t\t\"app\": params[\"app\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tVolumes: []apiv1.Volume{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: \"mem\",\n\t\t\t\t\t\t\t\tVolumeSource: apiv1.VolumeSource{\n\t\t\t\t\t\t\t\t\tHostPath: &apiv1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\t\tPath: \"/dev/mem\",\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\t{\n\t\t\t\t\t\t\t\tName: \"gpiomem\",\n\t\t\t\t\t\t\t\tVolumeSource: apiv1.VolumeSource{\n\t\t\t\t\t\t\t\t\tHostPath: &apiv1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\t\tPath: \"/dev/gpiomem\",\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\t// Create Deployment\n\t\tfmt.Println(\"Creating deployment...\")\n\t\tresult, err := deploymentsClient.Create(deployment)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Printf(\"Created deployment %q.\\n\", result.GetObjectMeta().GetName())\n\n\t} else {\n\n\t\tnodeLabel(params[\"node\"], \"app\", params[\"app\"], \"del\")\n\n\t\tfmt.Println(\"Deleting deployment...\")\n\t\tdeletePolicy := metav1.DeletePropagationForeground\n\t\tif err := deploymentsClient.Delete(deploymentName, &metav1.DeleteOptions{\n\t\t\tPropagationPolicy: &deletePolicy,\n\t\t}); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(\"Deleted deployment.\")\n\t}\n\n}", "func (client ConversationsClient) ReplyToActivityMethodResponder(resp *http.Response) (result ResourceResponseType, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusCreated,http.StatusAccepted),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client ModelClient) UpdateIntentResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (m *IosVppAppCollectionResponse) SetValue(value []IosVppAppable)() {\n err := m.GetBackingStore().Set(\"value\", value)\n if err != nil {\n panic(err)\n }\n}", "func (a *appHandler) GetApp(w http.ResponseWriter, r *http.Request) {\n\tvar app model.App\n\n\t// TODO : QUERY\n\n\tjsonR, err := json.Marshal(app)\n\tif err != nil {\n\t\ta.httpUtil.WriteJSONInternalServerErrorResponse(w, err)\n\t}\n\n\ta.httpUtil.WriteJSONSuccessResponse(w, jsonR)\n}", "func (app *App) Commit() (res abci.ResponseCommit) {\n\tapp.FlushMessages()\n\treturn app.BandApp.Commit()\n}", "func (p *Proxy) InstallApp(in Incoming, cc apps.Context, appID apps.AppID, deployType apps.DeployType, trusted bool, secret string) (*apps.App, string, error) {\n\tconf, _, log := p.conf.Basic()\n\tlog = log.With(\"app_id\", appID)\n\tm, err := p.store.Manifest.Get(appID)\n\tif err != nil {\n\t\treturn nil, \"\", errors.Wrap(err, \"failed to find manifest to install app\")\n\t}\n\tif !m.SupportsDeploy(deployType) {\n\t\treturn nil, \"\", errors.Errorf(\"app does not support %s deployment\", deployType)\n\t}\n\terr = CanDeploy(p, deployType)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tapp, err := p.store.App.Get(appID)\n\tif err != nil {\n\t\tif !errors.Is(err, utils.ErrNotFound) {\n\t\t\treturn nil, \"\", errors.Wrap(err, \"failed looking for existing app\")\n\t\t}\n\t\tapp = &apps.App{}\n\t}\n\n\tapp.DeployType = deployType\n\tapp.Manifest = *m\n\tif app.Disabled {\n\t\tapp.Disabled = false\n\t}\n\tapp.GrantedPermissions = m.RequestedPermissions\n\tapp.GrantedLocations = m.RequestedLocations\n\tif secret != \"\" {\n\t\tapp.Secret = secret\n\t}\n\n\tif app.GrantedPermissions.Contains(apps.PermissionRemoteWebhooks) {\n\t\tapp.WebhookSecret = model.NewId()\n\t}\n\n\ticon, err := p.getAppIcon(*app)\n\tif err != nil {\n\t\treturn nil, \"\", errors.Wrap(err, \"failed get bot icon\")\n\t}\n\tif icon != nil {\n\t\tdefer icon.Close()\n\t}\n\n\t// See if the app is inaaccessible. Call its ping path with nothing\n\t// expanded, ignore 404 errors coming back and consider everything else a\n\t// \"success\".\n\t//\n\t// Note that this check is often ineffective, but \"the best we can do\"\n\t// before we start the diffcult-to-revert install process.\n\t_, err = p.callApp(in, *app, apps.CallRequest{\n\t\tCall: apps.DefaultPing,\n\t\tContext: cc,\n\t})\n\tif err != nil && errors.Cause(err) != utils.ErrNotFound {\n\t\treturn nil, \"\", errors.Wrapf(err, \"failed to install, %s path is not accessible\", apps.DefaultPing.Path)\n\t}\n\n\tasAdmin, err := p.getAdminClient(in)\n\tif err != nil {\n\t\treturn nil, \"\", errors.Wrap(err, \"failed to get an admin HTTP client\")\n\t}\n\terr = p.ensureBot(asAdmin, log, app, icon)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tif app.GrantedPermissions.Contains(apps.PermissionActAsUser) {\n\t\tvar oAuthApp *model.OAuthApp\n\t\toAuthApp, err = p.ensureOAuthApp(asAdmin, log, conf, *app, trusted, in.ActingUserID)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tapp.MattermostOAuth2.ClientID = oAuthApp.Id\n\t\tapp.MattermostOAuth2.ClientSecret = oAuthApp.ClientSecret\n\t\tapp.Trusted = trusted\n\t}\n\n\terr = p.store.App.Save(*app)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tmessage := fmt.Sprintf(\"Installed %s.\", app.DisplayName)\n\tif app.OnInstall != nil {\n\t\tcresp := p.call(in, *app, *app.OnInstall, &cc)\n\t\tif cresp.Type == apps.CallResponseTypeError {\n\t\t\t// TODO: should fail and roll back.\n\t\t\tlog.WithError(cresp).Warnf(\"Installed %s, despite on_install failure.\", app.AppID)\n\t\t\tmessage = fmt.Sprintf(\"Installed %s, despite on_install failure: %s\", app.AppID, cresp.Error())\n\t\t} else if cresp.Markdown != \"\" {\n\t\t\tmessage += \"\\n\\n\" + cresp.Markdown\n\t\t}\n\t} else if len(app.GrantedLocations) > 0 {\n\t\t// Make sure the app's binding call is accessible.\n\t\tcresp := p.call(in, *app, app.Bindings.WithDefault(apps.DefaultBindings), &cc)\n\t\tif cresp.Type == apps.CallResponseTypeError {\n\t\t\t// TODO: should fail and roll back.\n\t\t\tlog.WithError(cresp).Warnf(\"Installed %s, despite bindings failure.\", app.AppID)\n\t\t\tmessage = fmt.Sprintf(\"Installed %s despite bindings failure: %s\", app.AppID, cresp.Error())\n\t\t}\n\t}\n\n\tp.conf.Telemetry().TrackInstall(string(app.AppID), string(app.DeployType))\n\n\tp.dispatchRefreshBindingsEvent(in.ActingUserID)\n\n\tlog.Infof(message)\n\treturn app, message, nil\n}", "func (client HTTPSuccessClient) Put202Responder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func (m *contextManager) onAssociateRequest(requestItems []pdu.SubItem) ([]pdu.SubItem, error) {\n\tresponses := []pdu.SubItem{\n\t\t&pdu.ApplicationContextItem{\n\t\t\tName: pdu.DICOMApplicationContextItemName,\n\t\t},\n\t}\n\tfor _, requestItem := range requestItems {\n\t\tswitch ri := requestItem.(type) {\n\t\tcase *pdu.ApplicationContextItem:\n\t\t\tif ri.Name != pdu.DICOMApplicationContextItemName {\n\t\t\t\tlogrus.Warnf(\"dicom_server.onAssociateRequest(%s): Found illegal applicationcontextname. Expect %v, found %v\",\n\t\t\t\t\tm.label, ri.Name, pdu.DICOMApplicationContextItemName)\n\t\t\t}\n\t\tcase *pdu.PresentationContextItem:\n\t\t\tvar sopUID string\n\t\t\tvar pickedTransferSyntaxUID string\n\t\t\tfor _, subItem := range ri.Items {\n\t\t\t\tswitch c := subItem.(type) {\n\t\t\t\tcase *pdu.AbstractSyntaxSubItem:\n\t\t\t\t\tif sopUID != \"\" {\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"dicom.onAssociateRequest: Multiple AbstractSyntaxSubItem found in %v\",\n\t\t\t\t\t\t\tri.String())\n\t\t\t\t\t}\n\t\t\t\t\tsopUID = c.Name\n\t\t\t\tcase *pdu.TransferSyntaxSubItem:\n\t\t\t\t\t// Just pick the first syntax UID proposed by the client.\n\t\t\t\t\tif pickedTransferSyntaxUID == \"\" {\n\t\t\t\t\t\tpickedTransferSyntaxUID = c.Name\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn nil, fmt.Errorf(\"dicom.onAssociateRequest: Unknown subitem in PresentationContext: %s\",\n\t\t\t\t\t\tsubItem.String())\n\t\t\t\t}\n\t\t\t}\n\t\t\tif sopUID == \"\" || pickedTransferSyntaxUID == \"\" {\n\t\t\t\treturn nil, fmt.Errorf(\"dicom.onAssociateRequest: SOP or transfersyntax not found in PresentationContext: %v\",\n\t\t\t\t\tri.String())\n\t\t\t}\n\t\t\tresponses = append(responses, &pdu.PresentationContextItem{\n\t\t\t\tType: pdu.ItemTypePresentationContextResponse,\n\t\t\t\tContextID: ri.ContextID,\n\t\t\t\tResult: 0, // accepted\n\t\t\t\tItems: []pdu.SubItem{&pdu.TransferSyntaxSubItem{Name: pickedTransferSyntaxUID}}})\n\t\t\tlogrus.Infof(\"dicom.onAssociateRequest(%s): Provider(%p): addmapping %v %v %v\",\n\t\t\t\tm.label, m, sopUID, pickedTransferSyntaxUID, ri.ContextID)\n\t\t\t// TODO 触发service provider的callback而不是随便接受sopclass\n\t\t\taddContextMapping(m, sopUID, pickedTransferSyntaxUID, ri.ContextID, pdu.PresentationContextAccepted)\n\t\tcase *pdu.UserInformationItem:\n\t\t\tfor _, subItem := range ri.Items {\n\t\t\t\tswitch c := subItem.(type) {\n\t\t\t\tcase *pdu.UserInformationMaximumLengthItem:\n\t\t\t\t\tm.peerMaxPDUSize = int(c.MaximumLengthReceived)\n\t\t\t\tcase *pdu.ImplementationClassUIDSubItem:\n\t\t\t\t\tm.peerImplementationClassUID = c.Name\n\t\t\t\tcase *pdu.ImplementationVersionNameSubItem:\n\t\t\t\t\tm.peerImplementationVersionName = c.Name\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tresponses = append(responses,\n\t\t&pdu.UserInformationItem{\n\t\t\tItems: []pdu.SubItem{&pdu.UserInformationMaximumLengthItem{MaximumLengthReceived: uint32(DefaultMaxPDUSize)}}})\n\tlogrus.Infof(\"dicom_server.onAssociateRequest(%s): Received associate request, #contexts:%v, maxPDU:%v, implclass:%v, version:%v\",\n\t\tm.label, len(m.contextIDToAbstractSyntaxNameMap),\n\t\tm.peerMaxPDUSize, m.peerImplementationClassUID, m.peerImplementationVersionName)\n\treturn responses, nil\n}", "func (w *AppResponseWriter) Write(data []byte) (n int, err error) {\n\tif !w.written {\n\t\tw.statusCode = http.StatusOK\n\t\tw.written = true\n\t}\n\treturn w.ResponseWriter.Write(data)\n}", "func (client ConversationsClient) UpdateActivityMethodResponder(resp *http.Response) (result ResourceResponseType, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusCreated,http.StatusAccepted),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (o *GetAppsInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(500)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (client AppsClient) PublishResponder(resp *http.Response) (result ProductionOrStagingEndpointInfo, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (o *PartialUpdateAppUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(401)\n\tif o.Payload != nil {\n\t\tif err := producer.Produce(rw, o.Payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (o *AddVappOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func CreateDeployK8sApplicationResponse() (response *DeployK8sApplicationResponse) {\n\tresponse = &DeployK8sApplicationResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateApplication() *Alpha {\n app := &Alpha{}\n app.Request = &Request{}\n app.Response = &Response{}\n app.init()\n return app\n}", "func (o *RegisterRecipientToProgramOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tpayload := o.Payload\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) // let the recovery middleware deal with this\n\t}\n}", "func (appHandler *ApplicationApiHandler) AddApplication(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar app entity.Application\n\terr := json.NewDecoder(r.Body).Decode(&app)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\t_, err = appHandler.appService.Store(&app)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tresponse, err := json.Marshal(app)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusCreated)\n\t_, err = w.Write(response)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n}", "func (client HTTPSuccessClient) Patch202Responder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func ReturnAssignmentResponse(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\tc := Assignment{\"assignmentID\", \"http://ispw:8080/ispw/ispw/assignments/assignmentid\"}\n\toutgoingJSON, err := json.Marshal(c)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tres.WriteHeader(http.StatusCreated)\n\tfmt.Fprint(res, string(outgoingJSON))\n}", "func (o *PostUserIDF2aOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func ApplicationCreate(w http.ResponseWriter, r *http.Request) {\n\tdb, err := database.Connect()\n\tdefer db.Close()\n\tif err != nil {\n\t\tlog.Printf(\"Database error: '%s'\\n\", err)\n\t\thttp.Error(w, \"there was an error when attempting to connect to the database\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar createForm struct {\n\t\tName string\n\t}\n\tdecoder := json.NewDecoder(r.Body)\n\terr = decoder.Decode(&createForm)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\tlog.Printf(\"decoding error: '%s'\\n\", err)\n\t\thttp.Error(w, \"there was an error when attempting to parse the form\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tapp := resources.Application{\n\t\tName: createForm.Name,\n\t}\n\t_, err = resources.CreateApplication(db, &app)\n\t// @todo handle failed save w/out error?\n\tif err != nil {\n\t\tlog.Printf(\"Error when retrieving application: '%s'\\n\", err)\n\t\thttp.Error(w, \"there was an error when retrieving application\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// @todo return some sort of content?\n\tw.WriteHeader(http.StatusCreated)\n\treturn\n}", "func (r *RepoStruct) SetApp(appRelName, appName string) (updated *bool, _ error) {\n\tif err := r.initApp(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tupdated = new(bool)\n\tif v, found := r.Apps[appRelName]; !found || (found && v != appName) {\n\t\t*updated = true\n\t}\n\tr.Apps[appRelName] = appName\n\n\tif set, err := r.SetInternalRelApp(appRelName, appName); set == nil {\n\t\treturn set, err\n\t}\n\treturn\n}", "func (o *UserEditBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(400)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (c Client) FetchApp() (*Identity, error) {\n\treturn c.fetchApp()\n}", "func AppUpdateHandler(context utils.Context, w http.ResponseWriter, r *http.Request) {\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.LogInfo.Printf(\"Error reading body: %v\", err)\n\t\thttp.Error(w, \"unable to read request body\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.LogInfo.Printf(\"Attempting to update : %s\\n\", string(body))\n\n\t//use decode here instead of unmarshal\n\tapplication, err := utils.ParseJson(body)\n\n\tif err != nil {\n\t\tlog.LogError.Println(err)\n\t\thttp.Error(w, \"unable to parse JSON\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdbConn := context.DBConn\n\tdbBucket := context.DBBucketApp\n\n\tkey := []byte(application.Environment + \"_\" + application.Name)\n\tvalue := []byte(body)\n\n\tif err := database.InsertDBValue(dbConn, dbBucket, key, value); err != nil {\n\t\tlog.LogInfo.Printf(\"Failed to update DB: %v\", err)\n\t}\n\n\tlog.LogInfo.Printf(\"application environment: %s\\n\", application.Environment)\n\n}", "func (c Client) createApp(body io.Reader) (*App, error) {\n\treq, err := http.NewRequest(\"POST\", c.getURL(\"/apps\"), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar marshalled map[string]*App\n\terr = c.executeRequestAndMarshal(req, &marshalled)\n\treturn marshalled[\"app\"], err\n}", "func (client CertificateOrdersClient) ResendCertificateEmailResponder(resp *http.Response) (result SetObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (appHandler *ApplicationApiHandler) DeleteApp(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := ps.ByName(\"id\")\n\tidint, err := strconv.Atoi(id)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tapp, err := appHandler.appService.DeleteApplication(idint)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tresponse, err := json.Marshal(app)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\t_, err = w.Write(response)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\n}", "func (client ApplicationsClient) RemoveOwnerResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (_m *AppFunctionContext) SetResponseData(data []byte) {\n\t_m.Called(data)\n}", "func (cli *OpsGenieAlertV2Client) Assign(req alertsv2.AssignAlertRequest) (*AsyncRequestResponse, error) {\n\treturn cli.sendAsyncPostRequest(&req)\n}", "func (this *IdpAuthnRequest) WriteResponse(w http.ResponseWriter) (err error) {\n\tif len(this.Response) == 0 {\n\t\treturn errors.New(\"empty response\")\n\t}\n\n\t// the only supported binding is the HTTP-POST binding\n\tswitch this.ACSEndpoint.Binding {\n\tcase HTTPPostBinding:\n\t\ttmpl := template.Must(template.New(\"saml-post-form\").Parse(`<html>` +\n\t\t\t`<form method=\"post\" action=\"{{.URL}}\" id=\"SAMLResponseForm\">` +\n\t\t\t`<input type=\"hidden\" name=\"SAMLResponse\" value=\"{{.SAMLResponse}}\" />` +\n\t\t\t`<input type=\"hidden\" name=\"RelayState\" value=\"{{.RelayState}}\" />` +\n\t\t\t`<input id=\"SAMLSubmitButton\" type=\"submit\" value=\"Continue\" />` +\n\t\t\t`</form>` +\n\t\t\t`<script>document.getElementById('SAMLSubmitButton').style.visibility='hidden';</script>` +\n\t\t\t`<script>document.getElementById('SAMLResponseForm').submit();</script>` +\n\t\t\t`</html>`))\n\t\tdata := struct {\n\t\t\tURL string\n\t\t\tSAMLResponse string\n\t\t\tRelayState string\n\t\t}{\n\t\t\tURL: this.ACSEndpoint.Location,\n\t\t\tSAMLResponse: base64.StdEncoding.EncodeToString(this.Response),\n\t\t\tRelayState: this.RelayState,\n\t\t}\n\n\t\tbuf := bytes.NewBuffer(nil)\n\t\tif err := tmpl.Execute(buf, data); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := io.Copy(w, buf); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\n\tdefault:\n\t\treturn fmt.Errorf(\"%s: unsupported binding %s\",\n\t\t\tthis.ServiceProviderMetadata.EntityID,\n\t\t\tthis.ACSEndpoint.Binding)\n\t}\n}", "func (o *PostUserIDF2aDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(o._statusCode)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func setResponse(data interface{}, w http.ResponseWriter) {\n\tmarshalResp, _ := json.Marshal(data)\n\n\t_, err := w.Write(marshalResp)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Print(err)\n\t}\n}", "func (o *GetOfficeUserOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (client AppsClient) ImportResponder(resp *http.Response) (result UUID, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (o *AddItemAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(202)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (s *server) Create(ctx context.Context, body *pb.RequestBody) (*pb.ResponseBody, error) {\n\tlanguage := body.GetLanguage()\n\tapp := &types.ApplicationConfig{}\n\n\terr := json.Unmarshal(body.GetData(), app)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser, err := mongo.FetchSingleUser(body.GetOwner())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmaxCount := configs.ServiceConfig.AppMaker.AppLimit\n\trateCount := configs.ServiceConfig.RateLimit\n\ttimeInterval := configs.ServiceConfig.RateInterval\n\tif !user.IsAdmin() && maxCount >= 0 {\n\t\trateLimitCount := mongo.CountInstanceInTimeFrame(body.GetOwner(), mongo.AppInstance, timeInterval)\n\t\ttotalCount := mongo.CountInstancesByUser(body.GetOwner(), mongo.AppInstance)\n\t\tif totalCount < maxCount {\n\t\t\tif rateLimitCount >= rateCount && rateCount >= 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"cannot deploy more than %d app instances in %d hours\", rateCount, timeInterval)\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"cannot deploy more than %d app instances\", maxCount)\n\t\t}\n\t}\n\n\tapp.SetLanguage(language)\n\tapp.SetOwner(body.GetOwner())\n\tapp.SetInstanceType(mongo.AppInstance)\n\tapp.SetHostIP(utils.HostIP)\n\tapp.SetNameServers(configs.GasperConfig.DNSServers)\n\tapp.SetDateTime()\n\n\tgendnsNameServers, _ := redis.FetchServiceInstances(types.GenDNS)\n\tfor _, nameServer := range gendnsNameServers {\n\t\tif strings.Contains(nameServer, \":\") {\n\t\t\tapp.AddNameServers(strings.Split(nameServer, \":\")[0])\n\t\t} else {\n\t\t\tutils.LogError(\"AppMaker-Controller-1\", fmt.Errorf(\"GenDNS instance %s is of invalid format\", nameServer))\n\t\t}\n\t}\n\n\tif pipeline[language] == nil {\n\t\treturn nil, fmt.Errorf(\"language `%s` is not supported\", language)\n\t}\n\tresErr := pipeline[language].create(app)\n\tif resErr != nil {\n\t\tif resErr.Message() != \"repository already exists\" && resErr.Message() != \"container already exists\" {\n\t\t\tgo diskCleanup(app.GetName())\n\t\t}\n\t\treturn nil, fmt.Errorf(resErr.Error())\n\t}\n\n\tsshEntrypointIP := configs.ServiceConfig.GenSSH.EntrypointIP\n\tif len(sshEntrypointIP) == 0 {\n\t\tsshEntrypointIP = utils.HostIP\n\t}\n\tapp.SetSSHCmd(configs.ServiceConfig.GenSSH.Port, app.GetName(), sshEntrypointIP)\n\n\tapp.SetAppURL(fmt.Sprintf(\"%s.%s.%s\", app.GetName(), cloudflare.ApplicationInstance, configs.GasperConfig.Domain))\n\n\tif configs.CloudflareConfig.PlugIn {\n\t\tresp, err := cloudflare.CreateApplicationRecord(app.GetName())\n\t\tif err != nil {\n\t\t\tgo diskCleanup(app.GetName())\n\t\t\treturn nil, err\n\t\t}\n\t\tapp.SetCloudflareID(resp.Result.ID)\n\t\tapp.SetPublicIP(configs.CloudflareConfig.PublicIP)\n\t}\n\n\terr = mongo.UpsertInstance(\n\t\ttypes.M{\n\t\t\tmongo.NameKey: app.GetName(),\n\t\t\tmongo.InstanceTypeKey: mongo.AppInstance,\n\t\t}, app)\n\n\tif err != nil && err != mongo.ErrNoDocuments {\n\t\tgo diskCleanup(app.GetName())\n\t\tgo stateCleanup(app.GetName())\n\t\treturn nil, err\n\t}\n\n\terr = redis.RegisterApp(\n\t\tapp.GetName(),\n\t\tfmt.Sprintf(\"%s:%d\", utils.HostIP, configs.ServiceConfig.AppMaker.Port),\n\t\tfmt.Sprintf(\"%s:%d\", utils.HostIP, app.GetContainerPort()),\n\t)\n\n\tif err != nil {\n\t\tgo diskCleanup(app.GetName())\n\t\tgo stateCleanup(app.GetName())\n\t\treturn nil, err\n\t}\n\n\terr = redis.IncrementServiceLoad(\n\t\tServiceName,\n\t\tfmt.Sprintf(\"%s:%d\", utils.HostIP, configs.ServiceConfig.AppMaker.Port),\n\t)\n\n\tif err != nil {\n\t\tgo diskCleanup(app.GetName())\n\t\tgo stateCleanup(app.GetName())\n\t\treturn nil, err\n\t}\n\n\tapp.SetSuccess(true)\n\n\tresponse, err := json.Marshal(app)\n\treturn &pb.ResponseBody{Data: response}, err\n}", "func CreateModifyContainerAppAttributesResponse() (response *ModifyContainerAppAttributesResponse) {\n\tresponse = &ModifyContainerAppAttributesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client ServicesClient) UpdateResponder(resp *http.Response) (result ServiceResource, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (tc *selectController) fetchAppPackage(pack, supplier string, userID int64) (*mr.App, error) {\n\tapp, err := mr.NewManager().FetchAppByPack(pack, supplier)\n\tif err != nil {\n\t\tapp, err = mr.NewManager().InsertApp(pack, supplier, userID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn app, nil\n}", "func CreateBindApplicationToEdgeInstanceResponse() (response *BindApplicationToEdgeInstanceResponse) {\n\tresponse = &BindApplicationToEdgeInstanceResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func sendResponse(w http.ResponseWriter, statusCode int, message string) {\n\tw.WriteHeader(statusCode)\n\tjson.NewEncoder(w).Encode(appResponse{Message: message})\n}", "func (handler *CommandHandler) HandleAssignCommand(text string) ([]byte, error) {\n\theader := NewHeaderBlock(UpdateHeader)\n\tdiv := NewDividerBlock()\n\tif !ValidateAssignCommandText(text) {\n\t\terrBlock := NewSectionTextBlock(\"plain_text\", AssignBadArgsText)\n\t\tresponse := NewResponse(header, div, errBlock)\n\t\tbyt, err := json.Marshal(response)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn byt, nil\n\t}\n\targs := strings.Split(text, \" \")\n\tid, _ := strconv.Atoi(args[0])\n\terr := handler.Repository.AssignTaskTo(id, args[1])\n\tif err == mysql.ErrNoRowOrMoreThanOne {\n\t\terrBlock := NewSectionTextBlock(\"plain_text\", NoSuchTaskIDText)\n\t\tresponse := NewResponse(header, div, errBlock)\n\t\tbyt, err := json.Marshal(response)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn byt, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\ttask, err := handler.Repository.GetTaskByID(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblock1 := NewSectionTextBlock(\"mrkdwn\", \"Assigned: \"+task.Title+\" - \"+task.AsigneeID)\n\tresp := NewResponse(header, div, block1)\n\tbyt, err := json.Marshal(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn byt, nil\n}", "func (p *AppsCreateOrUpdatePoller) Poll(ctx context.Context) (*http.Response, error) {\n\treturn p.pt.Poll(ctx)\n}", "func (m *TestFixClient) ToApp(msg *fix.Message, sID fix.SessionID) error {\n\tif !m.OmitLogMessages {\n\t\tlog.Printf(\"[FIX %s] MockFix.ToApp (outgoing): %s\", m.name, fixString(msg))\n\t}\n\ts := m.Sessions[sID.String()]\n\tseq, err := msg.Header.GetInt(34)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Sent[seq] = strings.Replace(msg.String(), string(0x1), \"|\", -1)\n\treturn nil\n}", "func (client ConversationsClient) SendToConversationMethodResponder(resp *http.Response) (result ResourceResponseType, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusCreated,http.StatusAccepted),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (o *UserEditOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses\n\n\trw.WriteHeader(200)\n}", "func (l ApplicationsCreateOrUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (ApplicationsCreateOrUpdateResponse, error) {\n\trespType := ApplicationsCreateOrUpdateResponse{}\n\tresp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.Application)\n\tif err != nil {\n\t\treturn respType, err\n\t}\n\trespType.RawResponse = resp\n\treturn respType, nil\n}", "func (s *SmartContract) assignOffice(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tempAsBytes, _ := APIstub.GetState(args[1])\n\temp := Employee{}\n\tjson.Unmarshal(empAsBytes, &emp)\n\temp.OfficeID = args[2]\n\n\tempAsBytes, _ = json.Marshal(emp)\n\tAPIstub.PutState(args[0], empAsBytes)\n\n\treturn shim.Success(nil)\n}", "func (o *CreateTaskAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(202)\n\tpayload := o.Payload\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) // let the recovery middleware deal with this\n\t}\n}", "func (o *CreateMailerEntryAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\t// response header Reload-ID\n\n\treloadID := o.ReloadID\n\tif reloadID != \"\" {\n\t\trw.Header().Set(\"Reload-ID\", reloadID)\n\t}\n\n\trw.WriteHeader(202)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (r *RepoStruct) SetInternalRelApp(appRelName, appName string) (updated *bool, _ error) {\n\tif err := r.initApp(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif v, found := r.Apps[appRelName]; found {\n\t\tappName = v // Set always declared one.\n\t}\n\n\tif app, err := r.forge.ForjCore.Apps.Found(appName); err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to set %s:%s. %s.\", appRelName, appName, err)\n\t} else if v, found := r.apps[appRelName]; !found || (found && v.name != appName) {\n\t\tr.apps[appRelName] = app\n\t\tupdated = new(bool)\n\t\t*updated = true\n\t}\n\n\treturn\n}", "func (fn PostAppsHandlerFunc) Handle(params PostAppsParams) middleware.Responder {\n\treturn fn(params)\n}", "func (c *KubeTestPlatform) PortForwardToApp(appName string, targetPorts ...int) ([]int, error) {\n\tapp := c.AppResources.FindActiveResource(appName)\n\tappManager := app.(*kube.AppManager)\n\n\t_, err := appManager.WaitUntilDeploymentState(appManager.IsDeploymentDone)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif targetPorts == nil {\n\t\treturn nil, fmt.Errorf(\"cannot open connection with no target ports\")\n\t}\n\treturn appManager.DoPortForwarding(\"\", targetPorts...)\n}", "func (client CertificateClient) UpdateResponder(resp *http.Response) (result Certificate, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}" ]
[ "0.5593733", "0.5504363", "0.55019164", "0.5395793", "0.5392725", "0.5316251", "0.5288861", "0.52742916", "0.51867074", "0.51809955", "0.5175763", "0.5174901", "0.5162368", "0.5161009", "0.51218617", "0.51115453", "0.50689", "0.504904", "0.50286883", "0.50016785", "0.4993926", "0.49890268", "0.49289763", "0.49203125", "0.48469678", "0.48367813", "0.48102766", "0.47931886", "0.47868794", "0.4773139", "0.47636658", "0.47603726", "0.4760182", "0.47580847", "0.47357574", "0.47304687", "0.47199416", "0.46947405", "0.4688848", "0.46882892", "0.46853656", "0.46764407", "0.46754503", "0.46730918", "0.46721742", "0.46718842", "0.46718735", "0.46655566", "0.46648023", "0.4656819", "0.46476558", "0.464307", "0.4641056", "0.46375033", "0.463581", "0.4635679", "0.46227196", "0.46155345", "0.46107802", "0.45927176", "0.45861852", "0.45857286", "0.45773664", "0.4573185", "0.45584872", "0.4554842", "0.4553965", "0.4552816", "0.45400563", "0.453724", "0.4524906", "0.45245916", "0.45216548", "0.45183554", "0.45118716", "0.45104995", "0.45029312", "0.44995332", "0.44976485", "0.44973677", "0.44958597", "0.44938254", "0.44932663", "0.44913387", "0.4489296", "0.44845343", "0.44838342", "0.4482787", "0.44741315", "0.4473318", "0.44694406", "0.44605523", "0.4460204", "0.44598177", "0.44556817", "0.4453651", "0.4449357", "0.444604", "0.4445481", "0.44425908" ]
0.7659439
0
GetAssigned gets the LUIS azure accounts assigned to the application for the user using his ARM token. Parameters: appID the application ID.
func (client AzureAccountsClient) GetAssigned(ctx context.Context, appID uuid.UUID) (result ListAzureAccountInfoObject, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/AzureAccountsClient.GetAssigned") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetAssignedPreparer(ctx, appID) if err != nil { err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "GetAssigned", nil, "Failure preparing request") return } resp, err := client.GetAssignedSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "GetAssigned", resp, "Failure sending request") return } result, err = client.GetAssignedResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "GetAssigned", resp, "Failure responding to request") } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AzureAccountsClient) GetAssignedPreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AzureAccountsClient) GetAssignedResponder(resp *http.Response) (result ListAzureAccountInfoObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client AzureAccountsClient) GetAssignedSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (m *User) GetAppRoleAssignments()([]AppRoleAssignmentable) {\n return m.appRoleAssignments\n}", "func (m *Group) GetAppRoleAssignments()([]AppRoleAssignmentable) {\n return m.appRoleAssignments\n}", "func (c *Client) ListAssignedIDs() (*[]aadpodid.AzureAssignedIdentity, error) {\n\tbegin := time.Now()\n\n\tvar resList []aadpodid.AzureAssignedIdentity\n\n\tlist := c.AssignedIDInformer.GetStore().List()\n\tfor _, assignedID := range list {\n\t\to, ok := assignedID.(*aadpodv1.AzureAssignedIdentity)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"failed to cast %T to %s\", assignedID, aadpodv1.AzureAssignedIDResource)\n\t\t}\n\t\t// Note: List items returned from cache have empty Kind and API version..\n\t\t// Work around this issue since we need that for event recording to work.\n\t\to.SetGroupVersionKind(schema.GroupVersionKind{\n\t\t\tGroup: aadpodv1.SchemeGroupVersion.Group,\n\t\t\tVersion: aadpodv1.SchemeGroupVersion.Version,\n\t\t\tKind: reflect.TypeOf(*o).String()})\n\t\tout := aadpodv1.ConvertV1AssignedIdentityToInternalAssignedIdentity(*o)\n\t\tresList = append(resList, out)\n\t\tklog.V(6).Infof(\"appending AzureAssignedIdentity: %s/%s to list.\", o.Namespace, o.Name)\n\t}\n\n\tstats.Aggregate(stats.AzureAssignedIdentityList, time.Since(begin))\n\treturn &resList, nil\n}", "func (s *TeamsServiceOp) GetTeamUsersAssigned(ctx context.Context, orgID, teamID string) ([]*User, *Response, error) {\n\tif orgID == \"\" {\n\t\treturn nil, nil, atlas.NewArgError(\"orgID\", \"must be set\")\n\t}\n\tif teamID == \"\" {\n\t\treturn nil, nil, atlas.NewArgError(\"teamID\", \"must be set\")\n\t}\n\n\tbasePath := fmt.Sprintf(teamsBasePath, orgID)\n\tpath := fmt.Sprintf(\"%s/%s/users\", basePath, teamID)\n\n\treq, err := s.Client.NewRequest(ctx, http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\troot := new(UsersResponse)\n\tresp, err := s.Client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\tif l := root.Links; l != nil {\n\t\tresp.Links = l\n\t}\n\n\treturn root.Results, resp, nil\n}", "func (m *AssignPostRequestBody) GetMobileAppAssignments()([]iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.MobileAppAssignmentable) {\n return m.mobileAppAssignments\n}", "func (o *User) GetAppRoleAssignments() []AppRoleAssignment {\n\tif o == nil || o.AppRoleAssignments == nil {\n\t\tvar ret []AppRoleAssignment\n\t\treturn ret\n\t}\n\treturn o.AppRoleAssignments\n}", "func (c *Client) ListAssignedIDsInMap() (map[string]aadpodid.AzureAssignedIdentity, error) {\n\tbegin := time.Now()\n\n\tresult := make(map[string]aadpodid.AzureAssignedIdentity)\n\tlist := c.AssignedIDInformer.GetStore().List()\n\tfor _, assignedID := range list {\n\n\t\to, ok := assignedID.(*aadpodv1.AzureAssignedIdentity)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"failed to cast %T to %s\", assignedID, aadpodv1.AzureAssignedIDResource)\n\t\t}\n\t\t// Note: List items returned from cache have empty Kind and API version..\n\t\t// Work around this issue since we need that for event recording to work.\n\t\to.SetGroupVersionKind(schema.GroupVersionKind{\n\t\t\tGroup: aadpodv1.SchemeGroupVersion.Group,\n\t\t\tVersion: aadpodv1.SchemeGroupVersion.Version,\n\t\t\tKind: reflect.TypeOf(*o).String()})\n\n\t\tout := aadpodv1.ConvertV1AssignedIdentityToInternalAssignedIdentity(*o)\n\t\t// assigned identities names are unique across namespaces as we use pod name-<id ns>-<id name>\n\t\tresult[o.Name] = out\n\t\tklog.V(6).Infof(\"added to map with key: %s\", o.Name)\n\t}\n\n\tstats.Aggregate(stats.AzureAssignedIdentityList, time.Since(begin))\n\treturn result, nil\n}", "func GetAssignment(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *AssignmentState, opts ...pulumi.ResourceOption) (*Assignment, error) {\n\tvar resource Assignment\n\terr := ctx.ReadResource(\"azure-native:blueprint:Assignment\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (client AzureAccountsClient) AssignToApp(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (result OperationStatus, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.AssignToApp\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: azureAccountInfoObject,\n\t\t\tConstraints: []validation.Constraint{{Target: \"azureAccountInfoObject\", Name: validation.Null, Rule: false,\n\t\t\t\tChain: []validation.Constraint{{Target: \"azureAccountInfoObject.AzureSubscriptionID\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.ResourceGroup\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.AccountName\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t}}}}}); err != nil {\n\t\treturn result, validation.NewError(\"authoring.AzureAccountsClient\", \"AssignToApp\", err.Error())\n\t}\n\n\treq, err := client.AssignToAppPreparer(ctx, appID, azureAccountInfoObject)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.AssignToAppSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.AssignToAppResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (m *MobileAppAssignmentItemRequestBuilder) Get(ctx context.Context, requestConfiguration *MobileAppAssignmentItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.MobileAppAssignmentable, error) {\n requestInfo, err := m.CreateGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.SendAsync(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateMobileAppAssignmentFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.MobileAppAssignmentable), nil\n}", "func (c *MockRoleAssignmentsClient) Get(ctx context.Context, scope string, roleAssignmentName string) (result authorizationmgmt.RoleAssignment, err error) {\n\treturn c.MockGet(ctx, scope, roleAssignmentName)\n}", "func (client AzureAccountsClient) AssignToAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\tif azureAccountInfoObject != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(azureAccountInfoObject))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (r *DeviceAndAppManagementRoleAssignmentRequest) Get(ctx context.Context) (resObj *DeviceAndAppManagementRoleAssignment, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}", "func (o *User) GetAssignedLicenses() []MicrosoftGraphAssignedLicense {\n\tif o == nil || o.AssignedLicenses == nil {\n\t\tvar ret []MicrosoftGraphAssignedLicense\n\t\treturn ret\n\t}\n\treturn *o.AssignedLicenses\n}", "func (o *MicrosoftGraphPlannerAssignment) GetAssignedBy() AnyOfmicrosoftGraphIdentitySet {\n\tif o == nil || o.AssignedBy == nil {\n\t\tvar ret AnyOfmicrosoftGraphIdentitySet\n\t\treturn ret\n\t}\n\treturn *o.AssignedBy\n}", "func (o DataPoolEncryptionResponseOutput) UserAssignedIdentity() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DataPoolEncryptionResponse) string { return v.UserAssignedIdentity }).(pulumi.StringOutput)\n}", "func (client AzureAccountsClient) AssignToAppSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (a *lbAgent) GetAppID(ctx context.Context, appName string) (string, error) {\n\treturn a.delegatedAgent.GetAppID(ctx, appName)\n}", "func (o *MicrosoftGraphEducationUser) GetAssignedLicenses() []MicrosoftGraphAssignedLicense {\n\tif o == nil || o.AssignedLicenses == nil {\n\t\tvar ret []MicrosoftGraphAssignedLicense\n\t\treturn ret\n\t}\n\treturn *o.AssignedLicenses\n}", "func (m *TelecomExpenseManagementPartner) GetAppAuthorized()(*bool) {\n val, err := m.GetBackingStore().Get(\"appAuthorized\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (m *SequentialActivationRenewalsAlertIncident) GetAssigneeId()(*string) {\n val, err := m.GetBackingStore().Get(\"assigneeId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (c *client) Get(ctx context.Context, inputRa *security.RoleAssignment) (*[]security.RoleAssignment, error) {\n\trequest, err := c.getRoleAssignmentRequest(wssdcloudcommon.Operation_GET, inputRa)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := c.RoleAssignmentAgentClient.Invoke(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tras, err := c.getRoleAssignmentFromResponse(response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ras, nil\n}", "func (m *EducationAssignment) GetAssignTo()(EducationAssignmentRecipientable) {\n return m.assignTo\n}", "func (r *OrganizationsAssignmentsService) Get(name string) *OrganizationsAssignmentsGetCall {\n\tc := &OrganizationsAssignmentsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (svc *SSHKeysService) ListAssigned(ctx context.Context, prj, dc, cls string) ([]SSHKey, *http.Response, error) {\n\tret := make([]SSHKey, 0)\n\tresp, err := svc.client.resourceList(ctx, clusterSSHKeysPath(prj, dc, cls), &ret)\n\treturn ret, resp, err\n}", "func (am *ArtifactMap) GetAppID(appName string) (string, error) {\n\tvalue, found := am.appTitleToID.Load(appName)\n\tif !found {\n\t\treturn \"\", errors.Errorf(\"key %s not found in app id map\", appName)\n\t}\n\treturn value.(string), nil\n}", "func (aaa *RolesService) AdminListAssignedUsersV4(input *roles.AdminListAssignedUsersV4Params) (*iamclientmodels.ModelListAssignedUsersV4Response, error) {\n\ttoken, err := aaa.TokenRepository.GetToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tok, badRequest, unauthorized, forbidden, notFound, err := aaa.Client.Roles.AdminListAssignedUsersV4(input, client.BearerToken(*token.AccessToken))\n\tif badRequest != nil {\n\t\treturn nil, badRequest\n\t}\n\tif unauthorized != nil {\n\t\treturn nil, unauthorized\n\t}\n\tif forbidden != nil {\n\t\treturn nil, forbidden\n\t}\n\tif notFound != nil {\n\t\treturn nil, notFound\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ok.GetPayload(), nil\n}", "func ExampleRoleAssignmentsClient_Get() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armauthorization.NewRoleAssignmentsClient(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.Get(ctx, \"subscriptions/a925f2f7-5c63-4b7b-8799-25a5f97bc3b2\", \"b0f43c54-e787-4862-89b1-a653fa9cf747\", &armauthorization.RoleAssignmentsClientGetOptions{TenantID: nil})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func fromAssigned(request *jsontree.JsonTree) []string {\n\tvar toNotify []string\n\tassignee, _ := request.Get(\"assignee\").Get(\"login\").String()\n\ttoNotify = append(toNotify, assignee)\n\treturn toNotify\n}", "func (m *User) GetAssignedLicenses()([]AssignedLicenseable) {\n return m.assignedLicenses\n}", "func (o AnalyzerStorageAccountOutput) UserAssignedIdentityId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AnalyzerStorageAccount) string { return v.UserAssignedIdentityId }).(pulumi.StringOutput)\n}", "func (o *User) SetAppRoleAssignments(v []AppRoleAssignment) {\n\to.AppRoleAssignments = v\n}", "func (client ManagementClient) GetMAMUserFlaggedEnrolledApps(hostName string, userName string, filter string, top *int32, selectParameter string) (result FlaggedEnrolledAppCollection, err error) {\n\treq, err := client.GetMAMUserFlaggedEnrolledAppsPreparer(hostName, userName, filter, top, selectParameter)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetMAMUserFlaggedEnrolledApps\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetMAMUserFlaggedEnrolledAppsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetMAMUserFlaggedEnrolledApps\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetMAMUserFlaggedEnrolledAppsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetMAMUserFlaggedEnrolledApps\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (o *User) GetAppRoleAssignmentsOk() ([]AppRoleAssignment, bool) {\n\tif o == nil || o.AppRoleAssignments == nil {\n\t\treturn nil, false\n\t}\n\treturn o.AppRoleAssignments, true\n}", "func (m *ItemRoleAssignmentsItemLinkedEligibleRoleAssignmentRequestBuilder) Get(ctx context.Context, requestConfiguration *ItemRoleAssignmentsItemLinkedEligibleRoleAssignmentRequestBuilderGetRequestConfiguration)(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.GovernanceRoleAssignmentable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.CreateGovernanceRoleAssignmentFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.GovernanceRoleAssignmentable), nil\n}", "func LookupScopeAssignment(ctx *pulumi.Context, args *LookupScopeAssignmentArgs, opts ...pulumi.InvokeOption) (*LookupScopeAssignmentResult, error) {\n\tvar rv LookupScopeAssignmentResult\n\terr := ctx.Invoke(\"azure-native:managednetwork:getScopeAssignment\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func (s *AutograderService) GetAssignments(ctx context.Context, in *pb.CourseRequest) (*pb.Assignments, error) {\n\tcourseID := in.GetCourseID()\n\tassignments, err := s.getAssignments(courseID)\n\tif err != nil {\n\t\ts.logger.Errorf(\"GetAssignments failed: %w\", err)\n\t\treturn nil, status.Errorf(codes.NotFound, \"no assignments found for course\")\n\t}\n\treturn assignments, nil\n}", "func (m *User) GetAssignedPlans()([]AssignedPlanable) {\n return m.assignedPlans\n}", "func (client AzureAccountsClient) AssignToAppResponder(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.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (rb *redisBackend) GetAssignments(ctx context.Context, id string, callback func(*pb.Assignment) error) error {\n\tredisConn, err := rb.redisPool.GetContext(ctx)\n\tif err != nil {\n\t\treturn status.Errorf(codes.Unavailable, \"GetAssignments, id: %s, failed to connect to redis: %v\", id, err)\n\t}\n\tdefer handleConnectionClose(&redisConn)\n\n\tbackoffOperation := func() error {\n\t\tvar ticket *pb.Ticket\n\t\tticket, err = rb.GetTicket(ctx, id)\n\t\tif err != nil {\n\t\t\treturn backoff.Permanent(err)\n\t\t}\n\n\t\terr = callback(ticket.GetAssignment())\n\t\tif err != nil {\n\t\t\treturn backoff.Permanent(err)\n\t\t}\n\n\t\treturn status.Error(codes.Unavailable, \"listening on assignment updates, waiting for the next backoff\")\n\t}\n\n\terr = backoff.Retry(backoffOperation, rb.newConstantBackoffStrategy())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *ResourcepoolPoolMember) GetAssignedToEntity() []MoBaseMoRelationship {\n\tif o == nil {\n\t\tvar ret []MoBaseMoRelationship\n\t\treturn ret\n\t}\n\treturn o.AssignedToEntity\n}", "func (o DataPoolEncryptionOutput) UserAssignedIdentity() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DataPoolEncryption) string { return v.UserAssignedIdentity }).(pulumi.StringOutput)\n}", "func (m *VppToken) GetAppleId()(*string) {\n return m.appleId\n}", "func (c *Client) GetAssignments() ([]Assignment, error) {\n\tquery := `\n\t\tSELECT\n\t\t\tCustomPollerAssignmentID\n\t\t\t,CustomPollerID\n\t\t\t,NodeID\n\t\t\t,InterfaceID\n\t\t\t,CustomPollerID\n\t\t\t,InstanceType\n\t\tFROM Orion.NPM.CustomPollerAssignment\n\t`\n\n\tres, err := c.Query(query, nil)\n\tif err != nil {\n\t\treturn []Assignment{}, fmt.Errorf(\"failed to query for assignments: %v\", err)\n\t}\n\n\tvar assignments []Assignment\n\tif err := json.Unmarshal(res, &assignments); err != nil {\n\t\treturn []Assignment{}, fmt.Errorf(\"failed to unmarshal assignments: %v\", err)\n\t}\n\n\treturn assignments, nil\n}", "func (r *ProjectsAssignmentsService) Get(name string) *ProjectsAssignmentsGetCall {\n\tc := &ProjectsAssignmentsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (o *MicrosoftGraphPlannerAssignment) GetAssignedDateTime() time.Time {\n\tif o == nil || o.AssignedDateTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.AssignedDateTime\n}", "func (o *DeeplinkRule) GetAppGuid() string {\n\tif o == nil || o.AppGuid == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.AppGuid\n}", "func (am *ArtifactMap) GetRandomApp(sessionState *State) (ArtifactEntry, error) {\n\tam.mu.Lock()\n\tdefer am.mu.Unlock()\n\n\tn := len(am.AppList)\n\tif n < 1 {\n\t\treturn ArtifactEntry{}, errors.New(\"cannot select random app: ArtifactMap is empty\")\n\t}\n\trandomIndex := sessionState.Randomizer().Rand(n)\n\tselectedKVP := am.AppList[randomIndex]\n\treturn *selectedKVP, nil\n}", "func (rb *redisBackend) GetAssignments(ctx context.Context, id string, callback func(*pb.Assignment) error) error {\n\tredisConn, err := rb.connect(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer handleConnectionClose(&redisConn)\n\n\tbackoffOperation := func() error {\n\t\tvar ticket *pb.Ticket\n\t\tticket, err = rb.GetTicket(ctx, id)\n\t\tif err != nil {\n\t\t\tredisLogger.WithError(err).Errorf(\"failed to get ticket %s when executing get assignments\", id)\n\t\t\treturn backoff.Permanent(err)\n\t\t}\n\n\t\terr = callback(ticket.GetAssignment())\n\t\tif err != nil {\n\t\t\treturn backoff.Permanent(err)\n\t\t}\n\n\t\treturn status.Error(codes.Unavailable, \"listening on assignment updates, waiting for the next backoff\")\n\t}\n\n\terr = backoff.Retry(backoffOperation, rb.newConstantBackoffStrategy())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o GetKubernetesClusterIngressApplicationGatewayIngressApplicationGatewayIdentityOutput) UserAssignedIdentityId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetKubernetesClusterIngressApplicationGatewayIngressApplicationGatewayIdentity) string {\n\t\treturn v.UserAssignedIdentityId\n\t}).(pulumi.StringOutput)\n}", "func (am *AppManager) GetAppData(appGUID string) AppInfo {\n\t//logger.Printf(\"Searching for %s\\n\", appGUID)\n\treq := readRequest{appGUID, make(chan AppInfo)}\n\tam.readChannel <- req\n\tai := <-req.responseChan\n\t//logger.Printf(\"Recevied response for %s: %+v\", appGUID, ai)\n\treturn ai\n}", "func ExampleRoleAssignmentsClient_GetByID() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armauthorization.NewRoleAssignmentsClient(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.GetByID(ctx, \"subscriptions/a925f2f7-5c63-4b7b-8799-25a5f97bc3b2/providers/Microsoft.Authorization/roleAssignments/b0f43c54-e787-4862-89b1-a653fa9cf747\", &armauthorization.RoleAssignmentsClientGetByIDOptions{TenantID: nil})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func (m *Application) GetAppRoles()([]AppRoleable) {\n return m.appRoles\n}", "func (m *DeviceManagementConfigurationPolicy) GetIsAssigned()(*bool) {\n val, err := m.GetBackingStore().Get(\"isAssigned\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (g *Grant) GetApp() *AuthorizationApp {\n\tif g == nil {\n\t\treturn nil\n\t}\n\treturn g.App\n}", "func GetRoleAssignment(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *RoleAssignmentState, opts ...pulumi.ResourceOption) (*RoleAssignment, error) {\n\tvar resource RoleAssignment\n\terr := ctx.ReadResource(\"azure:marketplace/roleAssignment:RoleAssignment\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (a LearningApi) GetLearningModulesAssignments(userIds []string, pageSize int, pageNumber int, searchTerm string, overdue string, assignmentStates []string, expand []string) (*Assignedlearningmoduledomainentitylisting, *APIResponse, error) {\n\tvar httpMethod = \"GET\"\n\t// create path and map variables\n\tpath := a.Configuration.BasePath + \"/api/v2/learning/modules/assignments\"\n\tdefaultReturn := new(Assignedlearningmoduledomainentitylisting)\n\tif true == false {\n\t\treturn defaultReturn, nil, errors.New(\"This message brought to you by the laws of physics being broken\")\n\t}\n\n\t// verify the required parameter 'userIds' is set\n\tif &userIds == nil {\n\t\t// true\n\t\treturn defaultReturn, nil, errors.New(\"Missing required parameter 'userIds' when calling LearningApi->GetLearningModulesAssignments\")\n\t}\n\n\theaderParams := make(map[string]string)\n\tqueryParams := make(map[string]string)\n\tformParams := url.Values{}\n\tvar postBody interface{}\n\tvar postFileName string\n\tvar fileBytes []byte\n\t// authentication (PureCloud OAuth) required\n\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\t\n\tqueryParams[\"userIds\"] = a.Configuration.APIClient.ParameterToString(userIds, \"multi\")\n\t\n\tqueryParams[\"pageSize\"] = a.Configuration.APIClient.ParameterToString(pageSize, \"\")\n\t\n\tqueryParams[\"pageNumber\"] = a.Configuration.APIClient.ParameterToString(pageNumber, \"\")\n\t\n\tqueryParams[\"searchTerm\"] = a.Configuration.APIClient.ParameterToString(searchTerm, \"\")\n\t\n\tqueryParams[\"overdue\"] = a.Configuration.APIClient.ParameterToString(overdue, \"\")\n\t\n\tqueryParams[\"assignmentStates\"] = a.Configuration.APIClient.ParameterToString(assignmentStates, \"multi\")\n\t\n\tqueryParams[\"expand\"] = a.Configuration.APIClient.ParameterToString(expand, \"multi\")\n\t\n\n\t// Find an replace keys that were altered to avoid clashes with go keywords \n\tcorrectedQueryParams := make(map[string]string)\n\tfor k, v := range queryParams {\n\t\tif k == \"varType\" {\n\t\t\tcorrectedQueryParams[\"type\"] = v\n\t\t\tcontinue\n\t\t}\n\t\tcorrectedQueryParams[k] = v\n\t}\n\tqueryParams = correctedQueryParams\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\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\tvar successPayload *Assignedlearningmoduledomainentitylisting\n\tresponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, postFileName, fileBytes)\n\tif err != nil {\n\t\t// Nothing special to do here, but do avoid processing the response\n\t} else if err == nil && response.Error != nil {\n\t\terr = errors.New(response.ErrorMessage)\n\t} else if response.HasBody {\n\t\tif \"Assignedlearningmoduledomainentitylisting\" == \"string\" {\n\t\t\tcopy(response.RawBody, &successPayload)\n\t\t} else {\n\t\t\terr = json.Unmarshal(response.RawBody, &successPayload)\n\t\t}\n\t}\n\treturn successPayload, response, err\n}", "func (m *UnifiedRoleAssignmentScheduleRequest) GetAppScopeId()(*string) {\n return m.appScopeId\n}", "func (m *Application) GetAppId()(*string) {\n return m.appId\n}", "func (o *User) GetAssignedPlans() []MicrosoftGraphAssignedPlan {\n\tif o == nil || o.AssignedPlans == nil {\n\t\tvar ret []MicrosoftGraphAssignedPlan\n\t\treturn ret\n\t}\n\treturn *o.AssignedPlans\n}", "func (m *EducationAssignment) GetAssignedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.assignedDateTime\n}", "func (r *AppsModulesService) Get(appsId string, modulesId string) *AppsModulesGetCall {\n\tc := &AppsModulesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.appsId = appsId\n\tc.modulesId = modulesId\n\treturn c\n}", "func (m *ScheduleChangeRequest) GetAssignedTo()(*ScheduleChangeRequestActor) {\n val, err := m.GetBackingStore().Get(\"assignedTo\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*ScheduleChangeRequestActor)\n }\n return nil\n}", "func (this *IPAMNetworkPool) isAssigned(probe net.IP) bool {\n\t_, found := this.assignedIPs[probe.String()]\n\treturn found\n}", "func (r *DeviceManagementIntentAssignmentRequest) Get(ctx context.Context) (resObj *DeviceManagementIntentAssignment, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}", "func (m *ServicePrincipalRiskDetection) GetAppId()(*string) {\n val, err := m.GetBackingStore().Get(\"appId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (f *Client) GetAppAccessToken() (string, error) {\n\tvar err error\n\n\treq := f.Get(\"/oauth/access_token\", GraphQueryString{\n\t\t\"client_id\": []string{f.appID},\n\t\t\"client_secret\": []string{f.secret},\n\t\t\"grant_type\": []string{\"client_credentials\"},\n\t})\n\n\ttarget_obj := struct {\n\t\tToken string `json:\"access_token\"`\n\t\tType string `json:\"token_type\"`\n\t}{}\n\terr = req.Exec(&target_obj)\n\tif err == nil {\n\t\treturn target_obj.Token, nil\n\t}\n\n\tfmt.Println(err)\n\n\ttarget_raw := []byte{}\n\terr = req.Exec(&target_raw)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"invalid response\")\n\t}\n\n\tvals, _ := url.ParseQuery(string(target_raw))\n\tstr, exists := vals[\"access_token\"]\n\tif !exists || str[0] == \"\" {\n\t\treturn \"\", fmt.Errorf(\"access token wasn't in response\")\n\t}\n\treturn str[0], nil\n}", "func (c *Client) GetAssignees(user, repo string) ([]*User, *Response, error) {\n\tif err := c.checkServerVersionGreaterThanOrEqual(version1_15_0); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err := escapeValidatePathSegments(&user, &repo); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tassignees := make([]*User, 0, 5)\n\tresp, err := c.getParsedResponse(\"GET\", fmt.Sprintf(\"/repos/%s/%s/assignees\", user, repo), nil, nil, &assignees)\n\treturn assignees, resp, err\n}", "func (o DataPoolEncryptionResponsePtrOutput) UserAssignedIdentity() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataPoolEncryptionResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.UserAssignedIdentity\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *SyntheticMonitorUpdate) GetManuallyAssignedApps() []string {\n\tif o == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\n\treturn o.ManuallyAssignedApps\n}", "func (o *User) GetAssignedLicensesOk() ([]MicrosoftGraphAssignedLicense, bool) {\n\tif o == nil || o.AssignedLicenses == nil {\n\t\tvar ret []MicrosoftGraphAssignedLicense\n\t\treturn ret, false\n\t}\n\treturn *o.AssignedLicenses, true\n}", "func (o *MicrosoftGraphPlannerAssignment) GetAssignedByOk() (AnyOfmicrosoftGraphIdentitySet, bool) {\n\tif o == nil || o.AssignedBy == nil {\n\t\tvar ret AnyOfmicrosoftGraphIdentitySet\n\t\treturn ret, false\n\t}\n\treturn *o.AssignedBy, true\n}", "func (r *EnrollmentConfigurationAssignmentRequest) Get(ctx context.Context) (resObj *EnrollmentConfigurationAssignment, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}", "func (client AppsClient) Get(ctx context.Context, appID uuid.UUID) (result ApplicationInfoResponse, err error) {\n\treq, err := client.GetPreparer(ctx, appID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.AppsClient\", \"Get\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.AppsClient\", \"Get\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.AppsClient\", \"Get\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (m *ChatMessageAttachment) GetTeamsAppId()(*string) {\n val, err := m.GetBackingStore().Get(\"teamsAppId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *MicrosoftGraphEducationUser) GetAssignedLicensesOk() ([]MicrosoftGraphAssignedLicense, bool) {\n\tif o == nil || o.AssignedLicenses == nil {\n\t\tvar ret []MicrosoftGraphAssignedLicense\n\t\treturn ret, false\n\t}\n\treturn *o.AssignedLicenses, true\n}", "func (taker *TakerGCP) GetApplication(rp *reportProject) (application *appengine.Application, err error) {\n\tgetResponse, getErr := taker.appEngine.Apps.Get(rp.gcpProject.ProjectId).Do()\n\tif getErr != nil {\n\t\t//\t\t\t\tlog.Println(\"cannot get application for project:\", appErr)\n\t\terr = getErr\n\t} else {\n\t\tapplication = getResponse\n\t}\n\treturn\n}", "func (r *DeviceEnrollmentConfigurationAssignmentsCollectionRequest) Get(ctx context.Context) ([]EnrollmentConfigurationAssignment, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil)\n}", "func (m *ApplicationResource) GetApplicationGroupAssignment(ctx context.Context, appId string, groupId string, qp *query.Params) (*ApplicationGroupAssignment, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/groups/%v\", appId, groupId)\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 applicationGroupAssignment *ApplicationGroupAssignment\n\n\tresp, err := rq.Do(ctx, req, &applicationGroupAssignment)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn applicationGroupAssignment, resp, nil\n}", "func (m *UserResource) ListAssignedRolesForUser(ctx context.Context, userId string, qp *query.Params) ([]*Role, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/users/%v/roles\", userId)\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 role []*Role\n\n\tresp, err := rq.Do(ctx, req, &role)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn role, resp, nil\n}", "func (r *OfficeClientConfigurationAssignmentsCollectionRequest) Get(ctx context.Context) ([]OfficeClientConfigurationAssignment, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil)\n}", "func (s *Service) GetPlainAppid() ([]string, error) {\n\treturn s.d.GetPlainAppid(context.Background())\n}", "func (ar AppResource) Get(ctx context.Context, r *http.Request) (int, interface{}) {\n\terr := requireScope(ctx, \"read:app\")\n\tif err != nil {\n\t\treturn http.StatusUnauthorized, err\n\t}\n\tu := getCurrentUser(ctx)\n\tmctx := getModelContext(ctx)\n\taId := params(ctx, \"id\")\n\tif aId == \"\" {\n\t\treturn http.StatusBadRequest, \"app id not given\"\n\t}\n\tid, err := strconv.Atoi(aId)\n\tif err != nil {\n\t\treturn http.StatusBadRequest, err\n\t}\n\tqueryApp, err := app.GetApp(mctx, id)\n\tif err != nil {\n\t\tif err == app.ErrAppNotFound {\n\t\t\treturn http.StatusBadRequest, \"app doesn't exist\"\n\t\t}\n\t\treturn http.StatusBadRequest, err\n\t}\n\trole, err := group.GetRoleOfUser(mctx, u.GetId(), queryApp.AdminGroupId)\n\tif role != group.ADMIN {\n\t\treturn http.StatusForbidden, \"only admins of the app can read it\"\n\t}\n\tresp := &App{\n\t\tId: queryApp.Id,\n\t\tFullName: queryApp.FullName,\n\t\tSecret: queryApp.Secret,\n\t\tRedirectUri: queryApp.RedirectUri,\n\t}\n\treturn http.StatusOK, resp\n}", "func (o *MicrosoftGraphEducationUser) GetAssignedPlans() []MicrosoftGraphAssignedPlan {\n\tif o == nil || o.AssignedPlans == nil {\n\t\tvar ret []MicrosoftGraphAssignedPlan\n\t\treturn ret\n\t}\n\treturn *o.AssignedPlans\n}", "func (r *TTNRandom) AppID() string {\n\treturn r.ID()\n}", "func (c Client) fetchApp() (*Identity, error) {\n\treq, err := http.NewRequest(\"GET\", c.getURL(\"/me\"), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar marshalled map[string]*Identity\n\terr = c.executeRequestAndMarshal(req, &marshalled)\n\treturn marshalled[\"identity\"], err\n}", "func (this *AppCollection) Get(identity interface{}) collection.Item {\n name := identity.(string)\n\n for _, a := range this.apps {\n if a.Info().Name() == name {\n return a\n }\n }\n\n return nil\n}", "func (tc TeresaClient) GetAppInfo(teamName, appName string) (appInfo AppInfo) {\n\tme, err := tc.Me()\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to get user information: %s\", err)\n\t}\n\tif len(me.Teams) > 1 && teamName == \"\" {\n\t\tlog.Fatalln(\"User is in more than one team and provided none\")\n\t}\n\tfor _, t := range me.Teams {\n\t\tif teamName == \"\" || *t.Name == teamName {\n\t\t\tappInfo.TeamID = t.ID\n\t\t\tfor _, a := range t.Apps {\n\t\t\t\tif *a.Name == appName {\n\t\t\t\t\tappInfo.AppID = a.ID\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tif appInfo.TeamID == 0 || appInfo.AppID == 0 {\n\t\tlog.Fatalf(\"Invalid Team [%s] or App [%s]\\n\", teamName, appName)\n\t}\n\treturn\n}", "func GetApp(c echo.Context) error {\n\tid := c.Param(\"id\")\n\tfmt.Println(\"id passed in : \", id)\n\tvar app models.App\n\tsqlStatment := `SELECT id, appname, disabled, globaldisablemessage FROM apps WHERE id=$1;`\n\trow := d.QueryRow(sqlStatment, id)\n\terr := row.Scan(&app.ID, &app.Appname, &app.Disabled, &app.GlobalDisableMessage)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.JSON(http.StatusOK, app)\n}", "func (o *WatchlistScreeningIndividualUpdateResponse) GetAssignee() string {\n\tif o == nil || o.Assignee.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.Assignee.Get()\n}", "func (am *ArtifactMap) LookupAppGUID(sessionState *State, guid string) (*ArtifactEntry, error) {\n\tentry, err := am.lookup(sessionState, guid, true)\n\tif err != nil {\n\t\t// GUID not found in map, create new entry with GUID (Supports using openapp with GUID and no preceeding OpenHub)\n\t\tentry = &ArtifactEntry{GUID: guid} // todo how to handle itemID?\n\t}\n\treturn entry, nil\n}", "func (a *lbAgent) GetAppByID(ctx context.Context, appID string) (*models.App, error) {\n\treturn a.delegatedAgent.GetAppByID(ctx, appID)\n}", "func (o KubernetesClusterWebAppRoutingWebAppRoutingIdentityOutput) UserAssignedIdentityId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterWebAppRoutingWebAppRoutingIdentity) *string { return v.UserAssignedIdentityId }).(pulumi.StringPtrOutput)\n}", "func (controller AppsController) GetByID(c *gin.Context) {\n\n\tvar appE entities.App\n\tapp, err := mongodb.GetByID(controller.MongoDBClient, Collections[\"apps\"], c.Params.ByName(\"id\"), appE)\n\tif err != nil {\n\t\tfmt.Printf(\"error %v\", err)\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"message\": \"Invalid Parameters\"})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"apps\": app})\n}", "func (o *MacpoolPoolMemberAllOf) GetAssignedToEntity() MoBaseMoRelationship {\n\tif o == nil || o.AssignedToEntity == nil {\n\t\tvar ret MoBaseMoRelationship\n\t\treturn ret\n\t}\n\treturn *o.AssignedToEntity\n}", "func (c *Client) CreateAssignedIdentity(assignedIdentity *aadpodid.AzureAssignedIdentity) (err error) {\n\tklog.Infof(\"creating assigned id %s/%s\", assignedIdentity.Namespace, assignedIdentity.Name)\n\tbegin := time.Now()\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tmerr := c.reporter.ReportKubernetesAPIOperationError(metrics.AssignedIdentityAdditionOperationName)\n\t\t\tif merr != nil {\n\t\t\t\tklog.Warningf(\"failed to report metrics, error: %+v\", merr)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tc.reporter.Report(\n\t\t\tmetrics.AssignedIdentityAdditionCountM.M(1),\n\t\t\tmetrics.AssignedIdentityAdditionDurationM.M(metrics.SinceInSeconds(begin)))\n\t}()\n\n\tvar res aadpodv1.AzureAssignedIdentity\n\tv1AssignedID := aadpodv1.ConvertInternalAssignedIdentityToV1AssignedIdentity(*assignedIdentity)\n\tif !hasFinalizer(&v1AssignedID) {\n\t\tv1AssignedID.SetFinalizers(append(v1AssignedID.GetFinalizers(), finalizerName))\n\t}\n\terr = c.rest.Post().Namespace(assignedIdentity.Namespace).Resource(aadpodid.AzureAssignedIDResource).Body(&v1AssignedID).Do(context.TODO()).Into(&res)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(5).Infof(\"time taken to create %s/%s: %v\", assignedIdentity.Namespace, assignedIdentity.Name, time.Since(begin))\n\tstats.AggregateConcurrent(stats.CreateAzureAssignedIdentity, begin, time.Now())\n\treturn nil\n}", "func (m *SequentialActivationRenewalsAlertIncident) GetAssigneeUserPrincipalName()(*string) {\n val, err := m.GetBackingStore().Get(\"assigneeUserPrincipalName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}" ]
[ "0.5868229", "0.57366514", "0.5638546", "0.5604989", "0.5456541", "0.54254115", "0.5297773", "0.51833236", "0.5043519", "0.49807158", "0.47909835", "0.47510183", "0.47359395", "0.46725827", "0.46622336", "0.4584894", "0.4562579", "0.45622185", "0.4552986", "0.4535627", "0.45248124", "0.4523758", "0.4522448", "0.4495567", "0.44748592", "0.4449825", "0.44454247", "0.44063285", "0.44032663", "0.4385584", "0.43750128", "0.43586808", "0.43394402", "0.43257383", "0.43134385", "0.4308402", "0.43063077", "0.4287729", "0.42863685", "0.42758018", "0.42753384", "0.4274505", "0.42699915", "0.42681703", "0.42557877", "0.4252687", "0.42461383", "0.42453638", "0.42325824", "0.4228579", "0.42243487", "0.4222513", "0.42023495", "0.42012477", "0.41998374", "0.4199111", "0.41780177", "0.4177306", "0.41770527", "0.4169761", "0.4166266", "0.4163183", "0.41629556", "0.4160831", "0.4160477", "0.41526282", "0.41513374", "0.4150411", "0.41452596", "0.41413605", "0.41411546", "0.41379276", "0.41338104", "0.41333157", "0.41292384", "0.41271377", "0.41269612", "0.41226345", "0.41221383", "0.4114158", "0.41127673", "0.41093254", "0.41070145", "0.41064194", "0.4105957", "0.4099317", "0.40874302", "0.40786737", "0.40785125", "0.40726206", "0.4070511", "0.4066838", "0.40541753", "0.40531743", "0.4050951", "0.4039703", "0.40335232", "0.4032798", "0.40326804", "0.4031642" ]
0.7801303
0
GetAssignedPreparer prepares the GetAssigned request.
func (client AzureAccountsClient) GetAssignedPreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) { urlParameters := map[string]interface{}{ "Endpoint": client.Endpoint, } pathParameters := map[string]interface{}{ "appId": autorest.Encode("path", appID), } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithCustomBaseURL("{Endpoint}/luis/api/v2.0", urlParameters), autorest.WithPathParameters("/apps/{appId}/azureaccounts", pathParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client RoleAssignmentScheduleRequestsClient) GetPreparer(ctx context.Context, scope string, roleAssignmentScheduleRequestName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"roleAssignmentScheduleRequestName\": autorest.Encode(\"path\", roleAssignmentScheduleRequestName),\n\t\t\"scope\": scope,\n\t}\n\n\tconst APIVersion = \"2020-10-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (alr AssignmentListResult) assignmentListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !alr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(alr.NextLink)))\n}", "func (ral RegistrationAssignmentList) registrationAssignmentListPreparer(ctx context.Context) (*http.Request, error) {\n\tif !ral.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(ral.NextLink)))\n}", "func (client AzureAccountsClient) GetAssignedResponder(resp *http.Response) (result ListAzureAccountInfoObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client RecommendedElasticPoolsClient) GetPreparer(resourceGroupName string, serverName string, recommendedElasticPoolName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"recommendedElasticPoolName\": autorest.Encode(\"path\", recommendedElasticPoolName),\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\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": client.APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/recommendedElasticPools/{recommendedElasticPoolName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client AccountClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client AzureAccountsClient) GetAssigned(ctx context.Context, appID uuid.UUID) (result ListAzureAccountInfoObject, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.GetAssigned\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.GetAssignedPreparer(ctx, appID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetAssigned\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetAssignedSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetAssigned\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetAssignedResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetAssigned\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (client DeploymentsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ProductsClient) GetPreparer(ctx context.Context, resourceGroup string, registrationName string, productName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"productName\": autorest.Encode(\"path\", productName),\n\t\t\"registrationName\": autorest.Encode(\"path\", registrationName),\n\t\t\"resourceGroup\": autorest.Encode(\"path\", resourceGroup),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2017-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.AzureStack/registrations/{registrationName}/products/{productName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AzureAccountsClient) GetAssignedSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (ralr RoleAssignmentListResult) roleAssignmentListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !ralr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(ralr.NextLink)))\n}", "func (client ExternalBillingAccountClient) GetPreparer(ctx context.Context, externalBillingAccountName string, expand string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"externalBillingAccountName\": autorest.Encode(\"path\", externalBillingAccountName),\n\t}\n\n\tconst APIVersion = \"2019-03-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (cmc ConsortiumMemberCollection) consortiumMemberCollectionPreparer(ctx context.Context) (*http.Request, error) {\n\tif !cmc.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(cmc.NextLink)))\n}", "func (client LabClient) GetResourcePreparer(ctx context.Context, resourceGroupName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2015-05-21-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{name}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ReferenceDataSetsClient) GetPreparer(ctx context.Context, resourceGroupName string, environmentName string, referenceDataSetName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"environmentName\": autorest.Encode(\"path\", environmentName),\n\t\t\"referenceDataSetName\": autorest.Encode(\"path\", referenceDataSetName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-05-15\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TimeSeriesInsights/environments/{environmentName}/referenceDataSets/{referenceDataSetName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client OpenShiftManagedClustersClient) GetPreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": v20180930preview.APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/openShiftManagedClusters/{resourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (pgr PermissionGetResult) permissionGetResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !pgr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(pgr.NextLink)))\n}", "func (client ViewsClient) GetByScopePreparer(ctx context.Context, scope string, viewName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"scope\": autorest.Encode(\"path\", scope),\n\t\t\"viewName\": autorest.Encode(\"path\", viewName),\n\t}\n\n\tconst APIVersion = \"2019-11-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{scope}/providers/Microsoft.CostManagement/views/{viewName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client RecoveryPointsClient) GetPreparer(ctx context.Context, fabricName string, protectionContainerName string, replicatedProtectedItemName string, recoveryPointName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"fabricName\": autorest.Encode(\"path\", fabricName),\n\t\t\"protectionContainerName\": autorest.Encode(\"path\", protectionContainerName),\n\t\t\"recoveryPointName\": autorest.Encode(\"path\", recoveryPointName),\n\t\t\"replicatedProtectedItemName\": autorest.Encode(\"path\", replicatedProtectedItemName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", client.ResourceGroupName),\n\t\t\"resourceName\": autorest.Encode(\"path\", client.ResourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2018-07-10\"\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(\"/Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/recoveryPoints/{recoveryPointName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client RoleAssignmentScheduleRequestsClient) ListForScopePreparer(ctx context.Context, scope string, filter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"scope\": scope,\n\t}\n\n\tconst APIVersion = \"2020-10-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (rmpalr RoleManagementPolicyAssignmentListResult) roleManagementPolicyAssignmentListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !rmpalr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(rmpalr.NextLink)))\n}", "func (client UsageDetailsClient) ListByDepartmentPreparer(ctx context.Context, departmentID string, expand string, filter string, skiptoken string, top *int32, apply string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"departmentId\": autorest.Encode(\"path\", departmentID),\n\t}\n\n\tconst APIVersion = \"2018-06-30\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif len(skiptoken) > 0 {\n\t\tqueryParameters[\"$skiptoken\"] = autorest.Encode(\"query\", skiptoken)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(apply) > 0 {\n\t\tqueryParameters[\"$apply\"] = autorest.Encode(\"query\", apply)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Billing/departments/{departmentId}/providers/Microsoft.Consumption/usageDetails\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client JobClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, jobName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"jobName\": jobName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/jobs/{jobName}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client ThreatIntelligenceIndicatorClient) GetPreparer(ctx context.Context, resourceGroupName string, workspaceName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"workspaceName\": autorest.Encode(\"path\", workspaceName),\n\t}\n\n\tconst APIVersion = \"2022-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{name}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (ecrlr EligibleChildResourcesListResult) eligibleChildResourcesListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !ecrlr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(ecrlr.NextLink)))\n}", "func (client IngestionSettingsClient) GetPreparer(ctx context.Context, ingestionSettingName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"ingestionSettingName\": autorest.Encode(\"path\", ingestionSettingName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2021-01-15-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/providers/Microsoft.Security/ingestionSettings/{ingestionSettingName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client StringClient) GetNotProvidedPreparer(ctx context.Context) (*http.Request, error) {\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/string/notProvided\"))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client Client) GetPreparer(ctx context.Context, accountName, containerName, blobName string, input GetInput) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"containerName\": autorest.Encode(\"path\", containerName),\n\t\t\"blobName\": autorest.Encode(\"path\", blobName),\n\t}\n\n\theaders := map[string]interface{}{\n\t\t\"x-ms-version\": APIVersion,\n\t}\n\n\tif input.StartByte != nil && input.EndByte != nil {\n\t\theaders[\"x-ms-range\"] = fmt.Sprintf(\"bytes=%d-%d\", *input.StartByte, *input.EndByte)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)),\n\t\tautorest.WithPathParameters(\"/{containerName}/{blobName}\", pathParameters),\n\t\tautorest.WithHeaders(headers))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AccountQuotaPolicyClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, policyName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"policyName\": policyName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/accountQuotaPolicies/{policyName}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client JobClient) GetPreparer(ctx context.Context, resourceGroupName string, automationAccountName string, jobName string, clientRequestID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"automationAccountName\": autorest.Encode(\"path\", automationAccountName),\n\t\t\"jobName\": autorest.Encode(\"path\", jobName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/jobs/{jobName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\tif len(clientRequestID) > 0 {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithHeader(\"clientRequestId\", autorest.String(clientRequestID)))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ListManagementTermListsClient) GetDetailsPreparer(ctx context.Context, listID string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"listId\": autorest.Encode(\"path\", listID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/contentmoderator/lists/v1.0/termlists/{listId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (r *OfficeClientConfigurationAssignmentsCollectionRequest) Get(ctx context.Context) ([]OfficeClientConfigurationAssignment, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil)\n}", "func (client EntitiesClient) ListPreparer(ctx context.Context, skiptoken string, skip *int32, top *int32, selectParameter string, search string, filter string, view string, groupName string, cacheControl string) (*http.Request, error) {\n\tconst APIVersion = \"2020-05-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(skiptoken) > 0 {\n\t\tqueryParameters[\"$skiptoken\"] = autorest.Encode(\"query\", skiptoken)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(string(search)) > 0 {\n\t\tqueryParameters[\"$search\"] = autorest.Encode(\"query\", search)\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif len(string(view)) > 0 {\n\t\tqueryParameters[\"$view\"] = autorest.Encode(\"query\", view)\n\t}\n\tif len(groupName) > 0 {\n\t\tqueryParameters[\"groupName\"] = autorest.Encode(\"query\", groupName)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/providers/Microsoft.Management/getEntities\"),\n\t\tautorest.WithQueryParameters(queryParameters))\n\tif len(cacheControl) > 0 {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithHeader(\"Cache-Control\", autorest.String(cacheControl)))\n\t} else {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithHeader(\"Cache-Control\", autorest.String(\"no-cache\")))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *EducationAssignmentItemRequestBuilder) Get(ctx context.Context, requestConfiguration *EducationAssignmentItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.EducationAssignmentable, error) {\n requestInfo, err := m.CreateGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.SendAsync(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateEducationAssignmentFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.EducationAssignmentable), nil\n}", "func (m *ItemRoleAssignmentsItemLinkedEligibleRoleAssignmentRequestBuilder) Get(ctx context.Context, requestConfiguration *ItemRoleAssignmentsItemLinkedEligibleRoleAssignmentRequestBuilderGetRequestConfiguration)(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.GovernanceRoleAssignmentable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.CreateGovernanceRoleAssignmentFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.GovernanceRoleAssignmentable), nil\n}", "func (a LearningApi) GetLearningModulesAssignments(userIds []string, pageSize int, pageNumber int, searchTerm string, overdue string, assignmentStates []string, expand []string) (*Assignedlearningmoduledomainentitylisting, *APIResponse, error) {\n\tvar httpMethod = \"GET\"\n\t// create path and map variables\n\tpath := a.Configuration.BasePath + \"/api/v2/learning/modules/assignments\"\n\tdefaultReturn := new(Assignedlearningmoduledomainentitylisting)\n\tif true == false {\n\t\treturn defaultReturn, nil, errors.New(\"This message brought to you by the laws of physics being broken\")\n\t}\n\n\t// verify the required parameter 'userIds' is set\n\tif &userIds == nil {\n\t\t// true\n\t\treturn defaultReturn, nil, errors.New(\"Missing required parameter 'userIds' when calling LearningApi->GetLearningModulesAssignments\")\n\t}\n\n\theaderParams := make(map[string]string)\n\tqueryParams := make(map[string]string)\n\tformParams := url.Values{}\n\tvar postBody interface{}\n\tvar postFileName string\n\tvar fileBytes []byte\n\t// authentication (PureCloud OAuth) required\n\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\t\n\tqueryParams[\"userIds\"] = a.Configuration.APIClient.ParameterToString(userIds, \"multi\")\n\t\n\tqueryParams[\"pageSize\"] = a.Configuration.APIClient.ParameterToString(pageSize, \"\")\n\t\n\tqueryParams[\"pageNumber\"] = a.Configuration.APIClient.ParameterToString(pageNumber, \"\")\n\t\n\tqueryParams[\"searchTerm\"] = a.Configuration.APIClient.ParameterToString(searchTerm, \"\")\n\t\n\tqueryParams[\"overdue\"] = a.Configuration.APIClient.ParameterToString(overdue, \"\")\n\t\n\tqueryParams[\"assignmentStates\"] = a.Configuration.APIClient.ParameterToString(assignmentStates, \"multi\")\n\t\n\tqueryParams[\"expand\"] = a.Configuration.APIClient.ParameterToString(expand, \"multi\")\n\t\n\n\t// Find an replace keys that were altered to avoid clashes with go keywords \n\tcorrectedQueryParams := make(map[string]string)\n\tfor k, v := range queryParams {\n\t\tif k == \"varType\" {\n\t\t\tcorrectedQueryParams[\"type\"] = v\n\t\t\tcontinue\n\t\t}\n\t\tcorrectedQueryParams[k] = v\n\t}\n\tqueryParams = correctedQueryParams\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\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\tvar successPayload *Assignedlearningmoduledomainentitylisting\n\tresponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, postFileName, fileBytes)\n\tif err != nil {\n\t\t// Nothing special to do here, but do avoid processing the response\n\t} else if err == nil && response.Error != nil {\n\t\terr = errors.New(response.ErrorMessage)\n\t} else if response.HasBody {\n\t\tif \"Assignedlearningmoduledomainentitylisting\" == \"string\" {\n\t\t\tcopy(response.RawBody, &successPayload)\n\t\t} else {\n\t\t\terr = json.Unmarshal(response.RawBody, &successPayload)\n\t\t}\n\t}\n\treturn successPayload, response, err\n}", "func (client BaseClient) GetExpectationsPreparer(ctx context.Context, tenant string, system string) (*http.Request, error) {\n\tqueryParameters := map[string]interface{}{\n\t\t\"tenant\": autorest.Encode(\"query\", tenant),\n\t}\n\tif len(system) > 0 {\n\t\tqueryParameters[\"system\"] = autorest.Encode(\"query\", system)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/api/expectations\"),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *AssignmentPoliciesRequestBuilder) Get(ctx context.Context, requestConfiguration *AssignmentPoliciesRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.AccessPackageAssignmentPolicyCollectionResponseable, error) {\n requestInfo, err := m.CreateGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.SendAsync(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateAccessPackageAssignmentPolicyCollectionResponseFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.AccessPackageAssignmentPolicyCollectionResponseable), nil\n}", "func (client DatasetClient) GetPreparer(ctx context.Context, datasetID string) (*http.Request, error) {\n urlParameters := map[string]interface{} {\n \"geography\": autorest.Encode(\"path\",client.Geography),\n }\n\n pathParameters := map[string]interface{} {\n \"datasetId\": autorest.Encode(\"path\",datasetID),\n }\n\n const APIVersion = \"2.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithCustomBaseURL(\"https://{geography}.atlas.microsoft.com\", urlParameters),\nautorest.WithPathParameters(\"/datasets/{datasetId}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (ralr RegisteredAsnListResult) registeredAsnListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !ralr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(ralr.NextLink)))\n}", "func (client CloudEndpointsClient) GetPreparer(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string, cloudEndpointName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"cloudEndpointName\": autorest.Encode(\"path\", cloudEndpointName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"storageSyncServiceName\": autorest.Encode(\"path\", storageSyncServiceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"syncGroupName\": autorest.Encode(\"path\", syncGroupName),\n\t}\n\n\tconst APIVersion = \"2020-03-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups/{syncGroupName}/cloudEndpoints/{cloudEndpointName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client Client) GetPreparer(resourceGroupName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": url.QueryEscape(name),\n\t\t\"resourceGroupName\": url.QueryEscape(resourceGroupName),\n\t\t\"subscriptionId\": url.QueryEscape(client.SubscriptionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/Redis/{name}\"),\n\t\tautorest.WithPathParameters(pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n}", "func (rasrlr RoleAssignmentScheduleRequestListResult) roleAssignmentScheduleRequestListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !rasrlr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(rasrlr.NextLink)))\n}", "func (client CertificateClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"accountName\": autorest.Encode(\"path\", accountName),\n\t\t\"certificateName\": autorest.Encode(\"path\", certificateName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2018-12-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ManagementClient) GetMAMUserFlaggedEnrolledAppsPreparer(hostName string, userName string, filter string, top *int32, selectParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostName\": autorest.Encode(\"path\", hostName),\n\t\t\"userName\": autorest.Encode(\"path\", userName),\n\t}\n\n\tconst APIVersion = \"2015-01-14-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Intune/locations/{hostName}/flaggedUsers/{userName}/flaggedEnrolledApps\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (cplr ComputePolicyListResult) computePolicyListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif cplr.NextLink == nil || len(to.String(cplr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(cplr.NextLink)))\n}", "func (m *TermsAndConditionsItemRequestBuilder) Assignments()(*i311c330be28d96ff5663f2910da29ba0b1a78acd2fc73a31a5135e243041cb6e.AssignmentsRequestBuilder) {\n return i311c330be28d96ff5663f2910da29ba0b1a78acd2fc73a31a5135e243041cb6e.NewAssignmentsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (client ProductsClient) ListDetailsPreparer(ctx context.Context, resourceGroup string, registrationName string, productName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"productName\": autorest.Encode(\"path\", productName),\n\t\t\"registrationName\": autorest.Encode(\"path\", registrationName),\n\t\t\"resourceGroup\": autorest.Encode(\"path\", resourceGroup),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2017-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.AzureStack/registrations/{registrationName}/products/{productName}/listDetails\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client SmartGroupsClient) GetByIDPreparer(ctx context.Context, smartGroupID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"smartGroupId\": autorest.Encode(\"path\", smartGroupID),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-05-05-preview\"\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(\"/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client RoleAssignmentScheduleRequestsClient) CreatePreparer(ctx context.Context, scope string, roleAssignmentScheduleRequestName string, parameters RoleAssignmentScheduleRequest) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"roleAssignmentScheduleRequestName\": autorest.Encode(\"path\", roleAssignmentScheduleRequestName),\n\t\t\"scope\": scope,\n\t}\n\n\tconst APIVersion = \"2020-10-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tparameters.ID = nil\n\tparameters.Name = nil\n\tparameters.Type = nil\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(\"/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ModelClient) GetExplicitListPreparer(ctx context.Context, appID uuid.UUID, versionID string, entityID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"entityId\": autorest.Encode(\"path\", entityID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/explicitlist\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func fromAssigned(request *jsontree.JsonTree) []string {\n\tvar toNotify []string\n\tassignee, _ := request.Get(\"assignee\").Get(\"login\").String()\n\ttoNotify = append(toNotify, assignee)\n\treturn toNotify\n}", "func (client NodeResources) NodeResourcesPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (client MeshNetworkClient) GetPreparer(ctx context.Context, networkResourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"networkResourceName\": networkResourceName,\n\t}\n\n\tconst APIVersion = \"6.4-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/Resources/Networks/{networkResourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client RecommendedElasticPoolsClient) ListPreparer(resourceGroupName string, serverName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\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\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": client.APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/recommendedElasticPools\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client RosettaNetProcessConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, rosettaNetProcessConfigurationName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"integrationAccountName\": autorest.Encode(\"path\", integrationAccountName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"rosettaNetProcessConfigurationName\": autorest.Encode(\"path\", rosettaNetProcessConfigurationName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2016-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/rosettanetprocessconfigurations/{rosettaNetProcessConfigurationName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ViewsClient) GetPreparer(ctx context.Context, viewName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"viewName\": autorest.Encode(\"path\", viewName),\n\t}\n\n\tconst APIVersion = \"2019-11-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.CostManagement/views/{viewName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client GroupClient) GetExternalDataSourcePreparer(accountName string, databaseName string, externalDataSourceName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"externalDataSourceName\": autorest.Encode(\"path\", externalDataSourceName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/externaldatasources/{externalDataSourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client MSIXPackagesClient) GetPreparer(ctx context.Context, resourceGroupName string, hostPoolName string, msixPackageFullName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostPoolName\": autorest.Encode(\"path\", hostPoolName),\n\t\t\"msixPackageFullName\": autorest.Encode(\"path\", msixPackageFullName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-09-21-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages/{msixPackageFullName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (mc MemberCollection) memberCollectionPreparer(ctx context.Context) (*http.Request, error) {\n\tif !mc.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(mc.NextLink)))\n}", "func (me *TGetAssignmentRequest) Walk() (err error) {\n\tif fn := WalkHandlers.TGetAssignmentRequest; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_AssignmentIdsequenceGetBonusPaymentsRequestschema_AssignmentId_XsdtString_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_ResponseGroupsequenceCreateHITRequestschema_ResponseGroup_XsdtString_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (client AppsClient) GetPreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client PrimitiveClient) GetDatePreparer() (*http.Request, error) {\n preparer := autorest.CreatePreparer(\n autorest.AsGet(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/complex/primitive/date\"))\n return preparer.Prepare(&http.Request{})\n}", "func (client IotHubResourceClient) GetPreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-04-30-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *EntitlementManagementAccessPackageAssignmentsItemAccessPackageAssignmentResourceRolesItemAccessPackageResourceScopeRequestBuilder) Get(ctx context.Context, requestConfiguration *EntitlementManagementAccessPackageAssignmentsItemAccessPackageAssignmentResourceRolesItemAccessPackageResourceScopeRequestBuilderGetRequestConfiguration)(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.AccessPackageResourceScopeable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.CreateAccessPackageResourceScopeFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.AccessPackageResourceScopeable), nil\n}", "func (client Collection) CollectionPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (client *HCRPAssignmentsClient) getCreateRequest(ctx context.Context, resourceGroupName string, guestConfigurationAssignmentName string, machineName string, options *HCRPAssignmentsClientGetOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridCompute/machines/{machineName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif guestConfigurationAssignmentName == \"\" {\n\t\treturn nil, errors.New(\"parameter guestConfigurationAssignmentName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{guestConfigurationAssignmentName}\", url.PathEscape(guestConfigurationAssignmentName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif machineName == \"\" {\n\t\treturn nil, errors.New(\"parameter machineName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{machineName}\", url.PathEscape(machineName))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-01-25\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (m *DelegatedAdminRelationshipsItemAccessAssignmentsDelegatedAdminAccessAssignmentItemRequestBuilder) Get(ctx context.Context, requestConfiguration *DelegatedAdminRelationshipsItemAccessAssignmentsDelegatedAdminAccessAssignmentItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DelegatedAdminAccessAssignmentable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateDelegatedAdminAccessAssignmentFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DelegatedAdminAccessAssignmentable), nil\n}", "func (rpoc ResourceProviderOperationCollection) resourceProviderOperationCollectionPreparer(ctx context.Context) (*http.Request, error) {\n\tif !rpoc.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(rpoc.NextLink)))\n}", "func (client GroupClient) GetCredentialPreparer(accountName string, databaseName string, credentialName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"credentialName\": autorest.Encode(\"path\", credentialName),\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/credentials/{credentialName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client InfraRoleInstancesClient) GetPreparer(ctx context.Context, location string, infraRoleInstance string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"infraRoleInstance\": autorest.Encode(\"path\", infraRoleInstance),\n\t\t\"location\": autorest.Encode(\"path\", location),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2016-05-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/infraRoleInstances/{infraRoleInstance}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ApplicationsClient) GetPreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (mrlr MonitoredResourceListResponse) monitoredResourceListResponsePreparer(ctx context.Context) (*http.Request, error) {\n\tif !mrlr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(mrlr.NextLink)))\n}", "func (m *DeviceConfigurationItemRequestBuilder) Assignments()(*i1acaef5ee6ae1997bcbb07d275900c5d95eb14266a9c79c9ee811bf4c0edefb4.AssignmentsRequestBuilder) {\n return i1acaef5ee6ae1997bcbb07d275900c5d95eb14266a9c79c9ee811bf4c0edefb4.NewAssignmentsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (svc *SSHKeysService) ListAssigned(ctx context.Context, prj, dc, cls string) ([]SSHKey, *http.Response, error) {\n\tret := make([]SSHKey, 0)\n\tresp, err := svc.client.resourceList(ctx, clusterSSHKeysPath(prj, dc, cls), &ret)\n\treturn ret, resp, err\n}", "func (client FirewallPolicyRuleGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleGroupName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"firewallPolicyName\": autorest.Encode(\"path\", firewallPolicyName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"ruleGroupName\": autorest.Encode(\"path\", ruleGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/ruleGroups/{ruleGroupName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ModelClient) ListCustomPrebuiltEntitiesPreparer(ctx context.Context, appID uuid.UUID, versionID string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/customprebuiltentities\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client UsageDetailsClient) ListByEnrollmentAccountPreparer(ctx context.Context, enrollmentAccountID string, expand string, filter string, skiptoken string, top *int32, apply string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"enrollmentAccountId\": autorest.Encode(\"path\", enrollmentAccountID),\n\t}\n\n\tconst APIVersion = \"2018-06-30\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif len(skiptoken) > 0 {\n\t\tqueryParameters[\"$skiptoken\"] = autorest.Encode(\"query\", skiptoken)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(apply) > 0 {\n\t\tqueryParameters[\"$apply\"] = autorest.Encode(\"query\", apply)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}/providers/Microsoft.Consumption/usageDetails\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (cl CreatorList) creatorListPreparer(ctx context.Context) (*http.Request, error) {\n\tif !cl.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(cl.NextLink)))\n}", "func (client AppsClient) ListAvailableCustomPrebuiltDomainsPreparer(ctx context.Context) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/apps/customprebuiltdomains\"))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (elr ExemptionListResult) exemptionListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !elr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(elr.NextLink)))\n}", "func (client ProcessesClient) GetPreparer(ctx context.Context, resourceGroupName string, workspaceName string, machineName string, processName string, timestamp *date.Time) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"machineName\": autorest.Encode(\"path\", machineName),\n\t\t\"processName\": autorest.Encode(\"path\", processName),\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 = \"2015-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif timestamp != nil {\n\t\tqueryParameters[\"timestamp\"] = autorest.Encode(\"query\", *timestamp)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/features/serviceMap/machines/{machineName}/processes/{processName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (ualr UsageAggregationListResult) usageAggregationListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif ualr.NextLink == nil || len(to.String(ualr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(ualr.NextLink)))\n}", "func (client ServicesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *MockSchedulingAlgorithm) GetTasksToBeAssigned(jobs []*jobState, stat stats.StatsReceiver, cs *clusterState, requestors map[string][]*jobState) ([]*taskState, []*taskState) {\n\tret := m.ctrl.Call(m, \"GetTasksToBeAssigned\", jobs, stat, cs, requestors)\n\tret0, _ := ret[0].([]*taskState)\n\tret1, _ := ret[1].([]*taskState)\n\treturn ret0, ret1\n}", "func (b *PolicySetRequestBuilder) Assignments() *PolicySetAssignmentsCollectionRequestBuilder {\n\tbb := &PolicySetAssignmentsCollectionRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/assignments\"\n\treturn bb\n}", "func (resrlr RoleEligibilityScheduleRequestListResult) roleEligibilityScheduleRequestListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !resrlr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(resrlr.NextLink)))\n}", "func (rlr ResourceListResult) resourceListResultPreparer() (*http.Request, error) {\n\tif rlr.NextLink == nil || len(to.String(rlr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(rlr.NextLink)))\n}", "func (client AppsClient) ListAvailableCustomPrebuiltDomainsForCulturePreparer(ctx context.Context, culture string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"culture\": autorest.Encode(\"path\", culture),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/customprebuiltdomains/{culture}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ManagementClient) GetAppsPreparer(hostName string, filter string, top *int32, selectParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostName\": autorest.Encode(\"path\", hostName),\n\t}\n\n\tconst APIVersion = \"2015-01-14-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Intune/locations/{hostName}/apps\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (c *Client) NewListAssignedResourceRolesRequest(ctx context.Context, path string) (*http.Request, error) {\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif c.JWTSigner != nil {\n\t\tc.JWTSigner.Sign(req)\n\t}\n\treturn req, nil\n}", "func (client BaseClient) GetSubscriptionPreparer(ctx context.Context, subscriptionID uuid.UUID, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"subscriptionId\": autorest.Encode(\"path\",subscriptionID),\n }\n\n const APIVersion = \"2.0.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\n autorest.AsGet(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPathParameters(\"/{subscriptionId}\",pathParameters),\n autorest.WithQueryParameters(queryParameters),\n autorest.WithHeader(\"Content-Type\", \"application/json\"))\n if xMsRequestid != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithHeader(\"x-ms-requestid\",autorest.String(xMsRequestid)))\n }\n if xMsCorrelationid != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithHeader(\"x-ms-correlationid\",autorest.String(xMsCorrelationid)))\n }\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client PrimitiveClient) GetIntPreparer() (*http.Request, error) {\n preparer := autorest.CreatePreparer(\n autorest.AsGet(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/complex/primitive/integer\"))\n return preparer.Prepare(&http.Request{})\n}", "func (calr ClassicAdministratorListResult) classicAdministratorListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !calr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(calr.NextLink)))\n}", "func (client ModelClient) GetPrebuiltPreparer(ctx context.Context, appID uuid.UUID, versionID string, prebuiltID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"prebuiltId\": autorest.Encode(\"path\", prebuiltID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/prebuilts/{prebuiltId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (a Accounts) accountsPreparer(ctx context.Context) (*http.Request, error) {\n\tif !a.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(a.NextLink)))\n}", "func (client ProductsClient) ListPreparer(ctx context.Context, resourceGroup string, registrationName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"registrationName\": autorest.Encode(\"path\", registrationName),\n\t\t\"resourceGroup\": autorest.Encode(\"path\", resourceGroup),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2017-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.AzureStack/registrations/{registrationName}/products\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *EmbeddedSIMActivationCodePoolsEmbeddedSIMActivationCodePoolItemRequestBuilder) Assignments()(*EmbeddedSIMActivationCodePoolsItemAssignmentsRequestBuilder) {\n return NewEmbeddedSIMActivationCodePoolsItemAssignmentsRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (client ModelClient) GetEntitySuggestionsPreparer(ctx context.Context, appID uuid.UUID, versionID string, entityID uuid.UUID, take *int32) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"entityId\": autorest.Encode(\"path\", entityID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{}\n\tif take != nil {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", *take)\n\t} else {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", 100)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/entities/{entityId}/suggest\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *EntitlementManagementAccessPackageAssignmentResourceRolesItemAccessPackageResourceScopeRequestBuilder) Get(ctx context.Context, requestConfiguration *EntitlementManagementAccessPackageAssignmentResourceRolesItemAccessPackageResourceScopeRequestBuilderGetRequestConfiguration)(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.AccessPackageResourceScopeable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.CreateAccessPackageResourceScopeFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.AccessPackageResourceScopeable), nil\n}" ]
[ "0.5963194", "0.5895939", "0.5568281", "0.541476", "0.5379276", "0.5376148", "0.5348158", "0.5313191", "0.5298953", "0.5291527", "0.5252276", "0.52092755", "0.5178264", "0.5147524", "0.51033354", "0.51019937", "0.5069028", "0.503377", "0.5029208", "0.50276953", "0.50211954", "0.49846628", "0.496869", "0.49455082", "0.4938507", "0.49355033", "0.49194065", "0.48896453", "0.48878828", "0.48527008", "0.48429328", "0.48405188", "0.48272413", "0.48052385", "0.4803236", "0.47842452", "0.4782437", "0.47804326", "0.47689426", "0.4768573", "0.47668433", "0.47590715", "0.47560766", "0.47554842", "0.47484532", "0.47371337", "0.47365052", "0.4730888", "0.47212732", "0.4720556", "0.47196895", "0.4706772", "0.46931657", "0.46930674", "0.46874186", "0.4684851", "0.46812567", "0.467931", "0.46743566", "0.46666554", "0.46622342", "0.46598563", "0.46560067", "0.4645532", "0.46423173", "0.4642053", "0.46416542", "0.4634133", "0.46270248", "0.4622372", "0.46177372", "0.46155444", "0.4611009", "0.46043798", "0.4600154", "0.4599914", "0.45995", "0.45981836", "0.45947456", "0.45947158", "0.4593535", "0.4591104", "0.45881426", "0.45862487", "0.4584033", "0.4582882", "0.45791444", "0.4579035", "0.4575909", "0.4575805", "0.45753404", "0.45629546", "0.45619768", "0.45604643", "0.4554058", "0.45519975", "0.45511281", "0.45506674", "0.45493007", "0.45462036" ]
0.77361584
0
GetAssignedSender sends the GetAssigned request. The method will close the http.Response Body if it receives an error.
func (client AzureAccountsClient) GetAssignedSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AzureAccountsClient) GetAssigned(ctx context.Context, appID uuid.UUID) (result ListAzureAccountInfoObject, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.GetAssigned\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.GetAssignedPreparer(ctx, appID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetAssigned\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetAssignedSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetAssigned\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetAssignedResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetAssigned\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (client AzureAccountsClient) GetAssignedResponder(resp *http.Response) (result ListAzureAccountInfoObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client RecommendedElasticPoolsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req)\n}", "func (client RoleAssignmentScheduleRequestsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client DeploymentsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client AccountClient) GetSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, azure.DoRetryWithRegistration(client.Client))\n }", "func (client AppsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client DatasetClient) GetSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func (client CloudEndpointsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client RecoveryPointsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client ApplicationsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ReferenceDataSetsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client OpenShiftManagedClustersClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n}", "func (r GetAssignmentRequest) Send(ctx context.Context) (*GetAssignmentResponse, 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 := &GetAssignmentResponse{\n\t\tGetAssignmentOutput: r.Request.Data.(*GetAssignmentOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (client JobClient) GetSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, azure.DoRetryWithRegistration(client.Client))\n }", "func (client ProductsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n}", "func (client ThreatIntelligenceIndicatorClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client ProcessesClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n}", "func (client AzureAccountsClient) GetAssignedPreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client MSIXPackagesClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (m *ScheduleChangeRequest) GetAssignedTo()(*ScheduleChangeRequestActor) {\n val, err := m.GetBackingStore().Get(\"assignedTo\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*ScheduleChangeRequestActor)\n }\n return nil\n}", "func (client ViewsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ServicesClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client PublishedBlueprintsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ExternalBillingAccountClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client StorageTargetsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client IotHubResourceClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client Client) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n}", "func (client Client) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req)\n}", "func (client IngestionSettingsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client LabClient) GetResourceSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n}", "func fromAssigned(request *jsontree.JsonTree) []string {\n\tvar toNotify []string\n\tassignee, _ := request.Get(\"assignee\").Get(\"login\").String()\n\ttoNotify = append(toNotify, assignee)\n\treturn toNotify\n}", "func (client JobClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client PrimitiveClient) GetIntSender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (client ScheduleMessageClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client PrimitiveClient) GetStringSender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (client SmartGroupsClient) GetByIDSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client RosettaNetProcessConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client DeviceClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (o *WatchlistScreeningIndividualUpdateResponse) GetAssignee() string {\n\tif o == nil || o.Assignee.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.Assignee.Get()\n}", "func (client ViewsClient) GetByScopeSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ModelClient) GetClosedListSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client InfraRoleInstancesClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n}", "func (client DatabasesClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req)\n}", "func (client BaseClient) ResolveSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func (client MeshNetworkClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client FirewallPolicyRuleGroupsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client BaseClient) GetSystemsSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (m *MobileAppAssignmentItemRequestBuilder) Get(ctx context.Context, requestConfiguration *MobileAppAssignmentItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.MobileAppAssignmentable, error) {\n requestInfo, err := m.CreateGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.SendAsync(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateMobileAppAssignmentFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.MobileAppAssignmentable), nil\n}", "func (client BaseClient) GetSubscriptionSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func (client Client) GetDetailSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AzureAccountsClient) AssignToAppSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AccountQuotaPolicyClient) GetSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, azure.DoRetryWithRegistration(client.Client))\n }", "func (client GroupClient) GetExternalDataSourceSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client,\n\t\treq,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client LinkedServiceClient) GetLinkedServiceSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (o *MicrosoftGraphPlannerAssignment) GetAssignedDateTime() time.Time {\n\tif o == nil || o.AssignedDateTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.AssignedDateTime\n}", "func (client CertificateClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n}", "func (client StringClient) GetNotProvidedSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client BaseClient) GetSystemSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client VersionsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (o DataPoolEncryptionResponseOutput) UserAssignedIdentity() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DataPoolEncryptionResponse) string { return v.UserAssignedIdentity }).(pulumi.StringOutput)\n}", "func (m *EducationAssignmentItemRequestBuilder) Get(ctx context.Context, requestConfiguration *EducationAssignmentItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.EducationAssignmentable, error) {\n requestInfo, err := m.CreateGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.SendAsync(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateEducationAssignmentFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.EducationAssignmentable), nil\n}", "func (client Client) GetListSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client StringClient) GetEmptySender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client StringClient) GetNullSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client GroupClient) GetViewSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client,\n\t\treq,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ManagementClient) GetAppsSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client,\n\t\treq,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (o *MicrosoftGraphPlannerAssignment) GetAssignedBy() AnyOfmicrosoftGraphIdentitySet {\n\tif o == nil || o.AssignedBy == nil {\n\t\tvar ret AnyOfmicrosoftGraphIdentitySet\n\t\treturn ret\n\t}\n\treturn *o.AssignedBy\n}", "func (client PortPluginClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (m *EntitlementManagementAssignmentsItemTargetRequestBuilder) Get(ctx context.Context, requestConfiguration *EntitlementManagementAssignmentsItemTargetRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.AccessPackageSubjectable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateAccessPackageSubjectFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.AccessPackageSubjectable), nil\n}", "func (m *EducationAssignment) GetAssignTo()(EducationAssignmentRecipientable) {\n return m.assignTo\n}", "func (client GroupClient) GetProcedureSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client,\n\t\treq,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (s *TeamsServiceOp) GetTeamUsersAssigned(ctx context.Context, orgID, teamID string) ([]*User, *Response, error) {\n\tif orgID == \"\" {\n\t\treturn nil, nil, atlas.NewArgError(\"orgID\", \"must be set\")\n\t}\n\tif teamID == \"\" {\n\t\treturn nil, nil, atlas.NewArgError(\"teamID\", \"must be set\")\n\t}\n\n\tbasePath := fmt.Sprintf(teamsBasePath, orgID)\n\tpath := fmt.Sprintf(\"%s/%s/users\", basePath, teamID)\n\n\treq, err := s.Client.NewRequest(ctx, http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\troot := new(UsersResponse)\n\tresp, err := s.Client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\tif l := root.Links; l != nil {\n\t\tresp.Links = l\n\t}\n\n\treturn root.Results, resp, nil\n}", "func (m *AssignmentPoliciesRequestBuilder) Get(ctx context.Context, requestConfiguration *AssignmentPoliciesRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.AccessPackageAssignmentPolicyCollectionResponseable, error) {\n requestInfo, err := m.CreateGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.SendAsync(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateAccessPackageAssignmentPolicyCollectionResponseFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.AccessPackageAssignmentPolicyCollectionResponseable), nil\n}", "func (client ModelClient) GetExplicitListItemSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client RoleAssignmentScheduleRequestsClient) Get(ctx context.Context, scope string, roleAssignmentScheduleRequestName string) (result RoleAssignmentScheduleRequest, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/RoleAssignmentScheduleRequestsClient.Get\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.GetPreparer(ctx, scope, roleAssignmentScheduleRequestName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authorization.RoleAssignmentScheduleRequestsClient\", \"Get\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authorization.RoleAssignmentScheduleRequestsClient\", \"Get\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authorization.RoleAssignmentScheduleRequestsClient\", \"Get\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (client ModelClient) GetExplicitListSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (svc *SSHKeysService) ListAssigned(ctx context.Context, prj, dc, cls string) ([]SSHKey, *http.Response, error) {\n\tret := make([]SSHKey, 0)\n\tresp, err := svc.client.resourceList(ctx, clusterSSHKeysPath(prj, dc, cls), &ret)\n\treturn ret, resp, err\n}", "func (m *SequentialActivationRenewalsAlertIncident) GetAssigneeId()(*string) {\n val, err := m.GetBackingStore().Get(\"assigneeId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (client PrimitiveClient) GetLongSender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (m *ItemRoleAssignmentsItemLinkedEligibleRoleAssignmentRequestBuilder) Get(ctx context.Context, requestConfiguration *ItemRoleAssignmentsItemLinkedEligibleRoleAssignmentRequestBuilderGetRequestConfiguration)(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.GovernanceRoleAssignmentable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.CreateGovernanceRoleAssignmentFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.GovernanceRoleAssignmentable), nil\n}", "func (client ModelClient) GetEntitySender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (i *IssueRequest) GetAssignee() string {\n\tif i == nil || i.Assignee == nil {\n\t\treturn \"\"\n\t}\n\treturn *i.Assignee\n}", "func (c *Client) Get(method rest.Method, endpoint string) (string, int, error) {\n\tvar req rest.Request\n\tif c.OnBehalfOf != \"\" {\n\t\treq = sendgrid.GetRequestSubuser(c.apiKey, endpoint, c.host, c.OnBehalfOf)\n\t} else {\n\t\treq = sendgrid.GetRequest(c.apiKey, endpoint, c.host)\n\t}\n\n\treq.Method = method\n\n\tresp, err := sendgrid.API(req)\n\tif err != nil {\n\t\treturn \"\", resp.StatusCode, fmt.Errorf(\"failed getting resource: %w\", err)\n\t}\n\n\treturn resp.Body, resp.StatusCode, nil\n}", "func (client HTTPSuccessClient) Get200Sender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (c *MockRoleAssignmentsClient) Get(ctx context.Context, scope string, roleAssignmentName string) (result authorizationmgmt.RoleAssignment, err error) {\n\treturn c.MockGet(ctx, scope, roleAssignmentName)\n}", "func (client ListManagementTermListsClient) GetDetailsSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (mr *MockSchedulingAlgorithmMockRecorder) GetTasksToBeAssigned(jobs, stat, cs, requestors interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetTasksToBeAssigned\", reflect.TypeOf((*MockSchedulingAlgorithm)(nil).GetTasksToBeAssigned), jobs, stat, cs, requestors)\n}", "func GetEmailSender(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *EmailSenderState, opts ...pulumi.ResourceOption) (*EmailSender, error) {\n\tvar resource EmailSender\n\terr := ctx.ReadResource(\"okta:index/emailSender:EmailSender\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (client VolumesClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n}", "func (o DataPoolEncryptionResponsePtrOutput) UserAssignedIdentity() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataPoolEncryptionResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.UserAssignedIdentity\n\t}).(pulumi.StringPtrOutput)\n}", "func (i *IssuesEvent) GetAssignee() *User {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Assignee\n}", "func (client BaseClient) GetExpectationsSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client RecommendedElasticPoolsClient) ListSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req)\n}", "func (client GroupClient) GetTableSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client,\n\t\treq,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (i *IssueEvent) GetAssignee() *User {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Assignee\n}", "func ReturnAssignmentResponse(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\tc := Assignment{\"assignmentID\", \"http://ispw:8080/ispw/ispw/assignments/assignmentid\"}\n\toutgoingJSON, err := json.Marshal(c)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tres.WriteHeader(http.StatusCreated)\n\tfmt.Fprint(res, string(outgoingJSON))\n}", "func (i *IssueEvent) GetAssigner() *User {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Assigner\n}", "func (client CertificateOrdersClient) GetCertificateOrdersSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n}", "func (r *Requestor) sendGetCandidate(hash []byte) error {\n\t// Send a request for this specific candidate\n\tbuf := bytes.NewBuffer(hash)\n\tif err := topics.Prepend(buf, topics.GetCandidate); err != nil {\n\t\treturn err\n\t}\n\n\tmsg := message.NewWithMetadata(topics.GetCandidate, buf, &message.Metadata{NumNodes: config.GetCandidateReceivers})\n\tr.publisher.Publish(topics.KadcastSendToMany, msg)\n\treturn nil\n}" ]
[ "0.6203293", "0.59076774", "0.58089674", "0.5721986", "0.5655053", "0.54219246", "0.5387857", "0.5382569", "0.5348779", "0.5340898", "0.5331885", "0.5289841", "0.528731", "0.52831715", "0.52681875", "0.5264625", "0.5263613", "0.5261128", "0.52494043", "0.5233055", "0.5223986", "0.5217525", "0.5195617", "0.51803744", "0.5178889", "0.5173159", "0.51665264", "0.51464844", "0.512452", "0.5108815", "0.5066192", "0.50424016", "0.5038195", "0.5030898", "0.50298095", "0.5012107", "0.5008081", "0.49979234", "0.49925655", "0.49650013", "0.49435416", "0.49374586", "0.49273643", "0.49246222", "0.49042273", "0.490058", "0.487345", "0.48708633", "0.4868847", "0.48447317", "0.48404413", "0.48402575", "0.48350048", "0.48258343", "0.48209602", "0.47885048", "0.4773173", "0.47730255", "0.4771647", "0.4769109", "0.47560185", "0.4744473", "0.4731133", "0.4716738", "0.47139508", "0.4710513", "0.4699036", "0.4698882", "0.46987695", "0.46697515", "0.46667075", "0.4660246", "0.4656363", "0.46537852", "0.46438462", "0.46114165", "0.4609967", "0.4580902", "0.4580852", "0.45781246", "0.45729494", "0.4555278", "0.45492378", "0.45293087", "0.45248276", "0.45219186", "0.4521765", "0.45207164", "0.45162705", "0.4507723", "0.45025873", "0.4500853", "0.4497631", "0.44911224", "0.4480002", "0.44733354", "0.44730192", "0.44713077", "0.44509676", "0.44503698" ]
0.75747406
0
GetAssignedResponder handles the response to the GetAssigned request. The method always closes the http.Response Body.
func (client AzureAccountsClient) GetAssignedResponder(resp *http.Response) (result ListAzureAccountInfoObject, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AzureAccountsClient) GetAssigned(ctx context.Context, appID uuid.UUID) (result ListAzureAccountInfoObject, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.GetAssigned\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.GetAssignedPreparer(ctx, appID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetAssigned\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetAssignedSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetAssigned\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetAssignedResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetAssigned\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (client *HCRPAssignmentsClient) getHandleResponse(resp *http.Response) (HCRPAssignmentsClientGetResponse, error) {\n\tresult := HCRPAssignmentsClientGetResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.Assignment); err != nil {\n\t\treturn HCRPAssignmentsClientGetResponse{}, err\n\t}\n\treturn result, nil\n}", "func ReturnAssignmentResponse(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\tc := Assignment{\"assignmentID\", \"http://ispw:8080/ispw/ispw/assignments/assignmentid\"}\n\toutgoingJSON, err := json.Marshal(c)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tres.WriteHeader(http.StatusCreated)\n\tfmt.Fprint(res, string(outgoingJSON))\n}", "func (client *RoleAssignmentsClient) getHandleResponse(resp *http.Response) (RoleAssignmentsGetResponse, error) {\n\tresult := RoleAssignmentsGetResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsGetResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client RecommendedElasticPoolsClient) GetResponder(resp *http.Response) (result RecommendedElasticPool, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client *HCRPAssignmentsClient) listHandleResponse(resp *http.Response) (HCRPAssignmentsClientListResponse, error) {\n\tresult := HCRPAssignmentsClientListResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.AssignmentList); err != nil {\n\t\treturn HCRPAssignmentsClientListResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client RoleAssignmentScheduleRequestsClient) GetResponder(resp *http.Response) (result RoleAssignmentScheduleRequest, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (handler *CommandHandler) HandleAssignCommand(text string) ([]byte, error) {\n\theader := NewHeaderBlock(UpdateHeader)\n\tdiv := NewDividerBlock()\n\tif !ValidateAssignCommandText(text) {\n\t\terrBlock := NewSectionTextBlock(\"plain_text\", AssignBadArgsText)\n\t\tresponse := NewResponse(header, div, errBlock)\n\t\tbyt, err := json.Marshal(response)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn byt, nil\n\t}\n\targs := strings.Split(text, \" \")\n\tid, _ := strconv.Atoi(args[0])\n\terr := handler.Repository.AssignTaskTo(id, args[1])\n\tif err == mysql.ErrNoRowOrMoreThanOne {\n\t\terrBlock := NewSectionTextBlock(\"plain_text\", NoSuchTaskIDText)\n\t\tresponse := NewResponse(header, div, errBlock)\n\t\tbyt, err := json.Marshal(response)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn byt, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\ttask, err := handler.Repository.GetTaskByID(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblock1 := NewSectionTextBlock(\"mrkdwn\", \"Assigned: \"+task.Title+\" - \"+task.AsigneeID)\n\tresp := NewResponse(header, div, block1)\n\tbyt, err := json.Marshal(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn byt, nil\n}", "func (client DeploymentsClient) GetResponder(resp *http.Response) (result DeploymentResource, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client AzureAccountsClient) GetAssignedSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AzureAccountsClient) AssignToAppResponder(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.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client LabClient) GetResourceResponder(resp *http.Response) (result Lab, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client ReferenceDataSetsClient) GetResponder(resp *http.Response) (result ReferenceDataSetResource, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client AccountClient) GetResponder(resp *http.Response) (result AccountResourceDescription, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client BaseClient) ResolveResponder(resp *http.Response) (result SetObject, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusBadRequest,http.StatusForbidden,http.StatusNotFound,http.StatusInternalServerError),\n autorest.ByUnmarshallingJSON(&result.Value),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client SmartGroupsClient) GetByIDResponder(resp *http.Response) (result SmartGroup, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (page AssignmentListResultPage) Response() AssignmentListResult {\n\treturn page.alr\n}", "func (c *Seaweed) Assign(args url.Values) (result *AssignResult, err error) {\n\tjsonBlob, _, err := c.client.get(encodeURI(*c.master, \"/dir/assign\", args), nil)\n\tif err == nil {\n\t\tresult = &AssignResult{}\n\t\tif err = json.Unmarshal(jsonBlob, result); err != nil {\n\t\t\terr = fmt.Errorf(\"/dir/assign result JSON unmarshal error:%v, json:%s\", err, string(jsonBlob))\n\t\t} else if result.Count == 0 {\n\t\t\terr = errors.New(result.Error)\n\t\t}\n\t}\n\n\treturn\n}", "func (client PublishedBlueprintsClient) GetResponder(resp *http.Response) (result PublishedBlueprint, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client DatasetClient) GetResponder(resp *http.Response) (result DatasetDetailInfo, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client *SQLResourcesClient) getSQLRoleAssignmentHandleResponse(resp *http.Response) (SQLResourcesClientGetSQLRoleAssignmentResponse, error) {\n\tresult := SQLResourcesClientGetSQLRoleAssignmentResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.SQLRoleAssignmentGetResults); err != nil {\n\t\treturn SQLResourcesClientGetSQLRoleAssignmentResponse{}, err\n\t}\n\treturn result, nil\n}", "func (me *TxsdGetAssignmentResponse) Walk() (err error) {\n\tif fn := WalkHandlers.TxsdGetAssignmentResponse; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_OperationRequest.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_GetAssignmentResultsequenceTxsdGetAssignmentResponseGetAssignmentResponseschema_GetAssignmentResult_TGetAssignmentResult_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (client AppsClient) GetResponder(resp *http.Response) (result ApplicationInfoResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (m *AssignmentPoliciesRequestBuilder) Get(ctx context.Context, requestConfiguration *AssignmentPoliciesRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.AccessPackageAssignmentPolicyCollectionResponseable, error) {\n requestInfo, err := m.CreateGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.SendAsync(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateAccessPackageAssignmentPolicyCollectionResponseFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.AccessPackageAssignmentPolicyCollectionResponseable), nil\n}", "func (client MSIXPackagesClient) GetResponder(resp *http.Response) (result MSIXPackage, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client JobClient) GetResponder(resp *http.Response) (result JobResourceDescription, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func NewAssigneeResponse() *AssigneeResponse {\n\tthis := AssigneeResponse{}\n\treturn &this\n}", "func (gp *GetProjects) GetResponse() ActionResponseInterface {\n\treturn <-gp.responseCh\n}", "func (client ProcessesClient) GetResponder(resp *http.Response) (result Process, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (me *XsdGoPkgHasElem_GetAssignmentResponse) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_GetAssignmentResponse; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.GetAssignmentResponse.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (client ViewsClient) GetByScopeResponder(resp *http.Response) (result View, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client *RoleAssignmentsClient) getByInvoiceSectionHandleResponse(resp *http.Response) (RoleAssignmentsClientGetByInvoiceSectionResponse, error) {\n\tresult := RoleAssignmentsClientGetByInvoiceSectionResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsClientGetByInvoiceSectionResponse{}, err\n\t}\n\treturn result, nil\n}", "func (me *XsdGoPkgHasElems_GetAssignmentResponse) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_GetAssignmentResponse; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfor _, x := range me.GetAssignmentResponses {\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (client ModelClient) GetClosedListResponder(resp *http.Response) (result ClosedListEntityExtractor, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client BaseClient) GetSubscriptionResponder(resp *http.Response) (result SetObject, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusForbidden,http.StatusNotFound,http.StatusInternalServerError),\n autorest.ByUnmarshallingJSON(&result.Value),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client *RoleAssignmentsClient) getByInvoiceSectionHandleResponse(resp *http.Response) (RoleAssignmentsClientGetByInvoiceSectionResponse, error) {\n\tresult := RoleAssignmentsClientGetByInvoiceSectionResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsClientGetByInvoiceSectionResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client *IPAllocationsClient) getHandleResponse(resp *http.Response) (IPAllocationsClientGetResponse, error) {\n\tresult := IPAllocationsClientGetResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.IPAllocation); err != nil {\n\t\treturn IPAllocationsClientGetResponse{}, err\n\t}\n\treturn result, nil\n}", "func (response ListAssignedSubscriptionLineItemsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}", "func GetAssignmentMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewPolicyAssignmentService(cs)\n\tassert.Nil(err, \"Couldn't load policyAssignment service\")\n\tassert.NotNil(ds, \"PolicyAssignment service not instanced\")\n\n\t// to json\n\tdIn, err := json.Marshal(policyAssignmentIn)\n\tassert.Nil(err, \"PolicyAssignment test data corrupted\")\n\n\t// call service\n\tcs.On(\"Get\", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID)).Return(dIn, 200, nil)\n\tpolicyAssignmentOut, err := ds.GetAssignment(policyAssignmentIn.ID)\n\n\tassert.Nil(err, \"Error getting policy assignment\")\n\tassert.Equal(*policyAssignmentIn, *policyAssignmentOut, \"GetAssignment returned different policy assignment\")\n\n\treturn policyAssignmentOut\n}", "func (m *EducationAssignmentItemRequestBuilder) Get(ctx context.Context, requestConfiguration *EducationAssignmentItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.EducationAssignmentable, error) {\n requestInfo, err := m.CreateGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.SendAsync(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateEducationAssignmentFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.EducationAssignmentable), nil\n}", "func (iter AssignmentListResultIterator) Response() AssignmentListResult {\n\treturn iter.page.Response()\n}", "func (client ApplicationsClient) GetResponder(resp *http.Response) (result Application, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (a LearningApi) GetLearningModulesAssignments(userIds []string, pageSize int, pageNumber int, searchTerm string, overdue string, assignmentStates []string, expand []string) (*Assignedlearningmoduledomainentitylisting, *APIResponse, error) {\n\tvar httpMethod = \"GET\"\n\t// create path and map variables\n\tpath := a.Configuration.BasePath + \"/api/v2/learning/modules/assignments\"\n\tdefaultReturn := new(Assignedlearningmoduledomainentitylisting)\n\tif true == false {\n\t\treturn defaultReturn, nil, errors.New(\"This message brought to you by the laws of physics being broken\")\n\t}\n\n\t// verify the required parameter 'userIds' is set\n\tif &userIds == nil {\n\t\t// true\n\t\treturn defaultReturn, nil, errors.New(\"Missing required parameter 'userIds' when calling LearningApi->GetLearningModulesAssignments\")\n\t}\n\n\theaderParams := make(map[string]string)\n\tqueryParams := make(map[string]string)\n\tformParams := url.Values{}\n\tvar postBody interface{}\n\tvar postFileName string\n\tvar fileBytes []byte\n\t// authentication (PureCloud OAuth) required\n\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\t\n\tqueryParams[\"userIds\"] = a.Configuration.APIClient.ParameterToString(userIds, \"multi\")\n\t\n\tqueryParams[\"pageSize\"] = a.Configuration.APIClient.ParameterToString(pageSize, \"\")\n\t\n\tqueryParams[\"pageNumber\"] = a.Configuration.APIClient.ParameterToString(pageNumber, \"\")\n\t\n\tqueryParams[\"searchTerm\"] = a.Configuration.APIClient.ParameterToString(searchTerm, \"\")\n\t\n\tqueryParams[\"overdue\"] = a.Configuration.APIClient.ParameterToString(overdue, \"\")\n\t\n\tqueryParams[\"assignmentStates\"] = a.Configuration.APIClient.ParameterToString(assignmentStates, \"multi\")\n\t\n\tqueryParams[\"expand\"] = a.Configuration.APIClient.ParameterToString(expand, \"multi\")\n\t\n\n\t// Find an replace keys that were altered to avoid clashes with go keywords \n\tcorrectedQueryParams := make(map[string]string)\n\tfor k, v := range queryParams {\n\t\tif k == \"varType\" {\n\t\t\tcorrectedQueryParams[\"type\"] = v\n\t\t\tcontinue\n\t\t}\n\t\tcorrectedQueryParams[k] = v\n\t}\n\tqueryParams = correctedQueryParams\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\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\tvar successPayload *Assignedlearningmoduledomainentitylisting\n\tresponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, postFileName, fileBytes)\n\tif err != nil {\n\t\t// Nothing special to do here, but do avoid processing the response\n\t} else if err == nil && response.Error != nil {\n\t\terr = errors.New(response.ErrorMessage)\n\t} else if response.HasBody {\n\t\tif \"Assignedlearningmoduledomainentitylisting\" == \"string\" {\n\t\t\tcopy(response.RawBody, &successPayload)\n\t\t} else {\n\t\t\terr = json.Unmarshal(response.RawBody, &successPayload)\n\t\t}\n\t}\n\treturn successPayload, response, err\n}", "func (client AzureAccountsClient) GetAssignedPreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ScheduleMessageClient) GetResponder(resp *http.Response) (result PushScheduleFetchParameter, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound, http.StatusInternalServerError),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client OpenShiftManagedClustersClient) GetResponder(resp *http.Response) (result v20180930preview.OpenShiftManagedCluster, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client FirewallPolicyRuleGroupsClient) GetResponder(resp *http.Response) (result FirewallPolicyRuleGroup, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (m *ScheduleChangeRequest) GetAssignedTo()(*ScheduleChangeRequestActor) {\n val, err := m.GetBackingStore().Get(\"assignedTo\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*ScheduleChangeRequestActor)\n }\n return nil\n}", "func (svc *SSHKeysService) ListAssigned(ctx context.Context, prj, dc, cls string) ([]SSHKey, *http.Response, error) {\n\tret := make([]SSHKey, 0)\n\tresp, err := svc.client.resourceList(ctx, clusterSSHKeysPath(prj, dc, cls), &ret)\n\treturn ret, resp, err\n}", "func (m *MobileAppAssignmentItemRequestBuilder) Get(ctx context.Context, requestConfiguration *MobileAppAssignmentItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.MobileAppAssignmentable, error) {\n requestInfo, err := m.CreateGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.SendAsync(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateMobileAppAssignmentFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.MobileAppAssignmentable), nil\n}", "func (page RegistrationAssignmentListPage) Response() RegistrationAssignmentList {\n\treturn page.ral\n}", "func (client ViewsClient) GetResponder(resp *http.Response) (result View, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (iter RegistrationAssignmentListIterator) Response() RegistrationAssignmentList {\n\treturn iter.page.Response()\n}", "func (me *TxsdGetAssignmentsForHITResponse) Walk() (err error) {\n\tif fn := WalkHandlers.TxsdGetAssignmentsForHITResponse; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_OperationRequest.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_GetAssignmentsForHITResultsequenceTxsdGetAssignmentsForHITResponseGetAssignmentsForHITResponseschema_GetAssignmentsForHITResult_TGetAssignmentsForHITResult_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (c *MockRoleAssignmentsClient) Get(ctx context.Context, scope string, roleAssignmentName string) (result authorizationmgmt.RoleAssignment, err error) {\n\treturn c.MockGet(ctx, scope, roleAssignmentName)\n}", "func (c *Client) ListAssignedIDs() (*[]aadpodid.AzureAssignedIdentity, error) {\n\tbegin := time.Now()\n\n\tvar resList []aadpodid.AzureAssignedIdentity\n\n\tlist := c.AssignedIDInformer.GetStore().List()\n\tfor _, assignedID := range list {\n\t\to, ok := assignedID.(*aadpodv1.AzureAssignedIdentity)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"failed to cast %T to %s\", assignedID, aadpodv1.AzureAssignedIDResource)\n\t\t}\n\t\t// Note: List items returned from cache have empty Kind and API version..\n\t\t// Work around this issue since we need that for event recording to work.\n\t\to.SetGroupVersionKind(schema.GroupVersionKind{\n\t\t\tGroup: aadpodv1.SchemeGroupVersion.Group,\n\t\t\tVersion: aadpodv1.SchemeGroupVersion.Version,\n\t\t\tKind: reflect.TypeOf(*o).String()})\n\t\tout := aadpodv1.ConvertV1AssignedIdentityToInternalAssignedIdentity(*o)\n\t\tresList = append(resList, out)\n\t\tklog.V(6).Infof(\"appending AzureAssignedIdentity: %s/%s to list.\", o.Namespace, o.Name)\n\t}\n\n\tstats.Aggregate(stats.AzureAssignedIdentityList, time.Since(begin))\n\treturn &resList, nil\n}", "func GetAssignmentInformation(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\tc := AssignmentInformation{\"FOO\", \"DEV1\", \"ASSIGNMENT FOR FOOBAR\", \"FOOUSR\", \"FB000001\", \"1234\", \"REL1\", \"BAR\", \"USRTAG\"}\n\toutgoingJSON, err := json.Marshal(c)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tres.WriteHeader(http.StatusCreated)\n\tfmt.Fprint(res, string(outgoingJSON))\n}", "func (o *PublicGetUserEntitlementByItemIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPublicGetUserEntitlementByItemIDOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewPublicGetUserEntitlementByItemIDNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested GET /platform/public/namespaces/{namespace}/users/{userId}/entitlements/byItemId returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (o *WatchlistScreeningIndividualUpdateResponse) GetAssignee() string {\n\tif o == nil || o.Assignee.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.Assignee.Get()\n}", "func (client CertificateOrdersClient) ResendCertificateEmailResponder(resp *http.Response) (result SetObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client RecoveryPointsClient) GetResponder(resp *http.Response) (result RecoveryPoint, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (o *GetUserTenantAssignmentsUsingGETReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetUserTenantAssignmentsUsingGETOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetUserTenantAssignmentsUsingGETBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewGetUserTenantAssignmentsUsingGETNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (client MultipleResponsesClient) Get202None204NoneDefaultNone400NoneResponder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func SlackAssignmentHandler(w http.ResponseWriter, r *http.Request) {\n\t// Get JSON from client and parse to byte array\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(r.Host, r.URL, string(body))\n\t// Create http req to slack webhook\n\tvar msg models.SlackMessage\n\tservices.AssignmentPost(body, msg)\n}", "func (client MultipleResponsesClient) Get202None204NoneDefaultNone204NoneResponder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func (client DataFlowClient) GetDataFlowResponder(resp *http.Response) (result DataFlowResource, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client *AvailabilityGroupListenersClient) getHandleResponse(resp *http.Response) (AvailabilityGroupListenersClientGetResponse, error) {\n\tresult := AvailabilityGroupListenersClientGetResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.AvailabilityGroupListener); err != nil {\n\t\treturn AvailabilityGroupListenersClientGetResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client Client) GetResponder(resp *http.Response) (result GetResult, err error) {\n\tif resp != nil && int(resp.ContentLength) > 0 {\n\t\tresult.Contents = make([]byte, resp.ContentLength)\n\t}\n\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusPartialContent),\n\t\tautorest.ByUnmarshallingBytes(&result.Contents),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\n\treturn\n}", "func (client Client) GetResponder(resp *http.Response) (result ResourceType, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (p *RoleAssignmentsClientListForScopePager) PageResponse() RoleAssignmentsClientListForScopeResponse {\n\treturn p.current\n}", "func LookupScopeAssignment(ctx *pulumi.Context, args *LookupScopeAssignmentArgs, opts ...pulumi.InvokeOption) (*LookupScopeAssignmentResult, error) {\n\tvar rv LookupScopeAssignmentResult\n\terr := ctx.Invoke(\"azure-native:managednetwork:getScopeAssignment\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func (client MultipleResponsesClient) Get200ModelA202ValidResponder(resp *http.Response) (result A, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n}", "func (o *RetrieveEmailsByCIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewRetrieveEmailsByCIDOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewRetrieveEmailsByCIDBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewRetrieveEmailsByCIDForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 429:\n\t\tresult := NewRetrieveEmailsByCIDTooManyRequests()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"[GET /users/queries/emails-by-cid/v1] RetrieveEmailsByCID\", response, response.Code())\n\t}\n}", "func (client ExternalBillingAccountClient) GetResponder(resp *http.Response) (result ExternalBillingAccountDefinition, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client *AssociationsClient) getHandleResponse(resp *http.Response) (AssociationsClientGetResponse, error) {\n\tresult := AssociationsClientGetResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.Association); err != nil {\n\t\treturn AssociationsClientGetResponse{}, err\n\t}\n\treturn result, nil\n}", "func (o *EmployeesByIDGetReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewEmployeesByIDGetOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 401:\n\t\tresult := NewEmployeesByIDGetUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (client *SQLResourcesClient) listSQLRoleAssignmentsHandleResponse(resp *http.Response) (SQLResourcesClientListSQLRoleAssignmentsResponse, error) {\n\tresult := SQLResourcesClientListSQLRoleAssignmentsResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.SQLRoleAssignmentListResult); err != nil {\n\t\treturn SQLResourcesClientListSQLRoleAssignmentsResponse{}, err\n\t}\n\treturn result, nil\n}", "func GetEmployee(w http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tid := p.ByName(\"id\")\n\n\te, err := repo.GetEmployee(id)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tej, _ := json.Marshal(e)\n\n\tw = setHeaders(w)\n\tfmt.Fprintf(w, \"%s\\n\", ej)\n}", "func (client PrimitiveClient) GetIntResponder(resp *http.Response) (result IntWrapper, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n}", "func (client MultipleResponsesClient) Get200ModelA400NoneResponder(resp *http.Response) (result A, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n}", "func (client IotHubResourceClient) GetResponder(resp *http.Response) (result IotHubDescription, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (me *XsdGoPkgHasElem_GetAssignmentsForHITResponse) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_GetAssignmentsForHITResponse; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.GetAssignmentsForHITResponse.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (client MultipleResponsesClient) Get200ModelA400ValidResponder(resp *http.Response) (result A, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n}", "func (client MeshNetworkClient) GetResponder(resp *http.Response) (result NetworkResourceDescription, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (r *OfficeClientConfigurationAssignmentsCollectionRequest) Get(ctx context.Context) ([]OfficeClientConfigurationAssignment, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil)\n}", "func (p *ClientCreateOrUpdateByIDPoller) FinalResponse(ctx context.Context) (ClientCreateOrUpdateByIDResponse, error) {\n\trespType := ClientCreateOrUpdateByIDResponse{}\n\tresp, err := p.pt.FinalResponse(ctx, &respType.GenericResource)\n\tif err != nil {\n\t\treturn ClientCreateOrUpdateByIDResponse{}, err\n\t}\n\trespType.RawResponse = resp\n\treturn respType, nil\n}", "func (client LinkedServiceClient) GetLinkedServiceResponder(resp *http.Response) (result LinkedServiceResource, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNotModified),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client CertificateClient) GetResponder(resp *http.Response) (result Certificate, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client GroupClient) GetExternalDataSourceResponder(resp *http.Response) (result USQLExternalDataSource, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client ManagementClient) GetAppsResponder(resp *http.Response) (result ApplicationCollection, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client CloudEndpointsClient) GetResponder(resp *http.Response) (result CloudEndpoint, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (me *XsdGoPkgHasElem_ApproveAssignmentResponse) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_ApproveAssignmentResponse; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.ApproveAssignmentResponse.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (me *TxsdApproveAssignmentResponse) Walk() (err error) {\n\tif fn := WalkHandlers.TxsdApproveAssignmentResponse; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_ApproveAssignmentResultsequenceTxsdApproveAssignmentResponseApproveAssignmentResponseschema_ApproveAssignmentResult_TApproveAssignmentResult_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_OperationRequest.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (o *GetIdentityIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (me *XsdGoPkgHasElems_ApproveAssignmentResponse) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_ApproveAssignmentResponse; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfor _, x := range me.ApproveAssignmentResponses {\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (client *RoleAssignmentsClient) createHandleResponse(resp *http.Response) (RoleAssignmentsCreateResponse, error) {\n\tresult := RoleAssignmentsCreateResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsCreateResponse{}, err\n\t}\n\treturn result, nil\n}", "func (handler Handler) GetArticleHandler(w http.ResponseWriter, r *http.Request) {\n\n\tid := mux.Vars(r)[\"id\"]\n\n\tresp := usecases.ResponseCollector{}\n\n\tuc := usecases.GetArticle{\n\t\tArticleRepository: handler.ArticleRepository,\n\t\tArticleID: id,\n\t\tResponse: &resp,\n\t}\n\n\tuc.Execute()\n\n\tlog.Printf(\"handler GetArticleHandler var id: %s\", id)\n\tlog.Printf(\"response collector received %s\", resp.Response)\n\n\tif resp.Error != nil {\n\t\tlog.Printf(\"response error %s (%s)\", resp.Error.Name, resp.Error.Description)\n\t\thandler.NotFoundHandler(w, r)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, handler.Presenter.GetArticle(resp.Response.Body[\"article\"].(entities.Article)))\n}", "func (client ProductsClient) GetResponder(resp *http.Response) (result Product, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client PortPluginClient) GetResponder(resp *http.Response) (result PortPluginDetailResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusUnauthorized, http.StatusInternalServerError),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client *CustomAssessmentAutomationsClient) getHandleResponse(resp *http.Response) (CustomAssessmentAutomationsGetResponse, error) {\n\tresult := CustomAssessmentAutomationsGetResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.CustomAssessmentAutomation); err != nil {\n\t\treturn CustomAssessmentAutomationsGetResponse{}, runtime.NewResponseError(err, resp)\n\t}\n\treturn result, nil\n}" ]
[ "0.6111585", "0.5768321", "0.5680579", "0.5334337", "0.5326905", "0.51573044", "0.50472397", "0.5023708", "0.49702942", "0.4953836", "0.4941508", "0.49411404", "0.48906282", "0.48504305", "0.48367667", "0.4814991", "0.47822592", "0.47806406", "0.4777876", "0.47725537", "0.47619912", "0.47618032", "0.4737527", "0.4735598", "0.4715129", "0.4705854", "0.46845978", "0.4682036", "0.4681907", "0.46792844", "0.46487793", "0.46323383", "0.46296147", "0.46294594", "0.46259195", "0.46245196", "0.46182823", "0.46115747", "0.45990822", "0.45866275", "0.45753983", "0.45727402", "0.4556665", "0.45547596", "0.4554563", "0.45478007", "0.45351785", "0.45289347", "0.45252243", "0.45221448", "0.4516854", "0.45158595", "0.45154768", "0.45016736", "0.44975367", "0.44960403", "0.4489791", "0.44854042", "0.44779775", "0.44725388", "0.44724306", "0.44723484", "0.44680908", "0.44662312", "0.44655848", "0.44645548", "0.44633925", "0.44624016", "0.44567475", "0.44508484", "0.4445415", "0.44411153", "0.44344732", "0.44326478", "0.44308257", "0.44271985", "0.4423546", "0.44169945", "0.44164345", "0.44111246", "0.44108754", "0.44073692", "0.44065773", "0.4399719", "0.4393243", "0.4389778", "0.4388418", "0.43854117", "0.43823633", "0.43804556", "0.4378887", "0.4374633", "0.43733722", "0.4373259", "0.43708405", "0.43655568", "0.43584824", "0.43583447", "0.4352277", "0.43516433" ]
0.74875396
0
GetUserLUISAccounts gets the LUIS azure accounts for the user using his ARM token.
func (client AzureAccountsClient) GetUserLUISAccounts(ctx context.Context) (result ListAzureAccountInfoObject, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/AzureAccountsClient.GetUserLUISAccounts") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetUserLUISAccountsPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "GetUserLUISAccounts", nil, "Failure preparing request") return } resp, err := client.GetUserLUISAccountsSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "GetUserLUISAccounts", resp, "Failure sending request") return } result, err = client.GetUserLUISAccountsResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "GetUserLUISAccounts", resp, "Failure responding to request") } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AzureAccountsClient) GetUserLUISAccountsSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AzureAccountsClient) GetUserLUISAccountsResponder(resp *http.Response) (result ListAzureAccountInfoObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client AzureAccountsClient) GetUserLUISAccountsPreparer(ctx context.Context) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/azureaccounts\"))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *WindowsKioskProfile) GetUserAccountsConfiguration()([]WindowsKioskUserable) {\n val, err := m.GetBackingStore().Get(\"userAccountsConfiguration\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]WindowsKioskUserable)\n }\n return nil\n}", "func (c *IloClient) GetUserAccountsDell() ([]Accounts, error) {\n\n\turl := c.Hostname + \"/redfish/v1/Managers/iDRAC.Embedded.1/Accounts\"\n\n\tresp, _, _, err := queryData(c, \"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar x MemberCountDell\n\tvar users []Accounts\n\n\tjson.Unmarshal(resp, &x)\n\n\tfor i := range x.Members {\n\t\t_url := c.Hostname + x.Members[i].OdataId\n\t\tresp, _, _, err := queryData(c, \"GET\", _url, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar y AccountsInfoDell\n\n\t\tjson.Unmarshal(resp, &y)\n\n\t\tuser := Accounts{\n\t\t\tName: y.Name,\n\t\t\tEnabled: y.Enabled,\n\t\t\tLocked: y.Locked,\n\t\t\tRoleId: y.RoleID,\n\t\t\tUsername: y.UserName,\n\t\t}\n\t\tusers = append(users, user)\n\n\t}\n\n\treturn users, nil\n\n}", "func (h *HUOBI) GetAccounts(ctx context.Context) ([]Account, error) {\n\tresult := struct {\n\t\tAccounts []Account `json:\"data\"`\n\t}{}\n\terr := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiAccounts, url.Values{}, nil, &result, false)\n\treturn result.Accounts, err\n}", "func (h *HUOBIHADAX) GetAccounts() ([]Account, error) {\n\ttype response struct {\n\t\tResponse\n\t\tAccountData []Account `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodGet, huobihadaxAccounts, url.Values{}, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.AccountData, err\n}", "func (auth Authenticate) GetAccounts(session *types.Session, roles []int) (*[]types.Account, error) {\n\taccount, err := auth.CheckAccountSession(session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//Get Account Roles\n\taccount = account.GetAccountPermissions()\n\n\t//Only Accounts with REGIONAL_SUPERVISOR privliges can make this request\n\tif !utils.Contains(\"ADMIN\", account.Roles) {\n\t\treturn nil, errors.New(\"Invalid Privilges: \" + account.Name)\n\t}\n\n\taccounts, err := manager.AccountManager{}.GetAccounts(roles, auth.DB)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn accounts, nil\n}", "func getAccounts() ([]string, error) {\n\tout, err := exec.Command(\"ykman\", \"oath\", \"accounts\", \"list\").Output()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t//fmt.Printf(\"Cmd out:\\n%s\\n\", out)\n\treturn strings.Split(strings.ReplaceAll(string(out), \"\\r\\n\", \"\\n\"), \"\\n\"), nil\n}", "func (r *NucypherAccountRepository) GetAccounts(createdBy string) ([]*model.NucypherAccount, error) {\n\tvar accounts []*model.NucypherAccount\n\n\tif err := r.store.db.Select(&accounts,\n\t\t\"SELECT account_id, name, organization_id, address, signing_key, encrypting_key, balance, tokens, is_active, is_private, created_by, created_at FROM nucypher_accounts WHERE created_by=$1\",\n\t\tcreatedBy,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn accounts, nil\n}", "func (client *ClientImpl) GetAccounts(ctx context.Context, args GetAccountsArgs) (*[]Account, error) {\n\tqueryParams := url.Values{}\n\tif args.OwnerId != nil {\n\t\tqueryParams.Add(\"ownerId\", (*args.OwnerId).String())\n\t}\n\tif args.MemberId != nil {\n\t\tqueryParams.Add(\"memberId\", (*args.MemberId).String())\n\t}\n\tif args.Properties != nil {\n\t\tqueryParams.Add(\"properties\", *args.Properties)\n\t}\n\tlocationId, _ := uuid.Parse(\"229a6a53-b428-4ffb-a835-e8f36b5b4b1e\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"7.1-preview.1\", nil, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []Account\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (client *Client) GetUserTokens(ctx context.Context, name string) ([]graylog.UserToken, *ErrorInfo, error) {\n\ttokens := map[string][]graylog.UserToken{}\n\tei, err := client.callGet(ctx, client.Endpoints().UserTokens(name), nil, &tokens)\n\tif a, ok := tokens[\"tokens\"]; ok {\n\t\treturn a, ei, err\n\t}\n\treturn nil, ei, err\n}", "func (w *ServerInterfaceWrapper) GetAccounts(ctx echo.Context) error {\n\tvar err error\n\n\tctx.Set(ApiKeyAuthScopes, []string{\"\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetAccounts(ctx)\n\treturn err\n}", "func (a *Api) GetAccounts(ctx echo.Context) error {\n\t// var result []Account\n\tvar accounts []Account\n\n\tdbResult := a.DB.Find(&accounts)\n\tif dbResult.Error != nil {\n\t\treturn sendApiError(ctx, http.StatusInternalServerError, \"DB error\")\n\t}\n\n\treturn ctx.JSONPretty(http.StatusOK, accounts, \" \")\n}", "func (pool *Pool) GetUserList() []string {\n\tpool.mu.Lock()\n\tusernames := make([]string, 0)\n\n\tfor client := range pool.Clients {\n\t\tusernames = append(usernames, client.Account.Username)\n\t}\n\n\tpool.mu.Unlock()\n\treturn usernames\n}", "func (p *UserStoreClient) GetUserUrls(ctx context.Context, authenticationToken string) (r *UserUrls, err error) {\n var _args17 UserStoreGetUserUrlsArgs\n _args17.AuthenticationToken = authenticationToken\n var _result18 UserStoreGetUserUrlsResult\n if err = p.Client_().Call(ctx, \"getUserUrls\", &_args17, &_result18); err != nil {\n return\n }\n switch {\n case _result18.UserException!= nil:\n return r, _result18.UserException\n case _result18.SystemException!= nil:\n return r, _result18.SystemException\n }\n\n return _result18.GetSuccess(), nil\n}", "func (a AuthService) GetUserRoles() []string {\n\treturn a.userRoles\n}", "func (mw loggingMiddleware) GetAccounts(ctx context.Context) (accounts []Account, err error) {\n\tdefer func(begin time.Time) {\n\t\tmw.logger.Log(\"method\", \"GetAddresses\", \"took\", time.Since(begin), \"err\", err)\n\t}(time.Now())\n\treturn mw.next.GetAccounts(ctx)\n}", "func (hc *Client) GetAccounts() ([]Account, error) {\n\tvar (\n\t\tresult AccountResponse\n\t)\n\tendpoint := fmt.Sprintf(\"%s/v1/account/accounts\", huobiEndpoint)\n\tres, err := hc.sendRequest(\n\t\thttp.MethodGet,\n\t\tendpoint,\n\t\tmap[string]string{},\n\t\ttrue,\n\t)\n\tif err != nil {\n\t\treturn result.Data, err\n\t}\n\terr = json.Unmarshal(res, &result)\n\tif result.Status != StatusOK.String() {\n\t\treturn result.Data, fmt.Errorf(\"received unexpect status: err=%s code=%s msg=%s\",\n\t\t\tresult.Status,\n\t\t\tresult.ErrorCode,\n\t\t\tresult.ErrorMessage)\n\t}\n\treturn result.Data, err\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\tdb, erro := database.Connect()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tdefer db.Close()\n\trepository := repositories.NewAccountRepository(db)\n\taccounts, erro := repository.FindAll()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, accounts)\n}", "func FindAccounts(tx *storage.Connection, userID uuid.UUID, pageParams *Pagination, sortParams *SortParams) ([]*Account, error) {\n\taccounts := []*Account{}\n\tvar err error\n\n\tpop.Debug = true\n\tq := tx.Q()\n\tif userID.String() != \"00000000-0000-0000-0000-000000000000\" {\n\t\t// UserID is not nil, so we have to query for the relations from\n\t\t// account_user\n\t\tq.RawQuery(`\n\t\tSELECT\n\t\t\taccounts.id as id,\n\t\t\taccounts.name as name,\n\t\t\taccounts.billing_name as billing_name,\n\t\t\taccounts.billing_email as billing_email,\n\t\t\taccounts.billing_details as billing_details,\n\t\t\taccounts.billing_period as billing_period,\n\t\t\taccounts.payment_method_id as payment_method_id,\n\t\t\taccounts.raw_owner_ids as raw_owner_ids,\n\t\t\taccounts.raw_account_meta_data as raw_account_meta_data,\n\t\t\taccounts.created_at as created_at,\n\t\t\taccounts.updated_at as updated_at\n\t\tFROM\n\t\t\taccounts_users as accounts_users\n\t\t\tJOIN accounts ON accounts.id = accounts_users.account_id\n\t\tWHERE\n\t\t\taccounts_users.user_id = ?`, userID)\n\n\t\terr = q.Eager(\"Roles\").All(&accounts)\n\t\treturn accounts, err\n\t}\n\n\tif sortParams != nil && len(sortParams.Fields) > 0 {\n\t\tfor _, field := range sortParams.Fields {\n\t\t\tq = q.Order(field.Name + \" \" + string(field.Dir))\n\t\t}\n\t}\n\n\tif pageParams != nil {\n\t\terr = q.Paginate(int(pageParams.Page), int(pageParams.PerPage)).Eager(\"Roles\").All(&accounts)\n\t\tpageParams.Count = uint64(q.Paginator.TotalEntriesSize)\n\t} else {\n\t\terr = q.Eager(\"Roles\").All(&accounts)\n\t}\n\treturn accounts, err\n}", "func (p *bitsharesAPI) GetAccounts(accounts ...objects.GrapheneObject) ([]objects.Account, error) {\n\tvar result []objects.Account\n\terr := p.call(p.databaseAPIID, \"get_accounts\", &result, accounts)\n\treturn result, err\n}", "func (p *provider) getUserTeams(token string) (sets.String, error) {\n\tuserTeams := sets.NewString()\n\terr := p.page(p.githubUserTeamURL, token,\n\t\tfunc() interface{} {\n\t\t\treturn &[]githubTeam{}\n\t\t},\n\t\tfunc(obj interface{}) error {\n\t\t\tfor _, team := range *(obj.(*[]githubTeam)) {\n\t\t\t\tif len(team.Slug) > 0 && len(team.Organization.Login) > 0 {\n\t\t\t\t\tuserTeams.Insert(strings.ToLower(team.Organization.Login + \"/\" + team.Slug))\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t)\n\treturn userTeams, err\n}", "func (db *InMemoryDB) GetAccounts(userID string) []model.Account {\n\taccountMap := db.getAccountMap(userID)\n\n\tresult := make([]model.Account, 0)\n\tfor _, value := range accountMap {\n\t\tresult = append(result, value)\n\t}\n\tsort.Slice(result, func(i, j int) bool {\n\t\treturn result[i].Payer < result[j].Payer\n\t})\n\treturn result\n}", "func (p *Policy) getBlockedAccounts(ic *interop.Context, _ []stackitem.Item) stackitem.Item {\n\tba, err := p.GetBlockedAccountsInternal(ic.DAO)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ba.ToStackItem()\n}", "func (e *Ethereum) Accounts() ([]string, error) {\n\tvar accounts []string\n\terr := e.rpcClient.CallContext(e.ctx, &accounts, \"eth_accounts\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"fail to call rpc.CallContext(eth_accounts)\")\n\t}\n\n\treturn accounts, nil\n}", "func (d *DB) GetTeamsByUser(useruuid string) ([]string, error) {\n\tres := []string{}\n\trows, err := d.db.Query(\"SELECT teamuuid FROM teammember WHERE useruuid = $1\", useruuid)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar teamuuid string\n\t\terr = rows.Scan(&teamuuid)\n\t\tif err != nil {\n\t\t\treturn res, err\n\t\t}\n\t\tres = append(res, teamuuid)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn res, err\n\t}\n\treturn res, nil\n}", "func (a *Client) ListAzureAccounts(params *ListAzureAccountsParams, opts ...ClientOption) (*ListAzureAccountsOK, *ListAzureAccountsMultiStatus, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListAzureAccountsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"ListAzureAccounts\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/kubernetes-protection/entities/accounts/azure/v1\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListAzureAccountsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tswitch value := result.(type) {\n\tcase *ListAzureAccountsOK:\n\t\treturn value, nil, nil\n\tcase *ListAzureAccountsMultiStatus:\n\t\treturn nil, value, nil\n\t}\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 kubernetes_protection: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (p *UserStoreClient) ListBusinessUsers(ctx context.Context, authenticationToken string) (r []*UserProfile, err error) {\n var _args25 UserStoreListBusinessUsersArgs\n _args25.AuthenticationToken = authenticationToken\n var _result26 UserStoreListBusinessUsersResult\n if err = p.Client_().Call(ctx, \"listBusinessUsers\", &_args25, &_result26); err != nil {\n return\n }\n switch {\n case _result26.UserException!= nil:\n return r, _result26.UserException\n case _result26.SystemException!= nil:\n return r, _result26.SystemException\n }\n\n return _result26.GetSuccess(), nil\n}", "func (c *GethClient) Accounts(ctx context.Context) ([]string, error) {\n\tvar result []string\n\terr := c.rpcCli.CallContext(ctx, &result, \"personal_listAccounts\")\n\treturn result, err\n}", "func (d *Dynamicd) GetMyAccounts() (*[]Account, error) {\n\tvar accountsGeneric map[string]interface{}\n\tvar accounts = []Account{}\n\treq, _ := NewRequest(\"dynamic-cli mybdapaccounts\")\n\trawResp := []byte(<-d.ExecCmdRequest(req))\n\terrUnmarshal := json.Unmarshal(rawResp, &accountsGeneric)\n\tif errUnmarshal != nil {\n\t\treturn &accounts, errUnmarshal\n\t}\n\tfor _, v := range accountsGeneric {\n\t\tb, err := json.Marshal(v)\n\t\tif err == nil {\n\t\t\tvar account Account\n\t\t\terrUnmarshal = json.Unmarshal(b, &account)\n\t\t\tif errUnmarshal != nil {\n\t\t\t\tutil.Error.Println(\"Inner error\", errUnmarshal)\n\t\t\t\treturn nil, errUnmarshal\n\t\t\t}\n\t\t\taccounts = append(accounts, account)\n\t\t}\n\t}\n\treturn &accounts, nil\n}", "func GetOnlineAccountsRestAPIPath() string {\n\treturn \"/api/rest/getOnlineAccounts\"\n}", "func Accounts(client *ticketmatic.Client) ([]*ticketmatic.AccountInfo, error) {\n\tr := client.NewRequest(\"GET\", \"/_/tools/accounts\", \"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 (a *Client) GetAzureStorageAccountsList(params *GetAzureStorageAccountsListParams, authInfo runtime.ClientAuthInfoWriter) (*GetAzureStorageAccountsListOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAzureStorageAccountsListParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getAzureStorageAccountsList\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/accounts/{id}/storageAccounts\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetAzureStorageAccountsListReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetAzureStorageAccountsListOK)\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 getAzureStorageAccountsList: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (client *Client) GetAzureCloudAccounts() (cloudAccounts []*CloudAccount, err error) {\n\tvar body []byte\n\tif body, err = client.executeRequest(http.MethodGet, getAzureCloudAccounts, nil); err == nil {\n\t\tcloudAccounts = make([]*CloudAccount, 0)\n\t\terr = json.Unmarshal(body, &cloudAccounts)\n\t}\n\n\treturn cloudAccounts, err\n}", "func GetAccounts(db gorm.DB) ([]AccountView, error) {\n\n\tvar rows []AccountView\n\tdb.Table(ACCOUNT_VIEW).Select(ACCOUNT_VIEW_COLS).Scan(&rows)\n\treturn rows, nil\n\n}", "func getUsers(githubAccessToken string, githubOrganization string, githubTeams string) []githubUser {\n\n\tvar users = make([]githubUser, 0)\n\n\tctx := context.Background()\n\tgithubClient := getGithubClient(ctx, githubAccessToken)\n\tteamsIds := getTeamsIds(ctx, githubClient, githubOrganization, githubTeams)\n\tfor _, teamId := range teamsIds {\n\t\tusers = append(users, getTeamUsers(ctx, githubClient, teamId, users)...)\n\t}\n\treturn users\n}", "func (t *SimpleChaincode) getUserAccount(stub shim.ChaincodeStubInterface, userId string)([]byte, error){\n\n\tfmt.Println(\"Start getUserAccount\")\n\tfmt.Println(\"Looking for user with ID \" + userId);\n\n\t//get the User index\n\tfdAsBytes, err := stub.GetState(userId)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get user account from blockchain\")\n\t}\n\n\treturn fdAsBytes, nil\n\n}", "func (api *API) LookupAccounts(ctx context.Context, lowerBoundName string, limit uint16) ([]string, error) {\n\tvar resp []string\n\terr := api.call(ctx, \"lookup_accounts\", []interface{}{lowerBoundName, limit}, &resp)\n\treturn resp, err\n}", "func (s *Service) GetAccounts() ([]entity.Account, error) {\n\treturn s.repo.GetAccounts()\n}", "func (a *api) h_GET_users_userId_userRoles(c *gin.Context) {\n\tlogin := c.Param(\"userId\")\n\taCtx := a.getAuthContext(c)\n\tif a.errorResponse(c, aCtx.AuthZUser(login)) {\n\t\treturn\n\t}\n\n\turs, err := a.Dc.GetUserRoles(login, 0)\n\tif a.errorResponse(c, err) {\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, a.muserRoles2userRoles(urs))\n}", "func (i *ImportedContacts) GetUserIDs() (value []int64) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.UserIDs\n}", "func (o *StorageNetAppCloudTargetAllOf) GetAzureAccount() string {\n\tif o == nil || o.AzureAccount == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.AzureAccount\n}", "func GetUsers(ctx context.Context, nk runtime.NakamaModule, usersID ...string) ([]User, error) {\n\tvar users []*api.User\n\tvar err error\n\t// I don't know if it's possible to have err == nil and len == 0\n\tif users, err = nk.UsersGetId(ctx, usersID); err != nil || len(users) == 0 {\n\t\treturn nil, errGetAccount\n\t}\n\tvar objectIds []*runtime.StorageRead\n\tfor _, user := range users {\n\t\tobjectIds = append(objectIds, &runtime.StorageRead{\n\t\t\tCollection: \"user\",\n\t\t\tKey: user.Id,\n\t\t\tUserID: user.Id,\n\t\t})\n\t}\n\n\t// We need to read our custom stored users\n\tobjects, err := nk.StorageRead(ctx, objectIds)\n\tif err != nil {\n\t\treturn nil, errGetAccount\n\t}\n\n\tvar usersStorage []User\n\tfor i, o := range objects {\n\t\tvar user User\n\t\tif err = jsonpb.UnmarshalString(o.Value, &user); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tuser.User = *users[i]\n\t\tusersStorage = append(usersStorage, user)\n\t}\n\n\treturn usersStorage, nil\n}", "func (a *FastlyIntegrationApi) ListFastlyAccounts(ctx _context.Context) (FastlyAccountsResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarReturnValue FastlyAccountsResponse\n\t)\n\n\tlocalBasePath, err := a.Client.Cfg.ServerURLWithContext(ctx, \"v2.FastlyIntegrationApi.ListFastlyAccounts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, datadog.GenericOpenAPIError{ErrorMessage: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v2/integrations/fastly/accounts\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tlocalVarHeaderParams[\"Accept\"] = \"application/json\"\n\n\tdatadog.SetAuthKeys(\n\t\tctx,\n\t\t&localVarHeaderParams,\n\t\t[2]string{\"apiKeyAuth\", \"DD-API-KEY\"},\n\t\t[2]string{\"appKeyAuth\", \"DD-APPLICATION-KEY\"},\n\t)\n\treq, err := a.Client.PrepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, nil)\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 := datadog.ReadBody(localVarHTTPResponse)\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := datadog.GenericOpenAPIError{\n\t\t\tErrorBody: localVarBody,\n\t\t\tErrorMessage: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 || localVarHTTPResponse.StatusCode == 403 || localVarHTTPResponse.StatusCode == 404 || localVarHTTPResponse.StatusCode == 429 {\n\t\t\tvar v APIErrorResponse\n\t\t\terr = a.Client.Decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.ErrorModel = 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 := datadog.GenericOpenAPIError{\n\t\t\tErrorBody: localVarBody,\n\t\t\tErrorMessage: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func getUFADetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tlogger.Info(\"getUFADetails called with UFA number: \" + args[0])\n\n\tvar outputRecord map[string]interface{}\n\tufanumber := args[0] //UFA ufanum\n\t//who :=args[1] //Role\n\trecBytes, _ := stub.GetState(ufanumber)\n\tjson.Unmarshal(recBytes, &outputRecord)\n\toutputBytes, _ := json.Marshal(outputRecord)\n\tlogger.Info(\"Returning records from getUFADetails \" + string(outputBytes))\n\treturn outputBytes, nil\n}", "func (a *AmoCrm) GetAccount(with []string) (*Account, error) {\n\tvar account *Account\n\treturn account, a.getItem([]string{accountEntity}, nil, &entitiesQuery{With: with}, &account)\n}", "func (_Storage *StorageCallerSession) Accounts() (*big.Int, error) {\n\treturn _Storage.Contract.Accounts(&_Storage.CallOpts)\n}", "func (api *API) GetAccounts(ctx context.Context, names ...string) ([]*Account, error) {\n\tvar resp []*Account\n\terr := api.call(ctx, \"get_accounts\", []interface{}{names}, &resp)\n\treturn resp, err\n}", "func (r *Roles) GetRoles(c *gin.Context) {\n\n\t//check is the user is authenticated first\n\tmetadata, err := r.tk.ExtractTokenMetadata(c.Request)\n\tif err != nil {\n\t\tc.JSON(http.StatusUnauthorized, \"unauthorized\")\n\t\treturn\n\t}\n\t//lookup the metadata in redis:\n\tuserID, err := r.rd.FetchAuth(metadata.TokenUuid)\n\tif err != nil {\n\t\tc.JSON(http.StatusUnauthorized, \"unauthorized\")\n\t\treturn\n\t}\n\n\tfmt.Printf(\"nosamb :%+v\\n\", userID)\n\n\troles := entity.Roles{} //customize user\n\t//us, err = application.UserApp.GetUsers()\n\troles, err = r.rl.GetRoles()\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, roles)\n}", "func (s *AccountService) GetAccounts() ([]Account, error) {\n\turl := \"manage\"\n\treq, err := s.client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn parseAccounts(resp)\n}", "func (controller *AccountController) GetAccounts(ctx *gin.Context) {\n\tinfo, err := authStuff.GetLoginInfoFromCtx(ctx)\n\tif err != nil {\n\t\tresponse, _ := restapi.NewErrorResponse(err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\taccs, err := controller.service.GetAccounts(info.Name)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"user\": info.Name}).WithError(err).Error(\"Account Error GetAll\")\n\n\t\tresponse, _ := restapi.NewErrorResponse(\"Could not get accounts because: \" + err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\tresponse, _ := restapi.NewOkResponse(accs).Marshal()\n\tfmt.Fprint(ctx.Writer, string(response))\n\tctx.Next()\n\n}", "func userDNs() []string {\n\tvar out []string\n\tvar verbose bool\n\tif utils.VERBOSE > 0 {\n\t\tverbose = true\n\t}\n\tcricUrl := fmt.Sprintf(\"%s?json&preset=roles\", services.CricUrl(\"\"))\n\tcricRecords, err := cmsauth.GetCricData(cricUrl, verbose)\n\tif err != nil {\n\t\tlog.Println(\"ERROR: unable to obtain cric records, error\", err)\n\t\treturn out\n\t}\n\t// convert cric records to list of DNs\n\tfor _, rec := range cricRecords {\n\t\tfor _, dn := range rec.DNs {\n\t\t\tout = append(out, dn)\n\t\t}\n\t}\n\tlog.Printf(\"get %d cric DNs\\n\", len(out))\n\treturn out\n}", "func (a *MemberAwaitility) GetUserAccount(name string) *toolchainv1alpha1.UserAccount {\n\tua := &toolchainv1alpha1.UserAccount{}\n\terr := a.Client.Get(context.TODO(), types.NamespacedName{Namespace: a.Ns, Name: name}, ua)\n\trequire.NoError(a.T, err)\n\treturn ua\n}", "func (e *SyncedEnforcer) GetRolesForUser(name string) ([]string, error) {\n\te.m.RLock()\n\tdefer e.m.RUnlock()\n\treturn e.Enforcer.GetRolesForUser(name)\n}", "func (account *Account) GetRoles() []int {\n\troles := make([]int, 0)\n\tfor k := range account.accountRoles {\n\t\troles = append(roles, k)\n\t}\n\treturn roles\n}", "func (e *Enforcer) GetUsersForRole(name string) ([]string, error) {\n\tres, err := e.model[\"g\"][\"g\"].RM.GetUsers(name)\n\treturn res, err\n}", "func (enterpriseManagement *EnterpriseManagementV1) ListAccountsWithContext(ctx context.Context, listAccountsOptions *ListAccountsOptions) (result *ListAccountsResponse, response *core.DetailedResponse, err error) {\n\terr = core.ValidateStruct(listAccountsOptions, \"listAccountsOptions\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbuilder := core.NewRequestBuilder(core.GET)\n\tbuilder = builder.WithContext(ctx)\n\tbuilder.EnableGzipCompression = enterpriseManagement.GetEnableGzipCompression()\n\t_, err = builder.ResolveRequestURL(enterpriseManagement.Service.Options.URL, `/accounts`, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor headerName, headerValue := range listAccountsOptions.Headers {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\n\tsdkHeaders := common.GetSdkHeaders(\"enterprise_management\", \"V1\", \"ListAccounts\")\n\tfor headerName, headerValue := range sdkHeaders {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\tbuilder.AddHeader(\"Accept\", \"application/json\")\n\n\tif listAccountsOptions.EnterpriseID != nil {\n\t\tbuilder.AddQuery(\"enterprise_id\", fmt.Sprint(*listAccountsOptions.EnterpriseID))\n\t}\n\tif listAccountsOptions.AccountGroupID != nil {\n\t\tbuilder.AddQuery(\"account_group_id\", fmt.Sprint(*listAccountsOptions.AccountGroupID))\n\t}\n\tif listAccountsOptions.NextDocid != nil {\n\t\tbuilder.AddQuery(\"next_docid\", fmt.Sprint(*listAccountsOptions.NextDocid))\n\t}\n\tif listAccountsOptions.Parent != nil {\n\t\tbuilder.AddQuery(\"parent\", fmt.Sprint(*listAccountsOptions.Parent))\n\t}\n\tif listAccountsOptions.Limit != nil {\n\t\tbuilder.AddQuery(\"limit\", fmt.Sprint(*listAccountsOptions.Limit))\n\t}\n\tif listAccountsOptions.IncludeDeleted != nil {\n\t\tbuilder.AddQuery(\"include_deleted\", fmt.Sprint(*listAccountsOptions.IncludeDeleted))\n\t}\n\n\trequest, err := builder.Build()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar rawResponse map[string]json.RawMessage\n\tresponse, err = enterpriseManagement.Service.Request(request, &rawResponse)\n\tif err != nil {\n\t\treturn\n\t}\n\tif rawResponse != nil {\n\t\terr = core.UnmarshalModel(rawResponse, \"\", &result, UnmarshalListAccountsResponse)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponse.Result = result\n\t}\n\n\treturn\n}", "func (r *APIClientRepository) Accounts() (gin.Accounts, error) {\n\tclients := []domain.APIClient{}\n\tif err := r.DB.Select(&clients, \"select * from api_clients\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\taccounts := gin.Accounts{}\n\tfor _, client := range clients {\n\t\taccounts[client.Key] = client.Secret\n\t}\n\n\treturn accounts, nil\n}", "func (db *LocalDb) GetOnlineUserList() []string {\n\n\tdb.mutex.RLock()\n\tdefer db.mutex.RUnlock()\n\n\tuserList := []string{}\n\n\tfor _, u := range db.users {\n\t\tif u.conn != nil {\n\t\t\tuserList = append(userList, u.Name)\n\t\t}\n\t}\n\n\treturn userList\n}", "func getUFADetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tlogger.Info(\"getUFADetails called with UFA number: \" + args[0])\r\n\r\n\tvar outputRecord map[string]string\r\n\tufanumber := args[0] //UFA ufanum\r\n\t//who :=args[1] //Role\r\n\trecBytes, _ := stub.GetState(ufanumber)\r\n\tjson.Unmarshal(recBytes, &outputRecord)\r\n\toutputBytes, _ := json.Marshal(outputRecord)\r\n\tlogger.Info(\"Returning records from getUFADetails \" + string(outputBytes))\r\n\treturn outputBytes, nil\r\n}", "func (m *MegaCorp) getAllAccounts() (accts []*Account) {\n\trg := Me.NewRangeGetter(Ledger, \"account\", \"\", false)\n\tfor rg.HasNext() {\n\t\tvar act Account\n\t\ttx := rg.Next()\n\t\tutil.FromJSON([]byte(tx.Value), &act)\n\t\taccts = append(accts, &act)\n\t}\n\treturn\n}", "func GetAccounts() (accounts []TestAccount, err error) {\n\tam := accountModule.NewAccountManager(TestKeystorePath)\n\tif len(am.Accounts) == 0 {\n\t\terr = fmt.Errorf(\"no ethereum accounts found in the directory [%s]\", TestKeystorePath)\n\t\treturn\n\t}\n\tfor _, a := range am.Accounts {\n\t\tvar keyBin []byte\n\t\tvar key *ecdsa.PrivateKey\n\t\tkeyBin, err = am.GetPrivateKey(a.Address, TestPassword)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tkey, err = crypto.ToECDSA(keyBin)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\taccounts = append(accounts, TestAccount{\n\t\t\tAddress: a.Address,\n\t\t\tPrivateKey: key,\n\t\t})\n\t}\n\treturn\n}", "func (cs *CachingAuthClient) GetUsers() ([]services.User, error) {\n\tcs.try(func() error {\n\t\tusers, err := cs.ap.GetUsers()\n\t\tif err == nil {\n\t\t\tcs.Lock()\n\t\t\tdefer cs.Unlock()\n\t\t\tcs.users = users\n\t\t}\n\t\treturn err\n\t})\n\tcs.RLock()\n\tdefer cs.RUnlock()\n\treturn cs.users, nil\n}", "func (account Account) GetAccountRoles() []AccountRole {\n\troles := make([]AccountRole, 0)\n\tfor _, v := range account.accountRoles {\n\t\troles = append(roles, v)\n\t}\n\treturn roles\n}", "func (x MobileApplicationEntity) GetAccount() accounts.AccountOutline {\n\treturn x.Account\n}", "func GetAllAccountsAPI(w http.ResponseWriter, req *http.Request) {\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"GetAllAccount\", \"Account\", \"_\", \"_\", \"_\", 0}\n\n\tAdminobj := admin.Admin{}\n\tdecoder := json.NewDecoder(req.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&Adminobj)\n\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request \")\n\t\tglobalPkg.WriteLog(logobj, \"failed to decode admin object\", \"failed\")\n\t\treturn\n\t}\n\t// if Adminobj.AdminUsername == globalPkg.AdminObj.AdminUsername && Adminobj.AdminPassword == globalPkg.AdminObj.AdminPassword {\n\tif admin.ValidationAdmin(Adminobj) {\n\t\tjsonObj, _ := json.Marshal(accountdb.GetAllAccounts())\n\t\tglobalPkg.SendResponse(w, jsonObj)\n\t\tglobalPkg.WriteLog(logobj, \"get all accounts\", \"success\")\n\t} else {\n\n\t\tglobalPkg.SendError(w, \"you are not the admin \")\n\t\tglobalPkg.WriteLog(logobj, \"you are not the admin to get all accounts \", \"failed\")\n\t}\n}", "func GetAccountManager() *OpenIdManager {\n\treturn accountManager\n}", "func (a *Client) GetAccounts(params *GetAccountsParams) (*GetAccountsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAccountsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getAccounts\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/AccountService/Accounts\",\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: &GetAccountsReader{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.(*GetAccountsOK), nil\n\n}", "func (c APIClient) GetUsers() ([]User, error) {\n\tvar users []User\n\t_, err := c.doHTTPUnmarshal(\"GET\", \"https://api.nsone.net/v1/account/users\", nil, &users)\n\treturn users, err\n}", "func (r *RevenueAccountRepository) GetList(params *listParams.ListParams) (\n\t[]*model.RevenueAccountModel, error,\n) {\n\tvar accounts []*model.RevenueAccountModel\n\n\tquery := r.db.\n\t\tLimit(params.GetLimit()).\n\t\tOffset(params.GetOffset())\n\n\tif err := query.Find(&accounts).Error; err != nil {\n\t\treturn accounts, err\n\t}\n\n\treturn accounts, nil\n}", "func (c users) GetWithTeams(userEmail string, tk *Token, l *log.Entry) (user *models.User, err error) {\n\t// only admins can see other users of the system\n\tif *tk.IsAdmin == false && *tk.Email != userEmail {\n\t\tl.WithField(\"user\", userEmail).Debug(\"user token is not allowed to see another user\")\n\t\treturn nil, NewUnauthorizedError(\"token is not allowed to see this user\")\n\t}\n\tuser, err = c.getWithTeams(userEmail, l)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn\n}", "func (s *Logic) Accounts() ([]*entity.Account, error) {\n\treturn s.accounts.GetAll()\n}", "func (c *Coinbene) GetAccountBalances() ([]UserBalanceData, error) {\n\tresp := struct {\n\t\tData []UserBalanceData `json:\"data\"`\n\t}{}\n\tpath := coinbeneAPIVersion + coinbeneGetUserBalance\n\terr := c.SendAuthHTTPRequest(exchange.RestSpot, http.MethodGet,\n\t\tpath,\n\t\tcoinbeneGetUserBalance,\n\t\tfalse,\n\t\tnil,\n\t\t&resp,\n\t\tspotAccountInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.Data, 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 (srv *Service) GetAllUsersFromWhitelist() (*[]models.WhitelistUser, error) {\n\t//call driven adapter responsible for getting a deployment from mongo database\n\tresponse, err := srv.mongoRepository.GetAllUsersFromWhitelist()\n\n\tif err != nil {\n\t\t//return the error sent by the repository\n\t\treturn nil, err\n\t}\n\n\treturn &response, nil\n}", "func GetRolesFromUsers(accounts []*amv1.Account,\n\tconn *sdk.Connection) (results map[*amv1.Account][]string, error error) {\n\t// Prepare the results:\n\tresults = map[*amv1.Account][]string{}\n\n\t// Prepare a map of accounts indexed by identifier:\n\taccountsMap := map[string]*amv1.Account{}\n\tfor _, account := range accounts {\n\t\taccountsMap[account.ID()] = account\n\t}\n\n\t// Prepare a query to retrieve all the role bindings that correspond to any of the\n\t// accounts:\n\tids := &bytes.Buffer{}\n\tfor i, account := range accounts {\n\t\tif i > 0 {\n\t\t\tfmt.Fprintf(ids, \", \")\n\t\t}\n\t\tfmt.Fprintf(ids, \"'%s'\", account.ID())\n\t}\n\tquery := fmt.Sprintf(\"account_id in (%s)\", ids)\n\n\tindex := 1\n\tsize := 100\n\n\tfor {\n\t\t// Prepare the request:\n\t\tresponse, err := conn.AccountsMgmt().V1().RoleBindings().List().\n\t\t\tSize(size).\n\t\t\tPage(index).\n\t\t\tParameter(\"search\", query).\n\t\t\tSend()\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Can't retrieve roles: %v\", err)\n\t\t}\n\t\t// Loop through the results and save them:\n\t\tresponse.Items().Each(func(item *amv1.RoleBinding) bool {\n\t\t\taccount := accountsMap[item.Account().ID()]\n\n\t\t\titemID := item.Role().ID()\n\n\t\t\tif _, ok := results[account]; ok {\n\t\t\t\tif !stringInList(results[account], itemID) {\n\t\t\t\t\tresults[account] = append(results[account], itemID)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresults[account] = append(results[account], itemID)\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\n\t\t// Break the loop if the page size is smaller than requested, as that indicates\n\t\t// that this is the last page:\n\t\tif response.Size() < size {\n\t\t\tbreak\n\t\t}\n\t\tindex++\n\t}\n\n\treturn\n}", "func GetUser_rolesViaBundle(iBundle string) (*User_roles, error) {\n\tvar _User_roles = &User_roles{Bundle: iBundle}\n\thas, err := Engine.Get(_User_roles)\n\tif has {\n\t\treturn _User_roles, err\n\t} else {\n\t\treturn nil, err\n\t}\n}", "func (client IdentityClient) listAuthTokens(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/{userId}/authTokens\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListAuthTokensResponse\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 (m *CommunicationsIdentitySet) GetAzureCommunicationServicesUser()(Identityable) {\n val, err := m.GetBackingStore().Get(\"azureCommunicationServicesUser\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(Identityable)\n }\n return nil\n}", "func (s *Service) GetFinancialAccounts(ctx context.Context, req *GetFinancialAccountsRequest) (*GetFinancialAccountsResponse, error) {\n\ttx, err := s.txRepo.StartTx(ctx)\n\tif err != nil {\n\t\tlogger(\"GetFinancialAccounts\", err).Error(utils.StartTxErrorMsg)\n\t\treturn nil, utils.InternalServerError\n\t}\n\n\tuserID, err := utils.GetUserIDMetadata(ctx)\n\tif err != nil {\n\t\tlogger(\"GetFinancialAccounts\", err).Error(fmt.Sprintf(\"GetUserIDMetadata failed\"))\n\t\treturn nil, utils.InternalServerError\n\t}\n\n\taccounts, err := s.financialAccountRepo.GetItemAccounts(tx, userID, req.ItemId)\n\tif err != nil {\n\t\tlogger(\"GetFinancialAccounts\", err).Error(fmt.Sprintf(\"Repo call to GetItemAccounts failed\"))\n\t\treturn nil, utils.InternalServerError\n\t}\n\tvar pbAccounts []*shared.FinancialAccount\n\tfor _, account := range accounts {\n\t\tpbAccounts = append(pbAccounts, dataToAccountPb(account))\n\t}\n\n\terr = s.txRepo.CommitTx(tx)\n\tif err != nil {\n\t\tlogger(\"GetFinancialAccounts\", err).Error(utils.CommitTxErrorMsg)\n\t\treturn nil, err\n\t}\n\n\tres := &GetFinancialAccountsResponse{\n\t\tFinancialAccounts: pbAccounts,\n\t}\n\treturn res, nil\n}", "func (e *Enforcer) GetRolesForUser(name string) ([]string, error) {\n\tres, err := e.model[\"g\"][\"g\"].RM.GetRoles(name)\n\treturn res, err\n}", "func (backend *Backend) Accounts() []accounts.Interface {\n\tdefer backend.accountsAndKeystoreLock.RLock()()\n\treturn backend.accounts\n}", "func (s *Service) GetAccounts(budgetID string, f *api.Filter) (*SearchResultSnapshot, error) {\n\tresModel := struct {\n\t\tData struct {\n\t\t\tAccounts []*Account `json:\"accounts\"`\n\t\t\tServerKnowledge uint64 `json:\"server_knowledge\"`\n\t\t} `json:\"data\"`\n\t}{}\n\n\turl := fmt.Sprintf(\"/budgets/%s/accounts\", budgetID)\n\tif f != nil {\n\t\turl = fmt.Sprintf(\"%s?%s\", url, f.ToQuery())\n\t}\n\tif err := s.c.GET(url, &resModel); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &SearchResultSnapshot{\n\t\tAccounts: resModel.Data.Accounts,\n\t\tServerKnowledge: resModel.Data.ServerKnowledge,\n\t}, nil\n}", "func ValidateGetOnlineAccountsResponseBody(body *GetOnlineAccountsResponseBody) (err error) {\n\tfor _, e := range body.Accounts {\n\t\tif e != nil {\n\t\t\tif err2 := ValidateRelayerAccountResponseBody(e); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (_Storage *StorageSession) Accounts() (*big.Int, error) {\n\treturn _Storage.Contract.Accounts(&_Storage.CallOpts)\n}", "func (e *CachedEnforcer) GetImplicitRolesForUser(user string, domain ...string) ([]string, error) {\n\treturn e.api.GetImplicitRolesForUser(user, domain...)\n}", "func (e *SyncedEnforcer) GetUsersForRole(name string) ([]string, error) {\n\te.m.RLock()\n\tdefer e.m.RUnlock()\n\treturn e.Enforcer.GetUsersForRole(name)\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 (m *Application) GetAppRoles()([]AppRoleable) {\n return m.appRoles\n}", "func (tmdb *TMDb) GetAccountLists(id int, sessionID string, options map[string]string) (*MovieLists, error) {\n\tvar availableOptions = map[string]struct{}{\n\t\t\"page\": {},\n\t\t\"language\": {}}\n\tvar lists MovieLists\n\toptionsString := getOptionsString(options, availableOptions)\n\turi := fmt.Sprintf(\"%s/account/%v/lists?api_key=%s&session_id=%s%s\", baseURL, id, tmdb.apiKey, sessionID, optionsString)\n\tresult, err := getTmdb(uri, &lists)\n\treturn result.(*MovieLists), err\n}", "func (p *UserStoreClient) GetAccountLimits(ctx context.Context, serviceLevel ServiceLevel) (r *AccountLimits, err error) {\n var _args29 UserStoreGetAccountLimitsArgs\n _args29.ServiceLevel = serviceLevel\n var _result30 UserStoreGetAccountLimitsResult\n if err = p.Client_().Call(ctx, \"getAccountLimits\", &_args29, &_result30); err != nil {\n return\n }\n switch {\n case _result30.UserException!= nil:\n return r, _result30.UserException\n }\n\n return _result30.GetSuccess(), nil\n}", "func (api *PublicEthereumAPI) Accounts() ([]common.Address, error) {\n\tapi.logger.Debug(\"eth_accounts\")\n\tapi.keyringLock.Lock()\n\tdefer api.keyringLock.Unlock()\n\n\taddresses := make([]common.Address, 0) // return [] instead of nil if empty\n\n\tinfos, err := api.clientCtx.Keybase.List()\n\tif err != nil {\n\t\treturn addresses, err\n\t}\n\n\tfor _, info := range infos {\n\t\taddressBytes := info.GetPubKey().Address().Bytes()\n\t\taddresses = append(addresses, common.BytesToAddress(addressBytes))\n\t}\n\n\treturn addresses, nil\n}", "func (o GetRestorableDatabaseAccountsResultOutput) Accounts() GetRestorableDatabaseAccountsAccountArrayOutput {\n\treturn o.ApplyT(func(v GetRestorableDatabaseAccountsResult) []GetRestorableDatabaseAccountsAccount { return v.Accounts }).(GetRestorableDatabaseAccountsAccountArrayOutput)\n}", "func (s *walletService) GetAccounts(ctx context.Context) ([]Account, error) {\n\ta, err := s.model.SelectAccounts(ctx)\n\treturn a, err\n}", "func (manager *OpenIdManager) GetAccountByIdToken(providerId string, oidToken *oidc.IDToken) (*models.UserAccount, error) {\n\toidAccount, err := models.FindOIdAccount(providerId, oidToken.Subject)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taccount, err := models.GetUserAccountById(oidAccount.OwnerId)\n\treturn account, err\n}", "func (p *UserStoreClient) GetUser(ctx context.Context, authenticationToken string) (r *User, err error) {\n var _args13 UserStoreGetUserArgs\n _args13.AuthenticationToken = authenticationToken\n var _result14 UserStoreGetUserResult\n if err = p.Client_().Call(ctx, \"getUser\", &_args13, &_result14); err != nil {\n return\n }\n switch {\n case _result14.UserException!= nil:\n return r, _result14.UserException\n case _result14.SystemException!= nil:\n return r, _result14.SystemException\n }\n\n return _result14.GetSuccess(), nil\n}", "func (m *AzureCommunicationServicesUserIdentity) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Identity.GetFieldDeserializers()\n res[\"azureCommunicationServicesResourceId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAzureCommunicationServicesResourceId(val)\n }\n return nil\n }\n return res\n}", "func (t *SimpleChaincode) get_account(stub *shim.ChaincodeStub, userID string) ([]byte, error) {\n\n\tbytes, err := stub.GetState(userID)\n\n\tif err != nil {\n\t\treturn nil, errors.New(\"Could not retrieve information for this user\")\n\t}\n\n\treturn bytes, nil\n\n}", "func (owner *WalletOwnerAPI) Accounts() (*[]libwallet.AccountPathMapping, error) {\n\tparams := struct {\n\t\tToken string `json:\"token\"`\n\t}{\n\t\tToken: owner.token,\n\t}\n\tparamsBytes, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvl, err := owner.client.EncryptedRequest(\"accounts\", paramsBytes, owner.sharedSecret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif envl == nil {\n\t\treturn nil, errors.New(\"WalletOwnerAPI: Empty RPC Response from grin-wallet\")\n\t}\n\tif envl.Error != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"code\": envl.Error.Code,\n\t\t\t\"message\": envl.Error.Message,\n\t\t}).Error(\"WalletOwnerAPI: RPC Error during Accounts\")\n\t\treturn nil, errors.New(string(envl.Error.Code) + \"\" + envl.Error.Message)\n\t}\n\tvar result Result\n\tif err = json.Unmarshal(envl.Result, &result); err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Err != nil {\n\t\treturn nil, errors.New(string(result.Err))\n\t}\n\tvar accounts []libwallet.AccountPathMapping\n\tif err = json.Unmarshal(result.Ok, &accounts); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accounts, nil\n}" ]
[ "0.6541407", "0.61770934", "0.60088694", "0.53321785", "0.5316703", "0.52682734", "0.5168463", "0.51263136", "0.51216424", "0.50471693", "0.5034282", "0.5014549", "0.5013848", "0.49872217", "0.49647138", "0.49388367", "0.49350622", "0.49126402", "0.49000898", "0.48184377", "0.48112905", "0.48054722", "0.4795724", "0.47706982", "0.4737612", "0.47183767", "0.47169098", "0.46915162", "0.46781376", "0.4646364", "0.4641151", "0.46226704", "0.46214312", "0.4616688", "0.45929682", "0.4580041", "0.4565363", "0.45619115", "0.4549758", "0.45472842", "0.45389134", "0.45257947", "0.45162803", "0.45012924", "0.45000422", "0.44965887", "0.4488949", "0.448082", "0.4477849", "0.4477544", "0.4473639", "0.44706833", "0.44703752", "0.4466548", "0.44656515", "0.44614026", "0.4456409", "0.44523436", "0.44481602", "0.44480997", "0.44449678", "0.44405106", "0.44351974", "0.4403942", "0.44032302", "0.43993142", "0.43954566", "0.4393013", "0.43906662", "0.4383368", "0.43792418", "0.437725", "0.43761778", "0.4375633", "0.4375342", "0.43707824", "0.43671563", "0.43655407", "0.43593472", "0.43547824", "0.43516874", "0.43485582", "0.4343982", "0.4342031", "0.43391857", "0.43233135", "0.43206793", "0.43166405", "0.43157187", "0.4310206", "0.43055132", "0.43020502", "0.43018848", "0.42999646", "0.42955643", "0.42907557", "0.42881137", "0.42877677", "0.42870045", "0.42815515" ]
0.7499883
0
GetUserLUISAccountsPreparer prepares the GetUserLUISAccounts request.
func (client AzureAccountsClient) GetUserLUISAccountsPreparer(ctx context.Context) (*http.Request, error) { urlParameters := map[string]interface{}{ "Endpoint": client.Endpoint, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithCustomBaseURL("{Endpoint}/luis/api/v2.0", urlParameters), autorest.WithPath("/azureaccounts")) return preparer.Prepare((&http.Request{}).WithContext(ctx)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a Accounts) accountsPreparer(ctx context.Context) (*http.Request, error) {\n\tif !a.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(a.NextLink)))\n}", "func (client ListClient) UsersMethodPreparer(ctx context.Context) (*http.Request, error) {\n queryParameters := map[string]interface{} {\n \"access_token\": autorest.Encode(\"query\",client.AccessToken),\n }\n\n preparer := autorest.CreatePreparer(\n autorest.AsGet(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/users\"),\n autorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client AccountClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client AccountListResult) AccountListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (dlsailr DataLakeStoreAccountInformationListResult) dataLakeStoreAccountInformationListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif dlsailr.NextLink == nil || len(to.String(dlsailr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(dlsailr.NextLink)))\n}", "func (client AzureAccountsClient) GetAssignedPreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (dlaalr DataLakeAnalyticsAccountListResult) dataLakeAnalyticsAccountListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif dlaalr.NextLink == nil || len(to.String(dlaalr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(dlaalr.NextLink)))\n}", "func (dlaalr DataLakeAnalyticsAccountListResult) dataLakeAnalyticsAccountListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif dlaalr.NextLink == nil || len(to.String(dlaalr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(dlaalr.NextLink)))\n}", "func (dlr DatabaseListResult) databaseListResultPreparer(ctx context.Context) (*http.Request, error) {\n if !dlr.hasNextLink() {\n return nil, nil\n }\n return autorest.Prepare((&http.Request{}).WithContext(ctx),\n autorest.AsJSON(),\n autorest.AsGet(),\n autorest.WithBaseURL(to.String( dlr.NextLink)));\n }", "func (client ManagementClient) GetMAMFlaggedUsersPreparer(hostName string, filter string, top *int32, selectParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostName\": autorest.Encode(\"path\", hostName),\n\t}\n\n\tconst APIVersion = \"2015-01-14-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Intune/locations/{hostName}/flaggedUsers\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client RosettaNetProcessConfigurationsClient) ListByIntegrationAccountsPreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, top *int32, filter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"integrationAccountName\": autorest.Encode(\"path\", integrationAccountName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2016-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/rosettanetprocessconfigurations\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (urlr UserRoleListResponse) userRoleListResponsePreparer(ctx context.Context) (*http.Request, error) {\n\tif !urlr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(urlr.NextLink)))\n}", "func (client GroupClient) ListTablesPreparer(accountName string, databaseName string, schemaName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"schemaName\": autorest.Encode(\"path\", schemaName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(orderby) > 0 {\n\t\tqueryParameters[\"$orderby\"] = autorest.Encode(\"query\", orderby)\n\t}\n\tif count != nil {\n\t\tqueryParameters[\"$count\"] = autorest.Encode(\"query\", *count)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/schemas/{schemaName}/tables\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client GroupClient) ListCredentialsPreparer(accountName string, databaseName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(orderby) > 0 {\n\t\tqueryParameters[\"$orderby\"] = autorest.Encode(\"query\", orderby)\n\t}\n\tif count != nil {\n\t\tqueryParameters[\"$count\"] = autorest.Encode(\"query\", *count)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/credentials\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (dslr DataSourceListResult) dataSourceListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !dslr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(dslr.NextLink)))\n}", "func (client GroupClient) ListViewsPreparer(accountName string, databaseName string, schemaName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"schemaName\": autorest.Encode(\"path\", schemaName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(orderby) > 0 {\n\t\tqueryParameters[\"$orderby\"] = autorest.Encode(\"query\", orderby)\n\t}\n\tif count != nil {\n\t\tqueryParameters[\"$count\"] = autorest.Encode(\"query\", *count)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/schemas/{schemaName}/views\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (palr PeerAsnListResult) peerAsnListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !palr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(palr.NextLink)))\n}", "func (client GroupClient) ListAssembliesPreparer(accountName string, databaseName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(orderby) > 0 {\n\t\tqueryParameters[\"$orderby\"] = autorest.Encode(\"query\", orderby)\n\t}\n\tif count != nil {\n\t\tqueryParameters[\"$count\"] = autorest.Encode(\"query\", *count)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/assemblies\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (vlr VaultListResult) vaultListResultPreparer() (*http.Request, error) {\n\tif vlr.NextLink == nil || len(to.String(vlr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(vlr.NextLink)))\n}", "func (client GroupClient) ListExternalDataSourcesPreparer(accountName string, databaseName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(orderby) > 0 {\n\t\tqueryParameters[\"$orderby\"] = autorest.Encode(\"query\", orderby)\n\t}\n\tif count != nil {\n\t\tqueryParameters[\"$count\"] = autorest.Encode(\"query\", *count)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/externaldatasources\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client ExternalBillingAccountClient) ListPreparer(ctx context.Context) (*http.Request, error) {\n\tconst APIVersion = \"2019-03-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/providers/Microsoft.CostManagement/externalBillingAccounts\"),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client GroupClient) ListDatabasesPreparer(accountName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(orderby) > 0 {\n\t\tqueryParameters[\"$orderby\"] = autorest.Encode(\"query\", orderby)\n\t}\n\tif count != nil {\n\t\tqueryParameters[\"$count\"] = autorest.Encode(\"query\", *count)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPath(\"/catalog/usql/databases\"),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (sailr StorageAccountInformationListResult) storageAccountInformationListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif sailr.NextLink == nil || len(to.String(sailr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(sailr.NextLink)))\n}", "func (client ManagementClient) GetMAMFlaggedUserByNamePreparer(hostName string, userName string, selectParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostName\": autorest.Encode(\"path\", hostName),\n\t\t\"userName\": autorest.Encode(\"path\", userName),\n\t}\n\n\tconst APIVersion = \"2015-01-14-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Intune/locations/{hostName}/flaggedUsers/{userName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (ralr RegisteredAsnListResult) registeredAsnListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !ralr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(ralr.NextLink)))\n}", "func (dlaalsar DataLakeAnalyticsAccountListStorageAccountsResult) dataLakeAnalyticsAccountListStorageAccountsResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif dlaalsar.NextLink == nil || len(to.String(dlaalsar.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(dlaalsar.NextLink)))\n}", "func (client ManagementClient) PostUserRetrievetokenforuseraccountPreparer(body *Model1) (*http.Request, error) {\n preparer := autorest.CreatePreparer(\n autorest.AsJSON(),\n autorest.AsPost(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/User/RetrieveTokenForUserAccount/\"))\n if body != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(body))\n }\n return preparer.Prepare(&http.Request{})\n }", "func (client GroupClient) ListTypesPreparer(accountName string, databaseName string, schemaName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"schemaName\": autorest.Encode(\"path\", schemaName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(orderby) > 0 {\n\t\tqueryParameters[\"$orderby\"] = autorest.Encode(\"query\", orderby)\n\t}\n\tif count != nil {\n\t\tqueryParameters[\"$count\"] = autorest.Encode(\"query\", *count)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/schemas/{schemaName}/types\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (splr ServiceProviderListResult) serviceProviderListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !splr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(splr.NextLink)))\n}", "func (sclr ServiceCountryListResult) serviceCountryListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !sclr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(sclr.NextLink)))\n}", "func (client AzureAccountsClient) GetUserLUISAccountsSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (clr ConfigurationListResult) configurationListResultPreparer(ctx context.Context) (*http.Request, error) {\n if !clr.hasNextLink() {\n return nil, nil\n }\n return autorest.Prepare((&http.Request{}).WithContext(ctx),\n autorest.AsJSON(),\n autorest.AsGet(),\n autorest.WithBaseURL(to.String( clr.NextLink)));\n }", "func (nlr NamespaceListResult) namespaceListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif nlr.NextLink == nil || len(to.String(nlr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(nlr.NextLink)))\n}", "func (clr CampaignsListResult) campaignsListResultPreparer() (*http.Request, error) {\n\tif clr.NextLink == nil || len(to.String(clr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(clr.NextLink)))\n}", "func (client AppsClient) ImportPreparer(ctx context.Context, luisApp LuisApp, appName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tqueryParameters := map[string]interface{}{}\n\tif len(appName) > 0 {\n\t\tqueryParameters[\"appName\"] = autorest.Encode(\"query\", appName)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/apps/import\"),\n\t\tautorest.WithJSON(luisApp),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client GroupClient) GetViewPreparer(accountName string, databaseName string, schemaName string, viewName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"schemaName\": autorest.Encode(\"path\", schemaName),\n\t\t\"viewName\": autorest.Encode(\"path\", viewName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/schemas/{schemaName}/views/{viewName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (cl CreatorList) creatorListPreparer(ctx context.Context) (*http.Request, error) {\n\tif !cl.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(cl.NextLink)))\n}", "func (client JobClient) ListByAccountPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/jobs\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client ManagementClient) GetMAMUserDevicesPreparer(hostName string, userName string, filter string, top *int32, selectParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostName\": autorest.Encode(\"path\", hostName),\n\t\t\"userName\": autorest.Encode(\"path\", userName),\n\t}\n\n\tconst APIVersion = \"2015-01-14-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Intune/locations/{hostName}/users/{userName}/devices\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (rlr ResourceListResult) resourceListResultPreparer() (*http.Request, error) {\n\tif rlr.NextLink == nil || len(to.String(rlr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(rlr.NextLink)))\n}", "func (client AccountClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client GroupClient) GetTablePreparer(accountName string, databaseName string, schemaName string, tableName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"schemaName\": autorest.Encode(\"path\", schemaName),\n\t\t\"tableName\": autorest.Encode(\"path\", tableName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/schemas/{schemaName}/tables/{tableName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client OperationsClient) preparer(ctx context.Context) (*http.Request, error) {\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.config.Endpoint),\n\t\tautorest.WithPath(\"/keys\"),\n\t\tNewHMACAuthorizer(client.config.ID, client.config.Secret).WithAuthorization(),\n\t)\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (calr ClassicAdministratorListResult) classicAdministratorListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !calr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(calr.NextLink)))\n}", "func (client AccountClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/providers/Microsoft.AISupercomputer/accounts\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client GroupClient) GetExternalDataSourcePreparer(accountName string, databaseName string, externalDataSourceName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"externalDataSourceName\": autorest.Encode(\"path\", externalDataSourceName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/externaldatasources/{externalDataSourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client ManagementClient) GetMAMUserFlaggedEnrolledAppsPreparer(hostName string, userName string, filter string, top *int32, selectParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostName\": autorest.Encode(\"path\", hostName),\n\t\t\"userName\": autorest.Encode(\"path\", userName),\n\t}\n\n\tconst APIVersion = \"2015-01-14-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Intune/locations/{hostName}/flaggedUsers/{userName}/flaggedEnrolledApps\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (itlr ImportTaskListResult) importTaskListResultPreparer() (*http.Request, error) {\n\tif itlr.NextLink == nil || len(to.String(itlr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(itlr.NextLink)))\n}", "func (client DatabaseOperationListResult) DatabaseOperationListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (client ModelClient) GetRegexEntityInfosPreparer(ctx context.Context, appID uuid.UUID, versionID string, skip *int32, take *int32) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{}\n\tif skip != nil {\n\t\tqueryParameters[\"skip\"] = autorest.Encode(\"query\", *skip)\n\t} else {\n\t\tqueryParameters[\"skip\"] = autorest.Encode(\"query\", 0)\n\t}\n\tif take != nil {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", *take)\n\t} else {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", 100)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/regexentities\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client GroupClient) ListSchemasPreparer(accountName string, databaseName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(orderby) > 0 {\n\t\tqueryParameters[\"$orderby\"] = autorest.Encode(\"query\", orderby)\n\t}\n\tif count != nil {\n\t\tqueryParameters[\"$count\"] = autorest.Encode(\"query\", *count)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/schemas\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client ModelClient) GetHierarchicalEntityRolesPreparer(ctx context.Context, appID uuid.UUID, versionID string, hEntityID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"hEntityId\": autorest.Encode(\"path\", hEntityID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}/roles\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DatasetClient) ListPreparer(ctx context.Context) (*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 }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\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 GroupClient) ListProceduresPreparer(accountName string, databaseName string, schemaName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"schemaName\": autorest.Encode(\"path\", schemaName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(orderby) > 0 {\n\t\tqueryParameters[\"$orderby\"] = autorest.Encode(\"query\", orderby)\n\t}\n\tif count != nil {\n\t\tqueryParameters[\"$count\"] = autorest.Encode(\"query\", *count)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/schemas/{schemaName}/procedures\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client GroupClient) GetCredentialPreparer(accountName string, databaseName string, credentialName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"credentialName\": autorest.Encode(\"path\", credentialName),\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/credentials/{credentialName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (clr ClusterListResult) clusterListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !clr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(clr.NextLink)))\n}", "func (client EncryptionProtectorListResult) EncryptionProtectorListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (silr StorageInsightListResult) storageInsightListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !silr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(silr.OdataNextLink)))\n}", "func (client AzureAccountsClient) GetUserLUISAccountsResponder(resp *http.Response) (result ListAzureAccountInfoObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client GroupClient) ListTableTypesPreparer(accountName string, databaseName string, schemaName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"schemaName\": autorest.Encode(\"path\", schemaName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(orderby) > 0 {\n\t\tqueryParameters[\"$orderby\"] = autorest.Encode(\"query\", orderby)\n\t}\n\tif count != nil {\n\t\tqueryParameters[\"$count\"] = autorest.Encode(\"query\", *count)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/schemas/{schemaName}/tabletypes\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client NetworkInterfaceListResult) NetworkInterfaceListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (slr ServerListResult) serverListResultPreparer(ctx context.Context) (*http.Request, error) {\n if !slr.hasNextLink() {\n return nil, nil\n }\n return autorest.Prepare((&http.Request{}).WithContext(ctx),\n autorest.AsJSON(),\n autorest.AsGet(),\n autorest.WithBaseURL(to.String( slr.NextLink)));\n }", "func (client CampaignsListResult) CampaignsListResultPreparer() (*http.Request, error) {\r\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\r\n\t\treturn nil, nil\r\n\t}\r\n\treturn autorest.Prepare(&http.Request{},\r\n\t\tautorest.AsJSON(),\r\n\t\tautorest.AsGet(),\r\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\r\n}", "func (tnc TransactionNodeCollection) transactionNodeCollectionPreparer(ctx context.Context) (*http.Request, error) {\n\tif !tnc.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(tnc.NextLink)))\n}", "func (client ImportTaskListResult) ImportTaskListResultPreparer() (*http.Request, error) {\r\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\r\n\t\treturn nil, nil\r\n\t}\r\n\treturn autorest.Prepare(&http.Request{},\r\n\t\tautorest.AsJSON(),\r\n\t\tautorest.AsGet(),\r\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\r\n}", "func setupPreparers(fixture consultest.Fixture) {\n\tfor _, node := range testNodes {\n\t\tkey := fmt.Sprintf(\"reality/%s/p2-preparer\", node)\n\t\tfixture.SetKV(key, []byte(testPreparerManifest))\n\t}\n}", "func (client ModelClient) GetPrebuiltEntityRolesPreparer(ctx context.Context, appID uuid.UUID, versionID string, entityID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"entityId\": autorest.Encode(\"path\", entityID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/prebuilts/{entityId}/roles\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client FailoverGroupListResult) FailoverGroupListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (dlr DefinitionListResult) definitionListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !dlr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(dlr.NextLink)))\n}", "func (client DatasetClient) GetPreparer(ctx context.Context, datasetID string) (*http.Request, error) {\n urlParameters := map[string]interface{} {\n \"geography\": autorest.Encode(\"path\",client.Geography),\n }\n\n pathParameters := map[string]interface{} {\n \"datasetId\": autorest.Encode(\"path\",datasetID),\n }\n\n const APIVersion = \"2.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithCustomBaseURL(\"https://{geography}.atlas.microsoft.com\", urlParameters),\nautorest.WithPathParameters(\"/datasets/{datasetId}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (ehdlr EndpointHealthDataListResult) endpointHealthDataListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !ehdlr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(ehdlr.NextLink)))\n}", "func (client WorkflowAccessKeyListResult) WorkflowAccessKeyListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (pgr PermissionGetResult) permissionGetResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !pgr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(pgr.NextLink)))\n}", "func (client KqlScriptsClient) GetAllPreparer(ctx context.Context) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\n\t\t\"endpoint\": client.Endpoint,\n\t}\n\n\tconst APIVersion = \"2021-06-01-preview\"\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.WithCustomBaseURL(\"{endpoint}\", urlParameters),\n\t\tautorest.WithPath(\"/kqlScripts\"),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ModelClient) GetExplicitListPreparer(ctx context.Context, appID uuid.UUID, versionID string, entityID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"entityId\": autorest.Encode(\"path\", entityID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/explicitlist\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (elr ExemptionListResult) exemptionListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !elr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(elr.NextLink)))\n}", "func (client AccountQuotaPolicyClient) ListByAccountPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/accountQuotaPolicies\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client WorkflowRunListResult) WorkflowRunListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (alr AssignmentListResult) assignmentListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !alr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(alr.NextLink)))\n}", "func (client ExternalBillingAccountClient) GetPreparer(ctx context.Context, externalBillingAccountName string, expand string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"externalBillingAccountName\": autorest.Encode(\"path\", externalBillingAccountName),\n\t}\n\n\tconst APIVersion = \"2019-03-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ManagementClient) PostUserRequestaudittrailPreparer(body *Model1) (*http.Request, error) {\n preparer := autorest.CreatePreparer(\n autorest.AsJSON(),\n autorest.AsPost(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/User/RequestAuditTrail/\"))\n if body != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(body))\n }\n return preparer.Prepare(&http.Request{})\n }", "func (silr StorageInsightListResult) storageInsightListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif silr.OdataNextLink == nil || len(to.String(silr.OdataNextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(silr.OdataNextLink)))\n}", "func (dlaaldlsr DataLakeAnalyticsAccountListDataLakeStoreResult) dataLakeAnalyticsAccountListDataLakeStoreResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif dlaaldlsr.NextLink == nil || len(to.String(dlaaldlsr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(dlaaldlsr.NextLink)))\n}", "func (client ModelClient) GetEntityRolesPreparer(ctx context.Context, appID uuid.UUID, versionID string, entityID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"entityId\": autorest.Encode(\"path\", entityID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/entities/{entityId}/roles\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AccountClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, body AccountResourceDescription) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPut(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}\",pathParameters),\nautorest.WithJSON(body),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client GroupClient) ListTablePartitionsPreparer(accountName string, databaseName string, schemaName string, tableName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"schemaName\": autorest.Encode(\"path\", schemaName),\n\t\t\"tableName\": autorest.Encode(\"path\", tableName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif skip != nil {\n\t\tqueryParameters[\"$skip\"] = autorest.Encode(\"query\", *skip)\n\t}\n\tif len(expand) > 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(orderby) > 0 {\n\t\tqueryParameters[\"$orderby\"] = autorest.Encode(\"query\", orderby)\n\t}\n\tif count != nil {\n\t\tqueryParameters[\"$count\"] = autorest.Encode(\"query\", *count)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/schemas/{schemaName}/tables/{tableName}/partitions\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (rdlr RoleDefinitionListResult) roleDefinitionListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif !rdlr.hasNextLink() {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(rdlr.NextLink)))\n}", "func (client GroupClient) GetSchemaPreparer(accountName string, databaseName string, schemaName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"schemaName\": autorest.Encode(\"path\", schemaName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/schemas/{schemaName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client KeyListResult) KeyListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (client AccountQuotaPolicyClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, policyName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"policyName\": policyName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/accountQuotaPolicies/{policyName}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client ModelClient) ListIntentsPreparer(ctx context.Context, appID uuid.UUID, versionID string, skip *int32, take *int32) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{}\n\tif skip != nil {\n\t\tqueryParameters[\"skip\"] = autorest.Encode(\"query\", *skip)\n\t} else {\n\t\tqueryParameters[\"skip\"] = autorest.Encode(\"query\", 0)\n\t}\n\tif take != nil {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", *take)\n\t} else {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", 100)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/intents\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (ualr UsageAggregationListResult) usageAggregationListResultPreparer(ctx context.Context) (*http.Request, error) {\n\tif ualr.NextLink == nil || len(to.String(ualr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((&http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(ualr.NextLink)))\n}", "func (client WorkflowListResult) WorkflowListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (client CertificateClient) ListByBatchAccountPreparer(ctx context.Context, resourceGroupName string, accountName string, maxresults *int32, selectParameter string, filter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"accountName\": autorest.Encode(\"path\", accountName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2018-12-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif maxresults != nil {\n\t\tqueryParameters[\"maxresults\"] = autorest.Encode(\"query\", *maxresults)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client LabClient) ListBySubscriptionPreparer(ctx context.Context, filter string, top *int32, orderBy string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2015-05-21-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(orderBy) > 0 {\n\t\tqueryParameters[\"$orderBy\"] = autorest.Encode(\"query\", orderBy)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/providers/Microsoft.DevTestLab/labs\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppsClient) GetPreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ModelClient) GetRegexEntityRolesPreparer(ctx context.Context, appID uuid.UUID, versionID string, entityID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"entityId\": autorest.Encode(\"path\", entityID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/regexentities/{entityId}/roles\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client SubscriptionListResult) SubscriptionListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (client GroupClient) GetDatabasePreparer(accountName string, databaseName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (frlr FirewallRuleListResult) firewallRuleListResultPreparer(ctx context.Context) (*http.Request, error) {\n if !frlr.hasNextLink() {\n return nil, nil\n }\n return autorest.Prepare((&http.Request{}).WithContext(ctx),\n autorest.AsJSON(),\n autorest.AsGet(),\n autorest.WithBaseURL(to.String( frlr.NextLink)));\n }" ]
[ "0.6216312", "0.62114084", "0.585652", "0.5843319", "0.5782225", "0.5713426", "0.56629455", "0.56629455", "0.56056523", "0.5594603", "0.55692697", "0.5554103", "0.5507621", "0.54846", "0.5483161", "0.54496515", "0.54217666", "0.5421436", "0.5418422", "0.5414073", "0.5398441", "0.53864545", "0.5378967", "0.53049636", "0.53035796", "0.52879137", "0.52648836", "0.5242474", "0.5231437", "0.52194077", "0.51997024", "0.51949716", "0.5192283", "0.5189235", "0.51776487", "0.51669115", "0.51570463", "0.5143137", "0.513485", "0.51292974", "0.51270986", "0.51248974", "0.5123039", "0.51230043", "0.511696", "0.51150537", "0.5097599", "0.5094377", "0.5079764", "0.5078153", "0.5072741", "0.50718063", "0.5067652", "0.50674605", "0.5067125", "0.50644594", "0.5061174", "0.506005", "0.5044126", "0.5041457", "0.5026929", "0.5026495", "0.5025271", "0.5004906", "0.4993766", "0.49873635", "0.49846852", "0.49825624", "0.4982545", "0.49777657", "0.49725989", "0.49705872", "0.4970308", "0.49674177", "0.49633238", "0.49583298", "0.49570334", "0.49545056", "0.49535072", "0.49531904", "0.49469107", "0.49448317", "0.49433032", "0.49359947", "0.4932622", "0.49291947", "0.49222142", "0.49128", "0.49073365", "0.49024087", "0.48961994", "0.48959312", "0.48931354", "0.4892512", "0.48922476", "0.48892015", "0.4882603", "0.4880023", "0.487945", "0.48769712" ]
0.80020416
0
GetUserLUISAccountsSender sends the GetUserLUISAccounts request. The method will close the http.Response Body if it receives an error.
func (client AzureAccountsClient) GetUserLUISAccountsSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AzureAccountsClient) GetUserLUISAccountsResponder(resp *http.Response) (result ListAzureAccountInfoObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client AzureAccountsClient) GetUserLUISAccounts(ctx context.Context) (result ListAzureAccountInfoObject, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.GetUserLUISAccounts\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.GetUserLUISAccountsPreparer(ctx)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetUserLUISAccounts\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetUserLUISAccountsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetUserLUISAccounts\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetUserLUISAccountsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetUserLUISAccounts\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (client ListClient) UsersMethodSender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req,\n autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func (client AzureAccountsClient) GetUserLUISAccountsPreparer(ctx context.Context) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/azureaccounts\"))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\n\t// Add header so that received knows they're receiving JSON\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// Retrieving name of node from query request\n\tnodeName := r.URL.Query().Get(\"name\")\n\tconfirmation, socket := checkNodeName(nodeName)\n\tif confirmation == false {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Node name requested doesn't exist\"})\n\t\treturn\n\t}\n\n\t// Retrieving height from query request\n\trecvHeight := r.URL.Query().Get(\"height\")\n\theight := checkHeight(recvHeight)\n\tif height == -1 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Unexepcted value found, height needs to be string of int!\"})\n\t\treturn\n\t}\n\n\t// Attempt to load connection with staking client\n\tconnection, so := loadStakingClient(socket)\n\n\t// Close connection once code underneath executes\n\tdefer connection.Close()\n\n\t// If null object was retrieved send response\n\tif so == nil {\n\n\t\t// Stop code here faild to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to establish connection using socket : \" + socket})\n\t\treturn\n\t}\n\n\t// Return accounts from staking client\n\taccounts, err := so.Addresses(context.Background(), height)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to get Accounts!\"})\n\t\tlgr.Error.Println(\n\t\t\t\"Request at /api/staking/accounts failed to retrieve Accounts : \",\n\t\t\terr)\n\t\treturn\n\t}\n\n\t// Respond with array of all accounts\n\tlgr.Info.Println(\"Request at /api/staking/accounts responding with \" +\n\t\t\"Accounts!\")\n\tjson.NewEncoder(w).Encode(responses.AllAccountsResponse{AllAccounts: accounts})\n}", "func (w *ServerInterfaceWrapper) GetAccounts(ctx echo.Context) error {\n\tvar err error\n\n\tctx.Set(ApiKeyAuthScopes, []string{\"\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetAccounts(ctx)\n\treturn err\n}", "func (client KqlScriptsClient) GetAllSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func GetUsers(ctx context.Context, req *pb.GetUserRequest) (*pb.GetUserResponse, error) {\n\tgetUserFunction := func(conn *grpc.ClientConn) (interface{}, error) {\n\t\tclient := pb.NewUserServiceClient(conn)\n\n\t\tmd1 := metadata.Pairs(\n\t\t\t\"X-Custom-orgname\", \"This is my Custom Header O_o Weird\",\n\t\t\t\"authorization\", \"bearer some_token_if8y3498eufhkfj\")\n\t\tctx := metadata.NewOutgoingContext(context.Background(), md1)\n\n\t\tresp, err := client.GetUser(ctx, req)\n\t\tif err != nil {\n\t\t\tentry.WithField(logrus.ErrorKey, err).Errorln(\"Error occurred while trying to Get Users Table\")\n\n\t\t\tst := status.Convert(err)\n\t\t\tfor _, detail := range st.Details() {\n\t\t\t\tswitch t := detail.(type) {\n\t\t\t\tcase *pb.Error:\n\t\t\t\t\tfmt.Println(\"Oops! Get request was rejected by the server.\")\n\t\t\t\t\tfmt.Printf(\"The %q field was wrong:\\n\", t.Message)\n\t\t\t\t\tfmt.Printf(\"\\t%d\\n\", t.Code)\n\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", t.Type)\n\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", t.DetailedMessage)\n\t\t\t\tdefault:\n\t\t\t\t\tfmt.Printf(\"Object found was %v with type %v\", detail, reflect.TypeOf(detail))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil, err\n\t\t}\n\t\treturn resp, nil\n\t}\n\tresp, err := SafeExecute(getUserFunction)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgetUserResponse, ok := resp.(*pb.GetUserResponse)\n\tif !ok {\n\t\treturn nil, errors.New(\"Could not cast response to get user\")\n\t}\n\treturn getUserResponse, nil\n}", "func (h *HUOBI) GetAccounts(ctx context.Context) ([]Account, error) {\n\tresult := struct {\n\t\tAccounts []Account `json:\"data\"`\n\t}{}\n\terr := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiAccounts, url.Values{}, nil, &result, false)\n\treturn result.Accounts, err\n}", "func (client Client) GetListSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\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 (s *Identity) AccountsGET(w http.ResponseWriter, r *http.Request) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\twriteResponse(s.addresses, w, r)\n}", "func GetAllEmailsUsernameAPI(w http.ResponseWriter, req *http.Request) {\n\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"GetAllEmailsUsernameAPI\", \"Account\", \"_\", \"_\", \"_\", 0}\n\n\tAdminobj := admin.Admin{}\n\n\tdecoder := json.NewDecoder(req.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&Adminobj)\n\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request \")\n\t\tglobalPkg.WriteLog(logobj, \"failed to decode admin object\", \"failed\")\n\t\treturn\n\t}\n\n\t// var sendJSON []byte\n\tarrEmailsUsername := []EmailuserStruct{}\n\n\tif admin.ValidationAdmin(Adminobj) {\n\t\taccountobj := accountdb.GetAllAccounts()\n\t\tfor _, account := range accountobj {\n\t\t\temailsUsername := EmailuserStruct{account.AccountName, account.AccountEmail}\n\t\t\tarrEmailsUsername = append(arrEmailsUsername, emailsUsername)\n\t\t}\n\n\t\tjsonObj, _ := json.Marshal(arrEmailsUsername)\n\t\tglobalPkg.SendResponse(w, jsonObj)\n\t\tglobalPkg.WriteLog(logobj, \"success to get all emails and username\", \"success\")\n\t} else {\n\t\tglobalPkg.SendError(w, \"you are not admin \")\n\t\tglobalPkg.WriteLog(logobj, \"you are not the admin to get all Emails and username \", \"failed\")\n\t}\n\n}", "func GetUsers(clients *common.ClientContainer, handler common.HandlerInterface) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tusers, err := handler.GetUsers(clients)\n\t\tif err != nil {\n\t\t\tlog.Logger.Error(err)\n\t\t\tcommon.WriteErrorToResponse(w, http.StatusInternalServerError,\n\t\t\t\thttp.StatusText(http.StatusInternalServerError),\n\t\t\t\t\"Internal server error occured\")\n\t\t\treturn\n\t\t}\n\t\tw.Write(users)\n\t}\n}", "func (client ConversationsClient) GetConversationsMethodSender(req *http.Request) (*http.Response, error) {\n sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n return autorest.SendWithSender(client, req, sd...)\n }", "func (client SmartGroupsClient) GetAllSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\tdb, erro := database.Connect()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tdefer db.Close()\n\trepository := repositories.NewAccountRepository(db)\n\taccounts, erro := repository.FindAll()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, accounts)\n}", "func GetUsers() UsersResponse {\n\tvar users UsersResponse\n\tresponse := network.Get(\"admin/users\")\n\tjson.Unmarshal(response, &users)\n\n\treturn users\n}", "func (h *HUOBIHADAX) GetAccounts() ([]Account, error) {\n\ttype response struct {\n\t\tResponse\n\t\tAccountData []Account `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodGet, huobihadaxAccounts, url.Values{}, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.AccountData, err\n}", "func (client AccountClient) GetSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, azure.DoRetryWithRegistration(client.Client))\n }", "func (client ExternalBillingAccountClient) ListSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ExternalBillingAccountClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\n\tjson.NewEncoder(w).Encode(nil)\n}", "func getUFADetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tlogger.Info(\"getUFADetails called with UFA number: \" + args[0])\r\n\r\n\tvar outputRecord map[string]string\r\n\tufanumber := args[0] //UFA ufanum\r\n\t//who :=args[1] //Role\r\n\trecBytes, _ := stub.GetState(ufanumber)\r\n\tjson.Unmarshal(recBytes, &outputRecord)\r\n\toutputBytes, _ := json.Marshal(outputRecord)\r\n\tlogger.Info(\"Returning records from getUFADetails \" + string(outputBytes))\r\n\treturn outputBytes, nil\r\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 getUFADetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tlogger.Info(\"getUFADetails called with UFA number: \" + args[0])\n\n\tvar outputRecord map[string]interface{}\n\tufanumber := args[0] //UFA ufanum\n\t//who :=args[1] //Role\n\trecBytes, _ := stub.GetState(ufanumber)\n\tjson.Unmarshal(recBytes, &outputRecord)\n\toutputBytes, _ := json.Marshal(outputRecord)\n\tlogger.Info(\"Returning records from getUFADetails \" + string(outputBytes))\n\treturn outputBytes, nil\n}", "func (uh UserHandler) GetAllUsers(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(utils.InfoLog + \"UserHandler:GetAllUsers called\")\n\n\tvar results *[]models.User\n\tresults, err := uh.UserManager.GetUsers(); 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\tjson.NewEncoder(w).Encode(results)\n\tw.WriteHeader(http.StatusOK)\n}", "func (client ApplicationsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AppsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (mw loggingMiddleware) GetAccounts(ctx context.Context) (accounts []Account, err error) {\n\tdefer func(begin time.Time) {\n\t\tmw.logger.Log(\"method\", \"GetAddresses\", \"took\", time.Since(begin), \"err\", err)\n\t}(time.Now())\n\treturn mw.next.GetAccounts(ctx)\n}", "func (client EntitiesClient) ListSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (a *WebhooksApiService) UsersUsernameHooksGet(ctx context.Context, username string) (PaginatedWebhookSubscriptions, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PaginatedWebhookSubscriptions\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/users/{username}/hooks\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"username\"+\"}\", fmt.Sprintf(\"%v\", username), -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\"}\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\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[\"Authorization\"] = key\n\t\t\t\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\tif err == nil { \n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v PaginatedWebhookSubscriptions\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (s *initServer) GetUser(ctx context.Context, in *pb.GetUserRequest) (*pb.GetUserResponse, error) {\t\n\tmd, _ := metadata.FromIncomingContext(ctx)\n\tresp := getUserResp(ctx)\n\t\n\tc := newConn(\"getUser: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(nil, err.Error(), code)\n\t}\n\n\tres, err := u.UserGet(ctx, &pbUser.UserGetRequest{Data: strings.Split(md[\"authorization\"][0], \" \")[1]})\n\tif err != nil {\n\t\treturn resp(nil, err.Error(), \"400\")\n\t}\n\n\treturn resp(&pb.UserData{\n\t\tLogin: res.Login, \n\t\tName: res.Name, \n\t\tEmail: res.Email,\n\t\tId: res.Id,\n\t}, res.Message, res.Code)\n}", "func (c *IloClient) GetUserAccountsDell() ([]Accounts, error) {\n\n\turl := c.Hostname + \"/redfish/v1/Managers/iDRAC.Embedded.1/Accounts\"\n\n\tresp, _, _, err := queryData(c, \"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar x MemberCountDell\n\tvar users []Accounts\n\n\tjson.Unmarshal(resp, &x)\n\n\tfor i := range x.Members {\n\t\t_url := c.Hostname + x.Members[i].OdataId\n\t\tresp, _, _, err := queryData(c, \"GET\", _url, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar y AccountsInfoDell\n\n\t\tjson.Unmarshal(resp, &y)\n\n\t\tuser := Accounts{\n\t\t\tName: y.Name,\n\t\t\tEnabled: y.Enabled,\n\t\t\tLocked: y.Locked,\n\t\t\tRoleId: y.RoleID,\n\t\t\tUsername: y.UserName,\n\t\t}\n\t\tusers = append(users, user)\n\n\t}\n\n\treturn users, nil\n\n}", "func (client AppsClient) ListSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func returnUsersAccounts(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar users []User\n\tvar orders []Orders\n\t//fmt.Println(\"Request URI: \", path.Base(r.RequestURI))\n\tusername := path.Base(r.RequestURI)\n\n\t// query for userid\n\tresults, err := db.Query(\"Select * from users where username = ?\", username)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tfor results.Next() {\n\t\tvar user User\n\t\terr := results.Scan(&user.ID, &user.Username)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\n\t\tusers = append(users, user)\n\t\tfmt.Println(\"Userid: \", users[0].ID)\n\t}\n\n\t// query the orders table with userid and return all rows\n\n\t//select orders.id, users.username, stocks.symbol, shares from orders inner join users on orders.user_id = users.id inner join stocks on orders.stock_id = stocks.id\n\tresults, err = db.Query(\"select orders.id, users.username, stocks.symbol, shares from orders inner join users on orders.user_id = users.id inner join stocks on orders.stock_id = stocks.id where orders.user_id = ?\", users[0].ID)\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tfor results.Next() {\n\t\tvar order Orders\n\t\terr = results.Scan(&order.ID, &order.Username, &order.Symbol, &order.Shares)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\torders = append(orders, order)\n\t}\n\tjson.NewEncoder(w).Encode(orders)\n}", "func (client DatasetClient) ListSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func (uc UserController) GetAllUsers(c *doze.Context) doze.ResponseSender {\n\treturn doze.NewOKJSONResponse(users)\n}", "func (client MSIXPackagesClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (c APIClient) GetUsers() ([]User, error) {\n\tvar users []User\n\t_, err := c.doHTTPUnmarshal(\"GET\", \"https://api.nsone.net/v1/account/users\", nil, &users)\n\treturn users, err\n}", "func (client ApplicationsClient) ListSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (uc UserController) GetAllUsers(c rest.Context) rest.ResponseSender {\n\treturn rest.NewOKJSONResponse(users)\n}", "func (client RecoveryPointsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (h *handler) Users(w http.ResponseWriter, r *http.Request) {\n\tapiReq, err := http.NewRequest(\"GET\", h.serverAddress+\"/users\", nil)\n\tif err != nil {\n\t\tserverError(w, err)\n\t\treturn\n\t}\n\n\tclient := &http.Client{}\n\tres, err := client.Do(apiReq)\n\tif err != nil {\n\t\tserverError(w, err)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tvar uis []socialnet.UserItem\n\terr = json.NewDecoder(res.Body).Decode(&uis)\n\tif err != nil {\n\t\tserverError(w, err)\n\t\treturn\n\t}\n\n\terr = h.template.ExecuteTemplate(w, \"users.html\", uis)\n\tif err != nil {\n\t\tserverError(w, fmt.Errorf(\"failed to execute template users.html: %s\", err))\n\t\treturn\n\t}\n}", "func (h *Handler) getAllUsers(c *gin.Context) handlerResponse {\n\n\tusers, err := h.service.User.GetAll()\n\tif err != nil {\n\t\treturn handleError(err)\n\t}\n\tremovePasswords(users)\n\treturn handleOK(StringMap{\"users\": users})\n}", "func (client DatasetClient) GetSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func (client *Client) GetUserInfos(allDomains bool, domainName string) ([]UserFullDataWrapper, error) {\n\tquery, _ := json.Marshal(InfoListData{\n\t\tAllDomains: allDomains,\n\t\tDomainName: domainName,\n\t})\n\n\tresRaw, err := client.ListClients([]byte(query))\n\tif err != nil {\n\t\treturn []UserFullDataWrapper{}, err\n\t}\n\n\tresUnmarshaled := []UserFullDataWrapper{}\n\tif err := json.Unmarshal(resRaw, &resUnmarshaled); err != nil {\n\t\treturn []UserFullDataWrapper{}, err\n\t}\n\n\treturn resUnmarshaled, err\n}", "func (client ModelClient) GetClosedListEntityRolesSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ViewsClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client MeshNetworkClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (auh *AdminUserHandler) GetUsers(w http.ResponseWriter,\n\tr *http.Request, _ httprouter.Params) {\n\n\tvar apiKey = r.Header.Get(\"api-key\")\n\tif apiKey == \"\" || apiKey != adminApiKey {\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\tusers, errs := auh.userService.Users()\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\toutput, err := json.MarshalIndent(users, \"\", \"\\t\")\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\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(output)\n\treturn\n\n}", "func ViewUsers(w http.ResponseWriter, r *http.Request) error {\n if r.Method == \"GET\" {\n myUid, err0 := GetMyUserId(r)\n if err0 != nil {\n return err0\n }\n ctx1, _ := context.WithTimeout(context.Background(), constant.ContextTimeoutDuration)\n response, err := BackendClientIns.FindAllUsers(ctx1, &FindAllUsersRequest{})\n if err != nil {\n return err\n }\n allUsers := response.Users\n newUserList := make([]user, 0)\n for _, value := range allUsers {\n if value.UserId == myUid { // Exclude myself\n continue\n }\n ctx, _ := context.WithTimeout(context.Background(), constant.ContextTimeoutDuration)\n responseFromWhetherFollowing, _ := BackendClientIns.UserCheckWhetherFollowing(ctx,\n &UserCheckWhetherFollowingRequest{\n SourceUserId: myUid,\n TargetUserId: value.UserId,\n })\n newUserList = append(newUserList, user{Name: value.UserName,\n Followed: responseFromWhetherFollowing.Ok,\n Id: strconv.Itoa(int(value.UserId))})\n }\n view := viewUserView{\n UserList: newUserList,\n }\n log.Println(view.UserList)\n t, _ := template.ParseFiles(constant.RelativePathForTemplate + \"users.html\")\n w.Header().Set(\"Content-Type\", \"text/html\")\n t.Execute(w, view)\n }\n return nil\n}", "func (client MSIXPackagesClient) ListSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\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 StreamUsers(ctx context.Context, req *pb.GetUserRequest) ([]*pb.GetUserResponse, error) {\n\tgetUsersFunction := func(conn *grpc.ClientConn) (interface{}, error) {\n\t\tclient := pb.NewUserServiceClient(conn)\n\t\tusersStream, err := client.StreamUsers(ctx, req)\n\t\tif err != nil {\n\t\t\tentry.WithField(logrus.ErrorKey, err).Errorln(\"Error occurred while trying to Stream Users Table\")\n\n\t\t\tst := status.Convert(err)\n\t\t\tfor _, detail := range st.Details() {\n\t\t\t\tswitch t := detail.(type) {\n\t\t\t\tcase *pb.Error:\n\t\t\t\t\tfmt.Println(\"Oops! Stream request was rejected by the server.\")\n\t\t\t\t\tfmt.Printf(\"The %q field was wrong:\\n\", t.Message)\n\t\t\t\t\tfmt.Printf(\"\\t%d\\n\", t.Code)\n\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", t.Type)\n\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", t.DetailedMessage)\n\t\t\t\tdefault:\n\t\t\t\t\tfmt.Printf(\"Object found was %v with type %v\", detail, reflect.TypeOf(detail))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar userResponses = make([]*pb.GetUserResponse, 1)\n\n\t\tfor {\n\t\t\tuserResponse, err := usersStream.Recv()\n\t\t\tif err == io.EOF {\n\t\t\t\treturn userResponses, nil\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tif err != nil {\n\t\t\t\t\tentry.WithField(logrus.ErrorKey, err).Errorln(\"Error occurred while trying to Stream Users Table\")\n\n\t\t\t\t\tst := status.Convert(err)\n\t\t\t\t\tfor _, detail := range st.Details() {\n\t\t\t\t\t\tswitch t := detail.(type) {\n\t\t\t\t\t\tcase *pb.Error:\n\t\t\t\t\t\t\tfmt.Println(\"Oops! Stream request was rejected by the server.\")\n\t\t\t\t\t\t\tfmt.Printf(\"The %q field was wrong:\\n\", t.Message)\n\t\t\t\t\t\t\tfmt.Printf(\"\\t%d\\n\", t.Code)\n\t\t\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", t.Type)\n\t\t\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", t.DetailedMessage)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfmt.Printf(\"Object found was %v with type %v\", detail, reflect.TypeOf(detail))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"Received Error : \"))\n\t\t\t}\n\t\t\tuserResponses = append(userResponses, userResponse)\n\t\t}\n\t}\n\n\tresp, err := SafeExecute(getUsersFunction)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tusersList, ok := resp.([]*pb.GetUserResponse)\n\tif !ok {\n\t\treturn nil, errors.New(\"Could not cast response to list of users\")\n\t}\n\treturn usersList, nil\n}", "func (a *BankAccountApiService) BankAccountsGet(ctx _context.Context, authorization string) (AllBankAccountResponse, *_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 AllBankAccountResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/bank-accounts\"\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\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(authorization, \"\")\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 GetAllUsers(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"Getting all users\"))\n}", "func (client DatabasesClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req)\n}", "func (w *ServerInterfaceWrapper) GetUsers(ctx echo.Context) error {\n\tvar err error\n\n\tctx.Set(\"OAuth.Scopes\", []string{\"\"})\n\n\t// Parameter object where we will unmarshal all parameters from the context\n\tvar params GetUsersParams\n\t// ------------- Optional query parameter \"page_size\" -------------\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"page_size\", ctx.QueryParams(), &params.PageSize)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter page_size: %s\", err))\n\t}\n\n\t// ------------- Optional query parameter \"page_number\" -------------\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"page_number\", ctx.QueryParams(), &params.PageNumber)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter page_number: %s\", err))\n\t}\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetUsers(ctx, params)\n\treturn err\n}", "func (u *UserCtr) GetUserAll(c *gin.Context) {\n\tusers, err := model.UserAll(u.DB)\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\tif len(users) == 0 {\n\t\tc.JSON(http.StatusOK, make([]*model.User, 0))\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"result\": users,\n\t})\n\treturn\n}", "func (client MeshNetworkClient) ListSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (a *UserApiService) GetUserFollowersExecute(r UserApiGetUserFollowersRequest) ([]User, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue []User\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"UserApiService.GetUserFollowers\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/users/{username}/followers\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"username\"+\"}\", url.PathEscape(parameterValueToString(r.username, \"username\")), -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{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, 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 == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v Error\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *Client) GetAccounts(params *GetAccountsParams) (*GetAccountsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAccountsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getAccounts\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/AccountService/Accounts\",\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: &GetAccountsReader{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.(*GetAccountsOK), nil\n\n}", "func (client InfraRoleInstancesClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n}", "func (client RecommendedElasticPoolsClient) GetDatabasesSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req)\n}", "func (service *ContrailService) GetUser(ctx context.Context, request *models.GetUserRequest) (response *models.GetUserResponse, err error) {\n\tspec := &models.ListSpec{\n\t\tLimit: 1,\n\t\tFilters: []*models.Filter{\n\t\t\t&models.Filter{\n\t\t\t\tKey: \"uuid\",\n\t\t\t\tValues: []string{request.ID},\n\t\t\t},\n\t\t},\n\t}\n\tlistRequest := &models.ListUserRequest{\n\t\tSpec: spec,\n\t}\n\tvar result *models.ListUserResponse\n\tif err := common.DoInTransaction(\n\t\tservice.DB,\n\t\tfunc(tx *sql.Tx) error {\n\t\t\tresult, err = db.ListUser(ctx, tx, listRequest)\n\t\t\treturn err\n\t\t}); err != nil {\n\t\treturn nil, common.ErrorInternal\n\t}\n\tif len(result.Users) == 0 {\n\t\treturn nil, common.ErrorNotFound\n\t}\n\tresponse = &models.GetUserResponse{\n\t\tUser: result.Users[0],\n\t}\n\treturn response, nil\n}", "func GetAllAccounts(w http.ResponseWriter, r *http.Request) {\n\t// Fetch the accounts.\n\n\tgetAccountsInput, err := parseGetAccountsInput(r)\n\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteRequestValidationError(w, fmt.Sprintf(\"Error parsing query params\"))\n\t\treturn\n\t}\n\n\tresult, err := Dao.GetAccounts(getAccountsInput)\n\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteServerError(w)\n\t\treturn\n\t}\n\n\t// Serialize them for the JSON response.\n\taccountResponses := []*response.AccountResponse{}\n\n\tfor _, a := range result.Results {\n\t\tacctRes := response.AccountResponse(*a)\n\t\taccountResponses = append(accountResponses, &acctRes)\n\t}\n\n\t// If the DB result has next keys, then the URL to retrieve the next page is put into the Link header.\n\tif len(result.NextKeys) > 0 {\n\t\tnextURL := response.BuildNextURL(r, result.NextKeys, baseRequest)\n\t\tw.Header().Add(\"Link\", fmt.Sprintf(\"<%s>; rel=\\\"next\\\"\", nextURL.String()))\n\t}\n\n\terr = json.NewEncoder(w).Encode(accountResponses)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteServerError(w)\n\t}\n}", "func (a *FundsApiService) GetUserWalletFunds(ctx context.Context, xAuthUserID string) (InlineResponse20019, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/users/wallets/funds\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\tif strlen(xAuthUserID) > 32 {\n\t\treturn localVarReturnValue, nil, reportError(\"xAuthUserID must have less than 32 elements\")\n\t}\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\tlocalVarHeaderParams[\"X-Auth-User-ID\"] = parameterToString(xAuthUserID, \"\")\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\tif err == nil { \n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 502 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 503 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 504 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (client ServicesClient) ListSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client ModelClient) GetClosedListSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ServicesClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func GetAllAccountsAPI(w http.ResponseWriter, req *http.Request) {\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"GetAllAccount\", \"Account\", \"_\", \"_\", \"_\", 0}\n\n\tAdminobj := admin.Admin{}\n\tdecoder := json.NewDecoder(req.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&Adminobj)\n\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request \")\n\t\tglobalPkg.WriteLog(logobj, \"failed to decode admin object\", \"failed\")\n\t\treturn\n\t}\n\t// if Adminobj.AdminUsername == globalPkg.AdminObj.AdminUsername && Adminobj.AdminPassword == globalPkg.AdminObj.AdminPassword {\n\tif admin.ValidationAdmin(Adminobj) {\n\t\tjsonObj, _ := json.Marshal(accountdb.GetAllAccounts())\n\t\tglobalPkg.SendResponse(w, jsonObj)\n\t\tglobalPkg.WriteLog(logobj, \"get all accounts\", \"success\")\n\t} else {\n\n\t\tglobalPkg.SendError(w, \"you are not the admin \")\n\t\tglobalPkg.WriteLog(logobj, \"you are not the admin to get all accounts \", \"failed\")\n\t}\n}", "func (client ConversationsClient) GetConversationMembersMethodSender(req *http.Request) (*http.Response, error) {\n sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n return autorest.SendWithSender(client, req, sd...)\n }", "func (client BaseClient) GetAllOperationsSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func (client FeatureStateClient) GetStatesSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func (client AppsClient) ListDomainsSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func GetAllUser(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(\"Context-Type\", \"application/x-www-form-urlencoded\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t// get all the users in the db\n\tusers, err := database.GetAllUsers()\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to get all user. %v\", err)\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\t// send all the users as response\n\terr = json.NewEncoder(w).Encode(&models.UserList{Users: users})\n\tif err != nil {\n\t\tlogrus.Errorf(err.Error())\n\t\treturn\n\t}\n}", "func (client JobClient) ListByAccountSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, azure.DoRetryWithRegistration(client.Client))\n }", "func hGetUsers(c echo.Context) error {\n\tvar e httpError\n\t// read from token user id\n\tvar tokenUserID int64\n\ttokenUserID = 2\n\n\tusers, errGetUsers := blog.GetAllUsers(tokenUserID, 50)\n\tif errGetUsers != nil {\n\t\te.TheError = errGetUsers.Error()\n\t\treturn c.JSON(http.StatusInternalServerError, e)\n\t}\n\treturn c.JSON(http.StatusOK, users)\n}", "func (hc *Client) GetAccounts() ([]Account, error) {\n\tvar (\n\t\tresult AccountResponse\n\t)\n\tendpoint := fmt.Sprintf(\"%s/v1/account/accounts\", huobiEndpoint)\n\tres, err := hc.sendRequest(\n\t\thttp.MethodGet,\n\t\tendpoint,\n\t\tmap[string]string{},\n\t\ttrue,\n\t)\n\tif err != nil {\n\t\treturn result.Data, err\n\t}\n\terr = json.Unmarshal(res, &result)\n\tif result.Status != StatusOK.String() {\n\t\treturn result.Data, fmt.Errorf(\"received unexpect status: err=%s code=%s msg=%s\",\n\t\t\tresult.Status,\n\t\t\tresult.ErrorCode,\n\t\t\tresult.ErrorMessage)\n\t}\n\treturn result.Data, err\n}", "func (client GroupClient) ListAssembliesSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client,\n\t\treq,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ApplicationsClient) ListOwnersSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client RosettaNetProcessConfigurationsClient) ListByIntegrationAccountsSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (a UsersApi) GetUsers(pageSize int, pageNumber int, id []string, jabberId []string, sortOrder string, expand []string, integrationPresenceSource string, state string) (*Userentitylisting, *APIResponse, error) {\n\tvar httpMethod = \"GET\"\n\t// create path and map variables\n\tpath := a.Configuration.BasePath + \"/api/v2/users\"\n\tdefaultReturn := new(Userentitylisting)\n\tif true == false {\n\t\treturn defaultReturn, nil, errors.New(\"This message brought to you by the laws of physics being broken\")\n\t}\n\n\n\theaderParams := make(map[string]string)\n\tqueryParams := make(map[string]string)\n\tformParams := url.Values{}\n\tvar postBody interface{}\n\tvar postFileName string\n\tvar fileBytes []byte\n\t// authentication (PureCloud OAuth) required\n\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\t\n\tqueryParams[\"pageSize\"] = a.Configuration.APIClient.ParameterToString(pageSize, \"\")\n\t\n\tqueryParams[\"pageNumber\"] = a.Configuration.APIClient.ParameterToString(pageNumber, \"\")\n\t\n\tqueryParams[\"id\"] = a.Configuration.APIClient.ParameterToString(id, \"multi\")\n\t\n\tqueryParams[\"jabberId\"] = a.Configuration.APIClient.ParameterToString(jabberId, \"multi\")\n\t\n\tqueryParams[\"sortOrder\"] = a.Configuration.APIClient.ParameterToString(sortOrder, \"\")\n\t\n\tqueryParams[\"expand\"] = a.Configuration.APIClient.ParameterToString(expand, \"multi\")\n\t\n\tqueryParams[\"integrationPresenceSource\"] = a.Configuration.APIClient.ParameterToString(integrationPresenceSource, \"\")\n\t\n\tqueryParams[\"state\"] = a.Configuration.APIClient.ParameterToString(state, \"\")\n\t\n\n\t// Find an replace keys that were altered to avoid clashes with go keywords \n\tcorrectedQueryParams := make(map[string]string)\n\tfor k, v := range queryParams {\n\t\tif k == \"varType\" {\n\t\t\tcorrectedQueryParams[\"type\"] = v\n\t\t\tcontinue\n\t\t}\n\t\tcorrectedQueryParams[k] = v\n\t}\n\tqueryParams = correctedQueryParams\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\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\tvar successPayload *Userentitylisting\n\tresponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, postFileName, fileBytes)\n\tif err != nil {\n\t\t// Nothing special to do here, but do avoid processing the response\n\t} else if err == nil && response.Error != nil {\n\t\terr = errors.New(response.ErrorMessage)\n\t} else if response.HasBody {\n\t\tif \"Userentitylisting\" == \"string\" {\n\t\t\tcopy(response.RawBody, &successPayload)\n\t\t} else {\n\t\t\terr = json.Unmarshal(response.RawBody, &successPayload)\n\t\t}\n\t}\n\treturn successPayload, response, err\n}", "func GetUser(c *context.Context) {\n\ta, _ := auth.GetCurrentTokenData(c)\n\n\turl := fmt.Sprintf(\"%s/users/show.json?source=%s&uid=%s&access_token=%s\",\n\t\tWEIBOSERVER, auth.APPKEY, a.UID, a.AccessToken)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tc.WriteJson(500, \"无法联系新浪服务器\")\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tc.WriteBody(resp.StatusCode, body)\n}", "func (client BaseClient) GetSystemsSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client InfraRoleInstancesClient) ListSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n}", "func (client BaseClient) GetFeaturesSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client Client) ListSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req)\n}", "func (client ViewsClient) ListSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (r ListAccountsRequest) Send(ctx context.Context) (*ListAccountsResponse, 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 := &ListAccountsResponse{\n\t\tListAccountsOutput: r.Request.Data.(*ListAccountsOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (s *AutograderService) GetUsers(ctx context.Context, in *pb.Void) (*pb.Users, error) {\n\tusr, err := s.getCurrentUser(ctx)\n\tif err != nil {\n\t\ts.logger.Errorf(\"GetUsers failed: authentication error: %w\", err)\n\t\treturn nil, ErrInvalidUserInfo\n\t}\n\tif !usr.IsAdmin {\n\t\ts.logger.Error(\"GetUsers failed: user is not admin\")\n\t\treturn nil, status.Errorf(codes.PermissionDenied, \"only admin can access other users\")\n\t}\n\tusrs, err := s.getUsers()\n\tif err != nil {\n\t\ts.logger.Errorf(\"GetUsers failed: %w\", err)\n\t\treturn nil, status.Errorf(codes.NotFound, \"failed to get users\")\n\t}\n\treturn usrs, nil\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 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 (client ThreatIntelligenceIndicatorClient) GetSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (a *WebhooksApiService) TeamsUsernameHooksGet(ctx context.Context, username string) (PaginatedWebhookSubscriptions, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PaginatedWebhookSubscriptions\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/teams/{username}/hooks\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"username\"+\"}\", fmt.Sprintf(\"%v\", username), -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\"}\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\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[\"Authorization\"] = key\n\t\t\t\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\tif err == nil { \n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v PaginatedWebhookSubscriptions\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (a *ApiDB) GetUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tvars := mux.Vars(r)\n\tId, err := strconv.Atoi(vars[\"Id\"])\n\t//have not id --> get all\n\tif err != nil {\n\t\tId = -1\n\t}\n\tList := BUSINESS.GetUsers(a.Db, Id)\n\tjsonlist, _ := json.Marshal(List)\n\tresult := List[0]\n\n\tstringresult := `{\"message\": \"Get Users success\",\"status\": 200,\"data\":{\"user\":`\n\tif len(List) == 1 {\n\t\tjsonresult, _ := json.Marshal(result)\n\t\tstringresult += string(jsonresult)\n\t} else {\n\t\tstringresult += string(jsonlist)\n\t}\n\tstringresult += \"}}\"\n\tio.WriteString(w, stringresult)\n}", "func (c *Client) GetUserAll() ([]User, error) {\n\trequest := userGetAllRequest\n\n\tresponse, err := c.QueryHouston(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"GetUserAll Failed\")\n\t}\n\n\treturn response.Data.GetUsers, nil\n}", "func (ctlr *userServiceController) GetUsers(ctx context.Context, req *mygrpc.GetUsersRequest) (*mygrpc.GetUsersResponse, error) {\n\tresultMap := ctlr.userService.GetUsersByIDs(req.GetIds())\n\n\tresp := &mygrpc.GetUsersResponse{}\n\tfor _, u := range resultMap {\n\t\tresp.Users = append(resp.Users, marshalUser(u))\n\t}\n\treturn resp, nil\n}", "func (_UserCrud *UserCrudCaller) GetUserCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _UserCrud.contract.Call(opts, out, \"getUserCount\")\n\treturn *ret0, err\n}" ]
[ "0.654766", "0.59861887", "0.5483136", "0.54178864", "0.5283321", "0.50561607", "0.48996797", "0.4896156", "0.48792005", "0.4762655", "0.47438532", "0.47303778", "0.4710069", "0.47092688", "0.4705149", "0.4693935", "0.46913356", "0.46863338", "0.46803197", "0.46774566", "0.46672595", "0.46401438", "0.46328315", "0.46324146", "0.46279618", "0.46180627", "0.46164343", "0.4596055", "0.45920637", "0.45720568", "0.4556386", "0.45444483", "0.45419446", "0.45322937", "0.4529506", "0.45220777", "0.45063376", "0.4498819", "0.44948465", "0.44945794", "0.44918782", "0.44795448", "0.44708452", "0.44630605", "0.44610816", "0.44607043", "0.44566315", "0.44560847", "0.44476068", "0.44323748", "0.44238323", "0.4420299", "0.4419961", "0.44198084", "0.44107306", "0.44101557", "0.44085178", "0.44050762", "0.4398398", "0.4393341", "0.4392363", "0.43869284", "0.43746796", "0.43718618", "0.43715414", "0.43691674", "0.43666765", "0.43647987", "0.43568677", "0.43563423", "0.4345359", "0.43448344", "0.43442872", "0.4341208", "0.43373108", "0.4335999", "0.43344212", "0.43265817", "0.43257338", "0.43254513", "0.43239346", "0.43154922", "0.4314082", "0.43135872", "0.43090123", "0.43082762", "0.4303918", "0.42999503", "0.42894524", "0.4286641", "0.42863864", "0.42821807", "0.42768452", "0.42763022", "0.42752767", "0.4272502", "0.42670736", "0.4266254", "0.4262067", "0.42610326" ]
0.78607565
0
GetUserLUISAccountsResponder handles the response to the GetUserLUISAccounts request. The method always closes the http.Response Body.
func (client AzureAccountsClient) GetUserLUISAccountsResponder(resp *http.Response) (result ListAzureAccountInfoObject, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AzureAccountsClient) GetUserLUISAccounts(ctx context.Context) (result ListAzureAccountInfoObject, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.GetUserLUISAccounts\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.GetUserLUISAccountsPreparer(ctx)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetUserLUISAccounts\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetUserLUISAccountsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetUserLUISAccounts\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetUserLUISAccountsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"GetUserLUISAccounts\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (client AzureAccountsClient) GetUserLUISAccountsSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ListClient) UsersMethodResponder(resp *http.Response) (result ListUserType, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result.Value),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client *SpatialAnchorsAccountsClient) getHandleResponse(resp *http.Response) (SpatialAnchorsAccountsClientGetResponse, error) {\n\tresult := SpatialAnchorsAccountsClientGetResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.SpatialAnchorsAccount); err != nil {\n\t\treturn SpatialAnchorsAccountsClientGetResponse{}, err\n\t}\n\treturn result, nil\n}", "func getUFADetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tlogger.Info(\"getUFADetails called with UFA number: \" + args[0])\r\n\r\n\tvar outputRecord map[string]string\r\n\tufanumber := args[0] //UFA ufanum\r\n\t//who :=args[1] //Role\r\n\trecBytes, _ := stub.GetState(ufanumber)\r\n\tjson.Unmarshal(recBytes, &outputRecord)\r\n\toutputBytes, _ := json.Marshal(outputRecord)\r\n\tlogger.Info(\"Returning records from getUFADetails \" + string(outputBytes))\r\n\treturn outputBytes, nil\r\n}", "func getUFADetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tlogger.Info(\"getUFADetails called with UFA number: \" + args[0])\n\n\tvar outputRecord map[string]interface{}\n\tufanumber := args[0] //UFA ufanum\n\t//who :=args[1] //Role\n\trecBytes, _ := stub.GetState(ufanumber)\n\tjson.Unmarshal(recBytes, &outputRecord)\n\toutputBytes, _ := json.Marshal(outputRecord)\n\tlogger.Info(\"Returning records from getUFADetails \" + string(outputBytes))\n\treturn outputBytes, nil\n}", "func (client *RestorableDatabaseAccountsClient) listHandleResponse(resp *azcore.Response) (RestorableDatabaseAccountsListResponse, error) {\n\tresult := RestorableDatabaseAccountsListResponse{RawResponse: resp.Response}\n\tif err := resp.UnmarshalAsJSON(&result.RestorableDatabaseAccountsListResult); err != nil {\n\t\treturn RestorableDatabaseAccountsListResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client AccountClient) GetResponder(resp *http.Response) (result AccountResourceDescription, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client AzureAccountsClient) GetUserLUISAccountsPreparer(ctx context.Context) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/azureaccounts\"))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *AccountsClient) listHandleResponse(resp *http.Response) (AccountsClientListResponse, error) {\n\tresult := AccountsClientListResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.AccountListResult); err != nil {\n\t\treturn AccountsClientListResponse{}, err\n\t}\n\treturn result, nil\n}", "func (w *ServerInterfaceWrapper) GetAccounts(ctx echo.Context) error {\n\tvar err error\n\n\tctx.Set(ApiKeyAuthScopes, []string{\"\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetAccounts(ctx)\n\treturn err\n}", "func UnmarshalListAccountsResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(ListAccountsResponse)\n\terr = core.UnmarshalPrimitive(m, \"rows_count\", &obj.RowsCount)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"next_url\", &obj.NextURL)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalModel(m, \"resources\", &obj.Resources, UnmarshalAccount)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (c *IloClient) GetUserAccountsDell() ([]Accounts, error) {\n\n\turl := c.Hostname + \"/redfish/v1/Managers/iDRAC.Embedded.1/Accounts\"\n\n\tresp, _, _, err := queryData(c, \"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar x MemberCountDell\n\tvar users []Accounts\n\n\tjson.Unmarshal(resp, &x)\n\n\tfor i := range x.Members {\n\t\t_url := c.Hostname + x.Members[i].OdataId\n\t\tresp, _, _, err := queryData(c, \"GET\", _url, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar y AccountsInfoDell\n\n\t\tjson.Unmarshal(resp, &y)\n\n\t\tuser := Accounts{\n\t\t\tName: y.Name,\n\t\t\tEnabled: y.Enabled,\n\t\t\tLocked: y.Locked,\n\t\t\tRoleId: y.RoleID,\n\t\t\tUsername: y.UserName,\n\t\t}\n\t\tusers = append(users, user)\n\n\t}\n\n\treturn users, nil\n\n}", "func (o *GetHiddenUsersV3Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetHiddenUsersV3OK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetHiddenUsersV3BadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewGetHiddenUsersV3Unauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 403:\n\t\tresult := NewGetHiddenUsersV3Forbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetHiddenUsersV3NotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewGetHiddenUsersV3InternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested GET /leaderboard/v3/admin/namespaces/{namespace}/leaderboards/{leaderboardCode}/users/hidden returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (client *AccountsClient) getHandleResponse(resp *http.Response) (AccountsClientGetResponse, error) {\n\tresult := AccountsClientGetResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.Account); err != nil {\n\t\treturn AccountsClientGetResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client ApplicationsClient) ListOwnersResponder(resp *http.Response) (result DirectoryObjectListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client *Client) GetUserInfos(allDomains bool, domainName string) ([]UserFullDataWrapper, error) {\n\tquery, _ := json.Marshal(InfoListData{\n\t\tAllDomains: allDomains,\n\t\tDomainName: domainName,\n\t})\n\n\tresRaw, err := client.ListClients([]byte(query))\n\tif err != nil {\n\t\treturn []UserFullDataWrapper{}, err\n\t}\n\n\tresUnmarshaled := []UserFullDataWrapper{}\n\tif err := json.Unmarshal(resRaw, &resUnmarshaled); err != nil {\n\t\treturn []UserFullDataWrapper{}, err\n\t}\n\n\treturn resUnmarshaled, err\n}", "func (client *NotebookWorkspacesClient) listByDatabaseAccountHandleResponse(resp *http.Response) (NotebookWorkspacesListByDatabaseAccountResponse, error) {\n\tresult := NotebookWorkspacesListByDatabaseAccountResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.NotebookWorkspaceListResult); err != nil {\n\t\treturn NotebookWorkspacesListByDatabaseAccountResponse{}, runtime.NewResponseError(err, resp)\n\t}\n\treturn result, nil\n}", "func (client ConversationsClient) GetConversationMembersMethodResponder(resp *http.Response) (result ListChannelAccountType, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result.Value),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func decodeGetResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\treturn nil, errors.New(\"'Users' Decoder is not impelemented\")\n}", "func (c AccountFiltersClient) responderForAccountFiltersList(resp *http.Response) (result AccountFiltersListOperationResponse, err error) {\n\ttype page struct {\n\t\tValues []AccountFilter `json:\"value\"`\n\t\tNextLink *string `json:\"@odata.nextLink\"`\n\t}\n\tvar respObj page\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&respObj),\n\t\tautorest.ByClosing())\n\tresult.HttpResponse = resp\n\tresult.Model = &respObj.Values\n\tresult.nextLink = respObj.NextLink\n\tif respObj.NextLink != nil {\n\t\tresult.nextPageFunc = func(ctx context.Context, nextLink string) (result AccountFiltersListOperationResponse, err error) {\n\t\t\treq, err := c.preparerForAccountFiltersListWithNextLink(ctx, nextLink)\n\t\t\tif err != nil {\n\t\t\t\terr = autorest.NewErrorWithError(err, \"accountfilters.AccountFiltersClient\", \"AccountFiltersList\", nil, \"Failure preparing request\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresult.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client))\n\t\t\tif err != nil {\n\t\t\t\terr = autorest.NewErrorWithError(err, \"accountfilters.AccountFiltersClient\", \"AccountFiltersList\", result.HttpResponse, \"Failure sending request\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresult, err = c.responderForAccountFiltersList(result.HttpResponse)\n\t\t\tif err != nil {\n\t\t\t\terr = autorest.NewErrorWithError(err, \"accountfilters.AccountFiltersClient\", \"AccountFiltersList\", result.HttpResponse, \"Failure responding to request\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (client RosettaNetProcessConfigurationsClient) ListByIntegrationAccountsResponder(resp *http.Response) (result IntegrationAccountRosettaNetProcessConfigurationListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\n\t// Add header so that received knows they're receiving JSON\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// Retrieving name of node from query request\n\tnodeName := r.URL.Query().Get(\"name\")\n\tconfirmation, socket := checkNodeName(nodeName)\n\tif confirmation == false {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Node name requested doesn't exist\"})\n\t\treturn\n\t}\n\n\t// Retrieving height from query request\n\trecvHeight := r.URL.Query().Get(\"height\")\n\theight := checkHeight(recvHeight)\n\tif height == -1 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Unexepcted value found, height needs to be string of int!\"})\n\t\treturn\n\t}\n\n\t// Attempt to load connection with staking client\n\tconnection, so := loadStakingClient(socket)\n\n\t// Close connection once code underneath executes\n\tdefer connection.Close()\n\n\t// If null object was retrieved send response\n\tif so == nil {\n\n\t\t// Stop code here faild to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to establish connection using socket : \" + socket})\n\t\treturn\n\t}\n\n\t// Return accounts from staking client\n\taccounts, err := so.Addresses(context.Background(), height)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to get Accounts!\"})\n\t\tlgr.Error.Println(\n\t\t\t\"Request at /api/staking/accounts failed to retrieve Accounts : \",\n\t\t\terr)\n\t\treturn\n\t}\n\n\t// Respond with array of all accounts\n\tlgr.Info.Println(\"Request at /api/staking/accounts responding with \" +\n\t\t\"Accounts!\")\n\tjson.NewEncoder(w).Encode(responses.AllAccountsResponse{AllAccounts: accounts})\n}", "func (client *SpatialAnchorsAccountsClient) listKeysHandleResponse(resp *http.Response) (SpatialAnchorsAccountsClientListKeysResponse, error) {\n\tresult := SpatialAnchorsAccountsClientListKeysResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.AccountKeys); err != nil {\n\t\treturn SpatialAnchorsAccountsClientListKeysResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client ConversationsClient) GetConversationsMethodResponder(resp *http.Response) (result ConversationsResultType, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (ur *UserResource) handleGetUsers(c *gin.Context) {\n\tusers, err := ur.Store.GetAllUsers()\n\tif err != nil {\n\t\tlogging.Logger.Errorln(\"[API] Failed to get all users\", err)\n\t}\n\n\tc.JSON(http.StatusOK, users)\n}", "func (h *HTTPClientHandler) getAllUsersHandler(w http.ResponseWriter, r *http.Request) {\n\n\tuserid, _ := r.URL.Query()[\"q\"]\n\t// looking for specific user\n\tif len(userid) > 0 {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"userid\": userid[0],\n\t\t}).Info(\"Looking for user..\")\n\n\t\tuser, err := h.db.getUser(userid[0])\n\n\t\tif err == nil {\n\t\t\t// Marshal provided interface into JSON structure\n\t\t\tresponse := UserResource{Data: user}\n\t\t\tuj, _ := json.Marshal(response)\n\n\t\t\t// Write content-type, statuscode, payload\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(200)\n\t\t\tfmt.Fprintf(w, \"%s\", uj)\n\t\t\treturn\n\t\t} else {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t}).Warn(\"Failed to insert..\")\n\n\t\t\tcontent, code := responseDetailsFromMongoError(err)\n\n\t\t\t// Marshal provided interface into JSON structure\n\t\t\tuj, _ := json.Marshal(content)\n\n\t\t\t// Write content-type, statuscode, payload\n\t\t\twriteJsonResponse(w, &uj, code)\n\t\t\treturn\n\n\t\t}\n\t}\n\n\tlog.Warn(len(userid))\n\t// displaying all users\n\tresults, err := h.db.getUsers()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Error(\"Got error when tried to get all users\")\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"count\": len(results),\n\t}).Info(\"number of users\")\n\n\t// Marshal provided interface into JSON structure\n\tresponse := UsersResource{Data: results}\n\tuj, _ := json.Marshal(response)\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 (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 (client KqlScriptsClient) GetAllResponder(resp *http.Response) (result KqlScriptsResourceCollectionResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client SmartGroupsClient) GetAllResponder(resp *http.Response) (result SmartGroupsList, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client ExternalBillingAccountClient) ListResponder(resp *http.Response) (result ExternalBillingAccountDefinitionListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func GetAllAccounts(w http.ResponseWriter, r *http.Request) {\n\t// Fetch the accounts.\n\n\tgetAccountsInput, err := parseGetAccountsInput(r)\n\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteRequestValidationError(w, fmt.Sprintf(\"Error parsing query params\"))\n\t\treturn\n\t}\n\n\tresult, err := Dao.GetAccounts(getAccountsInput)\n\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteServerError(w)\n\t\treturn\n\t}\n\n\t// Serialize them for the JSON response.\n\taccountResponses := []*response.AccountResponse{}\n\n\tfor _, a := range result.Results {\n\t\tacctRes := response.AccountResponse(*a)\n\t\taccountResponses = append(accountResponses, &acctRes)\n\t}\n\n\t// If the DB result has next keys, then the URL to retrieve the next page is put into the Link header.\n\tif len(result.NextKeys) > 0 {\n\t\tnextURL := response.BuildNextURL(r, result.NextKeys, baseRequest)\n\t\tw.Header().Add(\"Link\", fmt.Sprintf(\"<%s>; rel=\\\"next\\\"\", nextURL.String()))\n\t}\n\n\terr = json.NewEncoder(w).Encode(accountResponses)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteServerError(w)\n\t}\n}", "func (client GroupClient) ListAssembliesResponder(resp *http.Response) (result USQLAssemblyList, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (svc *Service) getAllUsersHandler(w http.ResponseWriter, r *http.Request) error {\n\t// TODO: Check errors in encoding\n\n\tusers, err := svc.invitationsAPI.GetAllUsers(svc.invitationsSource.GetAllPeople)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.NewEncoder(w).Encode(users)\n}", "func (h *GetUsersHandlerImpl) Handle(params user.GetUsersParams, principal interface{}) middleware.Responder {\n\tt := \"\"\n\tif params.TransactionID != nil {\n\t\tt = *params.TransactionID\n\t}\n\tconfiguration, err := h.Client.Configuration()\n\tif err != nil {\n\t\te := misc.HandleError(err)\n\t\treturn user.NewGetUsersDefault(int(*e.Code)).WithPayload(e)\n\t}\n\t_, userlist, err := configuration.GetUserList(params.Userlist, t)\n\tif userlist == nil {\n\t\treturn user.NewGetUserNotFound()\n\t}\n\tif err != nil {\n\t\treturn user.NewGetUserNotFound()\n\t}\n\tv, users, err := configuration.GetUsers(params.Userlist, t)\n\tif err != nil {\n\t\te := misc.HandleContainerGetError(err)\n\t\tif *e.Code == misc.ErrHTTPOk {\n\t\t\treturn user.NewGetUsersOK().WithPayload(&user.GetUsersOKBody{Version: v, Data: models.Users{}})\n\t\t}\n\t\treturn user.NewGetUsersDefault(int(*e.Code)).WithPayload(e)\n\t}\n\treturn user.NewGetUsersOK().WithPayload(&user.GetUsersOKBody{Version: v, Data: users})\n}", "func (client *KeyVaultClient) getStorageAccountsHandleResponse(resp *http.Response) (KeyVaultClientGetStorageAccountsResponse, error) {\n\tresult := KeyVaultClientGetStorageAccountsResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.StorageListResult); err != nil {\n\t\treturn KeyVaultClientGetStorageAccountsResponse{}, err\n\t}\n\treturn result, nil\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\tdb, erro := database.Connect()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tdefer db.Close()\n\trepository := repositories.NewAccountRepository(db)\n\taccounts, erro := repository.FindAll()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, accounts)\n}", "func AccountsHandler(w http.ResponseWriter, r *http.Request) {\n\tdatabase.GetConnection()\n\tdefer database.DBCon.Close(context.Background())\n\n\tq := \"select owner, balance, currency, created_at from accounts\"\n\n\trows, err := database.DBCon.Query(context.Background(), q)\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Query failed: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\taccounts := []models.Account{}\n\n\t// rows.Next() returns true if there is an actual row\n\t//(everytime is called, we will get the next row when calling rows.Scan())\n\tfor i := 0; rows.Next(); i++ {\n\t\tvar acc models.Account\n\n\t\t// Assing the current row to the Account struct\n\t\trows.Scan(&acc.Owner, &acc.Balance, &acc.Currency, &acc.CreatedAt)\n\t\taccounts = append(accounts, acc)\n\t}\n\n\t// Convert the slice of accounts into JSON format\n\tresponse, err := json.Marshal(accounts)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"content-type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\t// Send the response to the client\n\tw.Write(response)\n}", "func (api *API) getUsersHandler() service.Handler {\n\treturn func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\t\tusers, err := user.LoadAll(ctx, api.mustDB(), user.LoadOptions.WithOrganization)\n\t\tif err != nil {\n\t\t\treturn sdk.WrapError(err, \"cannot load user from db\")\n\t\t}\n\t\treturn service.WriteJSON(w, users, http.StatusOK)\n\t}\n}", "func ViewUsers(w http.ResponseWriter, r *http.Request) error {\n if r.Method == \"GET\" {\n myUid, err0 := GetMyUserId(r)\n if err0 != nil {\n return err0\n }\n ctx1, _ := context.WithTimeout(context.Background(), constant.ContextTimeoutDuration)\n response, err := BackendClientIns.FindAllUsers(ctx1, &FindAllUsersRequest{})\n if err != nil {\n return err\n }\n allUsers := response.Users\n newUserList := make([]user, 0)\n for _, value := range allUsers {\n if value.UserId == myUid { // Exclude myself\n continue\n }\n ctx, _ := context.WithTimeout(context.Background(), constant.ContextTimeoutDuration)\n responseFromWhetherFollowing, _ := BackendClientIns.UserCheckWhetherFollowing(ctx,\n &UserCheckWhetherFollowingRequest{\n SourceUserId: myUid,\n TargetUserId: value.UserId,\n })\n newUserList = append(newUserList, user{Name: value.UserName,\n Followed: responseFromWhetherFollowing.Ok,\n Id: strconv.Itoa(int(value.UserId))})\n }\n view := viewUserView{\n UserList: newUserList,\n }\n log.Println(view.UserList)\n t, _ := template.ParseFiles(constant.RelativePathForTemplate + \"users.html\")\n w.Header().Set(\"Content-Type\", \"text/html\")\n t.Execute(w, view)\n }\n return nil\n}", "func (client *WebAppsClient) listDomainOwnershipIdentifiersHandleResponse(resp *http.Response) (WebAppsListDomainOwnershipIdentifiersResponse, error) {\n\tresult := WebAppsListDomainOwnershipIdentifiersResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.IdentifierCollection); err != nil {\n\t\treturn WebAppsListDomainOwnershipIdentifiersResponse{}, runtime.NewResponseError(err, resp)\n\t}\n\treturn result, nil\n}", "func (a *BankAccountApiService) BankAccountsGet(ctx _context.Context, authorization string) (AllBankAccountResponse, *_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 AllBankAccountResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/bank-accounts\"\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\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(authorization, \"\")\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 (client IdentityClient) GetUser(ctx context.Context, request GetUserRequest) (response GetUserResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.getUser, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = GetUserResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = GetUserResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(GetUserResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into GetUserResponse\")\n\t}\n\treturn\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 (client *WebAppsClient) listDomainOwnershipIdentifiersSlotHandleResponse(resp *http.Response) (WebAppsListDomainOwnershipIdentifiersSlotResponse, error) {\n\tresult := WebAppsListDomainOwnershipIdentifiersSlotResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.IdentifierCollection); err != nil {\n\t\treturn WebAppsListDomainOwnershipIdentifiersSlotResponse{}, runtime.NewResponseError(err, resp)\n\t}\n\treturn result, nil\n}", "func (o *GetUsersByUserNameAndDomainUsingGETReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetUsersByUserNameAndDomainUsingGETOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewGetUsersByUserNameAndDomainUsingGETUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewGetUsersByUserNameAndDomainUsingGETForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewGetUsersByUserNameAndDomainUsingGETNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetUsersUserIDAcesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetUsersUserIDAcesOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetUsersUserIDAcesBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 401:\n\t\tresult := NewGetUsersUserIDAcesUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewGetUsersUserIDAcesForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewGetUsersUserIDAcesNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 409:\n\t\tresult := NewGetUsersUserIDAcesConflict()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 429:\n\t\tresult := NewGetUsersUserIDAcesTooManyRequests()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewGetUsersUserIDAcesInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 503:\n\t\tresult := NewGetUsersUserIDAcesServiceUnavailable()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (client *KeyVaultClient) getCertificateContactsHandleResponse(resp *http.Response) (KeyVaultClientGetCertificateContactsResponse, error) {\n\tresult := KeyVaultClientGetCertificateContactsResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.Contacts); err != nil {\n\t\treturn KeyVaultClientGetCertificateContactsResponse{}, err\n\t}\n\treturn result, nil\n}", "func (a *UserApiService) GetUserFollowersExecute(r UserApiGetUserFollowersRequest) ([]User, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue []User\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"UserApiService.GetUserFollowers\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/users/{username}/followers\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"username\"+\"}\", url.PathEscape(parameterValueToString(r.username, \"username\")), -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{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, 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 == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v Error\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\n\tjson.NewEncoder(w).Encode(nil)\n}", "func (client *LocalRulestacksClient) listCountriesHandleResponse(resp *http.Response) (LocalRulestacksClientListCountriesResponse, error) {\n\tresult := LocalRulestacksClientListCountriesResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.CountriesResponse); err != nil {\n\t\treturn LocalRulestacksClientListCountriesResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client CertificateClient) ListByBatchAccountResponder(resp *http.Response) (result ListCertificatesResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (h *getAccountListHandler) Handle(params accounts.GetAccountsListParams) middleware.Responder {\n\tnet, err := ToNetwork(params.Network)\n\tif err != nil {\n\t\treturn accounts.NewGetAccountsListBadRequest()\n\t}\n\tdb, err := h.provider.GetDb(net)\n\tif err != nil {\n\t\treturn accounts.NewGetAccountsListNotFound()\n\t}\n\tservice := services.New(repos.New(db), net)\n\tlimiter := NewLimiter(params.Limit, params.Offset)\n\tbefore := \"\"\n\tif params.AfterID != nil {\n\t\tbefore = *params.AfterID\n\t}\n\taccs, count, err := service.AccountList(before, limiter, params.Favorites)\n\tif err != nil {\n\t\tlog.Errorf(\"failed to get accounts: %s\", err.Error())\n\t\treturn accounts.NewGetAccountsListNotFound()\n\t}\n\treturn accounts.NewGetAccountsListOK().WithPayload(render.Accounts(accs)).WithXTotalCount(count)\n}", "func (client *SpatialAnchorsAccountsClient) updateHandleResponse(resp *http.Response) (SpatialAnchorsAccountsClientUpdateResponse, error) {\n\tresult := SpatialAnchorsAccountsClientUpdateResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.SpatialAnchorsAccount); err != nil {\n\t\treturn SpatialAnchorsAccountsClientUpdateResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client ModelClient) GetClosedListEntityRolesResponder(resp *http.Response) (result ListEntityRole, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func HandleGetUser(r *Request, body *userdef.GetUserRequest) (*userdef.GetUserResponse, error) {\n\tuser := &userdef.User{}\n\tif err := database.Find(user, body.UserId); err != nil {\n\t\treturn nil, oops.WithMessage(err, \"failed to find\")\n\t}\n\n\treturn &userdef.GetUserResponse{\n\t\tUser: user,\n\t}, nil\n}", "func returnUsersAccounts(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar users []User\n\tvar orders []Orders\n\t//fmt.Println(\"Request URI: \", path.Base(r.RequestURI))\n\tusername := path.Base(r.RequestURI)\n\n\t// query for userid\n\tresults, err := db.Query(\"Select * from users where username = ?\", username)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tfor results.Next() {\n\t\tvar user User\n\t\terr := results.Scan(&user.ID, &user.Username)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\n\t\tusers = append(users, user)\n\t\tfmt.Println(\"Userid: \", users[0].ID)\n\t}\n\n\t// query the orders table with userid and return all rows\n\n\t//select orders.id, users.username, stocks.symbol, shares from orders inner join users on orders.user_id = users.id inner join stocks on orders.stock_id = stocks.id\n\tresults, err = db.Query(\"select orders.id, users.username, stocks.symbol, shares from orders inner join users on orders.user_id = users.id inner join stocks on orders.stock_id = stocks.id where orders.user_id = ?\", users[0].ID)\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tfor results.Next() {\n\t\tvar order Orders\n\t\terr = results.Scan(&order.ID, &order.Username, &order.Symbol, &order.Shares)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\torders = append(orders, order)\n\t}\n\tjson.NewEncoder(w).Encode(orders)\n}", "func ParseUserInvitationsGetCollectionResponse(rsp *http.Response) (*UserInvitationsGetCollectionResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer func() { _ = rsp.Body.Close() }()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &UserInvitationsGetCollectionResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest UserInvitationsResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 400:\n\t\tvar dest ErrorResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON400 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 403:\n\t\tvar dest ErrorResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON403 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func (client ConversationsClient) GetActivityMembersMethodResponder(resp *http.Response) (result ListChannelAccountType, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result.Value),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client UsageDetailsClient) ListByBillingAccountResponder(resp *http.Response) (result UsageDetailsListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client *ManagedClustersClient) listClusterUserCredentialsHandleResponse(resp *http.Response) (ManagedClustersClientListClusterUserCredentialsResponse, error) {\n\tresult := ManagedClustersClientListClusterUserCredentialsResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.CredentialResults); err != nil {\n\t\treturn ManagedClustersClientListClusterUserCredentialsResponse{}, err\n\t}\n\treturn result, nil\n}", "func (uh UserHandler) GetAllUsers(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(utils.InfoLog + \"UserHandler:GetAllUsers called\")\n\n\tvar results *[]models.User\n\tresults, err := uh.UserManager.GetUsers(); 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\tjson.NewEncoder(w).Encode(results)\n\tw.WriteHeader(http.StatusOK)\n}", "func (client *AccountsClient) listKeysHandleResponse(resp *http.Response) (AccountsClientListKeysResponse, error) {\n\tresult := AccountsClientListKeysResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.APIKeys); err != nil {\n\t\treturn AccountsClientListKeysResponse{}, err\n\t}\n\treturn result, nil\n}", "func (s *Identity) AccountsGET(w http.ResponseWriter, r *http.Request) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\twriteResponse(s.addresses, w, r)\n}", "func (client AccountClient) ListBySubscriptionResponder(resp *http.Response) (result AccountResourceDescriptionList, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client AzureAccountsClient) GetAssignedResponder(resp *http.Response) (result ListAzureAccountInfoObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client ListManagementImageClient) GetAllImageIdsResponder(resp *http.Response) (result ImageIds, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (a *CardsApiService) GetUserWalletCards(ctx context.Context, maskNumber string, xAuthUserID string) (InlineResponse2003, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse2003\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/users/wallets/cards\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\tif strlen(xAuthUserID) > 32 {\n\t\treturn localVarReturnValue, nil, reportError(\"xAuthUserID must have less than 32 elements\")\n\t}\n\n\tlocalVarQueryParams.Add(\"mask_number\", parameterToString(maskNumber, \"\"))\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\tlocalVarHeaderParams[\"X-Auth-User-ID\"] = parameterToString(xAuthUserID, \"\")\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\tif err == nil {\n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse2003\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 401 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 502 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 503 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 504 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (o *GetEndusersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetEndusersOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetEndusersBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 401:\n\t\tresult := NewGetEndusersUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewGetEndusersForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewGetEndusersNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 405:\n\t\tresult := NewGetEndusersMethodNotAllowed()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 410:\n\t\tresult := NewGetEndusersGone()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewGetEndusersInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 503:\n\t\tresult := NewGetEndusersServiceUnavailable()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (client *ConsumerInvitationsClient) listInvitationsHandleResponse(resp *http.Response) (ConsumerInvitationsClientListInvitationsResponse, error) {\n\tresult := ConsumerInvitationsClientListInvitationsResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.ConsumerInvitationList); err != nil {\n\t\treturn ConsumerInvitationsClientListInvitationsResponse{}, err\n\t}\n\treturn result, nil\n}", "func (h *HUOBIHADAX) GetAccounts() ([]Account, error) {\n\ttype response struct {\n\t\tResponse\n\t\tAccountData []Account `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodGet, huobihadaxAccounts, url.Values{}, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.AccountData, err\n}", "func getNewUFADetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tlogger.Info(\"getUFADetails called with UFA number: \" + args[0])\r\n\tvar ufa map[string]string\r\n\t// outputRecord:= UFADetails{}\r\n\tufanumber := args[0] //UFA ufanum\r\n\t//who :=args[1] //Role\r\n\trecBytes, _ := stub.GetState(ufanumber)\r\n\tjson.Unmarshal(recBytes, &ufa)\r\n\r\n\tlineIds := ufa[\"lineItemsId\"]\r\n\tvar newData []map[string]string\r\n\tjson.Unmarshal([]byte(lineIds), &newData)\r\n\r\n\tfmt.Println(\"line id are:\" + lineIds)\r\n\tvar lineItems []map[string]string\r\n\r\n\tfor _, id := range newData {\r\n\t\tvar dataLine map[string]string = id\r\n\t\tfor key, value := range dataLine {\r\n\t\t\tif key == \"chargeLineId\" {\r\n\t\t\t\tu := make(map[string]string)\r\n\t\t\t\trecBytes, _ := stub.GetState(value)\r\n\t\t\t\tfmt.Println(\"inside getLineItem id is:\" + (value))\r\n\t\t\t\tjson.Unmarshal(recBytes, &u)\r\n\t\t\t\tfmt.Println(u)\r\n\t\t\t\tlineItems = append(lineItems, u)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tsrc_newId, _ := json.Marshal(lineItems)\r\n\r\n\tufa[\"lineItems\"] = ((string)(src_newId))\r\n\r\n\t//fmt.Println(\"inside object: \"+outputRecord.LineItems[0].BuyerTypeOfCharge)\r\n\toutputBytes, _ := json.Marshal(ufa)\r\n\tlogger.Info(\"Returning records from getUFADetails \" + string(outputBytes))\r\n\treturn outputBytes, nil\r\n}", "func (client *AFDOriginsClient) getHandleResponse(resp *http.Response) (AFDOriginsClientGetResponse, error) {\n\tresult := AFDOriginsClientGetResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.AFDOrigin); err != nil {\n\t\treturn AFDOriginsClientGetResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client ExternalBillingAccountClient) GetResponder(resp *http.Response) (result ExternalBillingAccountDefinition, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client ManagementClient) PostUserRequestaudittrailResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func GetnumberAccountsAPI(w http.ResponseWriter, req *http.Request) {\n\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"GetnumberAccountsAPI\", \"Account\", \"_\", \"_\", \"_\", 0}\n\n\tAdminobj := admin.Admin{}\n\n\tdecoder := json.NewDecoder(req.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&Adminobj)\n\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request \")\n\t\tglobalPkg.WriteLog(logobj, \"failed to decode admin object\", \"failed\")\n\t\treturn\n\t}\n\n\tif admin.ValidationAdmin(Adminobj) {\n\t\tdata := map[string]interface{}{\n\t\t\t\"Number_Of_Accounts\": len(accountdb.GetAllAccounts()),\n\t\t}\n\t\tjsonObj, _ := json.Marshal(data)\n\t\tglobalPkg.SendResponse(w, jsonObj)\n\t\tlogobj.OutputData = \"success to get number of accounts\"\n\t\tlogobj.Process = \"success\"\n\t\tglobalPkg.WriteLog(logobj, \"success to get number of accounts\", \"success\")\n\t} else {\n\t\tglobalPkg.SendError(w, \"you are not admin \")\n\t\tglobalPkg.WriteLog(logobj, \"you are not the admin to get all Emails and username \", \"failed\")\n\n\t}\n}", "func (client ManagementClient) PostUserRetrievetokenforuseraccountResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func GetnumAccountsAPI(w http.ResponseWriter, req *http.Request) {\n\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"GetnumberAccountsAPI\", \"Account\", \"_\", \"_\", \"_\", 0}\n\n\t// data := map[string]int{\n\t// \t\"NumberOfAccounts\": len(accountdb.GetAllAccounts()),\n\t// }\n\t// var responsedata globalPkg.StructData\n\t// for key, value := range data {\n\t// \tresponsedata.Name = key\n\t// \tresponsedata.Length = value\n\t// }\n\t// jsonObj, _ := json.Marshal(responsedata)\n\n\tglobalPkg.SendResponseMessage(w, strconv.Itoa(len(accountdb.GetAllAccounts())))\n\tlogobj.OutputData = \"success to get number of accounts\"\n\tlogobj.Process = \"success\"\n\tglobalPkg.WriteLog(logobj, \"success to get number of accounts\", \"success\")\n\n}", "func (client PermissionsClient) ListByBillingAccountResponder(resp *http.Response) (result PermissionsListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client UsageDetailsClient) ListByEnrollmentAccountResponder(resp *http.Response) (result UsageDetailsListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (a *ApiDB) GetUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tvars := mux.Vars(r)\n\tId, err := strconv.Atoi(vars[\"Id\"])\n\t//have not id --> get all\n\tif err != nil {\n\t\tId = -1\n\t}\n\tList := BUSINESS.GetUsers(a.Db, Id)\n\tjsonlist, _ := json.Marshal(List)\n\tresult := List[0]\n\n\tstringresult := `{\"message\": \"Get Users success\",\"status\": 200,\"data\":{\"user\":`\n\tif len(List) == 1 {\n\t\tjsonresult, _ := json.Marshal(result)\n\t\tstringresult += string(jsonresult)\n\t} else {\n\t\tstringresult += string(jsonlist)\n\t}\n\tstringresult += \"}}\"\n\tio.WriteString(w, stringresult)\n}", "func (o *AdminGetUserByUserIDV3Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewAdminGetUserByUserIDV3OK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewAdminGetUserByUserIDV3BadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewAdminGetUserByUserIDV3Unauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 403:\n\t\tresult := NewAdminGetUserByUserIDV3Forbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewAdminGetUserByUserIDV3NotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewAdminGetUserByUserIDV3InternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested GET /iam/v3/admin/namespaces/{namespace}/users/{userId} returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func GetUsersHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tj, status := users.GetAllUsers()\n\tw.WriteHeader(status)\n\tw.Write(j)\n}", "func (client JobClient) ListByAccountResponder(resp *http.Response) (result JobResourceDescriptionList, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func GetUsers(response http.ResponseWriter, request *http.Request) {\n\t//var results TDoc\n\tvar errorResponse = ErrorResponse{\n\t\tCode: http.StatusInternalServerError, Message: \"Internal Server Error.\",\n\t}\n\n\tcollection := Client.Database(\"msdb\").Collection(\"users\")\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tcursor, err := collection.Find(ctx, bson.M{})\n\tvar results []bson.M\n\terr = cursor.All(ctx, &results)\n\n\tdefer cancel()\n\n\tif err != nil {\n\t\terrorResponse.Message = \"Document not found\"\n\t\treturnErrorResponse(response, request, errorResponse)\n\t} else {\n\t\tvar successResponse = SuccessResponse{\n\t\t\tCode: http.StatusOK,\n\t\t\tMessage: \"Success\",\n\t\t\tResponse: results,\n\t\t}\n\n\t\tsuccessJSONResponse, jsonError := json.Marshal(successResponse)\n\n\t\tif jsonError != nil {\n\t\t\treturnErrorResponse(response, request, errorResponse)\n\t\t}\n\t\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\t\tresponse.Write(successJSONResponse)\n\t}\n\n}", "func (a *AllApiService) EnterpriseProxyGetEnterpriseProxyUsers(ctx _context.Context, body EnterpriseProxyGetEnterpriseProxyUsers) ([]EnterpriseProxyGetEnterpriseProxyUsersResultItem, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []EnterpriseProxyGetEnterpriseProxyUsersResultItem\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/enterpriseProxy/getEnterpriseProxyUsers\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v []EnterpriseProxyGetEnterpriseProxyUsersResultItem\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (h IndexOfficeUsersHandler) Handle(params officeuserop.IndexOfficeUsersParams) middleware.Responder {\n\treturn h.AuditableAppContextFromRequestWithErrors(params.HTTPRequest,\n\t\tfunc(appCtx appcontext.AppContext) (middleware.Responder, error) {\n\t\t\t// Here is where NewQueryFilter will be used to create Filters from the 'filter' query param\n\t\t\tqueryFilters := generateQueryFilters(appCtx.Logger(), params.Filter, officeUserFilterConverters)\n\n\t\t\tpagination := h.NewPagination(params.Page, params.PerPage)\n\t\t\tordering := query.NewQueryOrder(params.Sort, params.Order)\n\n\t\t\tqueryAssociations := query.NewQueryAssociationsPreload([]services.QueryAssociation{\n\t\t\t\tquery.NewQueryAssociation(\"User.Roles\"),\n\t\t\t})\n\n\t\t\tvar officeUsers models.OfficeUsers\n\t\t\terr := h.ListFetcher.FetchRecordList(appCtx, &officeUsers, queryFilters, queryAssociations, pagination, ordering)\n\t\t\tif err != nil {\n\t\t\t\treturn handlers.ResponseForError(appCtx.Logger(), err), err\n\t\t\t}\n\n\t\t\ttotalOfficeUsersCount, err := h.ListFetcher.FetchRecordCount(appCtx, &officeUsers, queryFilters)\n\t\t\tif err != nil {\n\t\t\t\treturn handlers.ResponseForError(appCtx.Logger(), err), err\n\t\t\t}\n\n\t\t\tqueriedOfficeUsersCount := len(officeUsers)\n\n\t\t\tpayload := make(adminmessages.OfficeUsers, queriedOfficeUsersCount)\n\n\t\t\tfor i, s := range officeUsers {\n\t\t\t\tpayload[i] = payloadForOfficeUserModel(s)\n\t\t\t}\n\n\t\t\treturn officeuserop.NewIndexOfficeUsersOK().WithContentRange(fmt.Sprintf(\"office users %d-%d/%d\", pagination.Offset(), pagination.Offset()+queriedOfficeUsersCount, totalOfficeUsersCount)).WithPayload(payload), nil\n\t\t})\n}", "func ViewUsers(w http.ResponseWriter, r *http.Request) { \n AuthorizePages(w,r) \n w.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n t, err := template.ParseFiles(\"templates/viewUsers.html\")\n if err != nil {\n fmt.Println(err) // Ugly debug output\n w.WriteHeader(http.StatusInternalServerError) // Proper HTTP response\n return\n }\n \n userId := UserIds{\n UserId: r.FormValue(\"userId\"),\n }\n\n var successMessage string\n var isShow bool \n\n if (userId.UserId != \"\" ) {\n if (dbquery.DeleteManagerUser(\"User\",userId.UserId)){\n isShow = true\n successMessage = \"User Deleted Successfully\"\n }\n }\n\n var userList []helpers.User \n userList = dbquery.GetUserByRole(\"\",\"'User'\")\n t.Execute(w, AllUsersResponse{Users: userList, SuccessMessage: successMessage, IsShow: isShow}) \n}", "func GetAllAccountsAPI(w http.ResponseWriter, req *http.Request) {\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"GetAllAccount\", \"Account\", \"_\", \"_\", \"_\", 0}\n\n\tAdminobj := admin.Admin{}\n\tdecoder := json.NewDecoder(req.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&Adminobj)\n\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request \")\n\t\tglobalPkg.WriteLog(logobj, \"failed to decode admin object\", \"failed\")\n\t\treturn\n\t}\n\t// if Adminobj.AdminUsername == globalPkg.AdminObj.AdminUsername && Adminobj.AdminPassword == globalPkg.AdminObj.AdminPassword {\n\tif admin.ValidationAdmin(Adminobj) {\n\t\tjsonObj, _ := json.Marshal(accountdb.GetAllAccounts())\n\t\tglobalPkg.SendResponse(w, jsonObj)\n\t\tglobalPkg.WriteLog(logobj, \"get all accounts\", \"success\")\n\t} else {\n\n\t\tglobalPkg.SendError(w, \"you are not the admin \")\n\t\tglobalPkg.WriteLog(logobj, \"you are not the admin to get all accounts \", \"failed\")\n\t}\n}", "func GetUsers(clients *common.ClientContainer, handler common.HandlerInterface) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tusers, err := handler.GetUsers(clients)\n\t\tif err != nil {\n\t\t\tlog.Logger.Error(err)\n\t\t\tcommon.WriteErrorToResponse(w, http.StatusInternalServerError,\n\t\t\t\thttp.StatusText(http.StatusInternalServerError),\n\t\t\t\t\"Internal server error occured\")\n\t\t\treturn\n\t\t}\n\t\tw.Write(users)\n\t}\n}", "func (client MSIXPackagesClient) GetResponder(resp *http.Response) (result MSIXPackage, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client ImageGroupClient) BMethodResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func (o *GetVcenterAccountsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetVcenterAccountsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetVcenterAccountsBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewGetVcenterAccountsNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewGetVcenterAccountsInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (a *IAMApiService) GetResourceUserActions(ctx context.Context, rid string, uid string) (InlineResponse200, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse200\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/acs/api/v1/acls/{rid}/users/{uid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"rid\"+\"}\", fmt.Sprintf(\"%v\", rid), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uid\"+\"}\", fmt.Sprintf(\"%v\", uid), -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{}\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\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse200\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 0 {\n\t\t\tvar v IamError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (r apiGetUserRolesRequest) Execute() (models.UserRolesResponse, *_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 models.UserRolesResponse\n\t)\n\n\tlocalBasePath, err := r.client.cfg.ServerURLWithContext(r.ctx, \"UsersApiService.GetUserRoles\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/1/users/{id}/roles\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", _neturl.QueryEscape(parameterToString(r.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\", \"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := r.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v models.UserRolesResponse\n\t\t\terr = r.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v models.Status\n\t\t\terr = r.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v models.Status\n\t\t\terr = r.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v models.Status\n\t\t\terr = r.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v models.Status\n\t\t\terr = r.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 = r.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 (client OperationsClient) responder(resp *http.Response) (result *ListKeyResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\treturn\n}", "func (client *KeyVaultClient) getCertificateIssuersHandleResponse(resp *http.Response) (KeyVaultClientGetCertificateIssuersResponse, error) {\n\tresult := KeyVaultClientGetCertificateIssuersResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.CertificateIssuerListResult); err != nil {\n\t\treturn KeyVaultClientGetCertificateIssuersResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client *AccountsClient) listModelsHandleResponse(resp *http.Response) (AccountsClientListModelsResponse, error) {\n\tresult := AccountsClientListModelsResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.AccountModelListResult); err != nil {\n\t\treturn AccountsClientListModelsResponse{}, err\n\t}\n\treturn result, nil\n}", "func (a *IAMApiService) GetUser(ctx context.Context, uid string) (IamUser, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IamUser\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/acs/api/v1/users/{uid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uid\"+\"}\", fmt.Sprintf(\"%v\", uid), -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{}\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\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v IamUser\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 0 {\n\t\t\tvar v IamError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (client *ConsumerInvitationsClient) getHandleResponse(resp *http.Response) (ConsumerInvitationsClientGetResponse, error) {\n\tresult := ConsumerInvitationsClientGetResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.ConsumerInvitation); err != nil {\n\t\treturn ConsumerInvitationsClientGetResponse{}, err\n\t}\n\treturn result, nil\n}" ]
[ "0.58462214", "0.5820445", "0.5711745", "0.50926214", "0.50854033", "0.50818324", "0.50647587", "0.5046757", "0.49768388", "0.4864818", "0.48228797", "0.48117575", "0.47768277", "0.47753862", "0.47753218", "0.47416285", "0.47392237", "0.47276378", "0.4708147", "0.4688189", "0.46671736", "0.46576297", "0.46513927", "0.45870772", "0.45856726", "0.45715743", "0.45688868", "0.45634282", "0.45526737", "0.45523608", "0.45509985", "0.45366958", "0.45362976", "0.4535139", "0.45348212", "0.45271304", "0.45153555", "0.45144174", "0.44943392", "0.44881", "0.44860706", "0.44801483", "0.44702572", "0.44685638", "0.44484437", "0.44431886", "0.44412875", "0.44394764", "0.4437345", "0.44332677", "0.4431676", "0.443126", "0.44278488", "0.4423223", "0.44173205", "0.44125286", "0.44120038", "0.44089344", "0.44067544", "0.4398827", "0.4395564", "0.43806657", "0.43763828", "0.43747708", "0.43722454", "0.43570483", "0.43544343", "0.43467942", "0.43437085", "0.4336751", "0.43341944", "0.43325782", "0.43312916", "0.43298033", "0.43278554", "0.4324993", "0.43239188", "0.43171987", "0.43170658", "0.4313382", "0.43034765", "0.43000215", "0.42996663", "0.4299411", "0.42981258", "0.42980498", "0.42963138", "0.42946905", "0.4292221", "0.4291991", "0.42909345", "0.42896166", "0.428758", "0.42874646", "0.42836478", "0.42830077", "0.42817205", "0.4277602", "0.4275989", "0.42733565" ]
0.8018874
0
RemoveFromApp removes assigned azure account from the application. Parameters: appID the application ID. azureAccountInfoObject the azure account information object.
func (client AzureAccountsClient) RemoveFromApp(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (result OperationStatus, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/AzureAccountsClient.RemoveFromApp") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: azureAccountInfoObject, Constraints: []validation.Constraint{{Target: "azureAccountInfoObject", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "azureAccountInfoObject.AzureSubscriptionID", Name: validation.Null, Rule: true, Chain: nil}, {Target: "azureAccountInfoObject.ResourceGroup", Name: validation.Null, Rule: true, Chain: nil}, {Target: "azureAccountInfoObject.AccountName", Name: validation.Null, Rule: true, Chain: nil}, }}}}}); err != nil { return result, validation.NewError("authoring.AzureAccountsClient", "RemoveFromApp", err.Error()) } req, err := client.RemoveFromAppPreparer(ctx, appID, azureAccountInfoObject) if err != nil { err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "RemoveFromApp", nil, "Failure preparing request") return } resp, err := client.RemoveFromAppSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "RemoveFromApp", resp, "Failure sending request") return } result, err = client.RemoveFromAppResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "authoring.AzureAccountsClient", "RemoveFromApp", resp, "Failure responding to request") } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AzureAccountsClient) RemoveFromAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\tif azureAccountInfoObject != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(azureAccountInfoObject))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AzureAccountsClient) RemoveFromAppSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func RemoveApp(appName string) error {\n\t_, err := client.HDel(ApplicationKey, appName).Result()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *Application) RemoveApp(id string) error {\n\treturn Remove(db, collection, bson.M{\"_id\": bson.ObjectIdHex(id)})\n}", "func (ds *MySQLDatastore) RemoveApp(ctx context.Context, appName string) error {\n\t_, err := ds.db.Exec(`\n\t DELETE FROM apps\n\t WHERE name = ?\n\t`, appName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Service) RemoveAppid(appid string) error {\n\treturn s.d.RemoveAppid(context.Background(), appid)\n}", "func (cache *LedisCacheStorage) RemoveApp(appID string) {\n\t_, err := cache.db.Del([]byte(\"app:\" + appID))\n\n\tif err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"Ledis Cache: failed to remove app %v\\n\", err)\n\t}\n}", "func (c Client) DeleteApplication(name string) (types.TaskRef, error) {\n var taskRef types.TaskRef\n\n app, err := c.Application(name)\n if err != nil {\n return taskRef, err\n }\n\n accounts := strings.Split(app.Accounts, \",\")\n\n var jobs []types.Job\n\n for _, account := range accounts {\n jobs = append(jobs, types.Job {\n Type: \"deleteApplication\",\n Account: account,\n User: \"\",\n Application: types.DeleteApplication {\n Name: app.Name,\n Accounts: app.Accounts,\n CloudProviders: app.CloudProviders.Names,\n },\n })\n }\n\n task := types.Task {\n Application: app.Name,\n Description: \"Deleting Application: \" + app.Name,\n Job : jobs,\n }\n\n resp, err := c.post(\"/applications/\" + name + \"/tasks\", task)\n defer ensureReaderClosed(resp)\n if err != nil {\n return taskRef, err\n }\n\n err = json.NewDecoder(resp.body).Decode(&taskRef)\n return taskRef, err\n}", "func (p *Pvr) RemoveApplication(appname string) error {\n\tappPath := filepath.Join(p.Dir, appname)\n\tif _, err := os.Stat(appPath); err != nil {\n\t\treturn errors.New(\"App '\" + appname + \"' doesn't exist\")\n\t}\n\terr := os.RemoveAll(appPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (psc *PartitionSchedulingContext) RemoveSchedulingApplication(appId string) (*SchedulingApplication, error) {\n psc.lock.Lock()\n defer psc.lock.Unlock()\n\n // Remove from applications map\n if psc.applications[appId] == nil {\n return nil, fmt.Errorf(\"removing application %s from partition %s, but application does not exist\", appId, psc.Name)\n }\n schedulingApp := psc.applications[appId]\n delete(psc.applications, appId)\n\n // Remove app under queue\n schedulingQueue := psc.queues[schedulingApp.ApplicationInfo.QueueName]\n if schedulingQueue == nil {\n // This is not normal\n panic(fmt.Sprintf(\"Failed to find queue %s for app=%s while removing application\", schedulingApp.ApplicationInfo.QueueName, appId))\n }\n schedulingQueue.RemoveSchedulingApplication(schedulingApp)\n\n return schedulingApp, nil\n}", "func (client AzureAccountsClient) RemoveFromAppResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (_Storage *StorageTransactor) RemoveAccount(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _Storage.contract.Transact(opts, \"removeAccount\", addr)\n}", "func uninstallApplication(appName string) {\n\tfullAppName := knf.GetS(MAIN_PREFIX) + appName\n\tapp := &procfile.Application{Name: fullAppName}\n\n\terr := getExporter().Uninstall(app)\n\n\tif err == nil {\n\t\tlog.Info(\"User %s (%d) uninstalled service %s\", user.RealName, user.RealUID, app.Name)\n\t} else {\n\t\tlog.Error(err.Error())\n\t\tprintErrorAndExit(err.Error())\n\t}\n}", "func (app *App) Remove(uuid gocql.UUID) (err error) {\n\tif err = app.tre.session.Query(`DELETE FROM applications WHERE uuid = ?`,\n\t\tuuid).Exec(); err != nil {\n\t\tfmt.Printf(\"Remove Error: %s\\n\", err.Error())\n\t\treturn\n\t}\n\terr = app.tre.com.RemoveAll(uuid)\n\treturn\n}", "func (client *Client) DeleteAppInfo(request *DeleteAppInfoRequest) (_result *DeleteAppInfoResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &DeleteAppInfoResponse{}\n\t_body, _err := client.DeleteAppInfoWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (am *ArtifactMap) DeleteApp(AppGUID string) {\n\tvar desiredApp *ArtifactEntry\n\tindex := 0\n\tfor i, app := range am.AppList {\n\t\tif app.GUID == AppGUID {\n\t\t\tdesiredApp = app\n\t\t\tindex = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif desiredApp != nil {\n\t\tam.AppList = append(am.AppList[:index], am.AppList[index+1:]...)\n\t\tam.appTitleToID.Delete(desiredApp.Title)\n\t\tam.appTitleToItemID.Delete(desiredApp.Title)\n\t}\n}", "func (c *Client) RemoveAccount(ctx context.Context, id string) error {\n\tinput := &dynamodb.DeleteItemInput{\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\taccountIDKey: {\n\t\t\t\tS: aws.String(id),\n\t\t\t},\n\t\t},\n\t\tTableName: aws.String(tableName),\n\t}\n\n\t_, err := c.dynamoDBClient.DeleteItem(input)\n\tif err != nil {\n\t\treturn &ErrorDeleteItem{err: err}\n\t}\n\n\treturn nil\n}", "func (as *AppStorage) DeleteApp(id string) error {\n\tinput := &dynamodb.DeleteItemInput{\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"id\": {S: aws.String(id)},\n\t\t},\n\t\tTableName: aws.String(appsTableName),\n\t}\n\t_, err := as.db.C.DeleteItem(input)\n\treturn err\n}", "func (k Keeper) RemoveRejectedAccount(\n\tctx sdk.Context,\n\taddress sdk.AccAddress,\n) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.RejectedAccountKeyPrefix))\n\tstore.Delete(types.RejectedAccountKey(\n\t\taddress,\n\t))\n}", "func unregApp(cmd marcopolo.CmdMsg, srvConn *marcopolo.ServerConn) {\n\tappName := cmd.AppNameParam.AppName\n\tfmt.Println(\"unregister app \", appName)\n\n\t// lookup regd app w. this name\n\tprevApp, found := apps[appName]\n\t_ = prevApp\n\tif found {\n\t\tfmt.Printf(\"unregapp, removing @ %s\\n\", prevApp.appAddr)\n\n\t\t// remove app entry\n\t\tdelete(apps, appName)\n\n\t\t// send OK to caller\n\t\tsrvConn.SendRespUnregApp(cmd.UdpPacket.RemoteAddr)\n\t} else {\n\t\terr := fmt.Errorf(\"unregapp, not found : '%s'\", appName)\n\t\tfmt.Println(err)\n\n\t\t// send error back to app\n\t\tsrvConn.SendRespUnregAppErr(err, cmd.UdpPacket.RemoteAddr)\n\t}\n}", "func (client AzureAccountsClient) AssignToApp(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (result OperationStatus, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.AssignToApp\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: azureAccountInfoObject,\n\t\t\tConstraints: []validation.Constraint{{Target: \"azureAccountInfoObject\", Name: validation.Null, Rule: false,\n\t\t\t\tChain: []validation.Constraint{{Target: \"azureAccountInfoObject.AzureSubscriptionID\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.ResourceGroup\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.AccountName\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t}}}}}); err != nil {\n\t\treturn result, validation.NewError(\"authoring.AzureAccountsClient\", \"AssignToApp\", err.Error())\n\t}\n\n\treq, err := client.AssignToAppPreparer(ctx, appID, azureAccountInfoObject)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.AssignToAppSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.AssignToAppResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"AssignToApp\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (s *stateManager) RemoveAccount(address crypto.Address) error {\n\treturn nil\n}", "func DeregisterApplication(ID common.Address) error {\n\tfileName := ID.Hex() + \".json\"\n\terr := os.Remove(dir + DirApps + \"/\" + fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c Client) revokeAppFromMerchant(merchantID string, appID string) error {\n\tpath := fmt.Sprintf(\"/merchants/%s/apps/%s\", merchantID, appID)\n\treq, err := http.NewRequest(\"DELETE\", c.getURL(path), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.executeRequestAndMarshal(req, nil)\n}", "func (s Store) DeleteApplication(title string) error {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tif !s.isTitlePresent(title) {\n\t\treturn messages.MetadataTitleAbsent\n\t}\n\n\tdelete(s.appToDetails, title)\n\treturn nil\n}", "func (s *Scim) RemoveAccountLookup(rev int64, realm, fedAcct string, r *http.Request, id *ga4gh.Identity, tx storage.Tx) error {\n\tlookup := &cpb.AccountLookup{\n\t\tSubject: \"\",\n\t\tRevision: rev,\n\t\tState: \"DELETED\",\n\t}\n\tif err := s.SaveAccountLookup(lookup, realm, fedAcct, r, id, tx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *ApplicationResource) DeactivateApplication(ctx context.Context, appId string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/lifecycle/deactivate\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func DeleteADApplication(ctx context.Context, appObjID string) (autorest.Response, error) {\n\tappClient := getApplicationsClient()\n\treturn appClient.Delete(ctx, appObjID)\n}", "func DeleteApplication(iq IQ, applicationID string) error {\n\tif resp, err := iq.Del(fmt.Sprintf(\"%s/%s\", restApplication, applicationID)); err != nil && resp.StatusCode != http.StatusNoContent {\n\t\treturn fmt.Errorf(\"application '%s' not deleted: %v\", applicationID, err)\n\t}\n\treturn nil\n}", "func DeleteApplication(kubeClient client.Client, ns string, relativePath string) error {\n\tapp, err := parseApplicationYaml(relativePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tobject := &applicationsv1beta1.Application{}\n\tobjectKey := types.NamespacedName{\n\t\tNamespace: ns,\n\t\tName: app.Name,\n\t}\n\terr = kubeClient.Get(context.TODO(), objectKey, object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn kubeClient.Delete(context.TODO(), object)\n}", "func RemoveAccountFromOSSettings(ctx context.Context, tconn *chrome.TestConn, cr *chrome.Chrome, email string) error {\n\tui := uiauto.New(tconn).WithTimeout(DefaultUITimeout)\n\tmoreActionsButton := nodewith.Name(\"More actions, \" + email).Role(role.Button)\n\n\tif err := uiauto.Combine(\"Click More actions\",\n\t\t// Open OS Settings again.\n\t\tOpenAccountManagerSettingsAction(tconn, cr),\n\t\t// Find and click \"More actions, <email>\" button.\n\t\tui.FocusAndWait(moreActionsButton),\n\t\tui.LeftClickUntil(moreActionsButton, ui.Exists(RemoveActionButton())),\n\t)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to click More actions button\")\n\t}\n\n\tif err := removeSelectedAccountFromOSSettings(ctx, tconn); err != nil {\n\t\treturn errors.Wrap(err, \"failed to remove account from OS Settings\")\n\t}\n\treturn nil\n}", "func (_Storage *StorageTransactorSession) RemoveAccount(addr common.Address) (*types.Transaction, error) {\n\treturn _Storage.Contract.RemoveAccount(&_Storage.TransactOpts, addr)\n}", "func (am *AccountManager) RemoveAccount(a *Account) {\n\tam.cmdChan <- &removeAccountCmd{\n\t\ta: a,\n\t}\n}", "func (c Client) RevokeAppFromMerchant(merchantID string, appID string) error {\n\treturn c.revokeAppFromMerchant(merchantID, appID)\n}", "func (pca Client) RemoveAccount(ctx context.Context, account Account) error {\n\treturn pca.base.RemoveAccount(ctx, account)\n}", "func (r *RBAC) RemoveFromBlackList(system, uid string, permission string) error {\n\tr.Cache.RemoveUser(system, uid)\n\treturn r.User.RemoveFromBlackList(system, uid, permission)\n}", "func (c *Client) DeleteApplication(applicationID string) error {\n\treq, err := http.NewRequest(\"DELETE\", fmt.Sprintf(\"%s/v1/application/%s\", c.HostURL, applicationID), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = c.doRequest(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a *API) DeleteApplication(appEUI lorawan.EUI64, deletedAppEUI *lorawan.EUI64) error {\n\tif err := DeleteApplication(a.ctx.DB, appEUI); err != nil {\n\t\treturn err\n\t}\n\t*deletedAppEUI = appEUI\n\treturn nil\n}", "func RemoveAccount(id int) error {\n\tquery := db.From(\"user\").Select(q.Eq(\"ID\", id))\n\treturn query.Delete(new(model.CloudAccount))\n}", "func (store *managerStore) DeleteApplication(runAs, appID string) error {\n\n\tpath := getApplicationRootPath() + runAs + \"/\" + appID\n\tblog.V(3).Infof(\"will delete applcation,path(%s)\", path)\n\n\tif err := store.Db.Delete(path); err != nil {\n\t\tblog.Error(\"fail to delete application, application id(%s), err:%s\", appID, err.Error())\n\t\treturn err\n\t}\n\tdeleteAppCacheNode(runAs, appID)\n\n\treturn nil\n}", "func (c *CvpClient) RemoveDevice(mac string) error {\n\tdata := struct {\n\t\tData []string `json:\"data\"`\n\t}{[]string{mac}}\n\tRemoveInventoryURL := \"/inventory/deleteDevices.do?\"\n\t_, err := c.Call(data, RemoveInventoryURL)\n\treturn err\n}", "func (_Storage *StorageSession) RemoveAccount(addr common.Address) (*types.Transaction, error) {\n\treturn _Storage.Contract.RemoveAccount(&_Storage.TransactOpts, addr)\n}", "func (r *RBAC) RemoveFromWhiteList(system, uid string, permission string) error {\n\tr.Cache.RemoveUser(system, uid)\n\treturn r.User.RemoveFromWhiteList(system, uid, permission)\n}", "func (m *ApplicationResource) DeleteApplication(ctx context.Context, appId string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func UninstallAppsWithAppInfoFile(appInfoFile, namespace string) error {\n\tbinary, err := exec.LookPath(kubectlCmd[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := ioutil.ReadFile(appInfoFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresources := strings.Split(string(data), \"\\n\")\n\t// Error from server (NotFound): tfjobs.kubeflow.org \"tf-standalone-test-3\" not found\n\n\tvar wg sync.WaitGroup\n\tlocker := new(sync.RWMutex)\n\terrs := []string{}\n\tfor _, r := range resources {\n\t\twg.Add(1)\n\t\tresource := r\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\targs := []string{binary, \"delete\", resource, \"--namespace\", namespace}\n\t\t\tlog.Debugf(\"Exec bash -c %v\", args)\n\t\t\tcmd := exec.Command(\"bash\", \"-c\", strings.Join(args, \" \"))\n\t\t\tout, err := cmd.CombinedOutput()\n\t\t\tif err != nil {\n\t\t\t\tif !strings.Contains(string(out), \"Error from server (NotFound): \") {\n\t\t\t\t\tlocker.Lock()\n\t\t\t\t\terrs = append(errs, string(out))\n\t\t\t\t\tlocker.Unlock()\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Debugf(\"%v\", out)\n\t\t}()\n\t}\n\twg.Wait()\n\tif len(errs) != 0 {\n\t\tlog.Debugf(\"Failed to uninstall app with app file,reason: %v\", errs)\n\t\treturn fmt.Errorf(\"%v\", strings.Join(errs, \"\\n\"))\n\t}\n\treturn nil\n}", "func DeleteApplication(db gorp.SqlExecutor, applicationID int64) error {\n\t// Delete variables\n\tif err := DeleteAllVariables(db, applicationID); err != nil {\n\t\treturn err\n\t}\n\n\t// Delete application_key\n\tif err := DeleteAllApplicationKeys(db, applicationID); err != nil {\n\t\treturn err\n\t}\n\n\tquery := `DELETE FROM application WHERE id=$1`\n\tif _, err := db.Exec(query, applicationID); err != nil {\n\t\tif e, ok := err.(*pq.Error); ok {\n\t\t\tswitch e.Code {\n\t\t\tcase gorpmapper.ViolateForeignKeyPGCode:\n\t\t\t\terr = sdk.NewErrorWithStack(err, sdk.ErrApplicationUsedByWorkflow)\n\t\t\t}\n\t\t}\n\t\treturn sdk.WrapError(err, \"cannot delete application\")\n\t}\n\n\treturn nil\n}", "func (a *Client) RemoveAccount(params *RemoveAccountParams) (*RemoveAccountNoContent, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewRemoveAccountParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"removeAccount\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/AccountService/Accounts/{name}\",\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: &RemoveAccountReader{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.(*RemoveAccountNoContent), nil\n\n}", "func RemoveMangaSubscription(db *models.DatabaseConfig, subscriptionID string) error {\n\n\tif db == nil {\n\t\tlog.Println(\"The DB model is nil\")\n\t\treturn errors.New(\"The DB model passed is nil, can't operate\")\n\t}\n\n\tid, err := primitive.ObjectIDFromHex(subscriptionID)\n\tif err != nil {\n\t\tlog.Println(\"Invalid subscription ID: \", subscriptionID)\n\t\treturn err\n\t}\n\n\tres, err := db.MongoClient.Collection(\"subscription\").DeleteOne(db.Ctx, bson.M{\"_id\": id})\n\tif err != nil {\n\t\tlog.Println(\"There was an error trying to remove subscription: \", err)\n\t\treturn err\n\t}\n\n\tif res.DeletedCount != 1 {\n\t\tlog.Println(\"Couldn't delete subscription: \", res.DeletedCount)\n\t\treturn errors.New(\"An unexpected error happened and the subscription was not deleted.\")\n\t}\n\n\treturn nil\n}", "func (_Token *TokenTransactor) RemoveFromMinters(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"removeFromMinters\", account)\n}", "func (m *UserResource) RemoveApplicationTargetFromAdministratorRoleForUser(ctx context.Context, userId string, roleId string, appName string, applicationId string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/users/%v/roles/%v/targets/catalog/apps/%v/%v\", userId, roleId, appName, applicationId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func (k Keeper) RemoveRecryptAccount(ctx sdk.Context, index string) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.RecryptAccountKey))\n\tstore.Delete(types.KeyPrefix(index))\n}", "func removeApp(search string, apps *applications) error {\n\tif i, found := stringInSlice(search, (*apps)[\"default\"]); found == true {\n\t\t(*apps)[\"default\"] = append((*apps)[\"default\"][:i], (*apps)[\"default\"][i+1:]...)\n\t\tmsg := fmt.Sprintf(\"Successfully removed %s from default opener group\", search)\n\t\terr := rewriteApps(apps, msg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tmsg := fmt.Sprintf(\"Could not find %s in configuration\\n\", search)\n\t\treturn errors.New(msg)\n\t}\n\n\treturn nil\n}", "func (a *appRuntimeStore) DeleteAppService(app *v1.AppService) {\n\t//a.appServices.Delete(v1.GetCacheKeyOnlyServiceID(app.ServiceID))\n\t//a.appCount--\n\t//logrus.Debugf(\"current have %d app after delete \\n\", a.appCount)\n}", "func (p *UserStoreClient) RemoveFromBusiness(ctx context.Context, authenticationToken string, emailAddress string) (err error) {\n var _args21 UserStoreRemoveFromBusinessArgs\n _args21.AuthenticationToken = authenticationToken\n _args21.EmailAddress = emailAddress\n var _result22 UserStoreRemoveFromBusinessResult\n if err = p.Client_().Call(ctx, \"removeFromBusiness\", &_args21, &_result22); err != nil {\n return\n }\n switch {\n case _result22.UserException!= nil:\n return _result22.UserException\n case _result22.SystemException!= nil:\n return _result22.SystemException\n case _result22.NotFoundException!= nil:\n return _result22.NotFoundException\n }\n\n return nil\n}", "func (b *Bluez) RemoveDevice(adapterName, deviceMac string) error {\n\tdevicePath := b.devicePath(adapterName, deviceMac)\n\tif err := b.CallAdapter(adapterName, \"RemoveDevice\", 0, devicePath).Store(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func DeleteApplication(applicationID string) error {\n\tendpoint, err := utils.ConstructURL(storeApplicationEndpoint, applicationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := creatHTTPDELETEAPIRequest(endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = send(ApplicationDeleteContext, req, nil, http.StatusOK)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Client) DisassociateSerialsToApp(appID string, serials []string) (*ManageVPPLicensesByAdamIdSrv, error) {\n\toptions := ManageVPPLicensesByAdamIdSrvOptions{\n\t\tDisassociateSerialNumbers: serials,\n\t}\n\n\tresponse, err := c.ManageVPPLicensesByAdamIdSrv(appID, options)\n\treturn &response, err\n}", "func (a *Application) DeleteObject(obj *LocalDeviceObject) error {\n\tlog.Debug().Stringer(\"obj\", obj).Msg(\"DeleteObject\")\n\n\t// extract the object name and identifier\n\tobjectName := obj.ObjectName\n\tobjectIdentifier := obj.ObjectIdentifier\n\n\t// delete it from the application\n\tdelete(a.objectName, objectName)\n\tdelete(a.objectIdentifier, objectIdentifier)\n\n\t// remove the object's identifier from the device's object list if there is one and has an object list property\n\tif a.localDevice != nil {\n\t\tfoundIndex := -1\n\t\tfor i, s := range a.localDevice.ObjectList {\n\t\t\tif s == objectIdentifier {\n\t\t\t\tfoundIndex = i\n\t\t\t}\n\t\t}\n\t\tif foundIndex >= 0 {\n\t\t\ta.localDevice.ObjectList = append(a.localDevice.ObjectList[0:foundIndex], a.localDevice.ObjectList[foundIndex+1:]...)\n\t\t}\n\t}\n\n\t// make sure the object knows it's detached from an application\n\tobj.App = nil\n\n\treturn nil\n}", "func (vu *VaultUsers) removeByEmail(email string) error {\n\n\tuser := vu.users[email]\n\n\tif user == nil {\n\t\treturn errors.New(\"No user found to remove:\" + email)\n\t}\n\n\terr := user.Remove()\n\n\tvu.users[email] = nil\n\n\treturn err\n}", "func removeSelectedAccountFromOSSettings(ctx context.Context, tconn *chrome.TestConn) error {\n\ttesting.ContextLog(ctx, \"Removing account\")\n\n\tui := uiauto.New(tconn).WithTimeout(DefaultUITimeout)\n\tremoveAccountButton := RemoveActionButton()\n\tif err := uiauto.Combine(\"Click Remove account\",\n\t\tui.WaitUntilExists(removeAccountButton),\n\t\tui.LeftClick(removeAccountButton),\n\t)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to to click Remove account\")\n\t}\n\n\treturn nil\n}", "func (client *Client) DeleteAppInfoWithOptions(request *DeleteAppInfoRequest, runtime *util.RuntimeOptions) (_result *DeleteAppInfoResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AppId)) {\n\t\tquery[\"AppId\"] = request.AppId\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"DeleteAppInfo\"),\n\t\tVersion: tea.String(\"2017-03-21\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &DeleteAppInfoResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (throttler *Throttler) UnthrottleApp(appName string) (appThrottle *base.AppThrottle) {\n\tthrottler.throttledApps.Delete(appName)\n\t// the app is likely to check\n\tgo throttler.heartbeatWriter.RequestHeartbeats()\n\treturn base.NewAppThrottle(appName, time.Now(), 0, false)\n}", "func (s *Scheduler) InnerDeleteApplication(runAs, appID string, enforce bool) error {\n\tblog.Info(\"inner delete application(%s.%s), enforce(%t)\", runAs, appID, enforce)\n\n\ts.store.LockApplication(runAs + \".\" + appID)\n\tdefer s.store.UnLockApplication(runAs + \".\" + appID)\n\n\tapp, err := s.store.FetchApplication(runAs, appID)\n\tif err != nil {\n\t\tblog.Warn(\"inner delete application: get application(%s.%s) err %s\", runAs, appID, err.Error())\n\t\treturn err\n\t}\n\tif app == nil {\n\t\tblog.Warn(\"inner delete application: get application(%s.%s) return nil\", runAs, appID)\n\t\treturn errors.New(\"application not found\")\n\t}\n\n\tif app.Status == types.APP_STATUS_OPERATING {\n\t\tblog.Warn(\"inner delete application: application (%s.%s) is in status(%s) now \", runAs, appID, app.Status)\n\t}\n\n\ttaskGroups, err := s.store.ListTaskGroups(runAs, appID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, taskGroup := range taskGroups {\n\t\tblog.Info(\"inner delete application: kill taskgroup(%s)\", taskGroup.ID)\n\t\tresp, err := s.KillTaskGroup(taskGroup)\n\t\tif err != nil {\n\t\t\tblog.Error(\"inner delete application: kill taskgroup(%s) failed: %s\", taskGroup.ID, err.Error())\n\t\t\treturn err\n\t\t}\n\t\tif resp == nil {\n\t\t\tblog.Error(\"inner delete application: kill taskGroup(%s) resp nil\", taskGroup.ID)\n\t\t\terr = fmt.Errorf(\"kill taskGroup(%s) resp is nil\", taskGroup.ID)\n\t\t\treturn err\n\t\t} else if resp.StatusCode != http.StatusAccepted {\n\t\t\tblog.Error(\"inner delete application: kill taskGroup(%s) resp code %d\", taskGroup.ID, resp.StatusCode)\n\t\t\terr = fmt.Errorf(\"kill taskGroup(%s) status code %d received\", taskGroup.ID, resp.StatusCode)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdeleteTrans := &types.Transaction{\n\t\tObjectKind: string(commtypes.BcsDataType_APP),\n\t\tObjectName: appID,\n\t\tNamespace: runAs,\n\t\tTransactionID: types.GenerateTransactionID(string(commtypes.BcsDataType_APP)),\n\t\tCreateTime: time.Now(),\n\t\tCheckInterval: 3 * time.Second,\n\t\tCurOp: &types.TransactionOperartion{\n\t\t\tOpType: types.TransactionOpTypeDelete,\n\t\t\tOpDeleteData: &types.TransAPIDeleteOpdata{\n\t\t\t\tEnforce: enforce,\n\t\t\t},\n\t\t},\n\t\tStatus: types.OPERATION_STATUS_INIT,\n\t}\n\tif err := s.store.SaveTransaction(deleteTrans); err != nil {\n\t\tblog.Errorf(\"save transaction(%s,%s) into db failed, err %s\", runAs, appID, err.Error())\n\t\treturn err\n\t}\n\tblog.Infof(\"transaction %s delete application(%s.%s) run begin\",\n\t\tdeleteTrans.TransactionID, deleteTrans.Namespace, deleteTrans.ObjectName)\n\n\ts.PushEventQueue(deleteTrans)\n\n\tapp.LastStatus = app.Status\n\tapp.Status = types.APP_STATUS_OPERATING\n\tapp.SubStatus = types.APP_SUBSTATUS_UNKNOWN\n\tapp.UpdateTime = time.Now().Unix()\n\tapp.Message = \"application in deleting\"\n\tif err := s.store.SaveApplication(app); err != nil {\n\t\tblog.Error(\"inner delete application: save application(%s.%s) status(%s) into db failed! err:%s\",\n\t\t\trunAs, appID, app.Status, err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func deleteAppHelm(root, profile, unit, application string) error {\n\tparser := yaml.NewParser()\n\terr := parser.Parse(profile)\n\tif err != nil {\n\t\tlog.Fatalf(\"parser.Parse profile error: err=%s\", err)\n\t}\n\texec := exec.NewExec(root)\n\tfor _, su := range parser.Profile.ServiceUnits {\n\t\tif !strings.EqualFold(su.Name, unit) {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, app := range su.Applications {\n\t\t\tif !strings.EqualFold(app.Name, application) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tshell := exec.Delete(app.Name)\n\t\t\tlog.Infof(\"Delete application: su=%s, app=%s, shell=%s\", su.Name, application, shell)\n\t\t\terr := exec.Do(shell)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Helm delete error: err=%s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (s *AccountService) RemoveEmailAddress(form bindings.UpdateEmail) error {\n\t// TODO: fix this\n\t// s.User.RemoveEmailAddress(form.Email)\n\t// err := s.User.Save()\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\treturn nil\n}", "func (_Token *TokenTransactorSession) RemoveFromMinters(account common.Address) (*types.Transaction, error) {\n\treturn _Token.Contract.RemoveFromMinters(&_Token.TransactOpts, account)\n}", "func (appHandler *ApplicationApiHandler) DeleteApp(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := ps.ByName(\"id\")\n\tidint, err := strconv.Atoi(id)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tapp, err := appHandler.appService.DeleteApplication(idint)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tresponse, err := json.Marshal(app)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\t_, err = w.Write(response)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\n}", "func (a *App) Destroy() error {\n\terr := destroyBucket(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(a.Units) > 0 {\n\t\terr = Provisioner.Destroy(a)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Failed to destroy the app: \" + err.Error())\n\t\t}\n\t\terr = a.unbind()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn db.Session.Apps().Remove(bson.M{\"name\": a.Name})\n}", "func (_Token *TokenSession) RemoveFromMinters(account common.Address) (*types.Transaction, error) {\n\treturn _Token.Contract.RemoveFromMinters(&_Token.TransactOpts, account)\n}", "func (client ApplicationsClient) Delete(ctx context.Context, applicationObjectID string) (result autorest.Response, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ApplicationsClient.Delete\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response != nil {\n\t\t\t\tsc = result.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.DeletePreparer(ctx, applicationObjectID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"graphrbac.ApplicationsClient\", \"Delete\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.DeleteSender(req)\n\tif err != nil {\n\t\tresult.Response = resp\n\t\terr = autorest.NewErrorWithError(err, \"graphrbac.ApplicationsClient\", \"Delete\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.DeleteResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"graphrbac.ApplicationsClient\", \"Delete\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *Scheduler) Remove(app string) error {\n\treturn s.stackBuilder.Remove(app)\n}", "func AccountRemove(c echo.Context) error {\n\tuserID := c.Param(\"id\")\n\tbsonObjectID, _ := primitive.ObjectIDFromHex(userID)\n\n\t_, err := models.UserCollection.DeleteOne(\n\t\tmodels.Ctx,\n\t\tbson.M{\"_id\": bsonObjectID},\n\t)\n\tif fmt.Sprint(err) == \"mongo: no documents in result\" {\n\t\treturn utils.ErrorHandler(404, \"This user does not exist\")\n\t}\n\tif err != nil {\n\t\treturn utils.ErrorHandler(500, \"An error occured, pls try again.\")\n\t}\n\treturn c.JSON(200, map[string]string{\"message\": \"User deleted successfully\"})\n}", "func DeleteApp(c echo.Context) error {\n\tid := c.Param(\"id\")\n\tsqlStatment := \"DELETE FROM apps WHERE id = $1\"\n\tres, err := d.Query(sqlStatment, id)\n\tif err != nil{\n\t\tfmt.Println(err)\n\t} else {\n\t\tfmt.Println(res)\n\t\treturn c.JSON(http.StatusOK, \"Deleted\")\n\t}\n\treturn c.JSON(http.StatusOK, \"Deleted\")\n}", "func (c Client) RemoveFromStore(o contracts.StoredObject) error {\n\terr := o.ValidateContract(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), c.Timeout)\n\tdefer cancel()\n\n\tfilter := bson.D{\n\t\tprimitive.E{Key: \"uuid\", Value: o.ID},\n\t\tprimitive.E{Key: \"appServiceKey\", Value: o.AppServiceKey},\n\t}\n\n\t_, err = c.Client.Collection(mongoCollection).DeleteOne(ctx, filter)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func removeAppIngress(ctx context.Context, h *helper.H, index int) {\n\tvar err error\n\n\tPublishingStrategyInstance, ps := getPublishingStrategy(ctx, h)\n\n\t// remove application ingress at index `index`\n\tappIngressList := PublishingStrategyInstance.Spec.ApplicationIngress\n\tPublishingStrategyInstance.Spec.ApplicationIngress = append(appIngressList[:index], appIngressList[index+1:]...)\n\n\tps.Object, err = runtime.DefaultUnstructuredConverter.ToUnstructured(&PublishingStrategyInstance)\n\tExpect(err).NotTo(HaveOccurred())\n\n\t// Update the publishingstrategy\n\tps, err = h.Dynamic().\n\t\tResource(schema.GroupVersionResource{Group: \"cloudingress.managed.openshift.io\", Version: \"v1alpha1\", Resource: \"publishingstrategies\"}).\n\t\tNamespace(OperatorNamespace).\n\t\tUpdate(ctx, ps, metav1.UpdateOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n}", "func (u *App) Delete(c echo.Context, id string) error {\n\tif err := u.rbac.EnforceRole(c, model.AdminRole); err != nil {\n\t\treturn err\n\t}\n\n\tvar applications int\n\tif err := u.db.Model(&model.Application{}).Where(\"application_course_id = ?\", id).Count(&applications).Error; err == nil && applications > 0 {\n\t\treturn zaplog.ZLog(fmt.Errorf(\"Existem %d candidaturas associadas a este curso. Não é possível eliminar\", applications))\n\t}\n\n\treturn u.udb.Delete(u.db, id)\n}", "func (s *OAuthStore) OAuthAccessTokenRemoveByCode(codeToDelete string) error {\n\n\tquery := \"DELETE FROM oauth_access_token WHERE code = ?\"\n\n\treturn s.db.CassandraSession.Query(query, codeToDelete).Exec()\n}", "func (cleaner *RegistryCleaner) DeleteApplicationData(ctx context.Context, applicationList []string) error {\n\tfor _, ids := range applicationList {\n\t\tappIds, err := unique.ToApplicationID(ids)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tctx, err = unique.WithContext(ctx, ids)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\twebhooks, err := cleaner.WebRegistry.List(ctx, appIds, []string{\"ids\"})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, webhook := range webhooks {\n\t\t\t_, err := cleaner.WebRegistry.Set(ctx, webhook.GetIds(), nil,\n\t\t\t\tfunc(webhook *ttnpb.ApplicationWebhook) (*ttnpb.ApplicationWebhook, []string, error) {\n\t\t\t\t\treturn nil, nil, nil\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\t\t}\n\t}\n\treturn nil\n}", "func (s *OAuthTokensStore) RemoveByCode(ctx context.Context, code string) error {\n\treturn s.Find(db.Cond{\"code\": code}).Delete()\n}", "func (client ApplicationsClient) RemoveOwner(ctx context.Context, applicationObjectID string, ownerObjectID string) (result autorest.Response, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ApplicationsClient.RemoveOwner\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response != nil {\n\t\t\t\tsc = result.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.RemoveOwnerPreparer(ctx, applicationObjectID, ownerObjectID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"graphrbac.ApplicationsClient\", \"RemoveOwner\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.RemoveOwnerSender(req)\n\tif err != nil {\n\t\tresult.Response = resp\n\t\terr = autorest.NewErrorWithError(err, \"graphrbac.ApplicationsClient\", \"RemoveOwner\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.RemoveOwnerResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"graphrbac.ApplicationsClient\", \"RemoveOwner\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (ouo *OrganizationUpdateOne) RemoveAccounts(a ...*Account) *OrganizationUpdateOne {\n\tids := make([]pulid.ID, len(a))\n\tfor i := range a {\n\t\tids[i] = a[i].ID\n\t}\n\treturn ouo.RemoveAccountIDs(ids...)\n}", "func (s Store) DeleteApplicationWithVersion(title, version string) error {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tif exists, err := s.isApplicationPresent(title, version); !exists {\n\t\treturn err\n\t}\n\n\tdelete(s.appToDetails[title], version)\n\treturn nil\n}", "func (client *Client) RemoveAppGroup(request *RemoveAppGroupRequest) (response *RemoveAppGroupResponse, err error) {\n\tresponse = CreateRemoveAppGroupResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func DeleteAccount(id string) (string, error) {\n\n\tvar ac []models.Account\n\tvar isAccountDeleted bool\n\n\t// take all accounts and range over the loop\n\tfor _, acc := range Accounts {\n\t\t// Check if account id is matching or not\n\t\t// If account id is not matching, store the account details back to same object\n\t\tif acc.ID != id {\n\t\t\tac = append(ac, acc)\n\t\t} else {\n\t\t\t// if account id is matching, mark the isAccountDeleted flag as true\n\t\t\tisAccountDeleted = true\n\t\t}\n\t}\n\tAccounts = ac\n\n\t// if account deleted, then send response to the user, saying account deleted\n\tif isAccountDeleted {\n\t\treturn \"Account deleted successfully\", nil\n\t}\n\treturn \"\", errors.New(\"Account not found\")\n}", "func (a *DefaultApiService) DeleteApplication(ctx _context.Context, id string) ApiDeleteApplicationRequest {\n\treturn ApiDeleteApplicationRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func (as *AppStorage) DisableApp(app model.AppData) error {\n\tif _, err := xid.FromString(app.ID()); err != nil {\n\t\tlog.Println(\"Incorrect AppID: \", app.ID())\n\t\treturn model.ErrorWrongDataFormat\n\t}\n\tinput := &dynamodb.UpdateItemInput{\n\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\":a\": {\n\t\t\t\tBOOL: aws.Bool(false),\n\t\t\t},\n\t\t},\n\t\tTableName: aws.String(appsTableName),\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"id\": {\n\t\t\t\tS: aws.String(app.ID()),\n\t\t\t},\n\t\t},\n\t\tReturnValues: aws.String(\"UPDATED_NEW\"),\n\t\tUpdateExpression: aws.String(\"set active = :a\"),\n\t}\n\n\t// Old approach was to delete the record for deactivated app, leave it here for a while.\n\t// input := &dynamodb.DeleteItemInput{\n\t// \tKey: map[string]*dynamodb.AttributeValue{\n\t// \t\t\"id\": {\n\t// \t\t\tS: aws.String(app.ID()),\n\t// \t\t},\n\t// \t},\n\t// \tTableName: aws.String(AppsTable),\n\t// }\n\t// _, err = as.db.C.DeleteItem(input)\n\n\tif _, err := as.db.C.UpdateItem(input); err != nil {\n\t\tlog.Println(\"Error updating app:\", err)\n\t\treturn ErrorInternalError\n\t}\n\treturn nil\n}", "func (c Client) DeactivateAccount(account Account) (Account, error) {\n\tdeactivateReq := struct {\n\t\tStatus string `json:\"status\"`\n\t}{\n\t\tStatus: \"deactivated\",\n\t}\n\n\t_, err := c.post(account.URL, account.URL, account.PrivateKey, deactivateReq, &account, http.StatusOK)\n\n\treturn account, err\n}", "func (m *userManager) RemoveBackupCode(username, backupCode string) error {\n\treturn m.db.Update(func(tx *bolt.Tx) error {\n\t\tusers := tx.Bucket(m.usersBucket)\n\t\tpropsBytes := users.Get([]byte(username))\n\t\tif propsBytes != nil {\n\t\t\tprops := &userProps{}\n\t\t\tif err := json.Unmarshal(propsBytes, props); err != nil {\n\t\t\t\treturn errors.New(\"Corrupt user properties: \" + err.Error())\n\t\t\t}\n\n\t\t\t// find the backup code\n\t\t\tbackupCodes := props.TotpBackupCodes\n\t\t\tindex := -1\n\t\t\tfor i, storedBackupCode := range backupCodes {\n\t\t\t\tif storedBackupCode == backupCode {\n\t\t\t\t\tindex = i\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// doesn't exist\n\t\t\tif index == -1 {\n\t\t\t\treturn errBackupCodeNotFound\n\t\t\t}\n\n\t\t\t// remove it\n\t\t\tprops.TotpBackupCodes = append(\n\t\t\t\tprops.TotpBackupCodes[:index],\n\t\t\t\tprops.TotpBackupCodes[index+1:]...)\n\n\t\t\t// store updated user\n\t\t\tbytes, err := json.Marshal(props)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn users.Put([]byte(username), bytes)\n\t\t}\n\t\treturn errUserNotFound\n\t})\n}", "func (client *Client) DeleteApplication(request *DeleteApplicationRequest) (_result *DeleteApplicationResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &DeleteApplicationResponse{}\n\t_body, _err := client.DeleteApplicationWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (d *dao) RemoveByCode(code string) error {\n\t_, err := d.DeleteSsoTokenX(context.TODO(), &model.SsoToken{Code: code})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func delete_account_ (stub shim.ChaincodeStubInterface, account_name string) error {\n _,err := util.DeleteTableRow(stub, ACCOUNT_TABLE, []string{account_name}, nil, util.FAIL_IF_MISSING)\n return err\n}", "func (a *Client) DeleteApplication(params *DeleteApplicationParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteApplicationOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteApplicationParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"deleteApplication\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/applications/{appName}\",\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: &DeleteApplicationReader{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.(*DeleteApplicationOK)\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 deleteApplication: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (api *API) RemoveTeam(id int) error {\n\t_, err := api.Organizations.DeleteTeam(context.Background(), id)\n\treturn err\n}", "func (ou *OrganizationUpdate) RemoveAccounts(a ...*Account) *OrganizationUpdate {\n\tids := make([]pulid.ID, len(a))\n\tfor i := range a {\n\t\tids[i] = a[i].ID\n\t}\n\treturn ou.RemoveAccountIDs(ids...)\n}", "func (ws *WSClient) UnsubscribeAccount() error {\n\treturn ws.unsubscribe(\"ACCOUNT\")\n}", "func (cloud *CloudCtx) RemoveApplicationInstanceConfig(id string) error {\n\tapplicationInstanceConfigInd, err := cloud.getApplicationInstanceInd(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tutils.DelEleInSlice(&cloud.applicationInstances, applicationInstanceConfigInd)\n\treturn nil\n}", "func (q *Q) RemoveAccountData(key xdr.LedgerKeyData) (int64, error) {\n\tlkey, err := ledgerKeyDataToString(key)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"Error running ledgerKeyDataToString\")\n\t}\n\n\tsql := sq.Delete(\"accounts_data\").\n\t\tWhere(sq.Eq{\"ledger_key\": lkey})\n\tresult, err := q.Exec(sql)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn result.RowsAffected()\n}", "func (o *MDRaid) RemoveDevice(ctx context.Context, device dbus.ObjectPath, options map[string]dbus.Variant) (err error) {\n\terr = o.object.CallWithContext(ctx, InterfaceMDRaid+\".RemoveDevice\", 0, device, options).Store()\n\treturn\n}", "func (m *UserResource) RemoveLinkedObjectForUser(ctx context.Context, userId string, relationshipName string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/users/%v/linkedObjects/%v\", userId, relationshipName)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func (c *RollbarAPIClient) RemoveTeamFromProject(teamID, projectID int) error {\n\tl := log.With().\n\t\tInt(\"teamID\", teamID).\n\t\tInt(\"projectID\", projectID).\n\t\tLogger()\n\tl.Debug().Msg(\"Removing team from project\")\n\tresp, err := c.Resty.R().\n\t\tSetPathParams(map[string]string{\n\t\t\t\"teamID\": strconv.Itoa(teamID),\n\t\t\t\"projectID\": strconv.Itoa(projectID),\n\t\t}).\n\t\tSetError(ErrorResult{}).\n\t\tDelete(c.BaseURL + pathTeamProject)\n\tif err != nil {\n\t\tl.Err(err).Msg(\"Error removing team from project\")\n\t\treturn err\n\t}\n\terr = errorFromResponse(resp)\n\tif err != nil {\n\t\tl.Err(err).Msg(\"Error removing team from project\")\n\t\treturn err\n\t}\n\tl.Debug().Msg(\"Successfully removed team from project\")\n\treturn nil\n}" ]
[ "0.6359929", "0.6353537", "0.6308262", "0.62563384", "0.61005205", "0.582663", "0.57143116", "0.5693641", "0.5608656", "0.5607049", "0.5391877", "0.5338707", "0.5303999", "0.5301591", "0.52733266", "0.52627945", "0.52621144", "0.5177809", "0.5122273", "0.5073616", "0.506702", "0.5057117", "0.5037651", "0.5033775", "0.5010427", "0.49881035", "0.49837446", "0.4969107", "0.49542838", "0.49273282", "0.49190277", "0.4885333", "0.4880521", "0.4859999", "0.48474684", "0.48466772", "0.4843151", "0.4836061", "0.4823915", "0.4808839", "0.4806916", "0.47977498", "0.47776437", "0.47604927", "0.4740316", "0.47381577", "0.4732628", "0.47313917", "0.4725432", "0.47101173", "0.47023284", "0.4695833", "0.46907356", "0.46893555", "0.4678668", "0.46665525", "0.4651113", "0.46359363", "0.463397", "0.46151465", "0.46116537", "0.46115696", "0.46039847", "0.4587859", "0.45870855", "0.45718074", "0.45693827", "0.45658845", "0.45562473", "0.45560196", "0.45399156", "0.45255458", "0.45232108", "0.4506689", "0.4486075", "0.44388646", "0.44333544", "0.4427606", "0.44052315", "0.43937927", "0.43799606", "0.43748507", "0.43689454", "0.43656635", "0.4361652", "0.4359172", "0.43591487", "0.43557954", "0.4342625", "0.43384287", "0.43380225", "0.43308568", "0.43303186", "0.4326127", "0.43223196", "0.431613", "0.431171", "0.4305141", "0.42951122", "0.4294017" ]
0.8058232
0
RemoveFromAppPreparer prepares the RemoveFromApp request.
func (client AzureAccountsClient) RemoveFromAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) { urlParameters := map[string]interface{}{ "Endpoint": client.Endpoint, } pathParameters := map[string]interface{}{ "appId": autorest.Encode("path", appID), } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsDelete(), autorest.WithCustomBaseURL("{Endpoint}/luis/api/v2.0", urlParameters), autorest.WithPathParameters("/apps/{appId}/azureaccounts", pathParameters)) if azureAccountInfoObject != nil { preparer = autorest.DecoratePreparer(preparer, autorest.WithJSON(azureAccountInfoObject)) } return preparer.Prepare((&http.Request{}).WithContext(ctx)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AppsClient) DeletePreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ApplicationsClient) RemoveOwnerPreparer(ctx context.Context, applicationObjectID string, ownerObjectID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"ownerObjectId\": autorest.Encode(\"path\", ownerObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}/$links/owners/{ownerObjectId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ApplicationsClient) DeletePreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AzureAccountsClient) RemoveFromAppSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AzureAccountsClient) RemoveFromAppResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (p *MemoryProposer) RemovePreparer(target Acceptor) error {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tif _, ok := p.preparers[target.Address()]; !ok {\n\t\treturn ErrNotFound\n\t}\n\tdelete(p.preparers, target.Address())\n\treturn nil\n}", "func (client ModelClient) DeletePrebuiltPreparer(ctx context.Context, appID uuid.UUID, versionID string, prebuiltID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"prebuiltId\": autorest.Encode(\"path\", prebuiltID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/prebuilts/{prebuiltId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client JobClient) RemovePreparer(ctx context.Context, resourceGroupName string, accountName string, jobName string, body *JobUserActionDescription) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"jobName\": jobName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPost(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/jobs/{jobName}/remove\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n if body != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(body))\n }\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client DeploymentsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DeploymentsClient) StopPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/stop\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppsClient) AddPreparer(ctx context.Context, applicationCreateObject ApplicationCreateObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/apps/\"),\n\t\tautorest.WithJSON(applicationCreateObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ServicesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (ds *MySQLDatastore) RemoveApp(ctx context.Context, appName string) error {\n\t_, err := ds.db.Exec(`\n\t DELETE FROM apps\n\t WHERE name = ?\n\t`, appName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (alr AppListResult) appListResultPreparer() (*http.Request, error) {\n\tif alr.NextLink == nil || len(to.String(alr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(alr.NextLink)))\n}", "func (client AppListResult) AppListResultPreparer() (*http.Request, error) {\r\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\r\n\t\treturn nil, nil\r\n\t}\r\n\treturn autorest.Prepare(&http.Request{},\r\n\t\tautorest.AsJSON(),\r\n\t\tautorest.AsGet(),\r\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\r\n}", "func PrepareApp(env env.Project, options *PrepareOptions) error {\n\treturn doPrepare(env, options)\n}", "func (client ModelClient) DeleteIntentPreparer(ctx context.Context, appID uuid.UUID, versionID string, intentID uuid.UUID, deleteUtterances *bool) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"intentId\": autorest.Encode(\"path\", intentID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{}\n\tif deleteUtterances != nil {\n\t\tqueryParameters[\"deleteUtterances\"] = autorest.Encode(\"query\", *deleteUtterances)\n\t} else {\n\t\tqueryParameters[\"deleteUtterances\"] = autorest.Encode(\"query\", false)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/intents/{intentId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AzureAccountsClient) AssignToAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\tif azureAccountInfoObject != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(azureAccountInfoObject))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppsClient) ImportPreparer(ctx context.Context, luisApp LuisApp, appName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tqueryParameters := map[string]interface{}{}\n\tif len(appName) > 0 {\n\t\tqueryParameters[\"appName\"] = autorest.Encode(\"query\", appName)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/apps/import\"),\n\t\tautorest.WithJSON(luisApp),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ManagementClient) WipeMAMUserDevicePreparer(hostName string, userName string, deviceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"deviceName\": autorest.Encode(\"path\", deviceName),\n\t\t\"hostName\": autorest.Encode(\"path\", hostName),\n\t\t\"userName\": autorest.Encode(\"path\", userName),\n\t}\n\n\tconst APIVersion = \"2015-01-14-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Intune/locations/{hostName}/users/{userName}/devices/{deviceName}/wipe\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client ServicesClient) StopPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/stop\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppsClient) UpdatePreparer(ctx context.Context, appID uuid.UUID, applicationUpdateObject ApplicationUpdateObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPut(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}\", pathParameters),\n\t\tautorest.WithJSON(applicationUpdateObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func handleRemoveTelemetryPreMitigationResource(request *libcoap.Pdu, context *libcoap.Context, uriFilterPreMitigationList []db_models.UriFilteringTelemetryPreMitigation) {\n requestPath := request.PathString()\n requestPathSplit := strings.Split(requestPath, \"/tmid=\")\n resource := context.GetResourceByQuery(&requestPath)\n if resource != nil {\n resource.ToRemovableResource()\n resource.SetQBlock2(false)\n libcoap.DeleteUriFilterByKey(requestPath)\n if len(requestPathSplit) <= 1 {\n // Delete resource one of telemetry pre-mitigation\n for _, v := range uriFilterPreMitigationList {\n queryOne := resource.UriPath()+\"/tmid=\"+strconv.Itoa(v.Tmid)\n resourceOne := context.GetResourceByQuery(&queryOne)\n if resourceOne != nil {\n resourceOne.ToRemovableResource()\n resourceOne.SetQBlock2(false)\n }\n // Delete resource (uri-path contains uri-query)\n libcoap.DeleteUriFilterByKey(queryOne)\n }\n }\n }\n}", "func (client ApplicationsClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\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\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ModelClient) DeleteCustomPrebuiltDomainPreparer(ctx context.Context, appID uuid.UUID, versionID string, domainName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"domainName\": autorest.Encode(\"path\", domainName),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/customprebuiltdomains/{domainName}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ManagementClient) GetAppsPreparer(hostName string, filter string, top *int32, selectParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostName\": autorest.Encode(\"path\", hostName),\n\t}\n\n\tconst APIVersion = \"2015-01-14-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Intune/locations/{hostName}/apps\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (client MSIXPackagesClient) DeletePreparer(ctx context.Context, resourceGroupName string, hostPoolName string, msixPackageFullName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostPoolName\": autorest.Encode(\"path\", hostPoolName),\n\t\t\"msixPackageFullName\": autorest.Encode(\"path\", msixPackageFullName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-09-21-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages/{msixPackageFullName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AzureAccountsClient) RemoveFromApp(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (result OperationStatus, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.RemoveFromApp\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: azureAccountInfoObject,\n\t\t\tConstraints: []validation.Constraint{{Target: \"azureAccountInfoObject\", Name: validation.Null, Rule: false,\n\t\t\t\tChain: []validation.Constraint{{Target: \"azureAccountInfoObject.AzureSubscriptionID\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.ResourceGroup\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.AccountName\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t}}}}}); err != nil {\n\t\treturn result, validation.NewError(\"authoring.AzureAccountsClient\", \"RemoveFromApp\", err.Error())\n\t}\n\n\treq, err := client.RemoveFromAppPreparer(ctx, appID, azureAccountInfoObject)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.RemoveFromAppSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.RemoveFromAppResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func AddToRequest(app *App) server.PreHandlerFunc {\n\treturn func(req *http.Request) *http.Request {\n\t\tnewCtx := With(req.Context(), app)\n\t\treturn req.Clone(newCtx)\n\t}\n}", "func (client ModelClient) DeleteSubListPreparer(ctx context.Context, appID uuid.UUID, versionID string, clEntityID uuid.UUID, subListID int32) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"clEntityId\": autorest.Encode(\"path\", clEntityID),\n\t\t\"subListId\": autorest.Encode(\"path\", subListID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/closedlists/{clEntityId}/sublists/{subListId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppCollectionListResult) AppCollectionListResultPreparer() (*http.Request, error) {\r\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\r\n\t\treturn nil, nil\r\n\t}\r\n\treturn autorest.Prepare(&http.Request{},\r\n\t\tautorest.AsJSON(),\r\n\t\tautorest.AsGet(),\r\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\r\n}", "func (m *Application) RemoveApp(id string) error {\n\treturn Remove(db, collection, bson.M{\"_id\": bson.ObjectIdHex(id)})\n}", "func (client AppsClient) ListPreparer(ctx context.Context, skip *int32, take *int32) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tqueryParameters := map[string]interface{}{}\n\tif skip != nil {\n\t\tqueryParameters[\"skip\"] = autorest.Encode(\"query\", *skip)\n\t} else {\n\t\tqueryParameters[\"skip\"] = autorest.Encode(\"query\", 0)\n\t}\n\tif take != nil {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", *take)\n\t} else {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", 100)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPath(\"/apps/\"),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (aclr AppCollectionListResult) appCollectionListResultPreparer() (*http.Request, error) {\n\tif aclr.NextLink == nil || len(to.String(aclr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(aclr.NextLink)))\n}", "func (client DeviceClient) DeletePreparer(ctx context.Context, serviceID string, userID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"serviceId\": serviceID,\n\t\t\"userId\": autorest.Encode(\"path\", userID),\n\t}\n\n\ttimestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)\n\tsec := security.NewSignature(client.Secretkey, crypto.SHA256)\n\tsignature, err := sec.Signature(\"DELETE\", common.GetPathParameters(DefaultBaseURI, \"/push/v2/services/{serviceId}/users/{userId}\", pathParameters), client.AccessKey, timestamp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/push/v2/services/{serviceId}/users/{userId}\", pathParameters),\n\t\tautorest.WithHeader(\"x-ncp-apigw-api-key\", client.APIGatewayAPIKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-timestamp\", timestamp),\n\t\tautorest.WithHeader(\"x-ncp-iam-access-key\", client.AccessKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-signature-v2\", signature))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ModelClient) DeletePrebuiltEntityRolePreparer(ctx context.Context, appID uuid.UUID, versionID string, entityID uuid.UUID, roleID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"entityId\": autorest.Encode(\"path\", entityID),\n\t\t\"roleId\": autorest.Encode(\"path\", roleID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/prebuilts/{entityId}/roles/{roleId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ManagementClient) GetMAMUserFlaggedEnrolledAppsPreparer(hostName string, userName string, filter string, top *int32, selectParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostName\": autorest.Encode(\"path\", hostName),\n\t\t\"userName\": autorest.Encode(\"path\", userName),\n\t}\n\n\tconst APIVersion = \"2015-01-14-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(filter) > 0 {\n\t\tqueryParameters[\"$filter\"] = autorest.Encode(\"query\", filter)\n\t}\n\tif top != nil {\n\t\tqueryParameters[\"$top\"] = autorest.Encode(\"query\", *top)\n\t}\n\tif len(selectParameter) > 0 {\n\t\tqueryParameters[\"$select\"] = autorest.Encode(\"query\", selectParameter)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.Intune/locations/{hostName}/flaggedUsers/{userName}/flaggedEnrolledApps\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func RemoveApp(appName string) error {\n\t_, err := client.HDel(ApplicationKey, appName).Result()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func unregApp(cmd marcopolo.CmdMsg, srvConn *marcopolo.ServerConn) {\n\tappName := cmd.AppNameParam.AppName\n\tfmt.Println(\"unregister app \", appName)\n\n\t// lookup regd app w. this name\n\tprevApp, found := apps[appName]\n\t_ = prevApp\n\tif found {\n\t\tfmt.Printf(\"unregapp, removing @ %s\\n\", prevApp.appAddr)\n\n\t\t// remove app entry\n\t\tdelete(apps, appName)\n\n\t\t// send OK to caller\n\t\tsrvConn.SendRespUnregApp(cmd.UdpPacket.RemoteAddr)\n\t} else {\n\t\terr := fmt.Errorf(\"unregapp, not found : '%s'\", appName)\n\t\tfmt.Println(err)\n\n\t\t// send error back to app\n\t\tsrvConn.SendRespUnregAppErr(err, cmd.UdpPacket.RemoteAddr)\n\t}\n}", "func (client AccountClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsDelete(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client ModelClient) DeleteRegexEntityModelPreparer(ctx context.Context, appID uuid.UUID, versionID string, regexEntityID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"regexEntityId\": autorest.Encode(\"path\", regexEntityID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/regexentities/{regexEntityId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppsClient) GetPreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AppsClient) PublishPreparer(ctx context.Context, appID uuid.UUID, applicationPublishObject ApplicationPublishObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/publish\", pathParameters),\n\t\tautorest.WithJSON(applicationPublishObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ContainerAppsRevisionsClient) DeactivateRevisionPreparer(ctx context.Context, resourceGroupName string, containerAppName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"containerAppName\": autorest.Encode(\"path\", containerAppName),\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2021-03-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/containerApps/{containerAppName}/revisions/{name}/deactivate\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ModelClient) ListPrebuiltsPreparer(ctx context.Context, appID uuid.UUID, versionID string, skip *int32, take *int32) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{}\n\tif skip != nil {\n\t\tqueryParameters[\"skip\"] = autorest.Encode(\"query\", *skip)\n\t} else {\n\t\tqueryParameters[\"skip\"] = autorest.Encode(\"query\", 0)\n\t}\n\tif take != nil {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", *take)\n\t} else {\n\t\tqueryParameters[\"take\"] = autorest.Encode(\"query\", 100)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/prebuilts\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DatabasesClient) DeletePreparer(resourceGroupName string, serverName string, databaseName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serverName\": autorest.Encode(\"path\", serverName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2014-04-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (m *resourcesMatcher) excludeApp(appName string) *resourcesMatcher {\n\tm.resources = resourcesFilter(m.resources, func(r unstructured.Unstructured) bool {\n\t\ta := r.GetAnnotations()\n\t\tif a == nil {\n\t\t\treturn true\n\t\t}\n\t\tif a[_const.NocalhostApplicationName] == appName {\n\t\t\treturn false\n\t\t}\n\t\tif a[_const.HelmReleaseName] == appName {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\treturn m\n}", "func (client ModelClient) DeleteClosedListPreparer(ctx context.Context, appID uuid.UUID, versionID string, clEntityID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"clEntityId\": autorest.Encode(\"path\", clEntityID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/closedlists/{clEntityId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client Client) RemoveAccessControlPreparer(ctx context.Context, nasVolumeInstanceNo string, serverInstanceNoListN string) (*http.Request, error) {\n\tqueryParameters := map[string]interface{}{\n\t\t\"nasVolumeInstanceNo\": autorest.Encode(\"query\", nasVolumeInstanceNo),\n\t\t\"responseFormatType\": autorest.Encode(\"query\", \"json\"),\n\t\t\"serverInstanceNoList.N\": autorest.Encode(\"query\", serverInstanceNoListN),\n\t}\n\n\tqueryParameters[\"regionCode\"] = autorest.Encode(\"query\", \"FKR\")\n\n\ttimestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)\n\tsec := security.NewSignature(client.Secretkey, crypto.SHA256)\n\tsignature, err := sec.Signature(\"POST\", common.GetPath(DefaultBaseURI, \"/removeNasVolumeAccessControl\")+\"?\"+common.GetQuery(queryParameters), client.AccessKey, timestamp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/removeNasVolumeAccessControl\"),\n\t\tautorest.WithQueryParameters(queryParameters),\n\t\tautorest.WithHeader(\"x-ncp-apigw-timestamp\", timestamp),\n\t\tautorest.WithHeader(\"x-ncp-iam-access-key\", client.AccessKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-signature-v2\", signature))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (gf *GlobalFilter) DeleteFromGlobalFilter(gdp *gdpv1alpha1.GlobalDeploymentPolicy) {\n\tgf.GlobalLock.Lock()\n\tdefer gf.GlobalLock.Unlock()\n\tgf.AppFilter = nil\n\tgf.NSFilter = nil\n\tgf.ApplicableClusters = []string{}\n\tgf.Checksum = 0\n\tgf.TrafficSplit = []ClusterTraffic{}\n}", "func (n *Notary) OnRequestRemoval(pld *payload.P2PNotaryRequest) {\n\tif n.getAccount() == nil {\n\t\treturn\n\t}\n\n\tn.reqMtx.Lock()\n\tdefer n.reqMtx.Unlock()\n\tr, ok := n.requests[pld.MainTransaction.Hash()]\n\tif !ok {\n\t\treturn\n\t}\n\tfor i, fb := range r.fallbacks {\n\t\tif fb.Hash().Equals(pld.FallbackTransaction.Hash()) {\n\t\t\tr.fallbacks = append(r.fallbacks[:i], r.fallbacks[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(r.fallbacks) == 0 {\n\t\tdelete(n.requests, r.main.Hash())\n\t}\n}", "func (client ModelClient) DeleteEntityPreparer(ctx context.Context, appID uuid.UUID, versionID string, entityID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"entityId\": autorest.Encode(\"path\", entityID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/entities/{entityId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client HTTPSuccessClient) Delete202Preparer(booleanValue *bool) (*http.Request, error) {\n preparer := autorest.CreatePreparer(\n autorest.AsJSON(),\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/http/success/202\"))\n if booleanValue != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(booleanValue))\n }\n return preparer.Prepare(&http.Request{})\n}", "func (client Client) DeletePreparer(resourceGroupName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": url.QueryEscape(name),\n\t\t\"resourceGroupName\": url.QueryEscape(resourceGroupName),\n\t\t\"subscriptionId\": url.QueryEscape(client.SubscriptionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/Redis/{name}\"),\n\t\tautorest.WithPathParameters(pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n}", "func (w *WebPurifyRequest) RemoveFromAllowList(word string) (response.WebPurifyRemoveFromAllowListResponse, error) {\n\n\t// create request parameter collection\n\trequestParameters := []WebPurifyRequestParameter{\n\t\t{Type: Word, Value: word},\n\t}\n\n\t// build http request\n\trequest, err := w.createRequest(RemoveFromAllowList, requestParameters...)\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\t// create http client\n\tclient := w.createHttpClient()\n\n\t// Execute http request\n\thttpResponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\t// convert response to struct\n\twebPurifyResponse, err := w.convertToRemoveFromAllowListResponse(*httpResponse)\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\treturn webPurifyResponse, nil\n}", "func (client BaseClient) DeleteSubscriptionPreparer(ctx context.Context, subscriptionID uuid.UUID, APIVersion string, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"subscriptionId\": autorest.Encode(\"path\",subscriptionID),\n }\n\n queryParameters := map[string]interface{} {\n \"ApiVersion\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPathParameters(\"/{subscriptionId}\",pathParameters),\n autorest.WithQueryParameters(queryParameters),\n autorest.WithHeader(\"Content-Type\", \"application/json\"))\n if xMsRequestid != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithHeader(\"x-ms-requestid\",autorest.String(xMsRequestid)))\n }\n if xMsCorrelationid != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithHeader(\"x-ms-correlationid\",autorest.String(xMsCorrelationid)))\n }\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func prepareApp(p *stage1commontypes.Pod, ra *schema.RuntimeApp) (*preparedApp, error) {\n\tpa := preparedApp{\n\t\tapp: ra,\n\t\tenv: ra.App.Environment,\n\t\tnoNewPrivileges: getAppNoNewPrivileges(ra.App.Isolators),\n\t}\n\tvar err error\n\n\t// Determine numeric uid and gid\n\tu, g, err := parseUserGroup(p, ra)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(errors.New(\"unable to determine app's uid and gid\"), err)\n\t}\n\tif u < 0 || g < 0 {\n\t\treturn nil, errors.New(\"Invalid uid or gid\")\n\t}\n\tpa.uid = uint32(u)\n\tpa.gid = uint32(g)\n\n\t// Set some rkt-provided environment variables\n\tpa.env.Set(\"AC_APP_NAME\", ra.Name.String())\n\tif p.MetadataServiceURL != \"\" {\n\t\tpa.env.Set(\"AC_METADATA_URL\", p.MetadataServiceURL)\n\t}\n\n\t// Determine capability set\n\tpa.capabilities, err = getAppCapabilities(ra.App.Isolators)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(errors.New(\"unable to construct capabilities\"), err)\n\t}\n\n\t// Determine mounts\n\tcfd := ConvertedFromDocker(p.Images[ra.Name.String()])\n\tpa.mounts, err = GenerateMounts(ra, p.Manifest.Volumes, cfd)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(errors.New(\"unable to compute mounts\"), err)\n\t}\n\n\t// Compute resources\n\tpa.resources, err = computeAppResources(ra.App.Isolators)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(errors.New(\"unable to compute resources\"), err)\n\t}\n\n\t// Protect kernel tunables by default\n\tif !p.InsecureOptions.DisablePaths {\n\t\tpa.roPaths = append(pa.roPaths, protectKernelROPaths...)\n\t\tpa.hiddenPaths = append(pa.hiddenDirs, protectKernelHiddenPaths...)\n\t\tpa.hiddenDirs = append(pa.hiddenDirs, protectKernelHiddenDirs...)\n\t}\n\n\t// Seccomp\n\tif !p.InsecureOptions.DisableSeccomp {\n\t\tpa.seccomp, err = generateSeccompFilter(p, &pa)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif pa.seccomp != nil && pa.seccomp.forceNoNewPrivileges {\n\t\t\tpa.noNewPrivileges = true\n\t\t}\n\t}\n\n\t// Write the systemd-sysusers config file\n\tif err := generateSysusers(p, pa.app, int(pa.uid), int(pa.gid), &p.UidRange); err != nil {\n\t\treturn nil, errwrap.Wrapf(\"unable to generate sysusers file\", err)\n\t}\n\n\treturn &pa, nil\n}", "func (client ApplicationsClient) AddOwnerPreparer(ctx context.Context, applicationObjectID string, parameters AddOwnerParameters) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}/$links/owners\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client IngestionSettingsClient) DeletePreparer(ctx context.Context, ingestionSettingName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"ingestionSettingName\": autorest.Encode(\"path\", ingestionSettingName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2021-01-15-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/providers/Microsoft.Security/ingestionSettings/{ingestionSettingName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client OpenShiftManagedClustersClient) DeletePreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": v20180930preview.APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/openShiftManagedClusters/{resourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func removeApp(search string, apps *applications) error {\n\tif i, found := stringInSlice(search, (*apps)[\"default\"]); found == true {\n\t\t(*apps)[\"default\"] = append((*apps)[\"default\"][:i], (*apps)[\"default\"][i+1:]...)\n\t\tmsg := fmt.Sprintf(\"Successfully removed %s from default opener group\", search)\n\t\terr := rewriteApps(apps, msg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tmsg := fmt.Sprintf(\"Could not find %s in configuration\\n\", search)\n\t\treturn errors.New(msg)\n\t}\n\n\treturn nil\n}", "func (client RosettaNetProcessConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, rosettaNetProcessConfigurationName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"integrationAccountName\": autorest.Encode(\"path\", integrationAccountName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"rosettaNetProcessConfigurationName\": autorest.Encode(\"path\", rosettaNetProcessConfigurationName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2016-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/rosettanetprocessconfigurations/{rosettaNetProcessConfigurationName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client JobClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, jobName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"jobName\": jobName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsDelete(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/jobs/{jobName}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func CreateRemoveAppGroupRequest() (request *RemoveAppGroupRequest) {\n\trequest = &RemoveAppGroupRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"OpenSearch\", \"2017-12-25\", \"RemoveAppGroup\", \"/v4/openapi/app-groups/[appGroupIdentity]\", \"\", \"\")\n\trequest.Method = requests.DELETE\n\treturn\n}", "func (client PatternClient) DeletePatternsPreparer(ctx context.Context, appID uuid.UUID, versionID string, patternIds []uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/patternrules\", pathParameters),\n\t\tautorest.WithJSON(patternIds))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (app *App) Remove(uuid gocql.UUID) (err error) {\n\tif err = app.tre.session.Query(`DELETE FROM applications WHERE uuid = ?`,\n\t\tuuid).Exec(); err != nil {\n\t\tfmt.Printf(\"Remove Error: %s\\n\", err.Error())\n\t\treturn\n\t}\n\terr = app.tre.com.RemoveAll(uuid)\n\treturn\n}", "func (client BaseClient) DeleteSystemPreparer(ctx context.Context, pathParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"path\": autorest.Encode(\"path\", pathParameter),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/api/systems/{path}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ApplicationsClient) ListOwnersPreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}/owners\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client IotHubResourceClient) DeletePreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-04-30-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (app *App) UnsetEnvsFromApp(variableNames []string, publicOnly, useQueue bool) error {\n\tif len(variableNames) > 0 {\n\t\tfor _, name := range variableNames {\n\t\t\tvar unset bool\n\t\t\te, err := app.getEnv(name)\n\t\t\tif !publicOnly || (err == nil && e.Public) {\n\t\t\t\tunset = true\n\t\t\t}\n\t\t\tif unset {\n\t\t\t\tdelete(app.Env, name)\n\t\t\t}\n\t\t}\n\t\tif err := db.Session.Apps().Update(bson.M{\"name\": app.Name}, app); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tapp.SerializeEnvVars()\n\t}\n\treturn nil\n}", "func (client ViewsClient) DeletePreparer(ctx context.Context, viewName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"viewName\": autorest.Encode(\"path\", viewName),\n\t}\n\n\tconst APIVersion = \"2019-11-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.CostManagement/views/{viewName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ModelClient) AddPrebuiltPreparer(ctx context.Context, appID uuid.UUID, versionID string, prebuiltExtractorNames []string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/prebuilts\", pathParameters),\n\t\tautorest.WithJSON(prebuiltExtractorNames))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ModelClient) DeletePrebuiltSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ListManagementTermListsClient) DeletePreparer(ctx context.Context, listID string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"listId\": autorest.Encode(\"path\", listID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/contentmoderator/lists/v1.0/termlists/{listId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ApplicationsClient) GetPreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (throttler *Throttler) UnthrottleApp(appName string) (appThrottle *base.AppThrottle) {\n\tthrottler.throttledApps.Delete(appName)\n\t// the app is likely to check\n\tgo throttler.heartbeatWriter.RequestHeartbeats()\n\treturn base.NewAppThrottle(appName, time.Now(), 0, false)\n}", "func (client ModelClient) ListPrebuiltEntitiesPreparer(ctx context.Context, appID uuid.UUID, versionID string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/listprebuilts\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ApplicationsClient) PatchPreparer(ctx context.Context, applicationObjectID string, parameters ApplicationUpdateParameters) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func DecodeRemoveRequest(_ context.Context, r *http.Request) (req interface{}, err error) {\n\treq = endpoints.RemoveRequest{Id: mux.Vars(r)[\"id\"]}\n\t//err = json.NewDecoder(r.Body).Decode(&r)\n\treturn req, err\n}", "func (client DeploymentsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, version []string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif version != nil && len(version) > 0 {\n\t\tqueryParameters[\"version\"] = version\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DeploymentsClient) DisableRemoteDebuggingPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/disableRemoteDebugging\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ReferenceDataSetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, environmentName string, referenceDataSetName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"environmentName\": autorest.Encode(\"path\", environmentName),\n\t\t\"referenceDataSetName\": autorest.Encode(\"path\", referenceDataSetName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-05-15\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TimeSeriesInsights/environments/{environmentName}/referenceDataSets/{referenceDataSetName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (_Token *TokenTransactor) RemoveFromMinters(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"removeFromMinters\", account)\n}", "func (reqSet *requestSet) DelRequest(name string) RequestSet {\n\tdelete((*reqSet), name)\n\treturn reqSet\n}", "func (_TxRelay *TxRelayTransactor) RemoveFromWhitelist(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _TxRelay.contract.Transact(opts, \"removeFromWhitelist\", addr)\n}", "func prepContext(r *http.Request) *http.Request {\n\tskip := getSkipFile(r)\n\tres := r.WithContext(\n\t\tcontext.WithValue(r.Context(), toSkip, skip+1),\n\t)\n\n\treturn res\n}", "func (client *WebAppsClient) deletePremierAddOnCreateRequest(ctx context.Context, resourceGroupName string, name string, premierAddOnName string, options *WebAppsDeletePremierAddOnOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/premieraddons/{premierAddOnName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif premierAddOnName == \"\" {\n\t\treturn nil, errors.New(\"parameter premierAddOnName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{premierAddOnName}\", url.PathEscape(premierAddOnName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func NewAppPreOrdersDeleteInstanceRequest(server string, id string) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParamWithLocation(\"simple\", false, \"id\", runtime.ParamLocationPath, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserverURL, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toperationPath := fmt.Sprintf(\"/v1/appPreOrders/%s\", pathParam0)\n\tif operationPath[0] == '/' {\n\t\toperationPath = \".\" + operationPath\n\t}\n\n\tqueryURL, err := serverURL.Parse(operationPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", queryURL.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (client CloudEndpointsClient) DeletePreparer(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string, cloudEndpointName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"cloudEndpointName\": autorest.Encode(\"path\", cloudEndpointName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"storageSyncServiceName\": autorest.Encode(\"path\", storageSyncServiceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"syncGroupName\": autorest.Encode(\"path\", syncGroupName),\n\t}\n\n\tconst APIVersion = \"2020-03-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups/{syncGroupName}/cloudEndpoints/{cloudEndpointName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client PatternClient) DeletePatternPreparer(ctx context.Context, appID uuid.UUID, versionID string, patternID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"patternId\": autorest.Encode(\"path\", patternID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/patternrules/{patternId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (psc *PartitionSchedulingContext) RemoveSchedulingApplication(appId string) (*SchedulingApplication, error) {\n psc.lock.Lock()\n defer psc.lock.Unlock()\n\n // Remove from applications map\n if psc.applications[appId] == nil {\n return nil, fmt.Errorf(\"removing application %s from partition %s, but application does not exist\", appId, psc.Name)\n }\n schedulingApp := psc.applications[appId]\n delete(psc.applications, appId)\n\n // Remove app under queue\n schedulingQueue := psc.queues[schedulingApp.ApplicationInfo.QueueName]\n if schedulingQueue == nil {\n // This is not normal\n panic(fmt.Sprintf(\"Failed to find queue %s for app=%s while removing application\", schedulingApp.ApplicationInfo.QueueName, appId))\n }\n schedulingQueue.RemoveSchedulingApplication(schedulingApp)\n\n return schedulingApp, nil\n}", "func (m *ManagedDeviceItemRequestBuilder) CleanWindowsDevice()(*i35e5de1b6d1217fb83cdfe34b93910dd53c07bcbaed491f2d9dd30bf097a2e27.CleanWindowsDeviceRequestBuilder) {\n return i35e5de1b6d1217fb83cdfe34b93910dd53c07bcbaed491f2d9dd30bf097a2e27.NewCleanWindowsDeviceRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (client DatasetClient) DeletePreparer(ctx context.Context, datasetID string) (*http.Request, error) {\n urlParameters := map[string]interface{} {\n \"geography\": autorest.Encode(\"path\",client.Geography),\n }\n\n pathParameters := map[string]interface{} {\n \"datasetId\": autorest.Encode(\"path\",datasetID),\n }\n\n const APIVersion = \"2.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsDelete(),\nautorest.WithCustomBaseURL(\"https://{geography}.atlas.microsoft.com\", urlParameters),\nautorest.WithPathParameters(\"/datasets/{datasetId}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func removeAppIngress(ctx context.Context, h *helper.H, index int) {\n\tvar err error\n\n\tPublishingStrategyInstance, ps := getPublishingStrategy(ctx, h)\n\n\t// remove application ingress at index `index`\n\tappIngressList := PublishingStrategyInstance.Spec.ApplicationIngress\n\tPublishingStrategyInstance.Spec.ApplicationIngress = append(appIngressList[:index], appIngressList[index+1:]...)\n\n\tps.Object, err = runtime.DefaultUnstructuredConverter.ToUnstructured(&PublishingStrategyInstance)\n\tExpect(err).NotTo(HaveOccurred())\n\n\t// Update the publishingstrategy\n\tps, err = h.Dynamic().\n\t\tResource(schema.GroupVersionResource{Group: \"cloudingress.managed.openshift.io\", Version: \"v1alpha1\", Resource: \"publishingstrategies\"}).\n\t\tNamespace(OperatorNamespace).\n\t\tUpdate(ctx, ps, metav1.UpdateOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n}", "func (znp *Znp) ZdoExtSeqApsRemoveReq(nwkAddress string, extendedAddress string, parentAddress string) (rsp *StatusResponse, err error) {\n\treq := &ZdoExtSeqApsRemoveReq{NwkAddress: nwkAddress, ExtendedAddress: extendedAddress, ParentAddress: parentAddress}\n\terr = znp.ProcessRequest(unp.C_SREQ, unp.S_ZDO, 0x51, req, &rsp)\n\treturn\n}", "func removeDataCapRequestIsValidOrAbort(rt runtime.Runtime, request RemoveDataCapRequest, id RmDcProposalID, toRemove DataCap, client address.Address) {\n\tproposal := RemoveDataCapProposal{\n\t\tRemovalProposalID: id,\n\t\tDataCapAmount: toRemove,\n\t\tVerifiedClient: client,\n\t}\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(SignatureDomainSeparation_RemoveDataCap)\n\tif err := proposal.MarshalCBOR(&buf); err != nil {\n\t\trt.Abortf(exitcode.ErrSerialization, \"remove datacap request failed to marshal request: %s\", err)\n\t}\n\n\tif err := rt.VerifySignature(request.VerifierSignature, request.Verifier, buf.Bytes()); err != nil {\n\t\trt.Abortf(exitcode.ErrIllegalArgument, \"remove datacap request signature is invalid: %s\", err)\n\t}\n}", "func (cache *LedisCacheStorage) RemoveApp(appID string) {\n\t_, err := cache.db.Del([]byte(\"app:\" + appID))\n\n\tif err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"Ledis Cache: failed to remove app %v\\n\", err)\n\t}\n}", "func PrepareApp() {\n\tdir.SetChangePermission(!DryRun)\n\tif DryRun {\n\t\tlogger.Verbose = true\n\t}\n}", "func (client ModelClient) ListCustomPrebuiltModelsPreparer(ctx context.Context, appID uuid.UUID, versionID string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/customprebuiltmodels\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client GroupClient) DeleteSecretPreparer(accountName string, databaseName string, secretName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"secretName\": autorest.Encode(\"path\", secretName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/secrets/{secretName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}" ]
[ "0.6263471", "0.60379064", "0.59360147", "0.58667725", "0.5662776", "0.556949", "0.53339285", "0.5283709", "0.5236506", "0.5202917", "0.51327795", "0.5104015", "0.5067082", "0.5027027", "0.49440998", "0.49312922", "0.49147373", "0.49062434", "0.4873404", "0.48475662", "0.48450953", "0.48421815", "0.4827639", "0.48076567", "0.47928172", "0.47914484", "0.47874168", "0.47489795", "0.4732781", "0.46902084", "0.46743682", "0.4663769", "0.4658013", "0.46245375", "0.46220684", "0.45978776", "0.45840058", "0.4563367", "0.4560505", "0.45601457", "0.4557994", "0.45250928", "0.4518101", "0.4517533", "0.45127952", "0.4510323", "0.4509314", "0.45038357", "0.44931707", "0.44818938", "0.44785583", "0.44763714", "0.4446832", "0.4437012", "0.443556", "0.4432561", "0.44238064", "0.44184262", "0.4408937", "0.4397967", "0.43867293", "0.43847978", "0.43802923", "0.43799686", "0.43708146", "0.43681118", "0.4368013", "0.43636826", "0.4359222", "0.43559402", "0.43512535", "0.43506458", "0.4345729", "0.4334971", "0.4332508", "0.43273166", "0.43159953", "0.4307215", "0.4295584", "0.42863542", "0.42798784", "0.42744997", "0.42576316", "0.42534325", "0.4251436", "0.4249203", "0.4235933", "0.42287207", "0.42199594", "0.42172873", "0.42146057", "0.4204601", "0.4196491", "0.4192687", "0.41831484", "0.41731134", "0.41705194", "0.4168123", "0.41612402", "0.41481507" ]
0.7731294
0
RemoveFromAppSender sends the RemoveFromApp request. The method will close the http.Response Body if it receives an error.
func (client AzureAccountsClient) RemoveFromAppSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client AzureAccountsClient) RemoveFromAppResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client ApplicationsClient) RemoveOwnerSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ApplicationsClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client JobClient) RemoveSender(req *http.Request) (future JobRemoveFuture, 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 (client AppsClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client MSIXPackagesClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client Client) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req)\n}", "func (client AzureAccountsClient) RemoveFromApp(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (result OperationStatus, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.RemoveFromApp\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: azureAccountInfoObject,\n\t\t\tConstraints: []validation.Constraint{{Target: \"azureAccountInfoObject\", Name: validation.Null, Rule: false,\n\t\t\t\tChain: []validation.Constraint{{Target: \"azureAccountInfoObject.AzureSubscriptionID\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.ResourceGroup\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.AccountName\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t}}}}}); err != nil {\n\t\treturn result, validation.NewError(\"authoring.AzureAccountsClient\", \"RemoveFromApp\", err.Error())\n\t}\n\n\treq, err := client.RemoveFromAppPreparer(ctx, appID, azureAccountInfoObject)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.RemoveFromAppSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.RemoveFromAppResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (r DeleteAppRequest) Send(ctx context.Context) (*DeleteAppResponse, 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 := &DeleteAppResponse{\n\t\tDeleteAppOutput: r.Request.Data.(*DeleteAppOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func RemoveApp(appName string) error {\n\t_, err := client.HDel(ApplicationKey, appName).Result()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (appHandler *ApplicationApiHandler) DeleteApp(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := ps.ByName(\"id\")\n\tidint, err := strconv.Atoi(id)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tapp, err := appHandler.appService.DeleteApplication(idint)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tresponse, err := json.Marshal(app)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\t_, err = w.Write(response)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\n}", "func (client Client) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (r DeleteAppRequest) Send(ctx context.Context) (*DeleteAppOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*DeleteAppOutput), nil\n}", "func (r DeleteAppRequest) Send(ctx context.Context) (*DeleteAppOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*DeleteAppOutput), nil\n}", "func (client DeviceClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client AzureAccountsClient) RemoveFromAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\tif azureAccountInfoObject != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(azureAccountInfoObject))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client VersionsClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client DatasetClient) DeleteSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func (client ManagementClient) WipeMAMUserDeviceSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client,\n\t\treq,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client HTTPSuccessClient) Delete202Sender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (client ApplicationsClient) RemoveOwnerResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (m *Application) RemoveApp(id string) error {\n\treturn Remove(db, collection, bson.M{\"_id\": bson.ObjectIdHex(id)})\n}", "func (client AccountClient) DeleteSender(req *http.Request) (future AccountDeleteFuture, 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 (client ViewsClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (app *App) Remove(uuid gocql.UUID) (err error) {\n\tif err = app.tre.session.Query(`DELETE FROM applications WHERE uuid = ?`,\n\t\tuuid).Exec(); err != nil {\n\t\tfmt.Printf(\"Remove Error: %s\\n\", err.Error())\n\t\treturn\n\t}\n\terr = app.tre.com.RemoveAll(uuid)\n\treturn\n}", "func unregApp(cmd marcopolo.CmdMsg, srvConn *marcopolo.ServerConn) {\n\tappName := cmd.AppNameParam.AppName\n\tfmt.Println(\"unregister app \", appName)\n\n\t// lookup regd app w. this name\n\tprevApp, found := apps[appName]\n\t_ = prevApp\n\tif found {\n\t\tfmt.Printf(\"unregapp, removing @ %s\\n\", prevApp.appAddr)\n\n\t\t// remove app entry\n\t\tdelete(apps, appName)\n\n\t\t// send OK to caller\n\t\tsrvConn.SendRespUnregApp(cmd.UdpPacket.RemoteAddr)\n\t} else {\n\t\terr := fmt.Errorf(\"unregapp, not found : '%s'\", appName)\n\t\tfmt.Println(err)\n\n\t\t// send error back to app\n\t\tsrvConn.SendRespUnregAppErr(err, cmd.UdpPacket.RemoteAddr)\n\t}\n}", "func (ds *MySQLDatastore) RemoveApp(ctx context.Context, appName string) error {\n\t_, err := ds.db.Exec(`\n\t DELETE FROM apps\n\t WHERE name = ?\n\t`, appName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (client ThreatIntelligenceIndicatorClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client BaseClient) DeleteSystemSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client RosettaNetProcessConfigurationsClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client ModelClient) DeleteIntentSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client MeshNetworkClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ModelClient) DeleteClosedListSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client IngestionSettingsClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client BaseClient) DeleteSubscriptionSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func (client JobClient) RemoveResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func (client HTTPSuccessClient) Delete200Sender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (client DeploymentsClient) DeleteSender(req *http.Request) (future DeploymentsDeleteFuture, err error) {\n\tvar resp *http.Response\n\tfuture.FutureAPI = &azure.Future{}\n\tresp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\tvar azf azure.Future\n\tazf, err = azure.NewFutureFromResponse(resp)\n\tfuture.FutureAPI = &azf\n\tfuture.Result = future.result\n\treturn\n}", "func (client ScheduleMessageClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client Client) RemoveAccessControlSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ServicesClient) DeleteSender(req *http.Request) (future ServicesDeleteFuture, err error) {\n\tvar resp *http.Response\n\tfuture.FutureAPI = &azure.Future{}\n\tresp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\tvar azf azure.Future\n\tazf, err = azure.NewFutureFromResponse(resp)\n\tfuture.FutureAPI = &azf\n\tfuture.Result = future.result\n\treturn\n}", "func (client DatabasesClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req)\n}", "func (p *Pvr) RemoveApplication(appname string) error {\n\tappPath := filepath.Join(p.Dir, appname)\n\tif _, err := os.Stat(appPath); err != nil {\n\t\treturn errors.New(\"App '\" + appname + \"' doesn't exist\")\n\t}\n\terr := os.RemoveAll(appPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (client PublishedBlueprintsClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client JobClient) DeleteSender(req *http.Request) (future JobDeleteFuture, 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 (client ModelClient) DeletePrebuiltSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ReferenceDataSetsClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (client DataControllersClient) DeleteDataControllerSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (s *Scheduler) Remove(app string) error {\n\treturn s.stackBuilder.Remove(app)\n}", "func (client ListManagementTermListsClient) DeleteSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (p *Pipe) RemoveSender() {\n\tp.senders--\n}", "func (client OpenShiftManagedClustersClient) DeleteSender(req *http.Request) (future OpenShiftManagedClustersDeleteFuture, err error) {\n\tvar resp *http.Response\n\tresp, err = autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\terr = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))\n\tif err != nil {\n\t\treturn\n\t}\n\tfuture.Future, err = azure.NewFutureFromResponse(resp)\n\treturn\n}", "func (client ModelClient) DeleteSubListSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client CloudEndpointsClient) DeleteSender(req *http.Request) (future CloudEndpointsDeleteFuture, err error) {\n\tvar resp *http.Response\n\tfuture.FutureAPI = &azure.Future{}\n\tresp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\tvar azf azure.Future\n\tazf, err = azure.NewFutureFromResponse(resp)\n\tfuture.FutureAPI = &azf\n\tfuture.Result = future.result\n\treturn\n}", "func (r StopAppReplicationRequest) Send(ctx context.Context) (*StopAppReplicationOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*StopAppReplicationOutput), nil\n}", "func (client JobClient) StopSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (a AppsApi) AppsAppDelete(app string) (*APIResponse, error) {\n\n\tvar localVarHttpMethod = strings.ToUpper(\"Delete\")\n\t// create path and map variables\n\tlocalVarPath := a.Configuration.BasePath + \"/apps/{app}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"app\"+\"}\", fmt.Sprintf(\"%v\", app), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := make(map[string]string)\n\tvar localVarPostBody interface{}\n\tvar localVarFileName string\n\tvar localVarFileBytes []byte\n\t// add default headers if any\n\tfor key := range a.Configuration.DefaultHeader {\n\t\tlocalVarHeaderParams[key] = a.Configuration.DefaultHeader[key]\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 := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tlocalVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\n\tvar localVarURL, _ = url.Parse(localVarPath)\n\tlocalVarURL.RawQuery = localVarQueryParams.Encode()\n\tvar localVarAPIResponse = &APIResponse{Operation: \"AppsAppDelete\", Method: localVarHttpMethod, RequestURL: localVarURL.String()}\n\tif localVarHttpResponse != nil {\n\t\tlocalVarAPIResponse.Response = localVarHttpResponse.RawResponse\n\t\tlocalVarAPIResponse.Payload = localVarHttpResponse.Body()\n\t}\n\n\tif err != nil {\n\t\treturn localVarAPIResponse, err\n\t}\n\treturn localVarAPIResponse, err\n}", "func (Protos) Remove(ctx context.Context) error {\n\tif err := removeProtosSubmodule(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (client CertificateClient) DeleteSender(req *http.Request) (future CertificateDeleteFuture, err error) {\n\tvar resp *http.Response\n\tresp, err = autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\tfuture.Future, err = azure.NewFutureFromResponse(resp)\n\treturn\n}", "func (h appHandler) deleteAppHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tprojectName := vars[\"project-name\"]\n\tcompositeAppName := vars[\"composite-app-name\"]\n\tcompositeAppVersion := vars[\"version\"]\n\tname := vars[\"app-name\"]\n\n\terr := h.client.DeleteApp(name, projectName, compositeAppName, compositeAppVersion)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}", "func (client ListManagementImageClient) DeleteImageSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func adapterSendUnRegisterToServices(c *gin.Context) {\n\t// trigger method to send all unregister messages to users\n\tsuccess := id.SendUnregisterUserFromYourUserList()\n\tif success {\n\t\tc.String(200, DefaultSuccessMessage)\n\t} else {\n\t\tc.String(404, DefaultErrorMessage)\n\t}\n\t// c.String(403, DefaultNotAvailableMessage)\n}", "func (r *ApplicationRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (p *UserStoreClient) RemoveFromBusiness(ctx context.Context, authenticationToken string, emailAddress string) (err error) {\n var _args21 UserStoreRemoveFromBusinessArgs\n _args21.AuthenticationToken = authenticationToken\n _args21.EmailAddress = emailAddress\n var _result22 UserStoreRemoveFromBusinessResult\n if err = p.Client_().Call(ctx, \"removeFromBusiness\", &_args21, &_result22); err != nil {\n return\n }\n switch {\n case _result22.UserException!= nil:\n return _result22.UserException\n case _result22.SystemException!= nil:\n return _result22.SystemException\n case _result22.NotFoundException!= nil:\n return _result22.NotFoundException\n }\n\n return nil\n}", "func (m *ApplicationResource) DeleteApplication(ctx context.Context, appId string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func (client AppsClient) Delete(ctx context.Context, appID uuid.UUID) (result OperationStatus, err error) {\n\treq, err := client.DeletePreparer(ctx, appID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.AppsClient\", \"Delete\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.DeleteSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.AppsClient\", \"Delete\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.DeleteResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.AppsClient\", \"Delete\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (client BaseClient) DeleteExpectationSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client HTTPSuccessClient) Delete204Sender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (r *app) Delete(appGUID string, opts ...bool) error {\n\tasync := true\n\trecursive := false\n\tif len(opts) > 0 {\n\t\tasync = opts[0]\n\t}\n\tif len(opts) > 1 {\n\t\trecursive = opts[1]\n\t}\n\trawURL := fmt.Sprintf(\"/v2/apps/%s?async=%t&recursive=%t\", appGUID, async, recursive)\n\t_, err := r.client.Delete(rawURL)\n\treturn err\n}", "func (cleaner *RegistryCleaner) DeleteApplicationData(ctx context.Context, applicationList []string) error {\n\tfor _, ids := range applicationList {\n\t\tappIds, err := unique.ToApplicationID(ids)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tctx, err = unique.WithContext(ctx, ids)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\twebhooks, err := cleaner.WebRegistry.List(ctx, appIds, []string{\"ids\"})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, webhook := range webhooks {\n\t\t\t_, err := cleaner.WebRegistry.Set(ctx, webhook.GetIds(), nil,\n\t\t\t\tfunc(webhook *ttnpb.ApplicationWebhook) (*ttnpb.ApplicationWebhook, []string, error) {\n\t\t\t\t\treturn nil, nil, nil\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\t\t}\n\t}\n\treturn nil\n}", "func sendMsgRemoveAdmin(\n\tr *rand.Rand, app *baseapp.BaseApp, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper,\n\tmsg *types.MsgRemoveAdmin, 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 (w *WebPurifyRequest) RemoveFromAllowList(word string) (response.WebPurifyRemoveFromAllowListResponse, error) {\n\n\t// create request parameter collection\n\trequestParameters := []WebPurifyRequestParameter{\n\t\t{Type: Word, Value: word},\n\t}\n\n\t// build http request\n\trequest, err := w.createRequest(RemoveFromAllowList, requestParameters...)\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\t// create http client\n\tclient := w.createHttpClient()\n\n\t// Execute http request\n\thttpResponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\t// convert response to struct\n\twebPurifyResponse, err := w.convertToRemoveFromAllowListResponse(*httpResponse)\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\treturn webPurifyResponse, nil\n}", "func (o *Originator) Remove(items []string) {\n\tfor _, item := range items {\n\t\tdelete(o.data, item)\n\t}\n}", "func (client IotHubResourceClient) DeleteSender(req *http.Request) (future IotHubResourceDeleteFuture, err error) {\n\tvar resp *http.Response\n\tfuture.FutureAPI = &azure.Future{}\n\tresp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\tvar azf azure.Future\n\tazf, err = azure.NewFutureFromResponse(resp)\n\tfuture.FutureAPI = &azf\n\tfuture.Result = future.result\n\treturn\n}", "func RemoveDeploymentEventClient(contextName string, namespace string, client chan DeploymentEvent) {\n\n\t// Get the context receiver\n\tctxReceiver, ok := contextReceivers[contextName]\n\tif !ok {\n\t\treturn\n\t}\n\n\t// Get the namespace receiver\n\tnsReceiver, ok := ctxReceiver.namespaceReceivers[namespace]\n\tif !ok {\n\t\treturn\n\t}\n\n\t// Get the receiver\n\treceiver := nsReceiver.deploymentEventReceiver\n\tif receiver == nil {\n\t\treturn\n\t}\n\n\t// Remove the client\n\treceiver.removeClient(client)\n\n\t// If no more client, stop receiving event\n\tif len(receiver.clients) == 0 {\n\t\treceiver.stop()\n\t\tnsReceiver.deploymentEventReceiver = nil\n\t}\n}", "func (psc *PartitionSchedulingContext) RemoveSchedulingApplication(appId string) (*SchedulingApplication, error) {\n psc.lock.Lock()\n defer psc.lock.Unlock()\n\n // Remove from applications map\n if psc.applications[appId] == nil {\n return nil, fmt.Errorf(\"removing application %s from partition %s, but application does not exist\", appId, psc.Name)\n }\n schedulingApp := psc.applications[appId]\n delete(psc.applications, appId)\n\n // Remove app under queue\n schedulingQueue := psc.queues[schedulingApp.ApplicationInfo.QueueName]\n if schedulingQueue == nil {\n // This is not normal\n panic(fmt.Sprintf(\"Failed to find queue %s for app=%s while removing application\", schedulingApp.ApplicationInfo.QueueName, appId))\n }\n schedulingQueue.RemoveSchedulingApplication(schedulingApp)\n\n return schedulingApp, nil\n}", "func (controller AppsController) Delete(c *gin.Context) {\n\t_, err := mongodb.DeleteByID(controller.MongoDBClient, Collections[\"apps\"], c.Params.ByName(\"id\"))\n\n\tif err != nil {\n\t\tfmt.Printf(\"error %v\", err)\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"message\": \"Unable to remove object\"})\n\t\treturn\n\t}\n\n\t// Remove all versions related\n\t/*_, err := mongodb.DeleteAll(controller.MongoDBClient, Collections[\"versions\"], bson.M{\"app_id\": c.Params.ByName(\"id\")})\n\tif err != nil {\n\t\tfmt.Printf(\"error %v\", err)\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"message\": \"Unable to remove object\"})\n\t\treturn\n\t}*/\n\n\tc.Status(http.StatusOK)\n}", "func (cache *LedisCacheStorage) RemoveApp(appID string) {\n\t_, err := cache.db.Del([]byte(\"app:\" + appID))\n\n\tif err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"Ledis Cache: failed to remove app %v\\n\", err)\n\t}\n}", "func (m *ApplicationResource) DeactivateApplication(ctx context.Context, appId string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/lifecycle/deactivate\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func (a *ApplicationsApiService) ApplicationsAppInstanceIdDELETE(ctx context.Context, appInstanceId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/applications/{appInstanceId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"appInstanceId\"+\"}\", fmt.Sprintf(\"%v\", appInstanceId), -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\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn 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\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (s *Server) Remove(ctx context.Context, message *todopb.RemoveRequest) (*todopb.RemoveResponse, error) {\n\tctx = context.WithValue(ctx, goa.MethodKey, \"remove\")\n\tctx = context.WithValue(ctx, goa.ServiceKey, \"todo\")\n\tresp, err := s.RemoveH.Handle(ctx, message)\n\tif err != nil {\n\t\treturn nil, goagrpc.EncodeError(err)\n\t}\n\treturn resp.(*todopb.RemoveResponse), nil\n}", "func (client FirewallPolicyRuleGroupsClient) DeleteSender(req *http.Request) (future FirewallPolicyRuleGroupsDeleteFuture, err error) {\n\tvar resp *http.Response\n\tfuture.FutureAPI = &azure.Future{}\n\tresp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\tvar azf azure.Future\n\tazf, err = azure.NewFutureFromResponse(resp)\n\tfuture.FutureAPI = &azf\n\tfuture.Result = future.result\n\treturn\n}", "func (l *Service) Remove(bytes []byte) ([]byte, error) {\n\trequest := &RemoveRequest{}\n\tif err := proto.Unmarshal(bytes, request); err != nil {\n\t\treturn nil, err\n\t}\n\n\tindex := request.Index\n\tif index >= uint32(len(l.values)) {\n\t\treturn nil, errors.NewInvalid(\"index %d out of bounds\", index)\n\t}\n\n\tvalue := l.values[index]\n\tl.values = append(l.values[:index], l.values[index+1:]...)\n\n\tl.sendEvent(&ListenResponse{\n\t\tType: ListenResponse_REMOVED,\n\t\tIndex: index,\n\t\tValue: value,\n\t})\n\n\treturn proto.Marshal(&RemoveResponse{\n\t\tStatus: ResponseStatus_OK,\n\t\tValue: value,\n\t})\n}", "func (r RemoveTagsFromResourceRequest) Send() (*RemoveTagsFromResourceOutput, error) {\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*RemoveTagsFromResourceOutput), nil\n}", "func (c *Client) Remove(ctx context.Context, id uint64) error {\n\trequest := protocol.Message{}\n\trequest.Init(4096)\n\tresponse := protocol.Message{}\n\tresponse.Init(4096)\n\n\tprotocol.EncodeRemove(&request, id)\n\n\tif err := c.protocol.Call(ctx, &request, &response); err != nil {\n\t\treturn err\n\t}\n\n\tif err := protocol.DecodeEmpty(&response); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (throttler *Throttler) UnthrottleApp(appName string) (appThrottle *base.AppThrottle) {\n\tthrottler.throttledApps.Delete(appName)\n\t// the app is likely to check\n\tgo throttler.heartbeatWriter.RequestHeartbeats()\n\treturn base.NewAppThrottle(appName, time.Now(), 0, false)\n}", "func (client ApplicationsClient) Delete(ctx context.Context, applicationObjectID string) (result autorest.Response, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ApplicationsClient.Delete\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response != nil {\n\t\t\t\tsc = result.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.DeletePreparer(ctx, applicationObjectID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"graphrbac.ApplicationsClient\", \"Delete\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.DeleteSender(req)\n\tif err != nil {\n\t\tresult.Response = resp\n\t\terr = autorest.NewErrorWithError(err, \"graphrbac.ApplicationsClient\", \"Delete\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.DeleteResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"graphrbac.ApplicationsClient\", \"Delete\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (client HTTPSuccessClient) Post204Sender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (client ConversationsClient) DeleteActivityMethodSender(req *http.Request) (*http.Response, error) {\n sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n return autorest.SendWithSender(client, req, sd...)\n }", "func (a *OAuthAuthorizationsApiService) AuthorizationsOwnerSubjectidApplicationAppidDelete(ctx _context.Context, subjectid string, appid string) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/authorizations/owner/{subjectid}/application/{appid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"subjectid\"+\"}\", _neturl.QueryEscape(parameterToString(subjectid, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"appid\"+\"}\", _neturl.QueryEscape(parameterToString(appid, \"\")) , -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{}\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 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\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 localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *Client) QuitApp() (e error) {\n\tclient := cast.NewClient(c.ip, c.port)\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\te = fmt.Errorf(\"Panic occurs on QuitApp [%w]\", err)\n\t\t}\n\t}()\n\n\treceiver := client.Receiver()\n\t_, err := receiver.QuitApp(c.ctx)\n\treturn err\n}", "func (client BaseClient) DeleteFeatureInstanceSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (c Client) DeleteApplication(name string) (types.TaskRef, error) {\n var taskRef types.TaskRef\n\n app, err := c.Application(name)\n if err != nil {\n return taskRef, err\n }\n\n accounts := strings.Split(app.Accounts, \",\")\n\n var jobs []types.Job\n\n for _, account := range accounts {\n jobs = append(jobs, types.Job {\n Type: \"deleteApplication\",\n Account: account,\n User: \"\",\n Application: types.DeleteApplication {\n Name: app.Name,\n Accounts: app.Accounts,\n CloudProviders: app.CloudProviders.Names,\n },\n })\n }\n\n task := types.Task {\n Application: app.Name,\n Description: \"Deleting Application: \" + app.Name,\n Job : jobs,\n }\n\n resp, err := c.post(\"/applications/\" + name + \"/tasks\", task)\n defer ensureReaderClosed(resp)\n if err != nil {\n return taskRef, err\n }\n\n err = json.NewDecoder(resp.body).Decode(&taskRef)\n return taskRef, err\n}", "func (c Client) RevokeAppFromMerchant(merchantID string, appID string) error {\n\treturn c.revokeAppFromMerchant(merchantID, appID)\n}", "func (s *Scheduler) InnerDeleteApplication(runAs, appID string, enforce bool) error {\n\tblog.Info(\"inner delete application(%s.%s), enforce(%t)\", runAs, appID, enforce)\n\n\ts.store.LockApplication(runAs + \".\" + appID)\n\tdefer s.store.UnLockApplication(runAs + \".\" + appID)\n\n\tapp, err := s.store.FetchApplication(runAs, appID)\n\tif err != nil {\n\t\tblog.Warn(\"inner delete application: get application(%s.%s) err %s\", runAs, appID, err.Error())\n\t\treturn err\n\t}\n\tif app == nil {\n\t\tblog.Warn(\"inner delete application: get application(%s.%s) return nil\", runAs, appID)\n\t\treturn errors.New(\"application not found\")\n\t}\n\n\tif app.Status == types.APP_STATUS_OPERATING {\n\t\tblog.Warn(\"inner delete application: application (%s.%s) is in status(%s) now \", runAs, appID, app.Status)\n\t}\n\n\ttaskGroups, err := s.store.ListTaskGroups(runAs, appID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, taskGroup := range taskGroups {\n\t\tblog.Info(\"inner delete application: kill taskgroup(%s)\", taskGroup.ID)\n\t\tresp, err := s.KillTaskGroup(taskGroup)\n\t\tif err != nil {\n\t\t\tblog.Error(\"inner delete application: kill taskgroup(%s) failed: %s\", taskGroup.ID, err.Error())\n\t\t\treturn err\n\t\t}\n\t\tif resp == nil {\n\t\t\tblog.Error(\"inner delete application: kill taskGroup(%s) resp nil\", taskGroup.ID)\n\t\t\terr = fmt.Errorf(\"kill taskGroup(%s) resp is nil\", taskGroup.ID)\n\t\t\treturn err\n\t\t} else if resp.StatusCode != http.StatusAccepted {\n\t\t\tblog.Error(\"inner delete application: kill taskGroup(%s) resp code %d\", taskGroup.ID, resp.StatusCode)\n\t\t\terr = fmt.Errorf(\"kill taskGroup(%s) status code %d received\", taskGroup.ID, resp.StatusCode)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdeleteTrans := &types.Transaction{\n\t\tObjectKind: string(commtypes.BcsDataType_APP),\n\t\tObjectName: appID,\n\t\tNamespace: runAs,\n\t\tTransactionID: types.GenerateTransactionID(string(commtypes.BcsDataType_APP)),\n\t\tCreateTime: time.Now(),\n\t\tCheckInterval: 3 * time.Second,\n\t\tCurOp: &types.TransactionOperartion{\n\t\t\tOpType: types.TransactionOpTypeDelete,\n\t\t\tOpDeleteData: &types.TransAPIDeleteOpdata{\n\t\t\t\tEnforce: enforce,\n\t\t\t},\n\t\t},\n\t\tStatus: types.OPERATION_STATUS_INIT,\n\t}\n\tif err := s.store.SaveTransaction(deleteTrans); err != nil {\n\t\tblog.Errorf(\"save transaction(%s,%s) into db failed, err %s\", runAs, appID, err.Error())\n\t\treturn err\n\t}\n\tblog.Infof(\"transaction %s delete application(%s.%s) run begin\",\n\t\tdeleteTrans.TransactionID, deleteTrans.Namespace, deleteTrans.ObjectName)\n\n\ts.PushEventQueue(deleteTrans)\n\n\tapp.LastStatus = app.Status\n\tapp.Status = types.APP_STATUS_OPERATING\n\tapp.SubStatus = types.APP_SUBSTATUS_UNKNOWN\n\tapp.UpdateTime = time.Now().Unix()\n\tapp.Message = \"application in deleting\"\n\tif err := s.store.SaveApplication(app); err != nil {\n\t\tblog.Error(\"inner delete application: save application(%s.%s) status(%s) into db failed! err:%s\",\n\t\t\trunAs, appID, app.Status, err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (d *DecodeService) Remove(w http.ResponseWriter, r *http.Request) {\n\tvar req request.UserNameAudioToken\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\tif err != nil {\n\t\tservice.ProcessBadFormat(w, service.ErrWrongFormat)\n\t\treturn\n\t}\n\n\tdb, err := d.adb.Get(req.Username)\n\tif err != nil {\n\t\tservice.ProcessServerError(w, service.ErrFindUser)\n\t\treturn\n\t}\n\n\tas, err := storage.NewAudioPostgres(db)\n\tif err != nil {\n\t\tservice.ProcessServerError(w, service.ErrFindUser)\n\t\treturn\n\t}\n\n\taudio, err := as.GetByToken(req.Token)\n\tif err != nil {\n\t\tservice.ProcessServerError(w, service.ErrFindUserAudio)\n\t\treturn\n\t}\n\n\terr = os.Remove(path.Join(getBaseDir(req.Username), audio.Name))\n\tlog.Println(err)\n\tas.Remove(audio)\n}", "func (c Client) revokeAppFromMerchant(merchantID string, appID string) error {\n\tpath := fmt.Sprintf(\"/merchants/%s/apps/%s\", merchantID, appID)\n\treq, err := http.NewRequest(\"DELETE\", c.getURL(path), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.executeRequestAndMarshal(req, nil)\n}", "func (s *server) Delete(ctx context.Context, body *pb.NameHolder) (*pb.DeletionResponse, error) {\n\tappName := body.GetName()\n\tfilter := types.M{\n\t\tmongo.NameKey: appName,\n\t\tmongo.InstanceTypeKey: mongo.AppInstance,\n\t}\n\n\tnode, _ := redis.FetchAppNode(appName)\n\tgo redis.DecrementServiceLoad(ServiceName, node)\n\tgo redis.RemoveApp(appName)\n\tgo diskCleanup(appName)\n\n\tif configs.CloudflareConfig.PlugIn {\n\t\tgo cloudflare.DeleteRecord(appName, mongo.AppInstance)\n\t}\n\n\t_, err := mongo.DeleteInstance(filter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pb.DeletionResponse{Success: true}, nil\n}", "func (client HTTPSuccessClient) Patch204Sender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (r TerminateAppRequest) Send(ctx context.Context) (*TerminateAppOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*TerminateAppOutput), nil\n}" ]
[ "0.68842465", "0.63266635", "0.6147839", "0.6085987", "0.60858536", "0.6000384", "0.5606856", "0.5588852", "0.5560981", "0.55208546", "0.5474393", "0.54733056", "0.54073346", "0.54073346", "0.5391004", "0.5374884", "0.5329832", "0.53290236", "0.53207594", "0.5297474", "0.5286642", "0.527884", "0.52642536", "0.52245146", "0.5209485", "0.5207763", "0.52060443", "0.5190783", "0.51899123", "0.5169633", "0.5168732", "0.5153616", "0.50937474", "0.50559807", "0.5032289", "0.5029053", "0.5022839", "0.5020476", "0.50131905", "0.50002193", "0.4986222", "0.4983137", "0.4978282", "0.49782613", "0.49728894", "0.49615583", "0.49469334", "0.49220073", "0.49019188", "0.49009395", "0.4899901", "0.48771983", "0.48739424", "0.48671922", "0.48639193", "0.4859914", "0.48560598", "0.48451275", "0.48381737", "0.4826128", "0.48022947", "0.47678128", "0.47677794", "0.4767766", "0.47481552", "0.474624", "0.47445852", "0.47443917", "0.4742359", "0.47289512", "0.47222692", "0.47124842", "0.47079608", "0.4696369", "0.4690683", "0.46895322", "0.46558955", "0.46549565", "0.46546766", "0.4650388", "0.46432903", "0.4639864", "0.4627595", "0.46144098", "0.46092469", "0.46048197", "0.4604458", "0.4604352", "0.46031755", "0.46016374", "0.4595386", "0.4592339", "0.45835617", "0.4582369", "0.45810482", "0.45765927", "0.4571773", "0.45696923", "0.45614868", "0.45586967" ]
0.79308885
0
RemoveFromAppResponder handles the response to the RemoveFromApp request. The method always closes the http.Response Body.
func (client AzureAccountsClient) RemoveFromAppResponder(resp *http.Response) (result OperationStatus, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client JobClient) RemoveResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func (client ApplicationsClient) RemoveOwnerResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client AzureAccountsClient) RemoveFromAppSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (client ApplicationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (appHandler *ApplicationApiHandler) DeleteApp(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := ps.ByName(\"id\")\n\tidint, err := strconv.Atoi(id)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tapp, err := appHandler.appService.DeleteApplication(idint)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tresponse, err := json.Marshal(app)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\t_, err = w.Write(response)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, http.StatusText(404), 404)\n\t\treturn\n\t}\n\n}", "func (client MSIXPackagesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client AppsClient) DeleteResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (h appHandler) deleteAppHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tprojectName := vars[\"project-name\"]\n\tcompositeAppName := vars[\"composite-app-name\"]\n\tcompositeAppVersion := vars[\"version\"]\n\tname := vars[\"app-name\"]\n\n\terr := h.client.DeleteApp(name, projectName, compositeAppName, compositeAppVersion)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}", "func (client DeploymentsClient) StopResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client HTTPSuccessClient) Delete202Responder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func (client Client) RemoveAccessControlResponder(resp *http.Response) (result VolumeAccessControlRemoveResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (m *Application) RemoveApp(id string) error {\n\treturn Remove(db, collection, bson.M{\"_id\": bson.ObjectIdHex(id)})\n}", "func (client HTTPSuccessClient) Delete200Responder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func RemoveApp(appName string) error {\n\t_, err := client.HDel(ApplicationKey, appName).Result()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func DecodeRemoveResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (interface{}, error) {\n\treturn func(resp *http.Response) (interface{}, error) {\n\t\tif restoreBody {\n\t\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(b))\n\t\t\tdefer func() {\n\t\t\t\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(b))\n\t\t\t}()\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusNoContent:\n\t\t\treturn nil, nil\n\t\tdefault:\n\t\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\treturn nil, goahttp.ErrInvalidResponse(\"blog\", \"remove\", resp.StatusCode, string(body))\n\t\t}\n\t}\n}", "func (client ServicesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client ModelClient) DeleteClosedListResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client AccountClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func (client DeploymentsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func DecodeRemoveResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (any, error) {\n\treturn func(resp *http.Response) (any, error) {\n\t\tif restoreBody {\n\t\t\tb, err := io.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\tdefer func() {\n\t\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\t}()\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusNoContent:\n\t\t\treturn nil, nil\n\t\tdefault:\n\t\t\tbody, _ := io.ReadAll(resp.Body)\n\t\t\treturn nil, goahttp.ErrInvalidResponse(\"storage\", \"remove\", resp.StatusCode, string(body))\n\t\t}\n\t}\n}", "func (client ModelClient) DeleteIntentResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client JobClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func (client CertificateClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client OpenShiftManagedClustersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client DatasetClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func (client ServicesClient) StopResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client ModelClient) DeleteSubListResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client FirewallPolicyRuleGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client ConversationsClient) DeleteActivityMethodResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func (client DataControllersClient) DeleteDataControllerResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client ViewsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func unregApp(cmd marcopolo.CmdMsg, srvConn *marcopolo.ServerConn) {\n\tappName := cmd.AppNameParam.AppName\n\tfmt.Println(\"unregister app \", appName)\n\n\t// lookup regd app w. this name\n\tprevApp, found := apps[appName]\n\t_ = prevApp\n\tif found {\n\t\tfmt.Printf(\"unregapp, removing @ %s\\n\", prevApp.appAddr)\n\n\t\t// remove app entry\n\t\tdelete(apps, appName)\n\n\t\t// send OK to caller\n\t\tsrvConn.SendRespUnregApp(cmd.UdpPacket.RemoteAddr)\n\t} else {\n\t\terr := fmt.Errorf(\"unregapp, not found : '%s'\", appName)\n\t\tfmt.Println(err)\n\n\t\t// send error back to app\n\t\tsrvConn.SendRespUnregAppErr(err, cmd.UdpPacket.RemoteAddr)\n\t}\n}", "func (client VersionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client DataFlowClient) DeleteDataFlowResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client CloudEndpointsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNotFound),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client HTTPSuccessClient) Post204Responder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func (client ScheduleMessageClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound, http.StatusInternalServerError),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client IotHubResourceClient) DeleteResponder(resp *http.Response) (result SetObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent, http.StatusNotFound),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client LabClient) DeleteResourceResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client ProviderShareSubscriptionsClient) RevokeResponder(resp *http.Response) (result ProviderShareSubscription, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (s *BaseSyslParserListener) ExitApplication(ctx *ApplicationContext) {}", "func (client ManagementClient) WipeMAMUserDeviceResponder(resp *http.Response) (result WipeDeviceOperationResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client DeviceClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound, http.StatusInternalServerError),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client HTTPSuccessClient) Delete204Responder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func (m *ApplicationResource) DeactivateApplication(ctx context.Context, appId string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/lifecycle/deactivate\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func (client JobClient) StopResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client RosettaNetProcessConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client BaseClient) DeleteSystemResponder(resp *http.Response) (result String, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client AzureAccountsClient) RemoveFromAppPreparer(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/azureaccounts\", pathParameters))\n\tif azureAccountInfoObject != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(azureAccountInfoObject))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AzureAccountsClient) RemoveFromApp(ctx context.Context, appID uuid.UUID, azureAccountInfoObject *AzureAccountInfoObject) (result OperationStatus, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AzureAccountsClient.RemoveFromApp\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: azureAccountInfoObject,\n\t\t\tConstraints: []validation.Constraint{{Target: \"azureAccountInfoObject\", Name: validation.Null, Rule: false,\n\t\t\t\tChain: []validation.Constraint{{Target: \"azureAccountInfoObject.AzureSubscriptionID\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.ResourceGroup\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t\t{Target: \"azureAccountInfoObject.AccountName\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t}}}}}); err != nil {\n\t\treturn result, validation.NewError(\"authoring.AzureAccountsClient\", \"RemoveFromApp\", err.Error())\n\t}\n\n\treq, err := client.RemoveFromAppPreparer(ctx, appID, azureAccountInfoObject)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.RemoveFromAppSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.RemoveFromAppResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"authoring.AzureAccountsClient\", \"RemoveFromApp\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (client LinkedServiceClient) DeleteLinkedServiceResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client BaseClient) DeleteSubscriptionResponder(resp *http.Response) (result Error, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted,http.StatusBadRequest,http.StatusForbidden,http.StatusNotFound,http.StatusInternalServerError),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client HTTPSuccessClient) Patch204Responder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func (client CertificateClient) CancelDeletionResponder(resp *http.Response) (result Certificate, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client ContainerAppsRevisionsClient) DeactivateRevisionResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client ListManagementTermListsClient) DeleteResponder(resp *http.Response) (result String, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client MeshNetworkClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func CreateRemoveAppGroupResponse() (response *RemoveAppGroupResponse) {\n\tresponse = &RemoveAppGroupResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client ReferenceDataSetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client ModelClient) DeletePrebuiltResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (a *OAuthAuthorizationsApiService) AuthorizationsOwnerSubjectidApplicationAppidDelete(ctx _context.Context, subjectid string, appid string) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/authorizations/owner/{subjectid}/application/{appid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"subjectid\"+\"}\", _neturl.QueryEscape(parameterToString(subjectid, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"appid\"+\"}\", _neturl.QueryEscape(parameterToString(appid, \"\")) , -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{}\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 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\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 localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (a *ApplicationsApiService) ApplicationsAppInstanceIdDELETE(ctx context.Context, appInstanceId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/applications/{appInstanceId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"appInstanceId\"+\"}\", fmt.Sprintf(\"%v\", appInstanceId), -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\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn 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\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (client ModelClient) DeleteRegexEntityModelResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client ThreatIntelligenceIndicatorClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client PublishedBlueprintsClient) DeleteResponder(resp *http.Response) (result PublishedBlueprint, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func removeProductHandle(response http.ResponseWriter, request *http.Request) {\n\torderId := strings.Split(request.URL.Path, \"/\")[3]\n\tlog.Printf(\"Remove product for order %s!\", orderId)\n\tdecoder := json.NewDecoder(request.Body)\n\tremoveProductCommand := commands.RemoveProduct{}\n\terr := decoder.Decode(&removeProductCommand)\n\tif err != nil {\n\t\twriteErrorResponse(response, err)\n\t}\n\torder := <-orderHandler.RemoveProductInOrder(OrderId{Id: orderId}, removeProductCommand)\n\twriteResponse(response, order)\n}", "func (client ModelClient) DeleteCustomPrebuiltDomainResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client FeatureStateClient) DeleteStatesetResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func (client Client) DeleteResponder(resp *http.Response) (result VolumeInstancesDeleteResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func HandleConsentRemoval(cb func(uid string)) http.HandlerFunc {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodDelete {\n\t\t\tw.Header().Set(\"Allow\", \"DELETE\")\n\t\t\thttp.Error(w, \"Unsupported method\", http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\t\tuid := path.Base(r.URL.Path)\n\t\tcb(uid)\n\t}\n\n\treturn fn\n}", "func cleanup() {\n\tserver.Applications = []*types.ApplicationMetadata{}\n}", "func (ds *MySQLDatastore) RemoveApp(ctx context.Context, appName string) error {\n\t_, err := ds.db.Exec(`\n\t DELETE FROM apps\n\t WHERE name = ?\n\t`, appName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (client BaseClient) DeleteFeatureInstanceResponder(resp *http.Response) (result FeatureInstance, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client *LocalRulestacksClient) listAppIDsHandleResponse(resp *http.Response) (LocalRulestacksClientListAppIDsResponse, error) {\n\tresult := LocalRulestacksClientListAppIDsResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.ListAppIDResponse); err != nil {\n\t\treturn LocalRulestacksClientListAppIDsResponse{}, err\n\t}\n\treturn result, nil\n}", "func (l *Service) Remove(bytes []byte) ([]byte, error) {\n\trequest := &RemoveRequest{}\n\tif err := proto.Unmarshal(bytes, request); err != nil {\n\t\treturn nil, err\n\t}\n\n\tindex := request.Index\n\tif index >= uint32(len(l.values)) {\n\t\treturn nil, errors.NewInvalid(\"index %d out of bounds\", index)\n\t}\n\n\tvalue := l.values[index]\n\tl.values = append(l.values[:index], l.values[index+1:]...)\n\n\tl.sendEvent(&ListenResponse{\n\t\tType: ListenResponse_REMOVED,\n\t\tIndex: index,\n\t\tValue: value,\n\t})\n\n\treturn proto.Marshal(&RemoveResponse{\n\t\tStatus: ResponseStatus_OK,\n\t\tValue: value,\n\t})\n}", "func (app *App) Remove(uuid gocql.UUID) (err error) {\n\tif err = app.tre.session.Query(`DELETE FROM applications WHERE uuid = ?`,\n\t\tuuid).Exec(); err != nil {\n\t\tfmt.Printf(\"Remove Error: %s\\n\", err.Error())\n\t\treturn\n\t}\n\terr = app.tre.com.RemoveAll(uuid)\n\treturn\n}", "func (a AppsApi) AppsAppDelete(app string) (*APIResponse, error) {\n\n\tvar localVarHttpMethod = strings.ToUpper(\"Delete\")\n\t// create path and map variables\n\tlocalVarPath := a.Configuration.BasePath + \"/apps/{app}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"app\"+\"}\", fmt.Sprintf(\"%v\", app), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := make(map[string]string)\n\tvar localVarPostBody interface{}\n\tvar localVarFileName string\n\tvar localVarFileBytes []byte\n\t// add default headers if any\n\tfor key := range a.Configuration.DefaultHeader {\n\t\tlocalVarHeaderParams[key] = a.Configuration.DefaultHeader[key]\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 := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tlocalVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\n\tvar localVarURL, _ = url.Parse(localVarPath)\n\tlocalVarURL.RawQuery = localVarQueryParams.Encode()\n\tvar localVarAPIResponse = &APIResponse{Operation: \"AppsAppDelete\", Method: localVarHttpMethod, RequestURL: localVarURL.String()}\n\tif localVarHttpResponse != nil {\n\t\tlocalVarAPIResponse.Response = localVarHttpResponse.RawResponse\n\t\tlocalVarAPIResponse.Payload = localVarHttpResponse.Body()\n\t}\n\n\tif err != nil {\n\t\treturn localVarAPIResponse, err\n\t}\n\treturn localVarAPIResponse, err\n}", "func (client ListManagementImageClient) DeleteImageResponder(resp *http.Response) (result String, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client FeatureStateClient) DeleteStateResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func removeBobba(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid, err := getRequestID(vars, \"id\")\n\n\t// Set JSON header\n\tw.Header().Set(\"Content-type\", \"application/json\")\n\tif err != nil {\n\t\terrPayload := buildErrorPayload(idEmptyRemove, 200)\n\n\t\tw.Write(errPayload)\n\t\treturn\n\t}\n\n\terr = runRemoveRoutine(id)\n\tif err != nil {\n\t\terrPayload := buildErrorPayload(err.Error(), 200)\n\t\tw.Write(errPayload)\n\t}\n\n\tpayload := buildSuccessPayload(\"success\", 200)\n\tw.Write(payload)\n}", "func AppDeleteHandler(context utils.Context, w http.ResponseWriter, r *http.Request) {\n\n\tdbConn := context.DBConn\n\tdbBucket := context.DBBucketApp\n\n\tvars := mux.Vars(r)\n\n\tenv := vars[\"environment\"]\n\tapp := vars[\"application\"]\n\n\tkey := []byte(env + \"_\" + app)\n\n\tif err := database.DeleteDBValue(dbConn, dbBucket, key); err != nil {\n\t\tlog.LogInfo.Printf(\"Failed to read db value: %v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"200 - OK: valued deleted or was not found\"))\n\n}", "func (client DatabasesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client PatternClient) DeletePatternResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (gc *GalleryContext) CloseApp() uiauto.Action {\n\treturn func(ctx context.Context) error {\n\t\treturn apps.Close(ctx, gc.tconn, apps.Gallery.ID)\n\t}\n}", "func (w *WebPurifyRequest) RemoveFromAllowList(word string) (response.WebPurifyRemoveFromAllowListResponse, error) {\n\n\t// create request parameter collection\n\trequestParameters := []WebPurifyRequestParameter{\n\t\t{Type: Word, Value: word},\n\t}\n\n\t// build http request\n\trequest, err := w.createRequest(RemoveFromAllowList, requestParameters...)\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\t// create http client\n\tclient := w.createHttpClient()\n\n\t// Execute http request\n\thttpResponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\t// convert response to struct\n\twebPurifyResponse, err := w.convertToRemoveFromAllowListResponse(*httpResponse)\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\treturn webPurifyResponse, nil\n}", "func Handler(request events.APIGatewayProxyRequest) (resp Response, err error) {\n\tvar buf bytes.Buffer\n\tvar message string\n\tvar person Person\n\tresp = Response{\n\t\tStatusCode: http.StatusOK,\n\t\tIsBase64Encoded: false,\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"X-MyCompany-Func-Reply\": \"delete-handler\",\n\t\t},\n\t}\n\n\terr = json.Unmarshal([]byte(request.Body), &person)\n\tif err != nil {\n\t\treturn Response{StatusCode: http.StatusBadRequest}, err\n\t}\n\n\tif person.Id > 0 {\n\t\tif err := connectDB(); err != nil {\n\t\t\treturn Response{StatusCode: http.StatusInternalServerError}, err\n\t\t}\n\n\t\t_, err := db.Exec(fmt.Sprintf(`DELETE FROM Persons WHERE PersonID = %d`, person.Id))\n\t\tif err != nil {\n\t\t\treturn Response{StatusCode: http.StatusInternalServerError}, err\n\t\t}\n\n\t\tmessage = fmt.Sprintf(\"Removed %d.\", person.Id)\n\t}else if person.Name != \"\" {\n\t\tif err := connectDB(); err != nil {\n\t\t\treturn Response{StatusCode: http.StatusInternalServerError}, err\n\t\t}\n\n\t\t_, err := db.Exec(fmt.Sprintf(`DELETE FROM Persons WHERE Name = '%s'`, person.Name))\n\t\tif err != nil {\n\t\t\treturn Response{StatusCode: http.StatusInternalServerError}, err\n\t\t}\n\n\t\tmessage = fmt.Sprintf(\"Removed %s.\", person.Name)\n\t} else {\n\t\tresp.StatusCode = http.StatusBadRequest\n\t\tmessage = \"parameters are invalid\"\n\t}\n\n\tbody, err := json.Marshal(map[string]interface{}{\n\t\t\"message\": message,\n\t})\n\tif err != nil {\n\t\treturn Response{StatusCode: http.StatusInternalServerError}, err\n\t}\n\n\tjson.HTMLEscape(&buf, body)\n\n\tresp.Body = buf.String()\n\n\treturn resp, nil\n}", "func (client IngestionSettingsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func RemoveDeploymentEventClient(contextName string, namespace string, client chan DeploymentEvent) {\n\n\t// Get the context receiver\n\tctxReceiver, ok := contextReceivers[contextName]\n\tif !ok {\n\t\treturn\n\t}\n\n\t// Get the namespace receiver\n\tnsReceiver, ok := ctxReceiver.namespaceReceivers[namespace]\n\tif !ok {\n\t\treturn\n\t}\n\n\t// Get the receiver\n\treceiver := nsReceiver.deploymentEventReceiver\n\tif receiver == nil {\n\t\treturn\n\t}\n\n\t// Remove the client\n\treceiver.removeClient(client)\n\n\t// If no more client, stop receiving event\n\tif len(receiver.clients) == 0 {\n\t\treceiver.stop()\n\t\tnsReceiver.deploymentEventReceiver = nil\n\t}\n}", "func (client *WebAppsClient) listHandleResponse(resp *http.Response) (WebAppsListResponse, error) {\n\tresult := WebAppsListResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.WebAppCollection); err != nil {\n\t\treturn WebAppsListResponse{}, runtime.NewResponseError(err, resp)\n\t}\n\treturn result, nil\n}", "func (s *Basememcached_protocolListener) ExitDeletion_response(ctx *Deletion_responseContext) {}", "func exitOnResp(resp *http.Response) {\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\texitOnErr(err)\n\t}\n\terr = resp.Body.Close()\n\tif err != nil {\n\t\texitOnErr(err)\n\t}\n\texitOnErr(\n\t\tfmt.Errorf(\"Received %s: %s\", resp.Status, string(b)))\n}", "func (app *App) Destroy() {\n}", "func (l *RemoteProvider) DeleteMesheryApplication(req *http.Request, applicationID string) ([]byte, error) {\n\tif !l.Capabilities.IsSupported(PersistMesheryApplications) {\n\t\tlogrus.Error(\"operation not available\")\n\t\treturn nil, ErrInvalidCapability(\"PersistMesheryApplications\", l.ProviderName)\n\t}\n\n\tep, _ := l.Capabilities.GetEndpointForFeature(PersistMesheryApplications)\n\n\tlogrus.Infof(\"attempting to fetch application from cloud for id: %s\", applicationID)\n\n\tremoteProviderURL, _ := url.Parse(fmt.Sprintf(\"%s%s/%s\", l.RemoteProviderURL, ep, applicationID))\n\tlogrus.Debugf(\"constructed application url: %s\", remoteProviderURL.String())\n\tcReq, _ := http.NewRequest(http.MethodDelete, remoteProviderURL.String(), nil)\n\n\ttokenString, err := l.GetToken(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := l.DoRequest(cReq, tokenString)\n\tif err != nil {\n\t\treturn nil, ErrDelete(err, \"Application :\"+applicationID, resp.StatusCode)\n\t}\n\tdefer func() {\n\t\t_ = resp.Body.Close()\n\t}()\n\tbdr, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, ErrDataRead(err, \"Application :\"+applicationID)\n\t}\n\n\tif resp.StatusCode == http.StatusOK {\n\t\tlogrus.Infof(\"application successfully retrieved from remote provider\")\n\t\treturn bdr, nil\n\t}\n\treturn nil, ErrDelete(err, \"Application :\"+applicationID, resp.StatusCode)\n}", "func (client CertificateOrdersClient) DeleteCertificateResponder(resp *http.Response) (result SetObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client HTTPSuccessClient) Put204Responder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func (o *DesktopApp) Delete() (*restapi.SliceResponse, error) {\n\tif o.ID == \"\" {\n\t\treturn nil, errors.New(\"error: ID is empty\")\n\t}\n\tvar queryArg = make(map[string]interface{})\n\tqueryArg[\"_RowKey\"] = []string{o.ID}\n\n\tresp, err := o.client.CallSliceAPI(o.apiDelete, queryArg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !resp.Success {\n\t\treturn nil, errors.New(resp.Message)\n\t}\n\treturn resp, nil\n}", "func (client CertificateOrdersClient) DeleteCertificateOrderResponder(resp *http.Response) (result SetObject, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (client *AlertProcessingRulesClient) deleteHandleResponse(resp *http.Response) (AlertProcessingRulesClientDeleteResponse, error) {\n\tresult := AlertProcessingRulesClientDeleteResponse{RawResponse: resp}\n\tif val := resp.Header.Get(\"x-ms-request-id\"); val != \"\" {\n\t\tresult.XMSRequestID = &val\n\t}\n\treturn result, nil\n}", "func (client ConversationsClient) DeleteConversationMemberMethodResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusNoContent),\n autorest.ByClosing())\n result.Response = resp\n return\n }" ]
[ "0.65704703", "0.61876976", "0.59043354", "0.5887065", "0.57693315", "0.57142407", "0.56424236", "0.5415801", "0.5325072", "0.5252524", "0.5250634", "0.5244083", "0.5216735", "0.5216142", "0.5211655", "0.52101165", "0.52086425", "0.52039236", "0.51945347", "0.5163457", "0.5162244", "0.51584166", "0.51572984", "0.513345", "0.51326716", "0.5123475", "0.5063627", "0.5056468", "0.5050516", "0.5049395", "0.5049347", "0.50412536", "0.5037522", "0.50308436", "0.50254583", "0.5024307", "0.5023043", "0.5009633", "0.49876243", "0.49844587", "0.49760133", "0.49723294", "0.4966933", "0.49636173", "0.49499384", "0.49479833", "0.49473092", "0.4943106", "0.4941713", "0.49230102", "0.49228168", "0.4922504", "0.49213082", "0.49040803", "0.48982698", "0.48932564", "0.4892276", "0.48793235", "0.4877817", "0.48747137", "0.4856813", "0.48560977", "0.48508868", "0.4839771", "0.4833318", "0.4829837", "0.4815901", "0.4813801", "0.48004493", "0.47995022", "0.47977695", "0.47974008", "0.47973058", "0.47964334", "0.4793094", "0.47878125", "0.47771645", "0.47557923", "0.4749453", "0.47479632", "0.47468492", "0.47296113", "0.47217643", "0.47213697", "0.47187728", "0.47096664", "0.47062892", "0.46975192", "0.4691629", "0.46870407", "0.46855468", "0.46794325", "0.46790808", "0.46789768", "0.46732202", "0.4661449", "0.46607167", "0.46597818", "0.46524853", "0.46520635" ]
0.7797749
0
RenderToBlazon renders a device as its blazon and returns it.
func (device Device) RenderToBlazon() string { blazon := "" if device.Field.Division.Name == "plain" { if device.Field.HasVariation { blazon = strings.Title(device.Field.Variation.Name) blazon += " " + device.Field.Variation.Tincture1.Name + " and " + device.Field.Variation.Tincture2.Name } else { blazon = strings.Title(device.Field.Tincture.Name) } } else { blazon = device.Field.Division.Blazon if device.Field.HasVariation { blazon += device.Field.Variation.Name blazon += " " + device.Field.Variation.Tincture1.Name + " and " + device.Field.Variation.Tincture2.Name } else { blazon += device.Field.Tincture.Name } } if device.Field.Division.Name != "plain" { blazon += " and " + device.Field.Division.Tincture.Name } if len(device.ChargeGroups) > 0 { numberOfCharges := "" for _, chargeGroup := range device.ChargeGroups { numberOfCharges = num2words.Convert(len(chargeGroup.Charges)) if len(chargeGroup.Charges) > 1 { blazon += ", " + numberOfCharges + " " + chargeGroup.Charges[0].NounPlural + " " + chargeGroup.Charges[0].Descriptor + " " + chargeGroup.Tincture.Name } else { blazon += ", " + chargeGroup.Charges[0].Article + " " + chargeGroup.Charges[0].Noun + " " + chargeGroup.Charges[0].Descriptor + " " + chargeGroup.Tincture.Name } } } blazon = strings.Replace(blazon, " ", " ", -1) return blazon }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (device Device) RenderToSVG(width int, height int) string {\n\tbuffer := new(bytes.Buffer)\n\n\tcenterX := int(width / 2)\n\tcenterY := int(height / 2)\n\n\tlineColor := \"#000000\"\n\n\tblazon := device.RenderToBlazon()\n\n\t/*\n\t\tblazonLength := len(blazon)\n\t\tblazonSize := \"10\"\n\n\t\tif blazonLength < 25 {\n\t\t\tblazonSize = \"28\"\n\t\t} else if blazonLength < 30 {\n\t\t\tblazonSize = \"26\"\n\t\t} else if blazonLength < 35 {\n\t\t\tblazonSize = \"20\"\n\t\t} else if blazonLength < 40 {\n\t\t\tblazonSize = \"18\"\n\t\t} else if blazonLength < 50 {\n\t\t\tblazonSize = \"14\"\n\t\t} else if blazonLength < 60 {\n\t\t\tblazonSize = \"12\"\n\t\t} else if blazonLength < 80 {\n\t\t\tblazonSize = \"11\"\n\t\t}\n\t*/\n\n\tcanvas := svg.New(buffer)\n\tcanvas.Start(width, height+50)\n\tcanvas.Title(blazon)\n\tcanvas.Def()\n\tcanvas.Mask(\"shieldmask\", 0, 0, width, height)\n\tcanvas.Path(\"m10.273 21.598v151.22c0 96.872 89.031 194.34 146.44 240.09 57.414-45.758 146.44-143.22 146.44-240.09v-151.22h-292.89z\", \"fill:#FFFFFF\")\n\tcanvas.MaskEnd()\n\tfor _, tincture := range device.AllTinctures {\n\t\tif tincture.Name == \"erminois\" {\n\t\t\tinsertErmine(canvas, \"erminois\")\n\t\t} else if tincture.Name == \"ermine\" {\n\t\t\tinsertErmine(canvas, \"ermine\")\n\t\t} else if tincture.Name == \"ermines\" {\n\t\t\tinsertErmine(canvas, \"ermines\")\n\t\t} else if tincture.Name == \"pean\" {\n\t\t\tinsertErmine(canvas, \"pean\")\n\t\t}\n\t}\n\tif device.Field.HasVariation {\n\t\tinsertVariationPattern(canvas, device.Field.Variation)\n\t}\n\tcanvas.DefEnd()\n\tcanvas.Group(\"mask='url(#shieldmask)'\")\n\n\tif device.Field.HasVariation {\n\t\tcanvas.Rect(0, 0, width, height, \"fill:url(#\"+device.Field.Variation.Name+\")\")\n\t} else {\n\t\tcanvas.Rect(0, 0, width, height, \"fill:\"+device.Field.Tincture.Hexcode)\n\t}\n\n\tswitch device.Field.Division.Name {\n\tcase \"plain\":\n\tcase \"pale\":\n\t\tcanvas.Rect(int(width/2), 0, int(width/2), height, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"fess\":\n\t\tcanvas.Rect(0, 0, width, int(height/2), \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"bend\":\n\t\tcanvas.Polygon([]int{0, 0, width}, []int{0, height, height}, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"bendsinister\":\n\t\tcanvas.Polygon([]int{0, width, 0}, []int{0, 0, height}, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"chevron\":\n\t\tcanvas.Polygon([]int{0, int(width / 2), width}, []int{height, int(height / 2), height}, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"quarterly\":\n\t\tcanvas.Rect(int(width/2), 0, int(width/2), int(height/2), \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\t\tcanvas.Rect(0, int(height/2), int(width/2), int(height/2), \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"saltire\":\n\t\tcanvas.Polygon([]int{0, int(width / 2), 0}, []int{0, int(height / 2), height}, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\t\tcanvas.Polygon([]int{width, int(width / 2), width}, []int{0, int(height / 2), height}, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\t}\n\tfor _, chargeGroup := range device.ChargeGroups {\n\t\tif len(chargeGroup.Charges) == 2 {\n\t\t\tcanvas.Scale(0.5)\n\t\t} else if len(chargeGroup.Charges) == 3 {\n\t\t\tcanvas.Scale(0.5)\n\t\t}\n\t\tfor index, charge := range chargeGroup.Charges {\n\t\t\tif len(chargeGroup.Charges) == 2 {\n\t\t\t\tif charge.Identifier == \"pale\" {\n\t\t\t\t\tif index == 0 {\n\t\t\t\t\t\tcanvas.Translate(20, 0)\n\t\t\t\t\t} else if index == 1 {\n\t\t\t\t\t\tcanvas.Translate(300, 0)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif index == 0 {\n\t\t\t\t\t\tcanvas.Translate(20, 200)\n\t\t\t\t\t} else if index == 1 {\n\t\t\t\t\t\tcanvas.Translate(300, 200)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if len(chargeGroup.Charges) == 3 {\n\t\t\t\tif charge.Identifier == \"pale\" {\n\t\t\t\t\tif index == 0 {\n\t\t\t\t\t\tcanvas.Translate(-20, 0)\n\t\t\t\t\t} else if index == 1 {\n\t\t\t\t\t\tcanvas.Translate(160, 0)\n\t\t\t\t\t} else if index == 2 {\n\t\t\t\t\t\tcanvas.Translate(340, 00)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif index == 0 {\n\t\t\t\t\t\tcanvas.Translate(20, 80)\n\t\t\t\t\t} else if index == 1 {\n\t\t\t\t\t\tcanvas.Translate(300, 80)\n\t\t\t\t\t} else if index == 2 {\n\t\t\t\t\t\tcanvas.Translate(160, 400)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif chargeGroup.Tincture.Name == \"sable\" {\n\t\t\t\tlineColor = \"#FFFFFF\"\n\t\t\t}\n\t\t\tswitch charge.Identifier {\n\t\t\tcase \"pale\":\n\t\t\t\tif len(chargeGroup.Charges) > 1 {\n\t\t\t\t\tcanvas.Rect(int(width/3), 0, int(width/3), height*2, \"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\t\t} else {\n\t\t\t\t\tcanvas.Rect(int(width/3), 0, int(width/3), height, \"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\t\t}\n\t\t\tcase \"fess\":\n\t\t\t\tcanvas.Rect(0, int(height/3), width, int(height/3), \"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"cross\":\n\t\t\t\tcrossHalfWidth := 40\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{centerX - crossHalfWidth, centerX + crossHalfWidth, centerX + crossHalfWidth, width, width, centerX + crossHalfWidth, centerX + crossHalfWidth, centerX - crossHalfWidth, centerX - crossHalfWidth, 0, 0, centerX - crossHalfWidth},\n\t\t\t\t\t[]int{0, 0, centerY - crossHalfWidth, centerY - crossHalfWidth, centerY + crossHalfWidth, centerY + crossHalfWidth, height, height, centerY + crossHalfWidth, centerY + crossHalfWidth, centerY - crossHalfWidth, centerY - crossHalfWidth},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"bend\":\n\t\t\t\tcanvas.TranslateRotate(-100, 135, -45)\n\t\t\t\tcanvas.Rect(int(width/3), 0, int(width/3), height, \"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\t\tcanvas.Gend()\n\t\t\tcase \"saltire\":\n\t\t\t\tsaltireHalfWidth := 30\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{0, saltireHalfWidth, centerX, width - saltireHalfWidth, width, width, centerX + saltireHalfWidth, width, width, width - saltireHalfWidth, centerX, saltireHalfWidth, 0, 0, centerX - saltireHalfWidth, 0},\n\t\t\t\t\t[]int{0, 0, centerY - saltireHalfWidth, 0, 0, saltireHalfWidth, centerY, height - saltireHalfWidth, height, height, centerY + saltireHalfWidth, height, height, height - saltireHalfWidth, centerY, saltireHalfWidth},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"chevron\":\n\t\t\t\tchevronHalfWidth := 40\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{0, centerX, width, width, centerX, 0},\n\t\t\t\t\t[]int{height - int(height/4), height - int(height/3) - (3 * chevronHalfWidth), height - int(height/4), height - int(height/4) + (2 * chevronHalfWidth), height - int(height/3) - chevronHalfWidth, height - int(height/4) + (2 * chevronHalfWidth)},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"chief\":\n\t\t\t\tcanvas.Rect(0, 0, width, int(height/3), \"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"pile\":\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{0, width, int(width / 2)},\n\t\t\t\t\t[]int{0, 0, int(height / 2)},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"pall\":\n\t\t\t\tpallHalfWidth := 40\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{0, pallHalfWidth, centerX, width - pallHalfWidth, width, width, centerX + pallHalfWidth - int(pallHalfWidth/3), centerX + pallHalfWidth - int(pallHalfWidth/3), centerX - pallHalfWidth + int(pallHalfWidth/3), centerX - pallHalfWidth + int(pallHalfWidth/3), 0},\n\t\t\t\t\t[]int{0, 0, centerY - pallHalfWidth, 0, 0, pallHalfWidth, centerY + pallHalfWidth - int(pallHalfWidth/3), height, height, centerY + pallHalfWidth - int(pallHalfWidth/3), pallHalfWidth},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"bordure\":\n\t\t\t\trenderBordureToSvg(canvas, chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"lozenge\":\n\t\t\t\tlozengeHalfWidth := 80\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{centerX, centerX + lozengeHalfWidth, centerX, centerX - lozengeHalfWidth},\n\t\t\t\t\t[]int{centerY - lozengeHalfWidth - int(lozengeHalfWidth/2), centerY, centerY + lozengeHalfWidth + int(lozengeHalfWidth/2), centerY},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"roundel\":\n\t\t\t\troundelRadius := 100\n\t\t\t\tcanvas.Circle(\n\t\t\t\t\tint(width/2),\n\t\t\t\t\tint(height/2),\n\t\t\t\t\troundelRadius,\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"eagle-displayed\":\n\t\t\t\trenderEagleDisplayedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"dragon-passant\":\n\t\t\t\trenderDragonPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"gryphon-passant\":\n\t\t\t\trenderGryphonPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"fox-passant\":\n\t\t\t\trenderFoxPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"antelope-passant\":\n\t\t\t\trenderAntelopePassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"antelope-rampant\":\n\t\t\t\trenderAntelopeRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bat-volant\":\n\t\t\t\trenderBatVolantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"battleaxe\":\n\t\t\t\trenderBattleaxeToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bear-head-couped\":\n\t\t\t\trenderBearHeadCoupedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bear-rampant\":\n\t\t\t\trenderBearRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bear-statant\":\n\t\t\t\trenderBearStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bee-volant\":\n\t\t\t\trenderBeeVolantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bell\":\n\t\t\t\trenderBellToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"boar-head-erased\":\n\t\t\t\trenderBoarHeadErasedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"boar-passant\":\n\t\t\t\trenderBoarPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"boar-rampant\":\n\t\t\t\trenderBoarRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bugle-horn\":\n\t\t\t\trenderBugleHornToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bull-passant\":\n\t\t\t\trenderBullPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bull-rampant\":\n\t\t\t\trenderBullRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"castle\":\n\t\t\t\trenderCastleToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"cock\":\n\t\t\t\trenderCockToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"cockatrice\":\n\t\t\t\trenderCockatriceToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"crown\":\n\t\t\t\trenderCrownToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"dolphin-hauriant\":\n\t\t\t\trenderDolphinHauriantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"double-headed-eagle-displayed\":\n\t\t\t\trenderDoubleHeadedEagleDisplayedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"dragon-rampant\":\n\t\t\t\trenderDragonRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"eagles-head-erased\":\n\t\t\t\trenderEaglesHeadErasedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"fox-sejant\":\n\t\t\t\trenderFoxSejantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"gryphon-segreant\":\n\t\t\t\trenderGryphonSegreantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"hare-salient\":\n\t\t\t\trenderHareSalientToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"hare\":\n\t\t\t\trenderHareToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"heron\":\n\t\t\t\trenderHeronToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"horse-passant\":\n\t\t\t\trenderHorsePassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"horse-rampant\":\n\t\t\t\trenderHorseRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"leopard-passant\":\n\t\t\t\trenderLeopardPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"lion-passant\":\n\t\t\t\trenderLionPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"lion-rampant\":\n\t\t\t\trenderLionRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"lions-head-erased\":\n\t\t\t\trenderLionsHeadErasedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"owl\":\n\t\t\t\trenderOwlToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"pegasus-passant\":\n\t\t\t\trenderPegasusPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"pegasus-rampant\":\n\t\t\t\trenderPegasusRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"ram-rampant\":\n\t\t\t\trenderRamRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"ram-statant\":\n\t\t\t\trenderRamStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"rose\":\n\t\t\t\trenderRoseToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"sea-horse\":\n\t\t\t\trenderSeaHorseToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"serpent-nowed\":\n\t\t\t\trenderSerpentNowedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"squirrel\":\n\t\t\t\trenderSquirrelToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"stag-lodged\":\n\t\t\t\trenderStagLodgedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"stag-statant\":\n\t\t\t\trenderStagStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"sun-in-splendor\":\n\t\t\t\trenderSunInSplendorToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"tiger-passant\":\n\t\t\t\trenderTigerPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"tiger-rampant\":\n\t\t\t\trenderTigerRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"tower\":\n\t\t\t\trenderTowerToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"two-axes-in-saltire\":\n\t\t\t\trenderTwoAxesInSaltireToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"two-bones-in-saltire\":\n\t\t\t\trenderTwoBonesInSaltireToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"unicorn-rampant\":\n\t\t\t\trenderUnicornRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"unicorn-statant\":\n\t\t\t\trenderUnicornStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"wolf-passant\":\n\t\t\t\trenderWolfPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"wolf-rampant\":\n\t\t\t\trenderWolfRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"wyvern\":\n\t\t\t\trenderWyvernToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\t}\n\t\t\tif len(chargeGroup.Charges) > 1 {\n\t\t\t\tcanvas.Gend()\n\t\t\t}\n\t\t}\n\t\tif len(chargeGroup.Charges) > 1 {\n\t\t\tcanvas.Gend()\n\t\t}\n\t}\n\n\tcanvas.Path(\"m10.273 21.598v151.22c0 96.872 89.031 194.34 146.44 240.09 57.414-45.758 146.44-143.22 146.44-240.09v-151.22h-292.89z\", \"stroke:#000000;stroke-width:4;fill:none\")\n\tcanvas.Gend()\n\t// canvas.Text(centerX, height+25, blazon, \"font-size:\"+blazonSize+\"px;text-anchor:middle\")\n\tcanvas.End()\n\n\treturn buffer.String()\n}", "func (b *Baa) Render() Renderer {\n\treturn b.GetDI(\"render\").(Renderer)\n}", "func (r Roundel) Blazon(count int, tincture string) (string, error) {\n\tblazon, err := blazonForCharge(count, \"roundel\", \"roundels\", \"\", tincture)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to generate blazon for roundel: %w\", err)\n\t\treturn \"\", err\n\t}\n\n\treturn blazon, nil\n}", "func (p Pale) Blazon(count int, tincture string) (string, error) {\n\tblazon, err := blazonForCharge(count, \"pale\", \"pales\", \"\", tincture)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to generate blazon for pale: %w\", err)\n\t\treturn \"\", err\n\t}\n\n\treturn blazon, nil\n}", "func (d *Device) Render() error {\n\tbuf := new(bytes.Buffer)\n\n\tfor _, chain := range d.LEDs {\n\t\tfor _, col := range chain {\n\t\t\tbuf.Write([]byte{col.R, col.G, col.B})\n\t\t}\n\t}\n\n\t_, err := Conn.WriteToUDP(buf.Bytes(), d.Addr)\n\treturn err\n}", "func (f Fess) Blazon(count int, tincture string) (string, error) {\n\tblazon, err := blazonForCharge(count, \"fess\", \"fesses\", \"\", tincture)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to generate blazon for fess: %w\", err)\n\t\treturn \"\", err\n\t}\n\n\treturn blazon, nil\n}", "func (c Cross) Blazon(count int, tincture string) (string, error) {\n\tblazon, err := blazonForCharge(count, \"cross\", \"crosses\", \"\", tincture)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to generate blazon for cross: %w\", err)\n\t\treturn \"\", err\n\t}\n\n\treturn blazon, nil\n}", "func NewBladeFromDevice(b *devices.Blade) (blade *Blade) {\n\tblade = &Blade{}\n\tblade.Name = b.Name\n\tblade.Serial = b.Serial\n\tblade.BiosVersion = b.BiosVersion\n\tblade.BmcType = b.BmcType\n\tblade.BmcAddress = b.BmcAddress\n\tblade.BmcVersion = b.BmcVersion\n\tblade.BmcLicenceType = b.BmcLicenceType\n\tblade.BmcLicenceStatus = b.BmcLicenceStatus\n\tblade.PowerState = b.PowerState\n\tblade.Nics = make([]*Nic, 0)\n\tfor _, nic := range b.Nics {\n\t\tblade.Nics = append(blade.Nics, &Nic{\n\t\t\tMacAddress: nic.MacAddress,\n\t\t\tName: nic.Name,\n\t\t\tBladeSerial: b.Serial,\n\t\t\tSpeed: nic.Speed,\n\t\t})\n\t}\n\tblade.BladePosition = b.BladePosition\n\tblade.ChassisSerial = b.ChassisSerial\n\tblade.Disks = make([]*Disk, 0)\n\tfor pos, disk := range b.Disks {\n\t\tif disk.Serial == \"\" {\n\t\t\tdisk.Serial = fmt.Sprintf(\"%s-failed-%d\", blade.Serial, pos)\n\t\t}\n\t\tblade.Disks = append(blade.Disks, &Disk{\n\t\t\tSerial: disk.Serial,\n\t\t\tSize: disk.Size,\n\t\t\tStatus: disk.Status,\n\t\t\tModel: disk.Model,\n\t\t\tLocation: disk.Location,\n\t\t\tType: disk.Type,\n\t\t\tFwVersion: disk.FwVersion,\n\t\t\tBladeSerial: b.Serial,\n\t\t})\n\t}\n\tblade.BladePosition = b.BladePosition\n\tblade.Model = b.Model\n\tblade.TempC = b.TempC\n\tblade.PowerKw = b.PowerKw\n\tblade.Status = b.Status\n\tblade.Vendor = b.Vendor\n\tblade.ChassisSerial = b.ChassisSerial\n\tblade.Processor = b.Processor\n\tblade.ProcessorCount = b.ProcessorCount\n\tblade.ProcessorCoreCount = b.ProcessorCoreCount\n\tblade.ProcessorThreadCount = b.ProcessorThreadCount\n\tblade.Memory = b.Memory\n\n\treturn blade\n}", "func (c *ConnectionSPI) Render(pixels []RGBPixel) {\r\n\tlogFields := log.Fields{\"package\": logPkg, \"conn\": \"SPI\", \"func\": \"RenderLEDs\"}\r\n\tlog.WithFields(logFields).Infof(\"Render %d LEDs\", len(pixels))\r\n\t// Fix for Raspberry Pi 3 Model B+ (5.15.84-v7+)\r\n\t// Data signal seems to be splitted sending less than 11 LEDS\r\n\tif len(pixels) < 11 {\r\n\t\tpixels = append(pixels, []RGBPixel{{}, {}, {}, {}, {}, {}, {}, {}, {}, {}}...)\r\n\t}\r\n\tvar translatedRGBs []uint8\r\n\tfor _, pixel := range pixels {\r\n\r\n\t\tcolorData := GetColorData(pixel, c.FixSPI)\r\n\t\tlog.WithFields(logFields).Tracef(\"%08b\", pixel)\r\n\r\n\t\tfor _, c := range colorData {\r\n\t\t\ttranslatedRGBs = append(translatedRGBs, c)\r\n\t\t}\r\n\t}\r\n\r\n\tc.transfer(translatedRGBs)\r\n}", "func (b *builder) Render() (*bytes.Buffer, error) {\n\tswitch b.chartType {\n\tcase \"pie\":\n\t\treturn b.renderChart(b.newPieChart())\n\tcase \"donut\":\n\t\treturn b.renderChart(b.newDonutChart())\n\tcase \"line\":\n\t\treturn b.renderChart(b.newLineChart())\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown chart type '%s'\", b.chartType)\n\t}\n}", "func Render(bima *bima.Bima) {\n\th := NewHeaderComponent(bima)\n\tbima.UI.Header = h.Render()\n\tgo bima.Sync.Watch()\n\n\t// If never see onboard yet, we should show up onboard screen to enter email and setup password\n\tif bima.Registry.HasOnboard() {\n\t\tc := NewPasswordComponent(bima, EnterPasswordForm)\n\t\tbima.Push(\"unlock\", c)\n\t} else {\n\t\t// No secret key are created yet. We start onboard process so it also give user a chance to save this secret key\n\t\tlog.Debug().Msg(\"Start onboard\")\n\t\tc := NewOnboardComponent(bima)\n\t\tbima.Push(\"onboard\", c)\n\t}\n\n\tbima.UI.Window.Resize(fyne.NewSize(320, 640))\n\tbima.UI.Window.ShowAndRun()\n}", "func (c *Car) Render(out chan<- string) {\n defer close(out) // Always close the channel!\n\n var vs string\n if vs = os.Getenv(\"BULLETTRAIN_CAR_VIRTUALENV_SYMBOL_ICON\"); vs == \"\" {\n vs = virtualenvSymbolIcon\n }\n\n var vsp string\n if vsp = os.Getenv(\"BULLETTRAIN_CAR_VIRTUALENV_SYMBOL_PAINT\"); vsp == \"\" {\n vsp = virtualenvSymbolPaint\n }\n\n var s string\n if s = os.Getenv(\"BULLETTRAIN_CAR_VIRTUALENV_TEMPLATE\"); s == \"\" {\n s = carTemplate\n }\n\n funcMap := template.FuncMap{\n // Pipeline functions for colouring.\n \"c\": func(t string) string { return ansi.Color(t, c.GetPaint()) },\n \"cs\": func(t string) string { return ansi.Color(t, vsp) },\n }\n\n tpl := template.Must(template.New(\"python\").Funcs(funcMap).Parse(s))\n data := struct {\n VenvIcon string\n Venv string\n }{\n VenvIcon: virtualenvSymbolIcon,\n Venv: path.Base(os.Getenv(\"VIRTUAL_ENV\")),\n }\n fromTpl := new(bytes.Buffer)\n err := tpl.Execute(fromTpl, data)\n if err != nil {\n log.Fatalf(\"Can't generate the python template: %s\", err.Error())\n }\n\n out <- fromTpl.String()\n}", "func FramebufferRenderbuffer(target uint32, attachment uint32, renderbuffertarget uint32, renderbuffer uint32) {\n C.glowFramebufferRenderbuffer(gpFramebufferRenderbuffer, (C.GLenum)(target), (C.GLenum)(attachment), (C.GLenum)(renderbuffertarget), (C.GLuint)(renderbuffer))\n}", "func Render(c Compo) {\n\tdriver.CallOnUIGoroutine(func() {\n\t\tdriver.Render(c)\n\t})\n}", "func (bp *Blueprint) Render() (string, error) {\n\tif bp.XMLData == nil {\n\t\treturn \"\", errors.ErrBlueprintXMLEmpty\n\t}\n\n\tvar buffer bytes.Buffer\n\tif _, err := bp.XMLData.WriteTo(&buffer); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn buffer.String(), nil\n}", "func New(uid string, ipcon *ipconnection.IPConnection) (DCV2Bricklet, error) {\n\tinternalIPCon := ipcon.GetInternalHandle().(IPConnection)\n\tdev, err := NewDevice([3]uint8{2, 0, 0}, uid, &internalIPCon, 0, DeviceIdentifier, DeviceDisplayName)\n\tif err != nil {\n\t\treturn DCV2Bricklet{}, err\n\t}\n\tdev.ResponseExpected[FunctionSetEnabled] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetEnabled] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetVelocity] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetVelocity] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionGetCurrentVelocity] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetMotion] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetMotion] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionFullBrake] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionSetDriveMode] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetDriveMode] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetPWMFrequency] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetPWMFrequency] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionGetPowerStatistics] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetErrorLEDConfig] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetErrorLEDConfig] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetEmergencyShutdownCallbackConfiguration] = ResponseExpectedFlagTrue\n\tdev.ResponseExpected[FunctionGetEmergencyShutdownCallbackConfiguration] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetVelocityReachedCallbackConfiguration] = ResponseExpectedFlagTrue\n\tdev.ResponseExpected[FunctionGetVelocityReachedCallbackConfiguration] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetCurrentVelocityCallbackConfiguration] = ResponseExpectedFlagTrue\n\tdev.ResponseExpected[FunctionGetCurrentVelocityCallbackConfiguration] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionGetSPITFPErrorCount] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetBootloaderMode] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionGetBootloaderMode] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetWriteFirmwarePointer] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionWriteFirmware] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetStatusLEDConfig] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetStatusLEDConfig] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionGetChipTemperature] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionReset] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionWriteUID] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionReadUID] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionGetIdentity] = ResponseExpectedFlagAlwaysTrue\n\treturn DCV2Bricklet{dev}, nil\n}", "func (atlan atlanticTimeZones) Bermuda() string {return \"Atlantic/Bermuda\" }", "func (cs *cpuState) Framebuffer() []byte {\n\treturn cs.LCD.framebuffer[:]\n}", "func Render(doc []byte) []byte {\n\trenderer := NewRoffRenderer()\n\n\treturn blackfriday.Run(doc,\n\t\t[]blackfriday.Option{blackfriday.WithRenderer(renderer),\n\t\t\tblackfriday.WithExtensions(renderer.GetExtensions())}...)\n}", "func (device *DCV2Bricklet) FullBrake() (err error) {\n\tvar buf bytes.Buffer\n\n\tresultBytes, err := device.device.Set(uint8(FunctionFullBrake), buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 8 {\n\t\t\treturn fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 8)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tbytes.NewBuffer(resultBytes[8:])\n\n\t}\n\n\treturn nil\n}", "func (native *OpenGL) BlitFramebuffer(srcX0 int32, srcY0 int32, srcX1 int32, srcY1 int32, dstX0 int32, dstY0 int32, dstX1 int32, dstY1 int32, mask uint32, filter uint32) {\n\tgl.BlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter)\n}", "func New(uid string, ipcon *ipconnection.IPConnection) (BarometerBricklet, error) {\n\tinternalIPCon := ipcon.GetInternalHandle().(IPConnection)\n\tdev, err := NewDevice([3]uint8{2, 0, 2}, uid, &internalIPCon, 0, DeviceIdentifier, DeviceDisplayName)\n\tif err != nil {\n\t\treturn BarometerBricklet{}, err\n\t}\n\tdev.ResponseExpected[FunctionGetAirPressure] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionGetAltitude] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetAirPressureCallbackPeriod] = ResponseExpectedFlagTrue\n\tdev.ResponseExpected[FunctionGetAirPressureCallbackPeriod] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetAltitudeCallbackPeriod] = ResponseExpectedFlagTrue\n\tdev.ResponseExpected[FunctionGetAltitudeCallbackPeriod] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetAirPressureCallbackThreshold] = ResponseExpectedFlagTrue\n\tdev.ResponseExpected[FunctionGetAirPressureCallbackThreshold] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetAltitudeCallbackThreshold] = ResponseExpectedFlagTrue\n\tdev.ResponseExpected[FunctionGetAltitudeCallbackThreshold] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetDebouncePeriod] = ResponseExpectedFlagTrue\n\tdev.ResponseExpected[FunctionGetDebouncePeriod] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetReferenceAirPressure] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetChipTemperature] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionGetReferenceAirPressure] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetAveraging] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetAveraging] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetI2CMode] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetI2CMode] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionGetIdentity] = ResponseExpectedFlagAlwaysTrue\n\treturn BarometerBricklet{dev}, nil\n}", "func (f *Framebuffer) Renderbuffer(attachment gfx.FramebufferAttachment, buf gfx.Renderbuffer) {\n\tf.useState()\n\tf.ctx.O.Call(\n\t\t\"framebufferTexture2D\",\n\t\tf.ctx.FRAMEBUFFER,\n\t\tf.ctx.Enums[int(attachment)],\n\t\tf.ctx.RENDERBUFFER,\n\t\tbuf.Object().(*js.Object),\n\t\t0,\n\t)\n}", "func FrameBuffer(m rv.RenderModel) {\n\tframebuffer(m)\n}", "func (obj *Device) GetBackBuffer(\n\tswapChain uint,\n\tbackBuffer uint,\n\ttyp BACKBUFFER_TYPE,\n) (*Surface, Error) {\n\tvar surface *Surface\n\tret, _, _ := syscall.Syscall6(\n\t\tobj.vtbl.GetBackBuffer,\n\t\t5,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(swapChain),\n\t\tuintptr(backBuffer),\n\t\tuintptr(typ),\n\t\tuintptr(unsafe.Pointer(&surface)),\n\t\t0,\n\t)\n\treturn surface, toErr(ret)\n}", "func (rf RendererFunc) Render(w io.Writer, v interface{}) error { return rf(w, v) }", "func (m *MockInterface) Render(client.RenderOptions) ([]byte, error) {\n\treturn nil, nil\n}", "func (native *OpenGL) FramebufferRenderbuffer(target uint32, attachment uint32, renderbuffertarget uint32, renderbuffer uint32) {\n\tgl.FramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer)\n}", "func FramebufferRenderbuffer(target uint32, attachment uint32, renderbuffertarget uint32, renderbuffer uint32) {\n\tC.glowFramebufferRenderbuffer(gpFramebufferRenderbuffer, (C.GLenum)(target), (C.GLenum)(attachment), (C.GLenum)(renderbuffertarget), (C.GLuint)(renderbuffer))\n}", "func FramebufferRenderbuffer(target uint32, attachment uint32, renderbuffertarget uint32, renderbuffer uint32) {\n\tC.glowFramebufferRenderbuffer(gpFramebufferRenderbuffer, (C.GLenum)(target), (C.GLenum)(attachment), (C.GLenum)(renderbuffertarget), (C.GLuint)(renderbuffer))\n}", "func Render(rawBytes []byte, urlPrefix string, metas map[string]string, isWiki bool) []byte {\n\thtmlWriter := org.NewHTMLWriter()\n\n\trenderer := &Renderer{\n\t\tHTMLWriter: htmlWriter,\n\t\tURLPrefix: urlPrefix,\n\t\tIsWiki: isWiki,\n\t}\n\n\thtmlWriter.ExtendingWriter = renderer\n\n\tres, err := org.New().Silent().Parse(bytes.NewReader(rawBytes), \"\").Write(renderer)\n\tif err != nil {\n\t\tlog.Error(\"Panic in orgmode.Render: %v Just returning the rawBytes\", err)\n\t\treturn rawBytes\n\t}\n\treturn []byte(res)\n}", "func (r *Renderer) Render() {\n\tsx, sz, sy := r.c.Bounds()\n\tsxf := float64(sx - 1)\n\tsyf := float64(sy - 1)\n\tszf := float64(sz - 1)\n\tfor z := 0; z < sz; z++ {\n\t\tfor y := 0; y < sy; y++ {\n\t\t\tfor x := 0; x < sx; x++ {\n\t\t\t\tvar lr, lg, lb, _ uint32\n\t\t\t\tn := uint32(0)\n\t\t\t\tfor _, o := range r.objects {\n\t\t\t\t\tr, g, b, _ := o.At(float64(x)/sxf, float64(y)/syf, float64(z)/szf).RGBA()\n\t\t\t\t\tlr += r >> 8\n\t\t\t\t\tlg += g >> 8\n\t\t\t\t\tlb += b >> 8\n\t\t\t\t\tn++\n\t\t\t\t}\n\t\t\t\tr.c.Set(x, y, z, color.RGBA{uint8(lr/n), uint8(lg/n), uint8(lb/n), 255})\n\t\t\t}\n\t\t}\n\t}\n\tr.c.Render()\n}", "func RenderByte(bytes float64) string {\n\tdivider := float64(1024)\n\n\tminus := false\n\tif bytes < 0 {\n\t\tbytes = -bytes\n\t\tminus = true\n\t} else if bytes == 0 {\n\t\treturn \"0B\"\n\t}\n\tret := func(s string) string {\n\t\tif minus {\n\t\t\treturn fmt.Sprintf(\"-%s\", s)\n\t\t}\n\t\treturn s\n\t}\n\n\t// 1 - 1023B\n\tb := bytes\n\tif LessInAccuracy(b, divider) {\n\t\treturn ret(fmt.Sprintf(\"%dB\", int(b)))\n\t}\n\n\t// 1 - 1023K\n\tkb := bytes / divider\n\tif LessInAccuracy(kb, divider) {\n\t\treturn ret(fmt.Sprintf(\"%.2fKB\", kb))\n\t}\n\n\t// 1 - 1023M\n\tmb := kb / divider\n\tif LessInAccuracy(mb, divider) {\n\t\treturn ret(fmt.Sprintf(\"%.2fMB\", mb))\n\t}\n\n\t// 1 - 1023G\n\tgb := mb / divider\n\tif LessInAccuracy(gb, divider) {\n\t\treturn ret(fmt.Sprintf(\"%.2fGB\", gb))\n\t}\n\n\t// 1T -\n\ttb := gb / divider\n\treturn ret(fmt.Sprintf(\"%.2fTB\", tb))\n}", "func (c *Controller) Render() error {\n\tif !c.EnableRender {\n\t\treturn nil\n\t}\n\trb, err := c.RenderBytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.Ctx.ResponseWriter.Header().Get(\"Content-Type\") == \"\" {\n\t\tc.Ctx.Output.Header(\"Content-Type\", \"text/html; charset=utf-8\")\n\t}\n\n\treturn c.Ctx.Output.Body(rb)\n}", "func (vd *videoDriver) Render(frameData []uint8) error {\n\tif !vd.readyForNewFrame {\n\t\treturn nil\n\t}\n\n\tvd.readyForNewFrame = false\n\n\tdoOnMainThread(func() {\n\t\tsurface, err := sdl.CreateRGBSurfaceFrom(\n\t\t\tunsafe.Pointer(&frameData[0]),\n\t\t\tgameboy.ScreenWidth,\n\t\t\tgameboy.ScreenHeight,\n\t\t\t32, // Bits per pixel\n\t\t\t4*gameboy.ScreenWidth, // Bytes per row\n\t\t\t0x000000FF, // Bitmask for R value\n\t\t\t0x0000FF00, // Bitmask for G value\n\t\t\t0x00FF0000, // Bitmask for B value\n\t\t\t0xFF000000, // Bitmask for alpha value\n\t\t)\n\t\tif err != nil {\n\t\t\terr = xerrors.Errorf(\"creating surface: %w\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer surface.Free()\n\n\t\ttexture, err := vd.renderer.CreateTextureFromSurface(surface)\n\t\tif err != nil {\n\t\t\terr = xerrors.Errorf(\"converting surface to a texture: %w\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer texture.Destroy()\n\n\t\terr = vd.renderer.Copy(texture, nil, nil)\n\t\tif err != nil {\n\t\t\terr = xerrors.Errorf(\"copying frame to screen: %w\", err)\n\t\t\treturn\n\t\t}\n\n\t\tvd.renderer.Present()\n\n\t\tif !vd.unlimitedFPS {\n\t\t\tif time.Since(vd.lastFrameTime) < time.Second/targetFPS {\n\t\t\t\ttime.Sleep((time.Second / targetFPS) - time.Since(vd.lastFrameTime))\n\t\t\t}\n\t\t\tvd.lastFrameTime = time.Now()\n\t\t}\n\n\t\tvd.readyForNewFrame = true\n\t}, true)\n\n\treturn nil\n}", "func (builder *Builder) RenderBlock(block *BlockInfo) (string, error) {\n\tfor i, renderer := range builder.BlockCompilers {\n\t\tnewVal, err := renderer(block)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"error in block renderer %d: \\n%s\", i, err.Error())\n\t\t}\n\n\t\tblock.Value = newVal\n\t}\n\n\treturn block.Value, nil\n}", "func BlitFramebuffer(srcX0 int32, srcY0 int32, srcX1 int32, srcY1 int32, dstX0 int32, dstY0 int32, dstX1 int32, dstY1 int32, mask uint32, filter uint32) {\n\tsyscall.Syscall12(gpBlitFramebuffer, 10, uintptr(srcX0), uintptr(srcY0), uintptr(srcX1), uintptr(srcY1), uintptr(dstX0), uintptr(dstY0), uintptr(dstX1), uintptr(dstY1), uintptr(mask), uintptr(filter), 0, 0)\n}", "func (msg *Message) RenderBuffer() *bytes.Buffer {\n\tbuffer := bufpool.New()\n\n\tif msg.Sender != EMPTY {\n\t\tbuffer.WriteString(COLON)\n\t\tbuffer.WriteString(msg.Sender)\n\t\tbuffer.WriteString(SPACE)\n\t}\n\n\tif msg.Code > 0 {\n\t\tbuffer.WriteString(fmt.Sprintf(PADNUM, msg.Code))\n\t} else if msg.Command != EMPTY {\n\t\tbuffer.WriteString(msg.Command)\n\t}\n\n\tif len(msg.Params) > 0 {\n\t\tif len(msg.Params) > 14 {\n\t\t\tmsg.Params = msg.Params[0:15]\n\t\t}\n\n\t\tbuffer.WriteString(SPACE)\n\t\tbuffer.WriteString(strings.Join(msg.Params, SPACE))\n\t}\n\n\tif msg.Text != EMPTY {\n\t\tbuffer.WriteString(SPACE)\n\t\tbuffer.WriteString(COLON)\n\t\tbuffer.WriteString(msg.Text)\n\t}\n\n\tbuffer.WriteString(CRLF)\n\n\treturn buffer\n}", "func Framebuffer() *framebuffer.Device {\n\treturn fb\n}", "func FramebufferRenderbuffer(target uint32, attachment uint32, renderbuffertarget uint32, renderbuffer uint32) {\n\tsyscall.Syscall6(gpFramebufferRenderbuffer, 4, uintptr(target), uintptr(attachment), uintptr(renderbuffertarget), uintptr(renderbuffer), 0, 0)\n}", "func (debugging *debuggingOpenGL) FramebufferRenderbuffer(target uint32, attachment uint32, renderbuffertarget uint32, renderbuffer uint32) {\n\tdebugging.recordEntry(\"FramebufferRenderbuffer\", target, attachment, renderbuffertarget, renderbuffer)\n\tdebugging.gl.FramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer)\n\tdebugging.recordExit(\"FramebufferRenderbuffer\")\n}", "func (b Builder) Render(c context.Context, r *http.Request, p httprouter.Params) (*templates.Args, error) {\n\t// Parse URL parameters.\n\tserver := r.FormValue(\"server\")\n\tif server == \"\" {\n\t\tserver = defaultServer\n\t}\n\n\tbucket := p.ByName(\"bucket\")\n\tif bucket == \"\" {\n\t\treturn nil, &miloerror.Error{\n\t\t\tMessage: \"No bucket\",\n\t\t\tCode: http.StatusBadRequest,\n\t\t}\n\t}\n\n\tbuilder := p.ByName(\"builder\")\n\tif builder == \"\" {\n\t\treturn nil, &miloerror.Error{\n\t\t\tMessage: \"No builder\",\n\t\t\tCode: http.StatusBadRequest,\n\t\t}\n\t}\n\n\t// numbuilds is a name of buildbot's query string parameter for specifying\n\t// maximum number of builds to show.\n\t// We are retaining the parameter name for user convenience.\n\tnumBuildsStr := r.FormValue(\"numbuilds\")\n\tnumBuilds := -1\n\tif numBuildsStr != \"\" {\n\t\tvar err error\n\t\tnumBuilds, err = strconv.Atoi(numBuildsStr)\n\t\tif err != nil {\n\t\t\treturn nil, &miloerror.Error{\n\t\t\t\tMessage: fmt.Sprintf(\"numbuilds parameter value %q is not a number: %s\", numBuildsStr, err),\n\t\t\t\tCode: http.StatusBadRequest,\n\t\t\t}\n\t\t}\n\t}\n\n\tresult, err := builderImpl(c, server, bucket, builder, numBuilds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Render into the template\n\targs := &templates.Args{\n\t\t\"Builder\": result,\n\t}\n\treturn args, nil\n}", "func Render(options cli.Options, base image.Image) image.Image {\n\tctx := gg.NewContextForImage(checkSize(base))\n\n\tif options.Top != \"\" {\n\t\tdrawTopBanner(ctx, options.Top)\n\t}\n\n\tif options.Bottom != \"\" {\n\t\tdrawBottomBanner(ctx, options.Bottom)\n\t}\n\n\treturn ctx.Image()\n}", "func NewFrameBuffer() *FrameBuffer {\n\n\tvar fb FrameBuffer\n\tfb.Strips = make([]LedStrip, 0, config.StripsPerTeensy)\n\n\tif config.Titania {\n\t\t// Titania config\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 229))\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(false, 178))\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(false, 228))\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 0))\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 0))\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 0))\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 0))\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 0))\n\t} else {\n\t\t// Bedroom config\n\t\t// 0, 1 Unused strips (bedroom)\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 0))\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 0))\n\n\t\t// 2 Bed wall\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(false, 168))\n\n\t\t// 3 Bed curtains\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 164))\n\n\t\t// 4 Bed ceiling\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(false, 165))\n\n\t\t// 5 Dressing table wall\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 85))\n\n\t\t// 6 Dressing table ceiling\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 80))\n\n\t\t// 7 Dressing table curtain\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(false, 162))\n\n\t\t// 8 Bathroom mirror wall\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 172))\n\n\t\t// 9 Bath ceiling\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(false, 226))\n\n\t\t// 10 Bath+ wall\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(false, 291))\n\n\t\t// 11 Bathroom mirror ceiling\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 162))\n\n\t\t// 12 Unused\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 0))\n\n\t\t// 13 Left of door ceiling\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(true, 88))\n\n\t\t// 14 Right of door ceiling\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(false, 142))\n\n\t\t// 15 Right of door wall\n\t\tfb.Strips = append(fb.Strips, *NewLedStrip(false, 122))\n\t}\n\n\t// Sanity check\n\tnumberOfStrips := len(fb.Strips)\n\tif numberOfStrips <= 0 || numberOfStrips%config.StripsPerTeensy != 0 {\n\t\tlog.WithField(\"StripsPerTeensy\", strconv.Itoa(config.StripsPerTeensy)).Panic(\"framebuffer strips must be multiple of\")\n\t}\n\treturn &fb\n}", "func (emu *emuState) Framebuffer() []byte {\n\treturn emu.framebuffer()\n}", "func (bp bitmapPart) ToBlock() (disk.Block, error) {\n\treturn bp.data, nil\n}", "func FramebufferRenderbuffer(target Enum, attachment Enum, renderbuffertarget Enum, renderbuffer Uint) {\n\tctarget, _ := (C.GLenum)(target), cgoAllocsUnknown\n\tcattachment, _ := (C.GLenum)(attachment), cgoAllocsUnknown\n\tcrenderbuffertarget, _ := (C.GLenum)(renderbuffertarget), cgoAllocsUnknown\n\tcrenderbuffer, _ := (C.GLuint)(renderbuffer), cgoAllocsUnknown\n\tC.glFramebufferRenderbuffer(ctarget, cattachment, crenderbuffertarget, crenderbuffer)\n}", "func ToBoinga(inlet string) string {\n length := len(inlet)\n outlet := make([]byte, length * 7)\n\n for i := 0; i < length; i++ {\n boinga := fromChar(inlet[i])\n for j := 0; j < 6; j++ {\n outlet[i * 7 + j] = boinga[j]\n }\n outlet[i * 7 + 6] = ' ';\n }\n\n return string(outlet[:len(outlet) - 1])\n}", "func (ob *Object) Render() {\n\tob.image.Draw(ob.x, ob.y, allegro.FLIP_NONE)\n}", "func (a AppblueprintApi) AppBlueprintsRenderPost(body AppBlueprintRenderInput) (*AppBlueprintRenderOutput, *APIResponse, error) {\n\n\tvar httpMethod = \"Post\"\n\t// create path and map variables\n\tpath := a.Configuration.BasePath + \"/app_blueprints/render\"\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 (basicAuth) required\n\n\t// http basic authentication required\n\tif a.Configuration.Username != \"\" || a.Configuration.Password != \"\" {\n\t\theaderParams[\"Authorization\"] = \"Basic \" + a.Configuration.GetBasicAuthEncodedString()\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\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\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\t// body params\n\tswitch reflect.TypeOf(body) {\n\tcase reflect.TypeOf(\"\"):\n\t\tpostBody = body\n\tdefault:\n\t\tpostBody = &body\n\t}\n\n\tvar successPayload = new(AppBlueprintRenderOutput)\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 (addon Addon) Render(addonConfiguration AddonConfiguration) (string, error) {\n\ttemplate, err := template.New(\"\").Parse(addon.templater(addonConfiguration))\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"could not parse manifest template\")\n\t}\n\treturn addon.renderTemplate(template, addonConfiguration)\n}", "func (w *windowImpl) bindBackBuffer() {\n\t// w.mu.Lock()\n\t// size := w.Sz\n\t// w.mu.Unlock()\n\t//\n\tw.backBufferBound = true\n\t// gl.BindFramebuffer(gl.FRAMEBUFFER, 0)\n\t// gl.Viewport(0, 0, int32(size.X), int32(size.Y))\n}", "func CreateBridge(ip net.IP, ipnet net.IPNet, netConf upsi.NetConf, containerPID int, containerID string) (string, string, error) {\n\tlog.Debug(\"\")\n\tones, _ := ipnet.Mask.Size()\n\tbr := \"lxc-br0\"\n\t//Run magical script IFNAME=$($PIPEWORK $BRNAME $NAME ${PREFIX}@$GW $MAC)\n\tpipeworkCmd := fmt.Sprintf(\"%s --quiet %s %d %s %s/%d\", os.Getenv(\"PIPEWORK\"), br, containerPID, containerID, ip, ones)\n\tif *netConf.Gw != \"\" {\n\t\tpipeworkCmd += \"@\" + *netConf.Gw\n\t}\n\tpipeworkCmd += fmt.Sprintf(\" %d %d %d\", *netConf.Group, *netConf.BD, *netConf.Namespace)\n\tif *netConf.MAC != \"\" {\n\t\tpipeworkCmd += \" \" + *netConf.MAC\n\t} else {\n\t\tpipeworkCmd += \" auto\"\n\t}\n\tif *netConf.Route != \"\" {\n\t\tpipeworkCmd += \" '\" + *netConf.Route + \"'\"\n\t}\n\tout, err := execShCommand(pipeworkCmd)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tret := strings.Split(string(out), \" \")\n\treturn ret[0], ret[1], nil\n}", "func RenderJobBPM(currentJob manifest.Job, jobInstances []manifest.JobInstance, baseDir string, manifestName string) error {\n\n\t// Location of the current job job.MF file\n\tjobSpecFile := filepath.Join(baseDir, \"jobs-src\", currentJob.Release, currentJob.Name, \"job.MF\")\n\n\tvar jobSpec struct {\n\t\tTemplates map[string]string `yaml:\"templates\"`\n\t}\n\n\t// First, we must figure out the location of the template.\n\t// We're looking for a template in the spec, whose result is a file \"bpm.yml\"\n\tyamlFile, err := ioutil.ReadFile(jobSpecFile)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to read the job spec file\")\n\t}\n\terr = yaml.Unmarshal(yamlFile, &jobSpec)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmarshal the job spec file\")\n\t}\n\n\tbpmSource := \"\"\n\tfor srcFile, dstFile := range jobSpec.Templates {\n\t\tif filepath.Base(dstFile) == \"bpm.yml\" {\n\t\t\tbpmSource = srcFile\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif bpmSource == \"\" {\n\t\treturn fmt.Errorf(\"can't find BPM template for job %s\", currentJob.Name)\n\t}\n\n\t// ### Render bpm.yml.erb for each job instance\n\n\terbFilePath := filepath.Join(baseDir, \"jobs-src\", currentJob.Release, currentJob.Name, \"templates\", bpmSource)\n\tif _, err := os.Stat(erbFilePath); err != nil {\n\t\treturn err\n\t}\n\n\tif jobInstances != nil {\n\t\tfor i, instance := range jobInstances {\n\n\t\t\tproperties := currentJob.Properties.ToMap()\n\n\t\t\trenderPointer := btg.NewERBRenderer(\n\t\t\t\t&btg.EvaluationContext{\n\t\t\t\t\tProperties: properties,\n\t\t\t\t},\n\n\t\t\t\t&btg.InstanceInfo{\n\t\t\t\t\tAddress: instance.Address,\n\t\t\t\t\tAZ: instance.AZ,\n\t\t\t\t\tID: instance.ID,\n\t\t\t\t\tIndex: string(instance.Index),\n\t\t\t\t\tDeployment: manifestName,\n\t\t\t\t\tName: instance.Name,\n\t\t\t\t},\n\n\t\t\t\tjobSpecFile,\n\t\t\t)\n\n\t\t\t// Would be good if we can write the rendered file into memory,\n\t\t\t// rather than to disk\n\t\t\ttmpfile, err := ioutil.TempFile(\"\", \"rendered.*.yml\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer os.Remove(tmpfile.Name())\n\n\t\t\tif err := renderPointer.Render(erbFilePath, tmpfile.Name()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbpmBytes, err := ioutil.ReadFile(tmpfile.Name())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Parse a rendered bpm.yml into the bpm Config struct\n\t\t\tjobInstances[i].BPM, err = bpm.NewConfig(bpmBytes)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Consider adding a Fingerprint to each job instance\n\t\t\t// instance.Fingerprint = generateSHA(fingerPrintBytes)\n\t\t}\n\t}\n\treturn nil\n}", "func (b *Board) Render() {\n\tfmt.Println() // to breathe\n\tfmt.Println(\" | a | b | c | d | e | f | g | h |\")\n\tfmt.Println(\" - +-----+-----+-----+-----+-----+-----+-----+-----+\")\n\n\tfor i := 0; i < 8; i++ {\n\t\tfmt.Printf(\" %d |\", i)\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tcell := b[i][j]\n\t\t\tfmt.Printf(\" %s |\", cell)\n\t\t}\n\t\tfmt.Println()\n\t}\n\n\tfmt.Println(\" - +-----+-----+-----+-----+-----+-----+-----+-----+\")\n\tfmt.Println() // breathe again\n}", "func (m KubedgeBaseManager) Render(ctx context.Context) (*av1.SubResourceList, error) {\n\treturn m.Renderer.RenderFile(m.PhaseName, m.PhaseNamespace, m.Source.Location)\n}", "func (res *ResponseAdapter) Buffer() *bytes.Buffer {\n\tres.bOnce.Do(func() {\n\t\tvar b bytes.Buffer\n\t\tif _, err := io.Copy(&b, res.Response().Body); err != nil {\n\t\t\tpanic(err) // xxx\n\t\t}\n\t\tres.bytes = b.Bytes()\n\t})\n\treturn bytes.NewBuffer(res.bytes)\n}", "func (c *Components) Render() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (v Binary) Render(i, width int, baseStyle lipgloss.Style) string {\n\tw := dataWidth(width)\n\t_, err := v.Seek(int64(i*w), io.SeekStart)\n\tif err != nil {\n\t\treturn baseStyle.Blink(true).Render(err.Error())\n\t}\n\tif len(v.b) != w {\n\t\tv.b = make([]byte, w)\n\t}\n\tn, err := v.Read(v.b)\n\tif err != nil && !errors.Is(err, io.EOF) {\n\t\treturn baseStyle.Blink(true).Render(err.Error())\n\t}\n\ts := fmt.Sprintf(\"% X%s \", v.b[0:n], strings.Repeat(\" \", w-n))\n\tvar x strings.Builder\n\tfor i := 0; i < n; i++ {\n\t\tif unicode.IsPrint(rune(v.b[i])) {\n\t\t\tx.WriteRune(rune(v.b[i]))\n\t\t} else {\n\t\t\tx.WriteRune('.')\n\t\t}\n\t}\n\treturn baseStyle.Render(s + x.String())\n}", "func New(uid string, ipcon *ipconnection.IPConnection) (DualButtonBricklet, error) {\n\tinternalIPCon := ipcon.GetInternalHandle().(IPConnection)\n\tdev, err := NewDevice([3]uint8{2, 0, 0}, uid, &internalIPCon, 0, DeviceIdentifier, DeviceDisplayName)\n\tif err != nil {\n\t\treturn DualButtonBricklet{}, err\n\t}\n\tdev.ResponseExpected[FunctionSetLEDState] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetLEDState] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionGetButtonState] = ResponseExpectedFlagAlwaysTrue\n\tdev.ResponseExpected[FunctionSetSelectedLEDState] = ResponseExpectedFlagFalse\n\tdev.ResponseExpected[FunctionGetIdentity] = ResponseExpectedFlagAlwaysTrue\n\treturn DualButtonBricklet{dev}, nil\n}", "func ToBuffer(closeCallback func(*bytes.Buffer) error) Dest {\n\treturn func() (io.WriteCloser, error) {\n\t\treturn &bufferCallback{closeCallback: closeCallback}, nil\n\t}\n}", "func newBall(renderer *sdl.Renderer, x, y int32) (bal Ball, err error) {\n\n\timg.Init(img.INIT_JPG | img.INIT_PNG)\n\tsdl.SetHint(sdl.HINT_RENDER_SCALE_QUALITY, \"1\")\n\tBallImg, err := img.Load(\"Ball.png\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn Ball{}, fmt.Errorf(\"%v\", err)\n\t}\n\tdefer BallImg.Free()\n\tbal.Tex, err = renderer.CreateTextureFromSurface(BallImg)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn Ball{}, fmt.Errorf(\"%v\", err)\n\t}\n\n\tbal.X = float64(x)\n\tbal.Y = float64(y)\n\tbal.Radius = radius\n\tbal.Xv = BallSpeedX\n\tbal.Yv = BallSpeedY\n\treturn bal, nil\n}", "func (r renderer) LineBreak(out *bytes.Buffer) {}", "func (ren *RenderComponent) generateBufferContent() []float32 {\n\tscaleX := ren.scale.X\n\tscaleY := ren.scale.Y\n\trotation := float32(0.0)\n\ttransparency := float32(1.0)\n\tc := ren.Color\n\n\tfx := float32(0)\n\tfy := float32(0)\n\tfx2 := ren.drawable.Width()\n\tfy2 := ren.drawable.Height()\n\n\tif scaleX != 1 || scaleY != 1 {\n\t\t//fx *= scaleX\n\t\t//fy *= scaleY\n\t\tfx2 *= scaleX\n\t\tfy2 *= scaleY\n\t}\n\n\tp1x := fx\n\tp1y := fy\n\tp2x := fx\n\tp2y := fy2\n\tp3x := fx2\n\tp3y := fy2\n\tp4x := fx2\n\tp4y := fy\n\n\tvar x1 float32\n\tvar y1 float32\n\tvar x2 float32\n\tvar y2 float32\n\tvar x3 float32\n\tvar y3 float32\n\tvar x4 float32\n\tvar y4 float32\n\n\tif rotation != 0 {\n\t\trot := rotation * (math.Pi / 180.0)\n\n\t\tcos := math.Cos(rot)\n\t\tsin := math.Sin(rot)\n\n\t\tx1 = cos*p1x - sin*p1y\n\t\ty1 = sin*p1x + cos*p1y\n\n\t\tx2 = cos*p2x - sin*p2y\n\t\ty2 = sin*p2x + cos*p2y\n\n\t\tx3 = cos*p3x - sin*p3y\n\t\ty3 = sin*p3x + cos*p3y\n\n\t\tx4 = x1 + (x3 - x2)\n\t\ty4 = y3 - (y2 - y1)\n\t} else {\n\t\tx1 = p1x\n\t\ty1 = p1y\n\n\t\tx2 = p2x\n\t\ty2 = p2y\n\n\t\tx3 = p3x\n\t\ty3 = p3y\n\n\t\tx4 = p4x\n\t\ty4 = p4y\n\t}\n\n\tcolorR, colorG, colorB, _ := c.RGBA()\n\n\tred := colorR\n\tgreen := colorG << 8\n\tblue := colorB << 16\n\talpha := uint32(transparency*255.0) << 24\n\n\ttint := math.Float32frombits((alpha | blue | green | red) & 0xfeffffff)\n\n\tu, v, u2, v2 := ren.drawable.View()\n\n\treturn []float32{x1, y1, u, v, tint, x4, y4, u2, v, tint, x3, y3, u2, v2, tint, x2, y2, u, v2, tint}\n}", "func FramebufferRenderbuffer(target, attachment, rbTarget Enum, rb Renderbuffer) {\n\tgl.FramebufferRenderbuffer(uint32(target), uint32(attachment), uint32(rbTarget), rb.Value)\n}", "func (c *Board) OnRender() {\n}", "func Render(c Compo) {\n\tUI(func() { render(c) })\n}", "func (display *WebDisplay) Render(solarSystem *System) {\n\t// given the solarSystem, which contains info on planets and drawable items\n\n\timage := image.NewRGBA(image.Rect(0, 0, display.width, display.height))\n\n\t// loop through every planet\n\tfor planetIndex := 0; planetIndex < PlanetCount; planetIndex++ {\n\t\tplanet := display.solarSystem.planets[planetIndex]\n\t\t//pos := planet.position\n\n\t\t// initialize default color for each led position\n\t\tfor led := 0; led < planet.ledCount; led++ {\n\t\t\tledPosition := solarSystem.LedPosition(PlanetIndex(planetIndex), led)\n\n\t\t\timageX := int(ledPosition.X * display.scale.X)\n\t\t\timageY := int(ledPosition.Y * display.scale.Y)\n\n\t\t\timage.SetRGBA(imageX, imageY, color.RGBA{R: 0, G: 0, B: 0, A: 255})\n\t\t}\n\n\t\t// loop through every drawable object\n\t\tfor curElement := solarSystem.drawables.Front(); curElement != nil; curElement = curElement.Next() {\n\t\t\tdrawable := curElement.Value.(Drawable)\n\n\t\t\t// for now want default color to be set for all leds\n\t\t\t// bounding circle check to see if this should affect this planet\n\t\t\t//if !drawable.Affects(pos, planet.radius) {\n\t\t\t//\tcontinue\n\t\t\t//}\n\n\t\t\t// loop through every led on this planet\n\t\t\tfor led := 0; led < planet.ledCount; led++ {\n\t\t\t\tledPosition := solarSystem.LedPosition(PlanetIndex(planetIndex), led)\n\n\t\t\t\timageX := int(ledPosition.X * display.scale.X)\n\t\t\t\timageY := int(ledPosition.Y * display.scale.Y)\n\n\t\t\t\tcurColor := RGBA(image.RGBAAt(imageX, imageY))\n\t\t\t\tcurColor = drawable.ColorAt(ledPosition, RGBA(curColor))\n\n\t\t\t\tcurColor.A = 255 // for rendering to image dont want to blend to nothing\n\t\t\t\timage.SetRGBA(imageX, imageY, color.RGBA(curColor))\n\t\t\t}\n\t\t}\n\t}\n\n\tdisplay.image = image\n}", "func (s *EntityStorage) Blanc() {\n\ts.freeIDs = append(s.freeIDs, len(s.vec))\n\ts.vec = append(s.vec, EntityCapsule{})\n}", "func (game *Game) Render() {\n\tallegro.ClearToColor(allegro.MapRGB(0, 0, 0))\n\tallegro.HoldBitmapDrawing(true)\n\tgame.background.Draw(0, 0, allegro.FLIP_NONE)\n\tgame.gopher.Render()\n\tallegro.HoldBitmapDrawing(false)\n\tallegro.FlipDisplay()\n}", "func (b *Bitmap) Buffer() []byte {\n\tl := b.Rows() * b.Pitch()\n\treturn C.GoBytes(unsafe.Pointer(b.handle.buffer), C.int(l))\n}", "func Render(mem *memory.Bank) *image.RGBA {\n\t// Top border\n\tfor pixel := 0; pixel < 4*width*BorderTop; pixel += 4 {\n\t\tborder := findBorderColour(pixelT[pixel/4])\n\t\timg.Pix[pixel] = border[0]\n\t\timg.Pix[pixel+1] = border[1]\n\t\timg.Pix[pixel+2] = border[2]\n\t}\n\n\t// Main screen and left/right border\n\tfor line, addr := range lines {\n\t\tpx := 4 * (width*(line+BorderTop) + BorderLeft)\n\n\t\t// Left border\n\t\tfor left := px - 4*BorderLeft; left < px; left += 4 {\n\t\t\tborder := findBorderColour(pixelT[left/4])\n\t\t\timg.Pix[left] = border[0]\n\t\t\timg.Pix[left+1] = border[1]\n\t\t\timg.Pix[left+2] = border[2]\n\t\t}\n\t\t// Right border\n\t\tfor right := px + 4*256; right < px+4*256+4*BorderRight; right += 4 {\n\t\t\tborder := findBorderColour(pixelT[right/4])\n\t\t\timg.Pix[right] = border[0]\n\t\t\timg.Pix[right+1] = border[1]\n\t\t\timg.Pix[right+2] = border[2]\n\t\t}\n\n\t\t// Centre\n\t\tfor col := 0; col < 32; col++ {\n\t\t\tattr := mem[0x5800+32*(line/8)+col-0x4000]\n\t\t\tcell := mem[addr+col-0x4000]\n\t\t\tfor _, bit := range []byte{0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01} {\n\t\t\t\tvar colour []byte\n\t\t\t\tflash := attr&0x80 != 0 && frame >= 32\n\t\t\t\ton := cell&bit != 0\n\t\t\t\tif on != flash {\n\t\t\t\t\tcolour = inkPalette[attr&0b01000111]\n\t\t\t\t} else {\n\t\t\t\t\tcolour = paperPalette[attr&0b01111000]\n\t\t\t\t}\n\t\t\t\timg.Pix[px] = colour[0]\n\t\t\t\timg.Pix[px+1] = colour[1]\n\t\t\t\timg.Pix[px+2] = colour[2]\n\t\t\t\tpx += 4\n\t\t\t}\n\t\t}\n\t}\n\n\t// Bottom border\n\tfor px := 4 * width * (BorderTop + 192); px < 4*width*(height); px += 4 {\n\t\tborder := findBorderColour(pixelT[px/4])\n\t\timg.Pix[px] = border[0]\n\t\timg.Pix[px+1] = border[1]\n\t\timg.Pix[px+2] = border[2]\n\t}\n\n\t// Can safely drop recorded states\n\tresetBorderStates()\n\n\t// Keep frame count for the \"flash\" attribute\n\tframe += 1\n\tif frame > 50 {\n\t\tframe = 1\n\t}\n\n\treturn img\n}", "func (r *Renderer) RenderFrame() RenderFrame {\n\tif targetA {return frameB}\n\treturn frameA\n}", "func (Empty) Render(width, height int) *term.Buffer {\n\treturn term.NewBufferBuilder(width).Buffer()\n}", "func GetDefaultCouchDeviceBuffer(couchaddr, database string, interval time.Duration) *CouchDeviceBuffer {\n\t//we'll need to initialize from the server\n\tval := &CouchDeviceBuffer{\n\t\tincomingChannel: make(chan sd.StaticDevice, 10000),\n\t\treingestionChannel: make(chan CouchStaticDevice, 1000),\n\t\trevChannel: make(chan []Rev, 100),\n\n\t\tcurBuffer: make(map[string]CouchStaticDevice), revBuffer: make(map[string]Rev),\n\n\t\tinterval: interval,\n\t\tdatabase: database,\n\t\tcouchaddr: couchaddr,\n\t}\n\n\tgo val.start()\n\treturn val\n}", "func (ctx *Context) Render(bytes []byte) {\n\t//debug\n\t//fmt.Println(\"response msg = \", string(bytes))\n\tctx.Writer.WriteHeader(200)\n\t_, err := ctx.Writer.Write(bytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (c *ZtunnelComponent) RenderManifest() (string, error) {\n\treturn renderManifest(c, c.CommonComponentFields)\n}", "func BlitNamedFramebuffer(readFramebuffer uint32, drawFramebuffer uint32, srcX0 int32, srcY0 int32, srcX1 int32, srcY1 int32, dstX0 int32, dstY0 int32, dstX1 int32, dstY1 int32, mask uint32, filter uint32) {\n\tsyscall.Syscall12(gpBlitNamedFramebuffer, 12, uintptr(readFramebuffer), uintptr(drawFramebuffer), uintptr(srcX0), uintptr(srcY0), uintptr(srcX1), uintptr(srcY1), uintptr(dstX0), uintptr(dstY0), uintptr(dstX1), uintptr(dstY1), uintptr(mask), uintptr(filter))\n}", "func (c *CaptureResponse) Render(w http.ResponseWriter, r *http.Request) error {\n\tc.Price = c.c.Price\n\tc.Status = c.c.Status.String()\n\n\treturn nil\n}", "func (b *MonopAmpBridge) Bridge(ctx context.Context) (*pb.Bridge, error) {\n\tbridge, err := b.persister.Bridge(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := &pb.Bridge{\n\t\tConfig: &pb.BridgeConfig{\n\t\t\tAddress: &pb.Address{\n\t\t\t\tUsb: &pb.Address_Usb{\n\t\t\t\t\tPath: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tTimezone: \"UTC\",\n\t\t},\n\t}\n\tproto.Merge(ret, baseMonopAmpBridge)\n\tproto.Merge(ret, bridge)\n\treturn ret, nil\n}", "func Render(w IWidget, size gowid.IRenderSize, focus gowid.Selector, app gowid.IApp) gowid.ICanvas {\n\tflow, isFlow := size.(gowid.IRenderFlowWith)\n\tif !isFlow {\n\t\tpanic(gowid.WidgetSizeError{Widget: w, Size: size, Required: \"gowid.IRenderFlowWith\"})\n\t}\n\tcols := flow.FlowColumns()\n\n\tdisplay := make([]rune, cols)\n\twi := w.Index()\n\tfor i := 0; i < cols; i++ {\n\t\tdisplay[i] = wave[wi]\n\t\twi += 1\n\t\tif wi == w.SpinnerLen() {\n\t\t\twi = 0\n\t\t}\n\t}\n\tbarCanvas :=\n\t\tstyled.New(\n\t\t\ttext.New(string(display)),\n\t\t\tw.Styler(),\n\t\t).Render(\n\n\t\t\tgowid.RenderBox{C: cols, R: 1}, gowid.NotSelected, app)\n\n\treturn barCanvas\n}", "func RenderTeapot(w http.ResponseWriter, message ...interface{}) {\n\tRender(w, Teapot(message...))\n}", "func (fb *FrameBuffer) ToImage() *ebiten.Image {\n\treturn fb.img\n}", "func (h *HAProxyManager) render(ports []uint16) ([]byte, error) {\n\n\t// prepare the context\n\td := make([]templateContext, len(ports))\n\tfor i, port := range ports {\n\t\tif i == len(h.serviceAddrs) {\n\t\t\th.logger.Warnf(\"got port index %d, but only have %d service addrs. ports=%v serviceAddrs=%v\", i, len(h.serviceAddrs), ports, h.serviceAddrs)\n\t\t\tcontinue\n\t\t}\n\t\td[i] = templateContext{Port: port, Source: h.listenAddr, Dest: h.serviceAddrs[i]}\n\t}\n\n\t// render the template\n\tbuf := &bytes.Buffer{}\n\tif err := h.template.Execute(buf, d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (o GetResolverFirewallRulesFirewallRuleOutput) BlockResponse() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetResolverFirewallRulesFirewallRule) string { return v.BlockResponse }).(pulumi.StringOutput)\n}", "func Ballmer(name, company, from string) (string, error) {\n\treturn makeRequest(\"ballmer\", name, company, from)\n}", "func (s Resource) Render(geometry Geometry) {\n\tcgeometry := geometry.c()\n\tdefer C.free(unsafe.Pointer(cgeometry))\n\tC.wlc_surface_render(C.wlc_resource(s), cgeometry)\n}", "func (s *ServicesWidget) Buffer() gizaktermui.Buffer {\n\ts.Lock()\n\tdefer s.Unlock()\n\tbuf := gizaktermui.NewBuffer()\n\tif !s.mounted {\n\t\treturn buf\n\t}\n\ty := s.screen.Bounds().Min.Y\n\n\ts.prepareForRendering()\n\twidgetHeader := appui.NewWidgetHeader()\n\twidgetHeader.HeaderEntry(\"Services\", strconv.Itoa(s.RowCount()))\n\tif s.filterPattern != \"\" {\n\t\twidgetHeader.HeaderEntry(\"Active filter\", s.filterPattern)\n\t}\n\twidgetHeader.Y = y\n\tbuf.Merge(widgetHeader.Buffer())\n\ty += widgetHeader.GetHeight()\n\t//Empty line between the header and the rest of the content\n\ty++\n\ts.updateHeader()\n\ts.header.SetY(y)\n\tbuf.Merge(s.header.Buffer())\n\ty += s.header.GetHeight()\n\n\tselected := s.selectedIndex - s.startIndex\n\n\tfor i, serviceRow := range s.visibleRows() {\n\t\tserviceRow.SetY(y)\n\t\ty += serviceRow.GetHeight()\n\t\tif i != selected {\n\t\t\tserviceRow.NotHighlighted()\n\t\t} else {\n\t\t\tserviceRow.Highlighted()\n\t\t}\n\t\tbuf.Merge(serviceRow.Buffer())\n\t}\n\treturn buf\n}", "func (r renderer) BlockCode(out *bytes.Buffer, text []byte, land string) {}", "func Render(state string, branch_length float64, branch_width float64, phase_diff float64, phase_init float64, canvas_size int, img_path string) {\n\td := gg.NewContext(canvas_size, canvas_size)\n\td.SetRGB(205, 133, 63)\n\td.SetLineWidth(branch_width)\n\t// Create a stack of branch-off points |b_stack|. |b| always points to the top of the stack.\n\tvar b_stack []Branch\n\tvar b *Branch\n\tvar b_new Branch\n\t// Initialize the stack.\n\tb_stack = append(b_stack, Branch{phase_init, complex(float64(canvas_size)/2, float64(canvas_size))})\n\tb = &b_stack[len(b_stack)-1]\n\n\t// Interpret each character of the input string as a drawing action.\n\tfor idx, c := range state {\n\t\tif c == 'F' {\n\t\t\t// Move forward from |b| to |b_new| and draw a line.\n\t\t\tb_new = Forward(*b, branch_length)\n\t\t\td.DrawLine(real(b.xy), imag(b.xy), real(b_new.xy), imag(b_new.xy))\n\t\t\td.Stroke()\n\t\t\t*b = b_new\n\t\t\td.SavePNG(img_path + \"/\" + strconv.Itoa(idx) + \".png\")\n\t\t} else if c == 'G' {\n\t\t\t// Move forward without drawing anything.\n\t\t\tb_new = Forward(*b, branch_length)\n\t\t\t*b = b_new\n\t\t} else if c == '-' {\n\t\t\t// Turn left.\n\t\t\t*b = Turn(*b, -1*phase_diff)\n\t\t} else if c == '+' {\n\t\t\t// Turn right.\n\t\t\t*b = Turn(*b, phase_diff)\n\t\t} else if c == '[' {\n\t\t\t// Store the current branch state.\n\t\t\tb_save := *b\n\t\t\tb_stack = append(b_stack, b_save)\n\t\t\tb = &b_stack[len(b_stack)-1]\n\t\t} else if c == ']' {\n\t\t\t// Return to the last saved branch state.\n\t\t\tb_stack = b_stack[:len(b_stack)-1]\n\t\t\tb = &b_stack[len(b_stack)-1]\n\t\t}\n\t}\n\tfmt.Println(\"Saved images to: \" + img_path)\n}", "func Render(w http.ResponseWriter, r *http.Request, v Renderer) error {\n\tif err := renderer(w, r, v); err != nil {\n\t\treturn err\n\t}\n\tRespond(w, r, v)\n\treturn nil\n}", "func (s *Surface) Blit(source *Surface, x, y float64) {\n\ts.Ctx.Call(\"drawImage\", source.Canvas, math.Floor(x), math.Floor(y))\n}", "func BlitFramebuffer(srcX0 int32, srcY0 int32, srcX1 int32, srcY1 int32, dstX0 int32, dstY0 int32, dstX1 int32, dstY1 int32, mask uint32, filter uint32) {\n C.glowBlitFramebuffer(gpBlitFramebuffer, (C.GLint)(srcX0), (C.GLint)(srcY0), (C.GLint)(srcX1), (C.GLint)(srcY1), (C.GLint)(dstX0), (C.GLint)(dstY0), (C.GLint)(dstX1), (C.GLint)(dstY1), (C.GLbitfield)(mask), (C.GLenum)(filter))\n}", "func draw(window *glfw.Window, reactProg, landProg uint32) {\n\n\tvar renderLoops = 4\n\tfor i := 0; i < renderLoops; i++ {\n\t\t// -- DRAW TO BUFFER --\n\t\t// define destination of pixels\n\t\t//gl.BindFramebuffer(gl.FRAMEBUFFER, 0)\n\t\tgl.BindFramebuffer(gl.FRAMEBUFFER, FBO[1])\n\n\t\tgl.Viewport(0, 0, width, height) // Retina display doubles the framebuffer !?!\n\n\t\tgl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)\n\t\tgl.UseProgram(reactProg)\n\n\t\t// bind Texture\n\t\tgl.ActiveTexture(gl.TEXTURE0)\n\t\tgl.BindTexture(gl.TEXTURE_2D, renderedTexture)\n\t\tgl.Uniform1i(uniTex, 0)\n\n\t\tgl.BindVertexArray(VAO)\n\t\tgl.DrawElements(gl.TRIANGLE_STRIP, int32(len(indices)), gl.UNSIGNED_INT, nil)\n\n\t\tgl.BindVertexArray(0)\n\n\t\t// -- copy back textures --\n\t\tgl.BindFramebuffer(gl.READ_FRAMEBUFFER, FBO[1]) // source is high res array\n\t\tgl.ReadBuffer(gl.COLOR_ATTACHMENT0)\n\t\tgl.BindFramebuffer(gl.DRAW_FRAMEBUFFER, FBO[0]) // destination is cells array\n\t\tgl.DrawBuffer(gl.COLOR_ATTACHMENT0)\n\t\tgl.BlitFramebuffer(0, 0, width, height,\n\t\t\t0, 0, cols, rows,\n\t\t\tgl.COLOR_BUFFER_BIT, gl.NEAREST) // downsample\n\t\tgl.BindFramebuffer(gl.READ_FRAMEBUFFER, FBO[0]) // source is low res array - put in texture\n\t\t// read pixels saves data read as unsigned bytes and then loads them in TexImage same way\n\t\tgl.ReadPixels(0, 0, cols, rows, gl.RGBA, gl.FLOAT, gl.Ptr(fData))\n\t\tgl.BindTexture(gl.TEXTURE_2D, renderedTexture)\n\t\tgl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, cols, rows, 0, gl.RGBA, gl.FLOAT, gl.Ptr(fData))\n\t\tCheckGLErrors()\n\t}\n\t// -- DRAW TO SCREEN --\n\tvar model glm.Mat4\n\n\t// destination 0 means screen\n\tgl.BindFramebuffer(gl.FRAMEBUFFER, 0)\n\tgl.Viewport(0, 0, width*2, height*2) // Retina display doubles the framebuffer !?!\n\tgl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)\n\tgl.UseProgram(landProg)\n\t// bind Texture\n\tgl.ActiveTexture(gl.TEXTURE0)\n\tgl.BindTexture(gl.TEXTURE_2D, drawTexture)\n\n\tvar view glm.Mat4\n\tvar brakeFactor = float64(20000.0)\n\tvar xCoord, yCoord float32\n\txCoord = float32(-3.0 * math.Sin(float64(myClock)))\n\tyCoord = float32(-3.0 * math.Cos(float64(myClock)))\n\t//xCoord = 0.0\n\t//yCoord = float32(-2.5)\n\tmyClock = math.Mod((myClock + float64(deltaTime)/brakeFactor), (math.Pi * 2))\n\tview = glm.LookAt(xCoord, yCoord, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)\n\tgl.UniformMatrix4fv(uniView, 1, false, &view[0])\n\tmodel = glm.HomogRotate3DX(glm.DegToRad(00.0))\n\tgl.UniformMatrix4fv(uniModel, 1, false, &model[0])\n\tgl.Uniform1i(uniTex2, 0)\n\n\t// render container\n\t//gl.PolygonMode(gl.FRONT_AND_BACK, gl.FILL)\n\t//gl.PolygonMode(gl.FRONT_AND_BACK, gl.LINE)\n\n\tgl.BindVertexArray(VAO)\n\tgl.DrawElements(gl.TRIANGLE_STRIP, int32(len(indices)), gl.UNSIGNED_INT, nil)\n\tgl.BindVertexArray(0)\n\n\tCheckGLErrors()\n\n\tglfw.PollEvents()\n\twindow.SwapBuffers()\n\n\t//time.Sleep(100 * 1000 * 1000)\n}", "func (m *GameMap) Render(gameCamera *camera.GameCamera, newCameraX, newCameraY int) {\n\n\tgameCamera.MoveCamera(newCameraX, newCameraY, m.Width, m.Height)\n\n\tfor x := 0; x < gameCamera.Width; x++ {\n\t\tfor y := 0; y < gameCamera.Height; y++ {\n\n\t\t\tmapX, mapY := gameCamera.X+x, gameCamera.Y+y\n\n\t\t\tif mapX < 0 {\n\t\t\t\tmapX = 0\n\t\t\t}\n\n\t\t\tif mapY < 0 {\n\t\t\t\tmapY = 0\n\t\t\t}\n\n\t\t\ttile := m.Tiles[mapX][mapY]\n\t\t\tcamX, camY := gameCamera.ToCameraCoordinates(mapX, mapY)\n\n\t\t\t// Print the tile, if it meets the following criteria:\n\t\t\t// 1. Its visible or explored\n\t\t\t// 2. It hasn't been printed yet. This will prevent over printing due to camera conversion\n\t\t\tif tile.Visible {\n\t\t\t\tui.PrintGlyph(camX, camY, tile.Glyph, \"\", 0)\n\t\t\t} else if tile.Explored {\n\t\t\t\tui.PrintGlyph(camX, camY, tile.Glyph, \"\", 0, true)\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Camera) Render(world, screen *ebiten.Image) error {\n\treturn screen.DrawImage(world, &ebiten.DrawImageOptions{\n\t\tGeoM: c.worldMatrix(),\n\t})\n}", "func (Parser) Render(rawBytes []byte, urlPrefix string, metas map[string]string, isWiki bool) []byte {\n\treturn Render(rawBytes, urlPrefix, metas, isWiki)\n}", "func BlitNamedFramebuffer(readFramebuffer uint32, drawFramebuffer uint32, srcX0 int32, srcY0 int32, srcX1 int32, srcY1 int32, dstX0 int32, dstY0 int32, dstX1 int32, dstY1 int32, mask uint32, filter uint32) {\n\tC.glowBlitNamedFramebuffer(gpBlitNamedFramebuffer, (C.GLuint)(readFramebuffer), (C.GLuint)(drawFramebuffer), (C.GLint)(srcX0), (C.GLint)(srcY0), (C.GLint)(srcX1), (C.GLint)(srcY1), (C.GLint)(dstX0), (C.GLint)(dstY0), (C.GLint)(dstX1), (C.GLint)(dstY1), (C.GLbitfield)(mask), (C.GLenum)(filter))\n}", "func BlitNamedFramebuffer(readFramebuffer uint32, drawFramebuffer uint32, srcX0 int32, srcY0 int32, srcX1 int32, srcY1 int32, dstX0 int32, dstY0 int32, dstX1 int32, dstY1 int32, mask uint32, filter uint32) {\n\tC.glowBlitNamedFramebuffer(gpBlitNamedFramebuffer, (C.GLuint)(readFramebuffer), (C.GLuint)(drawFramebuffer), (C.GLint)(srcX0), (C.GLint)(srcY0), (C.GLint)(srcX1), (C.GLint)(srcY1), (C.GLint)(dstX0), (C.GLint)(dstY0), (C.GLint)(dstX1), (C.GLint)(dstY1), (C.GLbitfield)(mask), (C.GLenum)(filter))\n}", "func BlitFramebuffer(srcX0 int32, srcY0 int32, srcX1 int32, srcY1 int32, dstX0 int32, dstY0 int32, dstX1 int32, dstY1 int32, mask uint32, filter uint32) {\n\tC.glowBlitFramebuffer(gpBlitFramebuffer, (C.GLint)(srcX0), (C.GLint)(srcY0), (C.GLint)(srcX1), (C.GLint)(srcY1), (C.GLint)(dstX0), (C.GLint)(dstY0), (C.GLint)(dstX1), (C.GLint)(dstY1), (C.GLbitfield)(mask), (C.GLenum)(filter))\n}" ]
[ "0.6053571", "0.5923409", "0.5577824", "0.5317886", "0.5277157", "0.5269256", "0.5146389", "0.48923406", "0.4845219", "0.4740202", "0.47288695", "0.47238946", "0.47081098", "0.4681865", "0.46178353", "0.46008968", "0.45710856", "0.45635307", "0.4534008", "0.45178184", "0.45023918", "0.44750848", "0.4469592", "0.44657362", "0.4455858", "0.44437012", "0.4433944", "0.44132322", "0.44054234", "0.44054234", "0.43624285", "0.4350659", "0.43492952", "0.43445158", "0.43348712", "0.43197188", "0.43101284", "0.43045413", "0.4283425", "0.42807707", "0.4270493", "0.4262294", "0.4255628", "0.42543015", "0.424301", "0.42340788", "0.42269105", "0.4226272", "0.4205368", "0.41923383", "0.41874242", "0.4173779", "0.41734868", "0.41726136", "0.41706556", "0.41643098", "0.41609928", "0.41551948", "0.41512528", "0.41447416", "0.41390687", "0.41375366", "0.413178", "0.41264886", "0.4126222", "0.41235527", "0.4121385", "0.41134122", "0.41116682", "0.41094926", "0.41072935", "0.41032162", "0.40999243", "0.4084323", "0.4081223", "0.40799433", "0.4078796", "0.40749285", "0.40644395", "0.40622643", "0.40557513", "0.40510064", "0.40498617", "0.40478647", "0.404548", "0.40411276", "0.40342292", "0.40338567", "0.40234", "0.4016283", "0.401048", "0.4006103", "0.4002637", "0.40007067", "0.3996779", "0.39964062", "0.3996173", "0.39952475", "0.39952475", "0.3995045" ]
0.77492094
0
RenderToSVG renders a device as SVG and outputs as a string
func (device Device) RenderToSVG(width int, height int) string { buffer := new(bytes.Buffer) centerX := int(width / 2) centerY := int(height / 2) lineColor := "#000000" blazon := device.RenderToBlazon() /* blazonLength := len(blazon) blazonSize := "10" if blazonLength < 25 { blazonSize = "28" } else if blazonLength < 30 { blazonSize = "26" } else if blazonLength < 35 { blazonSize = "20" } else if blazonLength < 40 { blazonSize = "18" } else if blazonLength < 50 { blazonSize = "14" } else if blazonLength < 60 { blazonSize = "12" } else if blazonLength < 80 { blazonSize = "11" } */ canvas := svg.New(buffer) canvas.Start(width, height+50) canvas.Title(blazon) canvas.Def() canvas.Mask("shieldmask", 0, 0, width, height) canvas.Path("m10.273 21.598v151.22c0 96.872 89.031 194.34 146.44 240.09 57.414-45.758 146.44-143.22 146.44-240.09v-151.22h-292.89z", "fill:#FFFFFF") canvas.MaskEnd() for _, tincture := range device.AllTinctures { if tincture.Name == "erminois" { insertErmine(canvas, "erminois") } else if tincture.Name == "ermine" { insertErmine(canvas, "ermine") } else if tincture.Name == "ermines" { insertErmine(canvas, "ermines") } else if tincture.Name == "pean" { insertErmine(canvas, "pean") } } if device.Field.HasVariation { insertVariationPattern(canvas, device.Field.Variation) } canvas.DefEnd() canvas.Group("mask='url(#shieldmask)'") if device.Field.HasVariation { canvas.Rect(0, 0, width, height, "fill:url(#"+device.Field.Variation.Name+")") } else { canvas.Rect(0, 0, width, height, "fill:"+device.Field.Tincture.Hexcode) } switch device.Field.Division.Name { case "plain": case "pale": canvas.Rect(int(width/2), 0, int(width/2), height, "fill:"+device.Field.Division.Tincture.Hexcode) case "fess": canvas.Rect(0, 0, width, int(height/2), "fill:"+device.Field.Division.Tincture.Hexcode) case "bend": canvas.Polygon([]int{0, 0, width}, []int{0, height, height}, "fill:"+device.Field.Division.Tincture.Hexcode) case "bendsinister": canvas.Polygon([]int{0, width, 0}, []int{0, 0, height}, "fill:"+device.Field.Division.Tincture.Hexcode) case "chevron": canvas.Polygon([]int{0, int(width / 2), width}, []int{height, int(height / 2), height}, "fill:"+device.Field.Division.Tincture.Hexcode) case "quarterly": canvas.Rect(int(width/2), 0, int(width/2), int(height/2), "fill:"+device.Field.Division.Tincture.Hexcode) canvas.Rect(0, int(height/2), int(width/2), int(height/2), "fill:"+device.Field.Division.Tincture.Hexcode) case "saltire": canvas.Polygon([]int{0, int(width / 2), 0}, []int{0, int(height / 2), height}, "fill:"+device.Field.Division.Tincture.Hexcode) canvas.Polygon([]int{width, int(width / 2), width}, []int{0, int(height / 2), height}, "fill:"+device.Field.Division.Tincture.Hexcode) } for _, chargeGroup := range device.ChargeGroups { if len(chargeGroup.Charges) == 2 { canvas.Scale(0.5) } else if len(chargeGroup.Charges) == 3 { canvas.Scale(0.5) } for index, charge := range chargeGroup.Charges { if len(chargeGroup.Charges) == 2 { if charge.Identifier == "pale" { if index == 0 { canvas.Translate(20, 0) } else if index == 1 { canvas.Translate(300, 0) } } else { if index == 0 { canvas.Translate(20, 200) } else if index == 1 { canvas.Translate(300, 200) } } } else if len(chargeGroup.Charges) == 3 { if charge.Identifier == "pale" { if index == 0 { canvas.Translate(-20, 0) } else if index == 1 { canvas.Translate(160, 0) } else if index == 2 { canvas.Translate(340, 00) } } else { if index == 0 { canvas.Translate(20, 80) } else if index == 1 { canvas.Translate(300, 80) } else if index == 2 { canvas.Translate(160, 400) } } } if chargeGroup.Tincture.Name == "sable" { lineColor = "#FFFFFF" } switch charge.Identifier { case "pale": if len(chargeGroup.Charges) > 1 { canvas.Rect(int(width/3), 0, int(width/3), height*2, "fill:"+chargeGroup.Tincture.Hexcode) } else { canvas.Rect(int(width/3), 0, int(width/3), height, "fill:"+chargeGroup.Tincture.Hexcode) } case "fess": canvas.Rect(0, int(height/3), width, int(height/3), "fill:"+chargeGroup.Tincture.Hexcode) case "cross": crossHalfWidth := 40 canvas.Polygon( []int{centerX - crossHalfWidth, centerX + crossHalfWidth, centerX + crossHalfWidth, width, width, centerX + crossHalfWidth, centerX + crossHalfWidth, centerX - crossHalfWidth, centerX - crossHalfWidth, 0, 0, centerX - crossHalfWidth}, []int{0, 0, centerY - crossHalfWidth, centerY - crossHalfWidth, centerY + crossHalfWidth, centerY + crossHalfWidth, height, height, centerY + crossHalfWidth, centerY + crossHalfWidth, centerY - crossHalfWidth, centerY - crossHalfWidth}, "fill:"+chargeGroup.Tincture.Hexcode) case "bend": canvas.TranslateRotate(-100, 135, -45) canvas.Rect(int(width/3), 0, int(width/3), height, "fill:"+chargeGroup.Tincture.Hexcode) canvas.Gend() case "saltire": saltireHalfWidth := 30 canvas.Polygon( []int{0, saltireHalfWidth, centerX, width - saltireHalfWidth, width, width, centerX + saltireHalfWidth, width, width, width - saltireHalfWidth, centerX, saltireHalfWidth, 0, 0, centerX - saltireHalfWidth, 0}, []int{0, 0, centerY - saltireHalfWidth, 0, 0, saltireHalfWidth, centerY, height - saltireHalfWidth, height, height, centerY + saltireHalfWidth, height, height, height - saltireHalfWidth, centerY, saltireHalfWidth}, "fill:"+chargeGroup.Tincture.Hexcode) case "chevron": chevronHalfWidth := 40 canvas.Polygon( []int{0, centerX, width, width, centerX, 0}, []int{height - int(height/4), height - int(height/3) - (3 * chevronHalfWidth), height - int(height/4), height - int(height/4) + (2 * chevronHalfWidth), height - int(height/3) - chevronHalfWidth, height - int(height/4) + (2 * chevronHalfWidth)}, "fill:"+chargeGroup.Tincture.Hexcode) case "chief": canvas.Rect(0, 0, width, int(height/3), "fill:"+chargeGroup.Tincture.Hexcode) case "pile": canvas.Polygon( []int{0, width, int(width / 2)}, []int{0, 0, int(height / 2)}, "fill:"+chargeGroup.Tincture.Hexcode) case "pall": pallHalfWidth := 40 canvas.Polygon( []int{0, pallHalfWidth, centerX, width - pallHalfWidth, width, width, centerX + pallHalfWidth - int(pallHalfWidth/3), centerX + pallHalfWidth - int(pallHalfWidth/3), centerX - pallHalfWidth + int(pallHalfWidth/3), centerX - pallHalfWidth + int(pallHalfWidth/3), 0}, []int{0, 0, centerY - pallHalfWidth, 0, 0, pallHalfWidth, centerY + pallHalfWidth - int(pallHalfWidth/3), height, height, centerY + pallHalfWidth - int(pallHalfWidth/3), pallHalfWidth}, "fill:"+chargeGroup.Tincture.Hexcode) case "bordure": renderBordureToSvg(canvas, chargeGroup.Tincture.Hexcode) case "lozenge": lozengeHalfWidth := 80 canvas.Polygon( []int{centerX, centerX + lozengeHalfWidth, centerX, centerX - lozengeHalfWidth}, []int{centerY - lozengeHalfWidth - int(lozengeHalfWidth/2), centerY, centerY + lozengeHalfWidth + int(lozengeHalfWidth/2), centerY}, "fill:"+chargeGroup.Tincture.Hexcode) case "roundel": roundelRadius := 100 canvas.Circle( int(width/2), int(height/2), roundelRadius, "fill:"+chargeGroup.Tincture.Hexcode) case "eagle-displayed": renderEagleDisplayedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "dragon-passant": renderDragonPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "gryphon-passant": renderGryphonPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "fox-passant": renderFoxPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "antelope-passant": renderAntelopePassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "antelope-rampant": renderAntelopeRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "bat-volant": renderBatVolantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "battleaxe": renderBattleaxeToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "bear-head-couped": renderBearHeadCoupedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "bear-rampant": renderBearRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "bear-statant": renderBearStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "bee-volant": renderBeeVolantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "bell": renderBellToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "boar-head-erased": renderBoarHeadErasedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "boar-passant": renderBoarPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "boar-rampant": renderBoarRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "bugle-horn": renderBugleHornToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "bull-passant": renderBullPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "bull-rampant": renderBullRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "castle": renderCastleToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "cock": renderCockToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "cockatrice": renderCockatriceToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "crown": renderCrownToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "dolphin-hauriant": renderDolphinHauriantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "double-headed-eagle-displayed": renderDoubleHeadedEagleDisplayedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "dragon-rampant": renderDragonRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "eagles-head-erased": renderEaglesHeadErasedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "fox-sejant": renderFoxSejantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "gryphon-segreant": renderGryphonSegreantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "hare-salient": renderHareSalientToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "hare": renderHareToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "heron": renderHeronToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "horse-passant": renderHorsePassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "horse-rampant": renderHorseRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "leopard-passant": renderLeopardPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "lion-passant": renderLionPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "lion-rampant": renderLionRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "lions-head-erased": renderLionsHeadErasedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "owl": renderOwlToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "pegasus-passant": renderPegasusPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "pegasus-rampant": renderPegasusRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "ram-rampant": renderRamRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "ram-statant": renderRamStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "rose": renderRoseToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "sea-horse": renderSeaHorseToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "serpent-nowed": renderSerpentNowedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "squirrel": renderSquirrelToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "stag-lodged": renderStagLodgedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "stag-statant": renderStagStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "sun-in-splendor": renderSunInSplendorToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "tiger-passant": renderTigerPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "tiger-rampant": renderTigerRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "tower": renderTowerToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "two-axes-in-saltire": renderTwoAxesInSaltireToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "two-bones-in-saltire": renderTwoBonesInSaltireToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "unicorn-rampant": renderUnicornRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "unicorn-statant": renderUnicornStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "wolf-passant": renderWolfPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "wolf-rampant": renderWolfRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) case "wyvern": renderWyvernToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor) } if len(chargeGroup.Charges) > 1 { canvas.Gend() } } if len(chargeGroup.Charges) > 1 { canvas.Gend() } } canvas.Path("m10.273 21.598v151.22c0 96.872 89.031 194.34 146.44 240.09 57.414-45.758 146.44-143.22 146.44-240.09v-151.22h-292.89z", "stroke:#000000;stroke-width:4;fill:none") canvas.Gend() // canvas.Text(centerX, height+25, blazon, "font-size:"+blazonSize+"px;text-anchor:middle") canvas.End() return buffer.String() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RenderToSVGFile(device Device, fileName string, width int, height int) {\n\tvar writer io.WriteCloser\n\twriter, err := os.Create(fileName)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tcontents := device.RenderToSVG(width, height)\n\n\tio.WriteString(writer, contents)\n\n\tdefer writer.Close()\n}", "func (s *SVG) Render(w io.Writer) error {\n\ttop := `<?xml version=\"1.0\"?>`\n\tif _, err := w.Write([]byte(top)); err != nil {\n\t\treturn err\n\t}\n\n\treturn s.render(w)\n}", "func RenderSVG(\n\ts sdf.SDF2, // sdf2 to render\n\tmeshCells int, // number of cells on the longest axis. e.g 200\n\tpath string, // path to filename\n\tlineStyle string, // SVG line style\n) error {\n\t// work out the sampling resolution to use\n\tbbSize := s.BoundingBox().Size()\n\tresolution := bbSize.MaxComponent() / float64(meshCells)\n\tcells := bbSize.DivScalar(resolution).ToV2i()\n\n\tfmt.Printf(\"rendering %s (%dx%d, resolution %.2f)\\n\", path, cells[0], cells[1], resolution)\n\n\t// write the line segments to an SVG file\n\tvar wg sync.WaitGroup\n\toutput, err := WriteSVG(&wg, path, lineStyle)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// run marching squares to generate the line segments\n\tmarchingSquaresQuadtree(s, resolution, output)\n\n\t// stop the SVG writer reading on the channel\n\tclose(output)\n\t// wait for the file write to complete\n\twg.Wait()\n\treturn nil\n}", "func SVG(width, height int) (Renderer, error) {\n\tbuffer := bytes.NewBuffer([]byte{})\n\tcanvas := newCanvas(buffer)\n\tcanvas.Start(width, height)\n\treturn &vectorRenderer{\n\t\tb: buffer,\n\t\tc: canvas,\n\t\ts: &Style{},\n\t\tp: []string{},\n\t}, nil\n}", "func RenderSVG(inputFile, outputFile, imageFile, shape string) {\n\tcolor.Yellow(\"Reading image file...\")\n\n\timg, err := util.DecodeImage(imageFile)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcolor.Yellow(\"Reading input file...\")\n\tpoints, err := decodePoints(inputFile)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcolor.Yellow(\"Generating SVG...\")\n\tfilename := outputFile\n\n\tif !strings.HasSuffix(filename, \".svg\") {\n\t\tfilename += \".svg\"\n\t}\n\n\tswitch shape {\n\tcase \"triangles\":\n\t\terr = triangles.WriteSVG(filename, points, img)\n\t\tbreak\n\tcase \"polygons\":\n\t\terr = polygons.WriteSVG(filename, points, img)\n\t\tbreak\n\tdefault:\n\t\terr = errors.New(\"invalid shape type\")\n\t}\n\n\tif err != nil {\n\t\tcolor.Red(\"error generating SVG\")\n\t\treturn\n\t}\n\n\tcolor.Green(\"Successfully generated SVG at %s.svg!\", filename)\n}", "func (b *BlockDAG) RenderSvg() ([]byte, error) {\n\t// Render the dag in graphviz dot format\n\tdot, err := b.RenderDot()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Render the graphviz DOT file as an SVG image\n\tsvg, err := soterutil.DotToSvg(dot)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn svg, nil\n}", "func (me TxsdPresentationAttributesGraphicsShapeRendering) String() string {\n\treturn xsdt.String(me).String()\n}", "func (p *Path) ToSVG() string {\n\tsb := strings.Builder{}\n\tx, y := 0.0, 0.0\n\tif len(p.d) > 0 && p.d[0] != moveToCmd {\n\t\tfmt.Fprintf(&sb, \"M0 0\")\n\t}\n\tfor i := 0; i < len(p.d); {\n\t\tcmd := p.d[i]\n\t\tswitch cmd {\n\t\tcase moveToCmd:\n\t\t\tx, y = p.d[i+1], p.d[i+2]\n\t\t\tfmt.Fprintf(&sb, \"M%v %v\", num(x), num(y))\n\t\tcase lineToCmd:\n\t\t\txStart, yStart := x, y\n\t\t\tx, y = p.d[i+1], p.d[i+2]\n\t\t\tif equal(x, xStart) && equal(y, yStart) {\n\t\t\t\t// nothing\n\t\t\t} else if equal(x, xStart) {\n\t\t\t\tfmt.Fprintf(&sb, \"V%v\", num(y))\n\t\t\t} else if equal(y, yStart) {\n\t\t\t\tfmt.Fprintf(&sb, \"H%v\", num(x))\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(&sb, \"L%v %v\", num(x), num(y))\n\t\t\t}\n\t\tcase quadToCmd:\n\t\t\tx, y = p.d[i+3], p.d[i+4]\n\t\t\tfmt.Fprintf(&sb, \"Q%v %v %v %v\", num(p.d[i+1]), num(p.d[i+2]), num(x), num(y))\n\t\tcase cubeToCmd:\n\t\t\tx, y = p.d[i+5], p.d[i+6]\n\t\t\tfmt.Fprintf(&sb, \"C%v %v %v %v %v %v\", num(p.d[i+1]), num(p.d[i+2]), num(p.d[i+3]), num(p.d[i+4]), num(x), num(y))\n\t\tcase arcToCmd:\n\t\t\trx, ry := p.d[i+1], p.d[i+2]\n\t\t\trot := p.d[i+3] * 180.0 / math.Pi\n\t\t\tlargeArc, sweep := fromArcFlags(p.d[i+4])\n\t\t\tx, y = p.d[i+5], p.d[i+6]\n\t\t\tsLargeArc := \"0\"\n\t\t\tif largeArc {\n\t\t\t\tsLargeArc = \"1\"\n\t\t\t}\n\t\t\tsSweep := \"0\"\n\t\t\tif sweep {\n\t\t\t\tsSweep = \"1\"\n\t\t\t}\n\t\t\tif 90.0 <= rot {\n\t\t\t\trx, ry = ry, rx\n\t\t\t\trot -= 90.0\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"A%v %v %v %s %s %v %v\", num(rx), num(ry), num(rot), sLargeArc, sSweep, num(p.d[i+5]), num(p.d[i+6]))\n\t\tcase closeCmd:\n\t\t\tx, y = p.d[i+1], p.d[i+2]\n\t\t\tfmt.Fprintf(&sb, \"z\")\n\t\t}\n\t\ti += cmdLen(cmd)\n\t}\n\treturn sb.String()\n}", "func (c *container) SVG(x, y, w, h float64) *SVG {\n\tr := &SVG{Width: w, Height: h, X: x, Y: y, container: container{name: \"svg\"}}\n\n\tc.contents = append(c.contents, r)\n\n\treturn r\n}", "func (s *SVG) Str() string {\n\treturn s.header() + s.svgString + s.footer()\n}", "func (me TxsdPresentationAttributesGraphicsShapeRendering) ToXsdtString() xsdt.String {\n\treturn xsdt.String(me)\n}", "func (me TxsdPresentationAttributesGraphicsTextRendering) String() string {\n\treturn xsdt.String(me).String()\n}", "func (s *SVG) RenderFragment(w io.Writer) error {\n\treturn s.render(w)\n}", "func SVGWriter(w io.Writer, t time.Time) {\n\tio.WriteString(w, svgStart)\n\tio.WriteString(w, bezel)\n\twriteHours(w, t)\n\twriteMins(w, t)\n\twriteSecs(w, t)\n\tio.WriteString(w, svgEnd)\n}", "func (m *BoundaryMap) AsSVG(attr string) (string, error) {\n\tvar (\n\t\tsvg = new(SVGStringBuilder)\n\t\tsvgpath = m.newSVGPath()\n\t\terr error\n\t)\n\n\tsvg.WriteTag(\"defs\", \"\", func(svg *SVGStringBuilder) error {\n\t\tsvg.WriteString(m.CSSTag())\n\t\treturn nil\n\t})\n\n\terr = svg.WriteTag(\n\t\t\"g\", Attr(map[string]string{\"id\": \"diagram\"}, \"\"),\n\t\tfunc(svg *SVGStringBuilder) error {\n\t\t\tif err := m.buildLayers(svgpath, svg); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err = m.writeCountry(svgpath, svg); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err = m.writeCutLine(svgpath, svg); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn SVGTag(\n\t\t\"svg\", Attr(map[string]string{\n\t\t\t\"viewBox\": svgpath.ViewBox(),\n\t\t\t\"xMidyMid\": \"meet\",\n\t\t\t\"version\": \"1.2\",\n\t\t\t\"baseProfile\": \"tiny\",\n\t\t\t\"xmlns\": \"http://www.w3.org/2000/svg\",\n\t\t}, attr),\n\t\tsvg.String(),\n\t), nil\n\n}", "func WriteSVG(wg *sync.WaitGroup, path, lineStyle string) (chan<- *Line, error) {\n\n\ts := NewSVG(path, lineStyle)\n\n\t// External code writes line segments to this channel.\n\t// This goroutine reads the channel and writes line segments to the file.\n\tc := make(chan *Line)\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor v := range c {\n\t\t\ts.Line(v[0], v[1])\n\t\t}\n\t\tif err := s.Save(); err != nil {\n\t\t\tfmt.Printf(\"%s\\n\", err)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn c, nil\n}", "func (me TxsdPresentationAttributesGraphicsTextRendering) ToXsdtString() xsdt.String {\n\treturn xsdt.String(me)\n}", "func svgEncode(w io.Writer, ii *IdentIcon, pixels int) error {\n\n\t// Padding is relative to the number of blocks.\n\tpadding := pixels / (ii.Size * MinSize)\n\tdrawableArea := pixels - (padding * 2)\n\tblockSize := drawableArea / ii.Size\n\n\t// Add the residue (pixels that won't be filled) to the padding.\n\t// Try to center the figure regardless when the drawable area is not\n\t// divisible by the block pixels.\n\tpadding += (drawableArea % ii.Size) / 2\n\n\tfillColor := colorToRGBAString(ii.FillColor)\n\tbackgroundColor := colorToRGBAString(ii.BackgroundColor)\n\n\tb, err := template.New(\"svg\").Parse(svgTemplate)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt := svgTmpl{\n\t\tPixels: pixels,\n\t\tBackgroundColor: backgroundColor,\n\t\tFillColor: fillColor,\n\t\tRects: make([]svgRect, ii.Canvas.FilledPoints),\n\t}\n\n\ti := 0\n\tfor y, mapX := range ii.Canvas.PointsMap {\n\t\tfor x := range mapX {\n\t\t\tt.Rects[i] = svgRect{\n\t\t\t\tblockSize*x + padding,\n\t\t\t\tblockSize*y + padding,\n\t\t\t\tblockSize,\n\t\t\t\tblockSize,\n\t\t\t\tfillColor,\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn b.Execute(w, t)\n}", "func (t *ArtNodeMinerRPC) GetSvgStringRPC(args *shared.Args, reply *shared.GetSvgStringReply) error {\n\t_, ok := allShapes[args.ShapeHash]\n\tif !ok {\n\t\t// if does not exists return empty reply\n\t\treturn nil\n\t}\n\t// grab the SVG string for this shape\n\tthisShape := allShapes[args.ShapeHash]\n\treply.Data = thisShape.AppShapeOp\n\treply.Found = true\n\treturn nil\n}", "func (me TxsdPresentationAttributesGraphicsDisplay) String() string { return xsdt.String(me).String() }", "func render(ctx Config, com Component, gfx *dot.Graph) *dot.Node {\n\n\timg := iconPath(ctx, com)\n\n\tif fc := strings.TrimSpace(com.FontColor); len(fc) == 0 {\n\t\tcom.FontColor = \"#000000ff\"\n\t}\n\n\tif imp := strings.TrimSpace(com.Impl); len(imp) == 0 {\n\t\tcom.Impl = \"&nbsp;\"\n\t}\n\n\tvar sb strings.Builder\n\tsb.WriteString(`<table border=\"0\" cellborder=\"0\">`)\n\tif ctx.showImpl {\n\t\tfmt.Fprintf(&sb, `<tr><td><font point-size=\"8\">%s</font></td></tr>`, com.Impl)\n\t}\n\n\tsb.WriteString(\"<tr>\")\n\tfmt.Fprintf(&sb, `<td fixedsize=\"true\" width=\"50\" height=\"50\"><img src=\"%s\" /></td>`, img)\n\tsb.WriteString(\"</tr>\")\n\n\tlabel := \"&nbsp;\"\n\tif s := strings.TrimSpace(com.Label); len(s) > 0 {\n\t\tlabel = s\n\t}\n\tfmt.Fprintf(&sb, `<tr><td><font point-size=\"7\">%s</font></td></tr>`, label)\n\tsb.WriteString(\"</table>\")\n\n\treturn node.New(gfx, com.ID,\n\t\tnode.Label(sb.String(), true),\n\t\tnode.FillColor(\"transparent\"),\n\t\tnode.Shape(\"plain\"),\n\t)\n}", "func (s *SVG) Save() error {\n\tf, err := os.Create(s.filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twidth := s.max.X - s.min.X\n\theight := s.max.Y - s.min.Y\n\tcanvas := svg.New(f)\n\tcanvas.Start(width, height)\n\tfor i, p0 := range s.p0s {\n\t\tp1 := s.p1s[i]\n\t\tcanvas.Line(p0.X-s.min.X, s.max.Y-p0.Y, p1.X-s.min.X, s.max.Y-p1.Y, s.lineStyle)\n\t}\n\tcanvas.End()\n\treturn f.Close()\n}", "func Marshal(i interface{}, size float64) ([]byte, error) {\n\tif size <= 0 {\n\t\treturn nil, fmt.Errorf(\"kandinsky: invalid marshal size\")\n\t}\n\n\tvar b bytes.Buffer\n\n\ts := gosvg.NewSVG(size, size)\n\tg := s.Group()\n\te := &encodeState{Group: g, size: size}\n\n\terr := e.marshal(reflect.ValueOf(i))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.Render(&b)\n\n\treturn b.Bytes(), nil\n}", "func handler(w http.ResponseWriter, r *http.Request) {\n\tconfig := make(map[string]string)\n\n\tw.Header().Set(\"Content-Type\", \"image/svg+xml\")\n\n\tif err := r.ParseForm(); err != nil {\n\t\tlog.Print(err)\n\t}\n\n\tfor k, v := range r.Form {\n\t\tconfig[k] = v[0]\n\t}\n\n\tsvg := svgplot.SVGPlotBuilder(config)\n\tsvg.Write(w)\n}", "func BuildAndWriteSVG(src io.Reader, dst io.Writer,\n\tsvgColorLightScheme, svgColorDarkScheme string) {\n\tsvg := buildSVG(src)\n\twriteBytes(dst, svg.String(svgColorLightScheme, svgColorDarkScheme))\n}", "func (me TSVGColorType) String() string { return xsdt.String(me).String() }", "func (me TSVGColorType) ToXsdtString() xsdt.String { return xsdt.String(me) }", "func (m *modules) Render() vdom.Element {\n\tengineUI := dspUI.MakeEngine(&m.dspEngine, 1400-m.state.vDividerPos-4, m.state.hDividerPos, &m.state.dspUIEngineState)\n\tfilePickerUI := dspUI.MakeFilePicker(&m.dspEngine, m.state.vDividerPos, m.state.hDividerPos, &m.state.dspUIFilePickerState)\n\tvSplit := vdomcomp.MakeLayoutVSplit(1200, m.state.hDividerPos, m.state.vDividerPos, 4, &m.state.vDividerMoving,\n\t\tfilePickerUI,\n\t\tengineUI,\n\t\tfunc(pos int) {\n\t\t\tif pos > 100 {\n\t\t\t\tm.state.vDividerPos = pos\n\t\t\t}\n\t\t},\n\t)\n\n\thSplit := vdomcomp.MakeLayoutHSplit(1400, 800, m.state.hDividerPos, 4, &m.state.hDividerMoving,\n\t\tvSplit, onscreenkeyboardUI.MakeKeyboard(&m.keyboard),\n\t\tfunc(pos int) {\n\t\t\tif pos > 100 {\n\t\t\t\tm.state.hDividerPos = pos\n\t\t\t}\n\t\t},\n\t)\n\n\telem := vdom.MakeElement(\"svg\",\n\t\t\"id\", \"root\",\n\t\t\"xmlns\", \"http://www.w3.org/2000/svg\",\n\t\t\"style\", \"width:100%;height:100%;position:fixed;top:0;left:0;bottom:0;right:0;\",\n\t\thSplit,\n\t)\n\n\treturn elem\n}", "func (me TxsdPresentationAttributesGraphicsDisplay) ToXsdtString() xsdt.String {\n\treturn xsdt.String(me)\n}", "func SaveSVG(path, lineStyle string, mesh []*Line) error {\n\ts := NewSVG(path, lineStyle)\n\tfor _, v := range mesh {\n\t\ts.Line(v[0], v[1])\n\t}\n\tif err := s.Save(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (svgp *SvgPath) Draw(r *rasterx.Dasher, opacity float64) {\n\tsvgp.DrawTransformed(r, opacity, rasterx.Identity)\n}", "func SVG(w io.Writer, key string, colors []color.RGBA, size int) {\n\tcanvas := svg.New(w)\n\tcanvas.Start(size, size)\n\n\tsquares := 6\n\tquadrantSize := size / squares\n\tmiddle := math.Ceil(float64(squares) / float64(2))\n\tcolorMap := make(map[int]color.RGBA)\n\tfor yQ := 0; yQ < squares; yQ++ {\n\t\ty := yQ * quadrantSize\n\t\tcolorMap = make(map[int]color.RGBA)\n\n\t\tfor xQ := 0; xQ < squares; xQ++ {\n\t\t\tx := xQ * quadrantSize\n\t\t\tif _, ok := colorMap[xQ]; !ok {\n\t\t\t\tif float64(xQ) < middle {\n\t\t\t\t\tcolorMap[xQ] = draw.PickColor(key, colors, xQ+3*yQ)\n\t\t\t\t} else if xQ < squares {\n\t\t\t\t\tcolorMap[xQ] = colorMap[squares-xQ-1]\n\t\t\t\t} else {\n\t\t\t\t\tcolorMap[xQ] = colorMap[0]\n\t\t\t\t}\n\t\t\t}\n\t\t\tcanvas.Rect(x, y, quadrantSize, quadrantSize, draw.FillFromRGBA(colorMap[xQ]))\n\t\t}\n\t}\n\tcanvas.End()\n}", "func (s *SVG) header() string {\n\treturn fmt.Sprintf(\"<svg xmlns='http://www.w3.org/2000/svg' width='%v' height='%v'>\", s.width, s.height)\n}", "func (d *FakeDocument) MakeSVGElement(class string) Element {\n\te := MakeFakeElement(class, SVGNamespaceURI)\n\tswitch class {\n\tcase \"text\":\n\t\te.Methods[\"getComputedTextLength\"] = func(...interface{}) interface{} {\n\t\t\treturn rand.Float64() * 200\n\t\t}\n\t\te.Methods[\"getBBox\"] = func(...interface{}) interface{} {\n\t\t\to := MakeFakeObject(nil)\n\t\t\to.Set(\"x\", 150.0)\n\t\t\to.Set(\"y\", 160.0)\n\t\t\to.Set(\"height\", 40.0)\n\t\t\to.Set(\"width\", 130.0)\n\t\t\treturn o\n\t\t}\n\t}\n\treturn e\n}", "func GenerateSvgBoxPath(data Coordinates, size float64, plotCoords chan<- Coordinate) {\n\n\tdefer close(plotCoords)\n\n\tminPoint, maxPoint := data.Extents()\n\n\timageSize := maxPoint.Minus(minPoint)\n\tscale := size / math.Max(imageSize.X, imageSize.Y)\n\n\tfmt.Println(\"SVG Min:\", minPoint, \"Max:\", maxPoint, \"Scale:\", scale)\n\n\tif imageSize.X*scale > (Settings.DrawingSurfaceMaxX_MM-Settings.DrawingSurfaceMinX_MM) || imageSize.Y*scale > (Settings.DrawingSurfaceMaxY_MM-Settings.DrawingSurfaceMinY_MM) {\n\t\tpanic(fmt.Sprint(\n\t\t\t\"SVG coordinates extend past drawable surface, as defined in setup. Scaled svg size was: \",\n\t\t\timageSize,\n\t\t\t\" And settings bounds are, X: \", Settings.DrawingSurfaceMaxX_MM, \" - \", Settings.DrawingSurfaceMinX_MM,\n\t\t\t\" Y: \", Settings.DrawingSurfaceMaxY_MM, \" - \", Settings.DrawingSurfaceMinY_MM))\n\t}\n\n\tplotCoords <- Coordinate{X: 0, Y: 0, PenUp: true}\n\tplotCoords <- Coordinate{X: 0, Y: 10, PenUp: true}\n\tplotCoords <- Coordinate{X: 0, Y: maxPoint.Y - minPoint.Y, PenUp: true}.Scaled(scale)\n\tplotCoords <- Coordinate{X: maxPoint.X - minPoint.X, Y: maxPoint.Y - minPoint.Y, PenUp: true}.Scaled(scale)\n\tplotCoords <- Coordinate{X: maxPoint.X - minPoint.X, Y: 0, PenUp: true}.Scaled(scale)\n\tplotCoords <- Coordinate{X: 0, Y: 0, PenUp: true}.Scaled(scale)\n\n\tfor index := 0; index < len(data); index++ {\n\t\tcurTarget := data[index]\n\t\tplotCoords <- curTarget.Minus(minPoint).Scaled(scale)\n\t}\n\n\tplotCoords <- Coordinate{X: 0, Y: 0, PenUp: true}\n}", "func NewSVG(width, height float64) *SVG {\n\treturn &SVG{\n\t\tWidth: width,\n\t\tHeight: height,\n\t\tcontainer: container{name: \"svg\"},\n\t}\n}", "func main() {\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"image/svg+xml\")\n\t\tsvg(w)\n\t})\n\tlog.Fatal(http.ListenAndServe(\":8000\", nil))\n}", "func GenerateSvgCenterPath(data Coordinates, size float64, plotCoords chan<- Coordinate) {\n\n\tdefer close(plotCoords)\n\n\tminPoint, maxPoint := data.Extents()\n\n\timageSize := maxPoint.Minus(minPoint)\n\tscale := size / imageSize.X\n\n\tfmt.Println(\"SVG Min:\", minPoint, \"Max:\", maxPoint, \"Scale:\", scale)\n\n\tif imageSize.X*scale > (Settings.DrawingSurfaceMaxX_MM-Settings.DrawingSurfaceMinX_MM) || imageSize.Y*scale > (Settings.DrawingSurfaceMaxY_MM-Settings.DrawingSurfaceMinY_MM) {\n\t\tpanic(fmt.Sprint(\n\t\t\t\"SVG coordinates extend past drawable surface, as defined in setup. Scaled svg size was: \",\n\t\t\timageSize,\n\t\t\t\" And settings bounds are, X: \", Settings.DrawingSurfaceMaxX_MM, \" - \", Settings.DrawingSurfaceMinX_MM,\n\t\t\t\" Y: \", Settings.DrawingSurfaceMaxY_MM, \" - \", Settings.DrawingSurfaceMinY_MM))\n\t}\n\n\t// want to center the image horizontally, so need actual world space location of gondola at start\n\tpolarSystem := PolarSystemFromSettings()\n\tpreviousPolarPos := PolarCoordinate{LeftDist: Settings.StartingLeftDist_MM, RightDist: Settings.StartingRightDist_MM}\n\tstartingLocation := previousPolarPos.ToCoord(polarSystem)\n\tsurfaceWidth := Settings.DrawingSurfaceMaxX_MM - Settings.DrawingSurfaceMinX_MM\n\n\t// actual starting location - desired = offset\n\timageDistanceFromLeftMargin := (surfaceWidth - (imageSize.X * scale)) / 2\n\tcenteringOffset := Coordinate{X: startingLocation.X - imageDistanceFromLeftMargin}\n\tfmt.Println(\"Pen starting position:\", startingLocation, \"Drawing surface width:\", surfaceWidth, \"Centering Offset:\", centeringOffset)\n\n\tplotCoords <- Coordinate{X: 0, Y: 0, PenUp: true}\n\n\tfor index := 0; index < len(data); index++ {\n\t\tcurTarget := data[index]\n\t\tplotCoords <- curTarget.Minus(minPoint).Scaled(scale).Minus(centeringOffset)\n\t}\n\n\tplotCoords <- Coordinate{X: 0, Y: 0, PenUp: true}\n}", "func thermometer(sw, sh int) (img draw.Image, err error) {\n\n\t// dynamic SVG\n\n\twt, ht := 120, 120\n\n\timg = image.NewRGBA(image.Rect(0, 0, sw, sh))\n\tvar iconMem = new(bytes.Buffer)\n\n\tvar canvas = svg.New(iconMem)\n\tcanvas.Start(wt, ht)\n\n\tbfs := svg.Filterspec{In: `SourceGraphic`}\n\tcanvas.Def()\n\tcanvas.Filter(`blur_f`, `filterUnits=\"objectBoundingBox\" x=\"-50%\" y=\"-50%\" width=\"200%\" height=\"200%\"`)\n\tcanvas.FeGaussianBlur(bfs, 6, 6)\n\tcanvas.Fend()\n\tcanvas.Filter(`blur_z`, `filterUnits=\"objectBoundingBox\" x=\"-50%\" y=\"-50%\" width=\"200%\" height=\"200%\"`)\n\tcanvas.FeGaussianBlur(bfs, 2, 2)\n\tcanvas.Fend()\n\tcanvas.Filter(`blur_k`, `filterUnits=\"objectBoundingBox\"`)\n\tcanvas.FeGaussianBlur(bfs, 1, 1)\n\tcanvas.Fend()\n\tcanvas.DefEnd()\n\n\tdegF := `m12.04517,17c0,-1.49271 0.53737,-2.77643 1.58227,-3.82133s2.32862,-1.58227 3.82133,-1.58227c1.46285,0 2.74658,0.53737 3.79148,1.58227c1.04489,1.07475 1.58227,2.32862 1.58227,3.82133c0,1.49271 -0.53737,2.77643 -1.58227,3.85118c-1.04489,1.07475 -2.32862,1.61212 -3.79148,1.61212s-2.74658,-0.53737 -3.82133,-1.61212c-1.04489,-1.07475 -1.58227,-2.35848 -1.58227,-3.85118zm2.62716,0c0,0.77621 0.26869,1.433 0.80606,2.00023c0.56723,0.56723 1.22402,0.83592 2.00023,0.83592s1.433,-0.26869 2.00023,-0.83592s0.83592,-1.22402 0.83592,-2.00023c0,-0.77621 -0.26869,-1.433 -0.83592,-1.97037c-0.56723,-0.53737 -1.22402,-0.83592 -2.00023,-0.83592c-0.77621,0 -1.433,0.26869 -2.00023,0.80606c-0.53737,0.53737 -0.80606,1.19417 -0.80606,2.00023zm13.16568,20.5695c0,0.41796 0.14927,0.80606 0.44781,1.1046s0.68665,0.44781 1.1046,0.44781c0.41796,0 0.80606,-0.14927 1.1046,-0.44781c0.29854,-0.29854 0.44781,-0.68665 0.44781,-1.1046l0,-11.31472l8.53828,0c0.41796,0 0.80606,-0.14927 1.1046,-0.47767s0.44781,-0.68665 0.44781,-1.13446c0,-0.44781 -0.14927,-0.80606 -0.44781,-1.13446c-0.29854,-0.29854 -0.68665,-0.44781 -1.13446,-0.44781l-8.53828,0l0,-8.15018l11.40428,0c0.41796,0 0.77621,-0.14927 1.07475,-0.44781s0.41796,-0.68665 0.41796,-1.13446s-0.14927,-0.80606 -0.41796,-1.13446s-0.62694,-0.44781 -1.07475,-0.44781l-14.24042,0c-0.20898,0 -0.29854,0.11942 -0.29854,0.3284l0,25.49544l0.05971,0z`\n\tdegC := `m75.50005,17c0,-1.49186 0.53707,-2.77486 1.58137,-3.81916c1.07414,-1.07414 2.3273,-1.58137 3.81916,-1.58137c1.46202,0 2.74502,0.53707 3.78933,1.58137c1.0443,1.07414 1.58137,2.3273 1.58137,3.81916c0,1.49186 -0.53707,2.77486 -1.58137,3.81916c-1.0443,1.07414 -2.3273,1.58137 -3.78933,1.58137c-1.49186,0 -2.77486,-0.53707 -3.81916,-1.58137s-1.58137,-2.3273 -1.58137,-3.81916zm2.62567,0c0,0.77577 0.26853,1.43219 0.8056,1.99909c0.56691,0.56691 1.22333,0.83544 1.99909,0.83544c0.77577,0 1.43219,-0.26853 1.99909,-0.83544s0.83544,-1.22333 0.83544,-1.99909c0,-0.77577 -0.26853,-1.43219 -0.83544,-1.99909s-1.22333,-0.83544 -1.99909,-0.83544c-0.77577,0 -1.43219,0.26853 -1.99909,0.83544c-0.53707,0.53707 -0.8056,1.22333 -0.8056,1.99909zm11.60667,13.18805c0,2.29747 0.62658,4.3264 1.90958,6.11663c0.65642,0.92495 1.58137,1.67088 2.77486,2.23779c1.16365,0.53707 2.50633,0.83544 3.99819,0.83544c4.35623,0 7.10126,-1.67088 8.20523,-4.98281c0.11935,-0.41772 0.05967,-0.83544 -0.17902,-1.22333c-0.2387,-0.38788 -0.56691,-0.59674 -0.98463,-0.68626c-0.41772,-0.11935 -0.83544,-0.05967 -1.19349,0.20886c-0.35805,0.2387 -0.59674,0.56691 -0.68626,1.01447c0,0.02984 0,0.05967 -0.02984,0.14919l-0.05967,0.20886c-0.32821,0.56691 -0.77577,1.01447 -1.34267,1.34267c-0.92495,0.56691 -2.14828,0.83544 -3.66998,0.83544c-0.92495,0 -1.7604,-0.14919 -2.47649,-0.4774c-1.19349,-0.50723 -2.02893,-1.40235 -2.53616,-2.65551c-0.32821,-0.8056 -0.50723,-1.79023 -0.50723,-2.89421l0,-9.60758c0,-0.44756 0.02984,-0.89512 0.08951,-1.34267c0.11935,-1.13381 0.56691,-2.17812 1.34267,-3.10307c0.86528,-1.0443 2.23779,-1.55153 4.11753,-1.55153c1.55153,0 2.77486,0.26853 3.66998,0.8056c0.59674,0.35805 1.0443,0.8056 1.34267,1.34267c0.02984,0.05967 0.02984,0.14919 0.05967,0.2387c0.02984,0.08951 0.02984,0.14919 0.02984,0.17902c0.11935,0.41772 0.35805,0.71609 0.68626,0.89512c0.35805,0.20886 0.74593,0.2387 1.19349,0.14919c0.41772,-0.08951 0.74593,-0.32821 0.98463,-0.68626c0.2387,-0.35805 0.29837,-0.74593 0.17902,-1.19349l0,-0.02984l-0.2387,-0.68626c-0.14919,-0.32821 -0.41772,-0.77577 -0.83544,-1.283c-0.38788,-0.53707 -0.86528,-0.95479 -1.34267,-1.31284c-0.62658,-0.44756 -1.43219,-0.8056 -2.44665,-1.13381c-1.01447,-0.29837 -2.11844,-0.44756 -3.31193,-0.44756c-1.5217,0 -2.83453,0.26853 -4.02802,0.8056c-1.16365,0.53707 -2.0886,1.25316 -2.71519,2.17812c-1.283,1.7604 -1.93942,3.81916 -1.93942,6.1763l0,9.57774l-0.05967,0z`\n\n\t// rear plane shadow -\n\tcanvas.Group(`style=\"fill:black;filter:url(#blur_f);\"`)\n\tcanvas.Path(\"m39.90978,78.17153c0,-3.4036 0.80084,-6.56694 2.36249,-9.53009s3.76398,-5.40572 6.60699,-7.3678l0,-39.72202c0,-3.20339 1.08115,-5.92626 3.28348,-8.12859s4.9252,-3.36355 8.12859,-3.36355c3.24344,0 5.96631,1.12118 8.16864,3.32351c2.20233,2.24237 3.32351,4.9252 3.32351,8.12859l0,39.72202c2.84301,1.96208 5.00529,4.4447 6.56694,7.3678s2.32246,6.12647 2.32246,9.53009c0,3.68389 -0.92097,7.12753 -2.72287,10.25083s-4.28452,5.60593 -7.40783,7.40783s-6.5269,2.72287 -10.25083,2.72287c-3.68389,0 -7.08749,-0.92097 -10.21079,-2.72287s-5.60593,-4.28452 -7.44787,-7.40783s-2.72287,-6.5269 -2.72287,-10.21079l-0.00004,0zm7.04746,0c0,3.72394 1.3214,6.92733 3.92416,9.57013c2.60276,2.6428 5.7661,3.96418 9.45,3.96418c3.72394,0 6.92733,-1.3214 9.61015,-4.00423s4.04427,-5.84617 4.04427,-9.49004c0,-2.48262 -0.64068,-4.80509 -1.92203,-6.92733c-1.28136,-2.12224 -3.04321,-3.76398 -5.28559,-4.9252l-1.12118,-0.56059c-0.40043,-0.16016 -0.60063,-0.56059 -0.60063,-1.16122l0,-43.08557c0,-1.28136 -0.44047,-2.36249 -1.36145,-3.24344c-0.92097,-0.84088 -2.04215,-1.28136 -3.4036,-1.28136c-1.28136,0 -2.40253,0.44047 -3.32351,1.28136c-0.92097,0.84088 -1.36145,1.92203 -1.36145,3.24344l0,43.00548c0,0.60063 -0.2002,1.00106 -0.56059,1.16122l-1.08115,0.56059c-2.20233,1.16122 -3.92416,2.80296 -5.16547,4.9252c-1.24131,2.12224 -1.84195,4.40466 -1.84195,6.96737l0.00002,0.00001zm3.1233,0c0,2.84301 0.96102,5.28559 2.9231,7.28771s4.28452,3.00317 7.04746,3.00317s5.12543,-1.00106 7.16758,-3.00317c2.04215,-2.00212 3.04321,-4.4447 3.04321,-7.24767c0,-2.52267 -0.88093,-4.76504 -2.60276,-6.68708c-1.72183,-1.92203 -3.84407,-3.08326 -6.32669,-3.4036l-2.44258,-0.08011c-2.44258,0.36038 -4.52479,1.48156 -6.2466,3.4036c-1.72183,1.96208 -2.56271,4.16441 -2.56271,6.72712l0,0.00002l-0.00001,0.00001z\")\n\tcanvas.Path(degF)\n\tcanvas.Path(degC)\n\tcanvas.Gend()\n\n\t// glassback -\n\tcanvas.Path(\"m39.90978,78.17153c0,-3.4036 0.80084,-6.56694 2.36249,-9.53009s3.76398,-5.40572 6.60699,-7.3678l0,-39.72202c0,-3.20339 1.08115,-5.92626 3.28348,-8.12859s4.9252,-3.36355 8.12859,-3.36355c3.24344,0 5.96631,1.12118 8.16864,3.32351c2.20233,2.24237 3.32351,4.9252 3.32351,8.12859l0,39.72202c2.84301,1.96208 5.00529,4.4447 6.56694,7.3678s2.32246,6.12647 2.32246,9.53009c0,3.68389 -0.92097,7.12753 -2.72287,10.25083s-4.28452,5.60593 -7.40783,7.40783s-6.5269,2.72287 -10.25083,2.72287c-3.68389,0 -7.08749,-0.92097 -10.21079,-2.72287s-5.60593,-4.28452 -7.44787,-7.40783s-2.72287,-6.5269 -2.72287,-10.21079l-0.00004,0z\",\n\t\t`style=\"fill:green;fill-opacity:0.45\"`)\n\n\t// glass -\n\tcanvas.Path(\"m39.90978,78.17153c0,-3.4036 0.80084,-6.56694 2.36249,-9.53009s3.76398,-5.40572 6.60699,-7.3678l0,-39.72202c0,-3.20339 1.08115,-5.92626 3.28348,-8.12859s4.9252,-3.36355 8.12859,-3.36355c3.24344,0 5.96631,1.12118 8.16864,3.32351c2.20233,2.24237 3.32351,4.9252 3.32351,8.12859l0,39.72202c2.84301,1.96208 5.00529,4.4447 6.56694,7.3678s2.32246,6.12647 2.32246,9.53009c0,3.68389 -0.92097,7.12753 -2.72287,10.25083s-4.28452,5.60593 -7.40783,7.40783s-6.5269,2.72287 -10.25083,2.72287c-3.68389,0 -7.08749,-0.92097 -10.21079,-2.72287s-5.60593,-4.28452 -7.44787,-7.40783s-2.72287,-6.5269 -2.72287,-10.21079l-0.00004,0zm7.04746,0c0,3.72394 1.3214,6.92733 3.92416,9.57013c2.60276,2.6428 5.7661,3.96418 9.45,3.96418c3.72394,0 6.92733,-1.3214 9.61015,-4.00423s4.04427,-5.84617 4.04427,-9.49004c0,-2.48262 -0.64068,-4.80509 -1.92203,-6.92733c-1.28136,-2.12224 -3.04321,-3.76398 -5.28559,-4.9252l-1.12118,-0.56059c-0.40043,-0.16016 -0.60063,-0.56059 -0.60063,-1.16122l0,-43.08557c0,-1.28136 -0.44047,-2.36249 -1.36145,-3.24344c-0.92097,-0.84088 -2.04215,-1.28136 -3.4036,-1.28136c-1.28136,0 -2.40253,0.44047 -3.32351,1.28136c-0.92097,0.84088 -1.36145,1.92203 -1.36145,3.24344l0,43.00548c0,0.60063 -0.2002,1.00106 -0.56059,1.16122l-1.08115,0.56059c-2.20233,1.16122 -3.92416,2.80296 -5.16547,4.9252c-1.24131,2.12224 -1.84195,4.40466 -1.84195,6.96737z\",\n\t\t`style=\"fill:lightskyblue;fill-opacity:0.3;stroke-width:0.4;stroke-opacity:0.2;stroke:midnightblue;\"`)\n\t// capillary -\n\tcanvas.Path(\"m46.95724,78.17153c0,3.72394 1.3214,6.92733 3.92416,9.57013c2.60276,2.6428 5.7661,3.96418 9.45,3.96418c3.72394,0 6.92733,-1.3214 9.61015,-4.00423s4.04427,-5.84617 4.04427,-9.49004c0,-2.48262 -0.64068,-4.80509 -1.92203,-6.92733c-1.28136,-2.12224 -3.04321,-3.76398 -5.28559,-4.9252l-1.12118,-0.56059c-0.40043,-0.16016 -0.60063,-0.56059 -0.60063,-1.16122l0,-43.08557c0,-1.28136 -0.44047,-2.36249 -1.36145,-3.24344c-0.92097,-0.84088 -2.04215,-1.28136 -3.4036,-1.28136c-1.28136,0 -2.40253,0.44047 -3.32351,1.28136c-0.92097,0.84088 -1.36145,1.92203 -1.36145,3.24344l0,43.00548c0,0.60063 -0.2002,1.00106 -0.56059,1.16122l-1.08115,0.56059c-2.20233,1.16122 -3.92416,2.80296 -5.16547,4.9252c-1.24131,2.12224 -1.84195,4.40466 -1.84195,6.96737z\",\n\t\t`style=\"fill:linen;filter:url(#blur_shadow);fill-opacity:0.4;\"`)\n\n\tcanvas.Group()\n\tcanvas.Path(degF, `style=\"fill:#0099ff;stroke-width:1.5;stroke-opacity:0.4;stroke:#0099ff;stroke-alignment:outside;\"`)\n\tcanvas.Path(degC, `style=\"fill:#66ff99;stroke-width:1.5;stroke-opacity:0.4;stroke:#66ff99;stroke-alignment:outside;\"`)\n\tcanvas.Gend()\n\n\talcoCol := `red`\n\talcoWidth := `3.1`\n\tif w.Current.tempF <= 32 {\n\t\talcoCol = `navy`\n\t}\n\t// bulb -\n\tcanvas.Circle(60, 78, 10, fmt.Sprintf(\"style=\\\"fill:%s\\\"\", alcoCol))\n\n\t// temperature -\n\t// ( 31 = -20) .. (11 = 120)\n\tcanvas.Group()\n\tcanvas.Line(60, 78, 60, 62, fmt.Sprintf(\"style=\\\"stroke-width:%s;stroke:%s;stroke-linecap:round\\\"\", alcoWidth, alcoCol))\n\tif w.Current.tempF > -20 {\n\t\ty2 := int(40.0 * (float64(20+w.Current.tempF) / 140.00))\n\t\tcanvas.Line(60, 78, 60, 62-y2, fmt.Sprintf(\"style=\\\"stroke-width:%s;stroke:%s;stroke-linecap:round\\\"\", alcoWidth, alcoCol))\n\t}\n\tcanvas.Gend()\n\n\t// pop -\n\tcanvas.Circle(60, 78, 8,\n\t\t`style=\"fill:orangered;filter:url(#blur_k);filter-opacity:0.1;fill-opacity:0.2;\"`)\n\tcanvas.Circle(60, 78, 7,\n\t\t`style=\"fill:white;filter:url(#blur_k);filter-opacity:0.1;fill-opacity:0.2;\"`)\n\tcanvas.Circle(56, 74, 4,\n\t\t`style=\"fill:white;filter:url(#blur_k);filter-opacity:0.1;fill-opacity:0.1;\"`)\n\n\t// ticks\n\tfor tick := 22; tick < 64; tick += 3 {\n\t\tdash := tick % 2\n\t\tcanvas.Line(50, tick, 56+(10*dash), tick, `style=\"stroke-width:1;stroke:greenyellow;stroke-linecap:round;stroke-opacity:0.3;\"`)\n\t}\n\n\t// glass 2 -\n\tcanvas.Path(\"m39.90978,78.17153c0,-3.4036 0.80084,-6.56694 2.36249,-9.53009s3.76398,-5.40572 6.60699,-7.3678l0,-39.72202c0,-3.20339 1.08115,-5.92626 3.28348,-8.12859s4.9252,-3.36355 8.12859,-3.36355c3.24344,0 5.96631,1.12118 8.16864,3.32351c2.20233,2.24237 3.32351,4.9252 3.32351,8.12859l0,39.72202c2.84301,1.96208 5.00529,4.4447 6.56694,7.3678s2.32246,6.12647 2.32246,9.53009c0,3.68389 -0.92097,7.12753 -2.72287,10.25083s-4.28452,5.60593 -7.40783,7.40783s-6.5269,2.72287 -10.25083,2.72287c-3.68389,0 -7.08749,-0.92097 -10.21079,-2.72287s-5.60593,-4.28452 -7.44787,-7.40783s-2.72287,-6.5269 -2.72287,-10.21079l-0.00004,0z\",\n\t\t`style=\"fill:lightskyblue;fill-opacity:0.2;stroke-width:1;stroke-opacity:0.4;stroke:midnightblue;\"`)\n\n\tcanvas.End()\n\n\ticonI, err := oksvg.ReadIconStream(iconMem)\n\tif err != nil {\n\t\treturn img, err\n\t}\n\n\tgv := rasterx.NewScannerGV(wt, ht, img, img.Bounds())\n\tr := rasterx.NewDasher(wt, ht, gv)\n\ticonI.SetTarget(0, 0, float64(sw), float64(sh))\n\ticonI.Draw(r, 1.0)\n\n\treturn img, nil\n\n}", "func (c *Canvas) printClose() {\n\tc.Println(\"</svg>\")\n}", "func Render(expr expreduceapi.Ex) (chart.Chart, error) {\n\tgraph := chart.Chart{\n\t\tWidth: 360,\n\t\tHeight: 220,\n\t\tXAxis: chart.XAxis{\n\t\t\tStyle: chart.Style{Show: true},\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tStyle: chart.Style{Show: true},\n\t\t},\n\t}\n\n\tgraphics, ok := atoms.HeadAssertion(expr, \"System`Graphics\")\n\tif !ok {\n\t\treturn graph, fmt.Errorf(\"trying to render a non-Graphics[] expression: %v\", expr)\n\t}\n\n\tif graphics.Len() < 1 {\n\t\treturn graph, errors.New(\"the Graphics[] expression must have at least one argument\")\n\t}\n\n\tstyle := chart.Style{\n\t\tShow: true,\n\t\tStrokeColor: drawing.ColorBlack,\n\t}\n\terr := renderPrimitive(&graph, graphics.GetPart(1), &style)\n\tif err != nil {\n\t\treturn graph, errors.New(\"failed to render primitive\")\n\t}\n\n\treturn graph, nil\n}", "func drawCanvas(allStrings []string) (err error) {\n\t//Create and write to HTML file\n\tfile, err := os.OpenFile(BA_FILE, os.O_CREATE|os.O_WRONLY, 0664)\n\tfile.Write([]byte(\"<svg height=\\\"\" + strconv.Itoa(int(Settings.CanvasXMax)) + \"\\\" width=\\\"\" + strconv.Itoa(int(Settings.CanvasYMax)) + \"\\\">\\n\"))\n\tfor _, str := range allStrings {\n\t\tfile.Write([]byte(str))\n\t}\n\tfile.Write([]byte(\"</svg>\"))\n\tfile.Close()\n\tfmt.Println(\"Canvas can be seen at \", BA_FILE)\n\treturn nil\n}", "func Svg(raw []byte, limit uint32) bool {\n\treturn bytes.Contains(raw, []byte(\"<svg\"))\n}", "func NewSVG() *SVG {\n\treturn &SVG{\n\t\twidth: 100,\n\t\theight: 100,\n\t\tContent: make([]SVGWriter, 0),\n\t}\n}", "func (me TxsdPresentationAttributesGraphicsVisibility) String() string {\n\treturn xsdt.String(me).String()\n}", "func (c *chart) renderChart() (string, error) {\n\tchartData := metricsToPoints(c.metrics)\n\n\tchart := getChart(chartData, c.metricName, c.color)\n\n\ts, err := chart.Render()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"rendering chart failed\")\n\t}\n\n\treturn s, nil\n}", "func (me TxsdPresentationAttributesGraphicsVisibility) ToXsdtString() xsdt.String {\n\treturn xsdt.String(me)\n}", "func PlotToPng(dev scope.Device, width, height int, traceParams map[scope.ChanID]scope.TraceParams, cols map[scope.ChanID]color.RGBA, outputFile string) error {\n\tplot, err := CreatePlot(dev, width, height, traceParams, cols)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(outputFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tpng.Encode(f, plot)\n\treturn nil\n}", "func (bp *Blueprint) Render() (string, error) {\n\tif bp.XMLData == nil {\n\t\treturn \"\", errors.ErrBlueprintXMLEmpty\n\t}\n\n\tvar buffer bytes.Buffer\n\tif _, err := bp.XMLData.WriteTo(&buffer); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn buffer.String(), nil\n}", "func (vr *vectorRenderer) Stroke() {\n\tvr.drawPath(vr.s.SVGStroke())\n}", "func (me TxsdPresentationAttributesColorColorRendering) ToXsdtString() xsdt.String {\n\treturn xsdt.String(me)\n}", "func (me TxsdPresentationAttributesColorColorRendering) String() string {\n\treturn xsdt.String(me).String()\n}", "func (d Device) String() string { return cu.Device(d).String() }", "func (s *SVG) Path(str string, args map[string]interface{}) {\n\tpathStr := fmt.Sprintf(\"<path d='%s' %s />\", str, s.WriteArgs(args))\n\ts.svgString += pathStr\n}", "func RenderAsPNG(expr expreduceapi.Ex) (string, error) {\n\tgraph, err := Render(expr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbuffer := bytes.NewBuffer([]byte{})\n\terr = graph.Render(chart.PNG, buffer)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn buffer.String(), nil\n}", "func New(sp *svg.SVG, width, height int, font string, fontsize int, background color.RGBA) *SvgGraphics {\n\tif font == \"\" {\n\t\tfont = \"Helvetica\"\n\t}\n\tif fontsize == 0 {\n\t\tfontsize = 12\n\t}\n\ts := SvgGraphics{svg: sp, w: width, h: height, font: font, fs: fontsize, bg: background}\n\treturn &s\n}", "func (me TStrokeWidthValueType) ToXsdtString() xsdt.String { return xsdt.String(me) }", "func (sheet *Sheet) Execute(wr io.Writer, tplContext GridTemplateContext) error {\n\treturn sheet.svgTemplate.Execute(wr, tplContext)\n}", "func renderDagHTML(h *rpctest.Harness) (string, error) {\n\tresult, err := h.Node.RenderDag()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to render dag: %s\", err)\n\t}\n\n\tsvg, err := soterutil.DotToSvg([]byte(result.Dot))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to convert dot to svg: %s\", err)\n\t}\n\n\tsvgEmbed, err := soterutil.StripSvgXmlDecl(svg)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to strip svg xml declaration tag: %s\", err)\n\t}\n\n\thtml, err := soterutil.RenderSvgHTML(svgEmbed, \"dag\")\n\n\tfh, err := ioutil.TempFile(\"\", \"dag_*.html\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = save(html, fh)\n\tif err != nil {\n\t\treturn fh.Name(), err\n\t}\n\n\treturn fh.Name(), err\n}", "func (tc *TermColor) RenderTo(w io.Writer, str string) {\n\tw.Write(types.UnsafeBytes(tc.Render(str)))\n}", "func (s *ImageSpec) ToXml() string {\n\tc_str := C.ImageSpec_to_xml(s.ptr)\n\tret := C.GoString(c_str)\n\tC.free(unsafe.Pointer(c_str))\n\truntime.KeepAlive(s)\n\treturn ret\n}", "func ToGraphics(jsStruct interface{}) *Graphics {\n if object, ok := jsStruct.(*js.Object); ok {\n\t\treturn &Graphics{Object: object}\n\t}\n\treturn nil\n}", "func svgPath(p int) string {\n\tconst radius = (svgSize / 2) - (svgStroke / 2) // Radius of the circle\n\tconst cx = svgSize / 2 // Center of the circle X\n\tconst cy = svgSize / 2 // Center of the circle Y\n\tconst fx = svgSize / 2 // Finish point X\n\tconst fy = svgStroke / 2 // Finish point Y\n\tcomplete := (((float64(p)) / 100) * (2 * math.Pi)) - (math.Pi / 2)\n\ty := cy + (radius * math.Sin(complete))\n\tx := cx + (radius * math.Cos(complete))\n\tf := 0\n\tif p > 50 {\n\t\tf = 1\n\t}\n\tif y == fy {\n\t\tx = x - 0.1\n\t}\n\treturn fmt.Sprintf(\n\t\t\"M %.2f %.2f A %d %d, 0, %d, 0, %d %d\",\n\t\tx,\n\t\ty,\n\t\tradius,\n\t\tradius,\n\t\tf,\n\t\tfx,\n\t\tfy)\n}", "func (me TStrokeWidthValueType) String() string { return xsdt.String(me).String() }", "func (me *TxsdPresentationAttributesGraphicsShapeRendering) Set(s string) { (*xsdt.String)(me).Set(s) }", "func (rf RendererFunc) Render(w io.Writer, v interface{}) error { return rf(w, v) }", "func (r *ChartRenderer) Render(chartPath, releaseName, namespace string, values map[string]interface{}) (*chartrenderer.RenderedChart, error) {\n\treturn r.renderFunc()\n}", "func (s GetDeviceOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func RenderString(s string) {\n\tq, err := qrcode.New(s, qrcode.Medium)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(q.ToSmallString(false))\n}", "func Generate(name string) string {\n\tname = strings.ToLower(name)\n\tvar (\n\t\tr, g, b int\n\t)\n\tif len(name) > 0 {\n\t\tr = (int(name[0]) - 97) * 155 / 26\n\t}\n\tif len(name) > 1 {\n\t\tg = (int(name[1]) - 97) * 155 / 26\n\t}\n\tif len(name) > 2 {\n\t\tb = (int(name[2]) - 97) * 155 / 26\n\t}\n\ttext := initials(name)\n\tfontSize := int(500 / math.Pow(float64(len(text)), 0.7))\n\n\tdata := fmt.Sprintf(`<?xml version=\"1.0\"?>\n<svg width=\"1000\" height=\"1000\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n\t<circle cx=\"500\" cy=\"500\" r=\"500\" style=\"fill:rgb(%d,%d,%d)\" />\n\t<circle cx=\"500\" cy=\"500\" r=\"480\" style=\"fill:rgb(%d,%d,%d)\" />\n\t<text x=\"500\" y=\"500\" style=\"text-anchor:middle;font-size:%dpx;alignment-baseline:middle;font-family:Arial,Helvetica;fill:rgb(%d,%d,%d)\">%s</text>\n</svg>\n`, r, g, b, r+100, g+100, b+100, fontSize, r, g, b, text)\n\treturn data\n}", "func (r *Renderer) Save(fileName string) {\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\tpng.Encode(file, flipper.FlipV(r.img))\n}", "func (vr *vectorRenderer) Text(body string, x, y int) {\n\tstyle := vr.s.SVGText()\n\tvr.c.Text(x, y, body, &style)\n}", "func (g *Graph) Render() *ebiten.Image {\n\tif g.simulation.IsPaused() {\n\t\treturn g.graphImage\n\t}\n\n\tvar img *ebiten.Image\n\tif g.shouldRefresh() {\n\t\timg = g.renderAll()\n\t} else if g.shouldAddBar() {\n\t\timg = g.renderNewBar()\n\t} else {\n\t\treturn g.graphImage\n\t}\n\n\tg.graphImage = ebiten.NewImage(realGraphWidth, realGraphHeight)\n\tg.graphImage.DrawImage(img, nil)\n\n\treturn img\n}", "func (me TPreserveAspectRatioSpecType) ToXsdtString() xsdt.String { return xsdt.String(me) }", "func (r *renderer) renderToString(tree *ast.Tree) (string, error) {\n\tsubRenderer := &renderer{\n\t\ttemplate: r.template,\n\t\tstack: r.stack,\n\t\tdepth: 0,\n\t\tw: strings.Builder{},\n\t\tindent: \"\",\n\t\tindentNext: false,\n\t}\n\terr := subRenderer.walk(tree.Name, tree)\n\ts := subRenderer.String()\n\n\t// the subRenderer may have pushed and popped enough contexts onto the stack\n\t// to cause the slice to allocate to a new larger underlaying array. If this\n\t// has happened, we want to keep the pointer to that larger array to minimize\n\t// allocations.\n\tr.stack = subRenderer.stack\n\n\treturn s, err\n}", "func (c *Calendar) SVG(w io.Writer, t *Theme) error {\n\tif t == nil {\n\t\tt = Default\n\t}\n\tsize := t.Length + t.Space // the size of one cell\n\n\t// Print headers\n\tw.Write([]byte(`<?xml version=\"1.0\" encoding=\"UTF-8\"?><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 ` +\n\t\tstrconv.Itoa(size*53-t.Space) +\n\t\t` ` +\n\t\tstrconv.Itoa(\n\t\t\tlen(c.Years)*(t.Title.Height+t.Title.Bottom+size*7)+\n\t\t\t\tt.HoverLines*t.Hover.Height) +\n\t\t`\" >`))\n\tdefer w.Write([]byte(`</svg>`))\n\n\tenc := xml.NewEncoder(w)\n\theight := 0\n\tfor _, y := range c.years() {\n\t\t// Print the title\n\t\tyc := c.Years[y]\n\t\theight += t.Title.Height\n\t\terr := enc.Encode(&text{\n\t\t\tY: height,\n\t\t\tStyle: t.Title.Style,\n\t\t\tText: y,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\theight += t.Title.Bottom\n\n\t\t// Print cells\n\t\tmax := yc.max()\n\t\toffset := int(time.Date(y, time.January, 1, 0, 0, 0, 0, c.location).Weekday())\n\t\toffset = (offset+6)%7 - 1\n\t\tfor i, d := range yc {\n\t\t\tif d.Date.IsZero() {\n\t\t\t\td.Date = time.Date(y, time.January, i+1, 0, 0, 0, 0, c.location)\n\t\t\t}\n\t\t\tfill := t.Colors[0]\n\t\t\tif d.Value != 0 {\n\t\t\t\tfill = t.Colors[d.Value*(len(t.Colors)-2)/max+1]\n\t\t\t}\n\t\t\terr = enc.Encode(&rect{\n\t\t\t\tX: (d.Date.YearDay() + offset) / 7 * size,\n\t\t\t\tY: height + int(d.Date.Weekday()+6)%7*size,\n\t\t\t\tWidth: t.Length,\n\t\t\t\tHeight: t.Length,\n\t\t\t\tRx: t.Round,\n\t\t\t\tRy: t.Round,\n\t\t\t\tFill: fill,\n\t\t\t\tData: d.Data,\n\t\t\t\tDate: d.Date,\n\t\t\t\tValue: d.Value,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\theight += size * 7\n\t}\n\n\tif t.HoverLines != 0 {\n\t\theight += t.Hover.Height\n\t\tenc.Encode(&text{\n\t\t\tY: height,\n\t\t\tStyle: t.Hover.Style,\n\t\t})\n\t\tenc.Encode(&script{Content: hover})\n\t}\n\n\treturn nil\n}", "func TestSparkling_Render(t *testing.T) {\n\tvar buf bytes.Buffer\n\tsp := New(&buf)\n\tsp.AddSeries([]float64{0, 30, 55, 80, 33, 150}, \"Awesome\")\n\tsp.Render()\n\n\twant := \"Awesome ▁▂▃▄▂█\\n\"\n\n\ts := buf.String()\n\tgot := s[len(s)-len(want):]\n\n\tif got != want {\n\t\tt.Errorf(\"sparkling.Render() = %s, want: %s\", got, want)\n\t}\n}", "func (m *Marker) SetSVGMarker(f SVGMarker) {\n\tm.drawSVG = f\n}", "func (s *SVG) Group(elements [2]string, args map[string]interface{}) {\n\ts.svgString += fmt.Sprintf(\"<g %s>\", s.WriteArgs(args))\n\ts.svgString += elements[0] + elements[1]\n\ts.svgString += \"</g>\"\n}", "func (script Script) RenderHTML() {\n\tsymbols := []string{}\n\ttemplateHTML := `\n<!DOCTYPE html>\n<html>\n <head>\n <title>Writing System</title>\n <style type=\"text/css\">\n body, html { font-size: 28px; }\n div.container { display: flex; flex-wrap: wrap; width: 1600px; margin: 1rem auto; }\n div.cell { width: 100px; height: 100px; margin: 1rem; text-align: center; font-weight: 700; }\n div.cell > img { display: block; }\n </style>\n </head>\n <body>\n\t\t<div class=\"container\">\n\t\t\t{{range $index, $element := .}}\n <div class=\"cell\">\n <img src=\"{{ $element }}.png\">\n <p>{{ $element }}</p>\n </div>\n {{end}}\n </div>\n </body>\n</html>\n`\n\n\twriter, err := os.Create(\"./output/index.html\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tt, err := template.New(\"htmlIndex\").Parse(templateHTML)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfor _, g := range script.Glyphs {\n\t\tsymbols = append(symbols, g.Representation)\n\t}\n\n\terr = t.Execute(writer, symbols)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tdefer writer.Close()\n}", "func ScatterPlot(x, y []float64) string {\n svg := SVG(400, 400)\n \n for i := range x {\n child := Circle(x[i], y[i], 2)\n svg.AddChild(child)\n }\n \n return svg.String()\n}", "func GridSVG(w io.Writer, color1, color2 color.RGBA, size int) {\n\tcanvas := svg.New(w)\n\tcanvas.Start(size, size)\n\tsquares := 6\n\tquadrantSize := size / squares\n\tcolorMap := make(map[int]color.RGBA)\n\tfor yQ := 0; yQ < squares; yQ++ {\n\t\ty := yQ * quadrantSize\n\t\tcolorMap = make(map[int]color.RGBA)\n\n\t\tfor xQ := 0; xQ < squares; xQ++ {\n\t\t\tx := xQ * quadrantSize\n\t\t\tif _, ok := colorMap[xQ]; !ok {\n\t\t\t\tif (xQ+yQ)%2 == 0 {\n\t\t\t\t\tcolorMap[xQ] = color1\n\t\t\t\t} else {\n\t\t\t\t\tcolorMap[xQ] = color2\n\t\t\t\t}\n\t\t\t}\n\t\t\tcanvas.Rect(x, y, quadrantSize, quadrantSize, draw.FillFromRGBA(colorMap[xQ]))\n\t\t}\n\t}\n\tcanvas.End()\n}", "func (me TxsdColorProfileTypeRenderingIntent) ToXsdtString() xsdt.String { return xsdt.String(me) }", "func (d *Device) Render() error {\n\tbuf := new(bytes.Buffer)\n\n\tfor _, chain := range d.LEDs {\n\t\tfor _, col := range chain {\n\t\t\tbuf.Write([]byte{col.R, col.G, col.B})\n\t\t}\n\t}\n\n\t_, err := Conn.WriteToUDP(buf.Bytes(), d.Addr)\n\treturn err\n}", "func GenerateSvgTopPath(data Coordinates, size float64, plotCoords chan<- Coordinate) {\n\n\tdefer close(plotCoords)\n\n\tminPoint, maxPoint := data.Extents()\n\n\timageSize := maxPoint.Minus(minPoint)\n\tscale := size / math.Max(imageSize.X, imageSize.Y)\n\n\tfmt.Println(\"SVG Min:\", minPoint, \"Max:\", maxPoint, \"Scale:\", scale)\n\n\tif imageSize.X*scale > (Settings.DrawingSurfaceMaxX_MM-Settings.DrawingSurfaceMinX_MM) || imageSize.Y*scale > (Settings.DrawingSurfaceMaxY_MM-Settings.DrawingSurfaceMinY_MM) {\n\t\tpanic(fmt.Sprint(\n\t\t\t\"SVG coordinates extend past drawable surface, as defined in setup. Scaled svg size was: \",\n\t\t\timageSize,\n\t\t\t\" And settings bounds are, X: \", Settings.DrawingSurfaceMaxX_MM, \" - \", Settings.DrawingSurfaceMinX_MM,\n\t\t\t\" Y: \", Settings.DrawingSurfaceMaxY_MM, \" - \", Settings.DrawingSurfaceMinY_MM))\n\t}\n\n\t// find top most svg point, so that the path can start there\t244\t\t// find minPoint of coordinates, which will be upper left, where the pen will start\n\tinitialPositionIndex := 0\n\tinitialPosition := Coordinate{X: 100000.0, Y: 100000.0}\n\tfor index, point := range data {\n\t\tif point.Y < initialPosition.Y || (point.Y == initialPosition.Y && point.X < initialPosition.X) {\n\t\t\tinitialPositionIndex = index\n\t\t\tinitialPosition = point\n\t\t}\n\t}\n\tinitialPosition.PenUp = false\n\n\tfmt.Println(\"SVG initial top position:\", initialPosition)\n\n\tfor index := 0; index < len(data); index++ {\n\t\tcurTarget := data[(index+initialPositionIndex)%len(data)]\n\t\tplotCoords <- curTarget.Minus(initialPosition).Scaled(scale)\n\t}\n\n\tplotCoords <- Coordinate{X: 0, Y: 0, PenUp: true}\n}", "func (me TxsdPresentationAttributesFontSpecificationFontStretch) ToXsdtString() xsdt.String {\n\treturn xsdt.String(me)\n}", "func (g *Game) Render() string {\n\tascii := \"\"\n\n\tm := g.generateScreen()\n\tfor _, row := range m.cells {\n\t\tascii += strings.Join(row, \"\") + \"\\n\"\n\t}\n\n\treturn ascii\n}", "func (c *Chart) Render(\n\tchartRenderer chartrenderer.Interface,\n\tnamespace string,\n\timageVector imagevector.ImageVector,\n\truntimeVersion, targetVersion string,\n\tadditionalValues map[string]interface{},\n) (string, []byte, error) {\n\n\t// Get values with injected images\n\tvalues, err := c.injectImages(imageVector, runtimeVersion, targetVersion)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\t// Apply chart\n\trc, err := chartRenderer.Render(c.Path, c.Name, namespace, utils.MergeMaps(values, additionalValues))\n\tif err != nil {\n\t\treturn \"\", nil, errors.Wrapf(err, \"could not render chart '%s' in namespace '%s'\", c.Name, namespace)\n\t}\n\treturn rc.ChartName, rc.Manifest(), nil\n}", "func (svgp *SvgPath) DrawTransformed(r *rasterx.Dasher, opacity float64, t rasterx.Matrix2D) {\n\tm := svgp.mAdder.M\n\tsvgp.mAdder.M = t.Mult(m)\n\tdefer func() { svgp.mAdder.M = m }() // Restore untransformed matrix\n\tif svgp.fillerColor != nil {\n\t\tr.Clear()\n\t\trf := &r.Filler\n\t\trf.SetWinding(svgp.UseNonZeroWinding)\n\t\tsvgp.mAdder.Adder = rf // This allows transformations to be applied\n\t\tsvgp.Path.AddTo(&svgp.mAdder)\n\n\t\tswitch fillerColor := svgp.fillerColor.(type) {\n\t\tcase color.Color:\n\t\t\trf.SetColor(rasterx.ApplyOpacity(fillerColor, svgp.FillOpacity*opacity))\n\t\tcase rasterx.Gradient:\n\t\t\tif fillerColor.Units == rasterx.ObjectBoundingBox {\n\t\t\t\tfRect := rf.Scanner.GetPathExtent()\n\t\t\t\tmnx, mny := float64(fRect.Min.X)/64, float64(fRect.Min.Y)/64\n\t\t\t\tmxx, mxy := float64(fRect.Max.X)/64, float64(fRect.Max.Y)/64\n\t\t\t\tfillerColor.Bounds.X, fillerColor.Bounds.Y = mnx, mny\n\t\t\t\tfillerColor.Bounds.W, fillerColor.Bounds.H = mxx-mnx, mxy-mny\n\t\t\t}\n\t\t\trf.SetColor(fillerColor.GetColorFunction(svgp.FillOpacity * opacity))\n\t\t}\n\t\trf.Draw()\n\t\t// default is true\n\t\trf.SetWinding(true)\n\t}\n\tif svgp.linerColor != nil {\n\t\tr.Clear()\n\t\tsvgp.mAdder.Adder = r\n\t\tlineGap := svgp.LineGap\n\t\tif lineGap == nil {\n\t\t\tlineGap = DefaultStyle.LineGap\n\t\t}\n\t\tlineCap := svgp.LineCap\n\t\tif lineCap == nil {\n\t\t\tlineCap = DefaultStyle.LineCap\n\t\t}\n\t\tleadLineCap := lineCap\n\t\tif svgp.LeadLineCap != nil {\n\t\t\tleadLineCap = svgp.LeadLineCap\n\t\t}\n\t\tr.SetStroke(fixed.Int26_6(svgp.LineWidth*64),\n\t\t\tfixed.Int26_6(svgp.MiterLimit*64), leadLineCap, lineCap,\n\t\t\tlineGap, svgp.LineJoin, svgp.Dash, svgp.DashOffset)\n\t\tsvgp.Path.AddTo(&svgp.mAdder)\n\t\tswitch linerColor := svgp.linerColor.(type) {\n\t\tcase color.Color:\n\t\t\tr.SetColor(rasterx.ApplyOpacity(linerColor, svgp.LineOpacity*opacity))\n\t\tcase rasterx.Gradient:\n\t\t\tif linerColor.Units == rasterx.ObjectBoundingBox {\n\t\t\t\tfRect := r.Scanner.GetPathExtent()\n\t\t\t\tmnx, mny := float64(fRect.Min.X)/64, float64(fRect.Min.Y)/64\n\t\t\t\tmxx, mxy := float64(fRect.Max.X)/64, float64(fRect.Max.Y)/64\n\t\t\t\tlinerColor.Bounds.X, linerColor.Bounds.Y = mnx, mny\n\t\t\t\tlinerColor.Bounds.W, linerColor.Bounds.H = mxx-mnx, mxy-mny\n\t\t\t}\n\t\t\tr.SetColor(linerColor.GetColorFunction(svgp.LineOpacity * opacity))\n\t\t}\n\t\tr.Draw()\n\t}\n}", "func (d *Diagram) String() string { return toString(d) }", "func (me TxsdPresentationAttributesFontSpecificationFontStretch) String() string {\n\treturn xsdt.String(me).String()\n}", "func (me TPreserveAspectRatioSpecType) String() string { return xsdt.String(me).String() }", "func SVGTriangle(m Marker, b *bytes.Buffer) {\n\tw := int(m.size / 2)\n\th := w * 2\n\tc := int(float64(h) * 0.33)\n\n\tb.WriteString(fmt.Sprintf(\"<g id=\\\"%s\\\"><path d=\\\"M%d %d l%d 0 l-%d -%d l-%d %d Z\\\" fill=\\\"%s\\\" opacity=\\\"0.5\\\">\",\n\t\tm.id, int(m.x), int(m.y)+c, w, w, h, w, h, m.svgColour))\n\tb.WriteString(`<desc>` + m.label + `.</desc>`)\n\tb.WriteString(`<set attributeName=\"opacity\" from=\"0.5\" to=\"1\" begin=\"mouseover\" end=\"mouseout\" dur=\"2s\"/></path>`)\n\tb.WriteString(fmt.Sprintf(\"<path d=\\\"M%d %d l%d 0 l-%d -%d l-%d %d Z\\\" stroke=\\\"%s\\\" stroke-width=\\\"1\\\" fill=\\\"none\\\" opacity=\\\"1\\\" /></g>\",\n\t\tint(m.x), int(m.y)+c, w, w, h, w, h, m.svgColour))\n}", "func RenderSVGSlow(\n\ts sdf.SDF2, // sdf2 to render\n\tmeshCells int, // number of cells on the longest axis. e.g 200\n\tpath string, // path to filename\n\tlineStyle string, // SVG line style\n) error {\n\t// work out the region we will sample\n\tbb0 := s.BoundingBox()\n\tbb0Size := bb0.Size()\n\tmeshInc := bb0Size.MaxComponent() / float64(meshCells)\n\tbb1Size := bb0Size.DivScalar(meshInc)\n\tbb1Size = bb1Size.Ceil().AddScalar(1)\n\tcells := bb1Size.ToV2i()\n\tbb1Size = bb1Size.MulScalar(meshInc)\n\tbb := sdf.NewBox2(bb0.Center(), bb1Size)\n\n\tfmt.Printf(\"rendering %s (%dx%d)\\n\", path, cells[0], cells[1])\n\n\t// run marching squares to generate the line segments\n\tm := marchingSquares(s, bb, meshInc)\n\treturn SaveSVG(path, lineStyle, m)\n}", "func NewSVGSurface(filename string, widthInPoints, heightInPoints float64, version SVGVersion) *Surface {\n\tcs := C.CString(filename)\n\tdefer C.free(unsafe.Pointer(cs))\n\ts := C.cairo_svg_surface_create(cs, C.double(widthInPoints), C.double(heightInPoints))\n\tC.cairo_svg_surface_restrict_to_version(s, C.cairo_svg_version_t(version))\n\tsurface := &Surface{surface: s, context: C.cairo_create(s)}\n\treturn surface\n}", "func (s *SVG) footer() string {\n\treturn \"</svg>\"\n}", "func (me TxsdPresentationAttributesFillStrokeStrokeLinecap) String() string {\n\treturn xsdt.String(me).String()\n}", "func render(fset *token.FileSet, x interface{}) string {\n\tvar buf bytes.Buffer\n\tif err := printer.Fprint(&buf, fset, x); err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf.String()\n}", "func render(fset *token.FileSet, x interface{}) string {\n\tvar buf bytes.Buffer\n\tif err := printer.Fprint(&buf, fset, x); err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf.String()\n}", "func RenderTextToImage(text []string, w, h int, fntSize float64, fnt *truetype.Font, textColor color.Color) (*ebiten.Image, error) {\n\n\tdrawImage, err := ebiten.NewImage(w, h, ebiten.FilterNearest)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t//w, h := t.GetSize()\n\tdst := image.NewRGBA(image.Rect(0, 0, w, h))\n\t//const size = 24\n\tconst dpi = 72\n\td := &font.Drawer{\n\t\tDst: dst,\n\t\tSrc: image.NewUniform(textColor), //image.White,\n\t\tFace: truetype.NewFace(fnt, &truetype.Options{\n\t\t\tSize: fntSize,\n\t\t\tDPI: dpi,\n\t\t\tHinting: font.HintingNone,\n\t\t}),\n\t}\n\t/*highlight := color.White\n\tif t.textColor != color.Black {\n\t\thighlight = color.Black\n\t}\n\td2 := &font.Drawer{\n\t\tDst: dst,\n\t\tSrc: image.NewUniform(highlight),\n\t\tFace: truetype.NewFace(t.font, &truetype.Options{\n\t\t\tSize: t.fntSize,\n\t\t\tDPI: t.fntDpi,\n\t\t\tHinting: font.HintingFull,\n\t\t}),\n\t}*/\n\ty := fntSize\n\tfor _, s := range text {\n\t\t//d2.Dot = fixed.P(+1, int(y+1))\n\t\t//d2.DrawString(s)\n\t\td.Dot = fixed.P(0, int(y))\n\t\td.DrawString(s)\n\t\ty += fntSize\n\t}\n\n\terr = drawImage.ReplacePixels(dst.Pix)\n\treturn drawImage, err\n\n}" ]
[ "0.76019734", "0.64254194", "0.6330242", "0.6327324", "0.61420524", "0.60255545", "0.5748516", "0.57274735", "0.5592269", "0.54836124", "0.54574144", "0.54271656", "0.5374808", "0.5338089", "0.53020936", "0.5245086", "0.52353805", "0.52148926", "0.51652586", "0.50771606", "0.5039058", "0.50386745", "0.50066084", "0.4951763", "0.49468058", "0.48712745", "0.48640266", "0.4850541", "0.48308012", "0.48068443", "0.47976306", "0.47624162", "0.4737816", "0.47102952", "0.46785802", "0.46714595", "0.46560618", "0.46029773", "0.46016642", "0.45860773", "0.45791343", "0.45711416", "0.4533753", "0.4480834", "0.4473289", "0.4442597", "0.44375885", "0.4433427", "0.442589", "0.44255194", "0.44246078", "0.44210845", "0.44109017", "0.44087958", "0.44045988", "0.43619832", "0.43548128", "0.4354325", "0.43524387", "0.43477303", "0.43462837", "0.43393964", "0.43227088", "0.43065885", "0.4264975", "0.42590714", "0.425476", "0.42488238", "0.4245395", "0.42448163", "0.42443967", "0.42436868", "0.42400476", "0.42333248", "0.42319024", "0.42314643", "0.42282957", "0.42199653", "0.42183256", "0.42133933", "0.42131558", "0.41875902", "0.41859022", "0.4185146", "0.41796556", "0.41671726", "0.4167087", "0.41637754", "0.41613072", "0.4161178", "0.41568723", "0.4152116", "0.41486135", "0.4143925", "0.4134446", "0.41329613", "0.41124493", "0.41062278", "0.41062278", "0.40918025" ]
0.7593732
1
RenderToSVGFile renders a device as SVG and writes to fileName
func RenderToSVGFile(device Device, fileName string, width int, height int) { var writer io.WriteCloser writer, err := os.Create(fileName) if err != nil { fmt.Println(err) return } contents := device.RenderToSVG(width, height) io.WriteString(writer, contents) defer writer.Close() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RenderSVG(inputFile, outputFile, imageFile, shape string) {\n\tcolor.Yellow(\"Reading image file...\")\n\n\timg, err := util.DecodeImage(imageFile)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcolor.Yellow(\"Reading input file...\")\n\tpoints, err := decodePoints(inputFile)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcolor.Yellow(\"Generating SVG...\")\n\tfilename := outputFile\n\n\tif !strings.HasSuffix(filename, \".svg\") {\n\t\tfilename += \".svg\"\n\t}\n\n\tswitch shape {\n\tcase \"triangles\":\n\t\terr = triangles.WriteSVG(filename, points, img)\n\t\tbreak\n\tcase \"polygons\":\n\t\terr = polygons.WriteSVG(filename, points, img)\n\t\tbreak\n\tdefault:\n\t\terr = errors.New(\"invalid shape type\")\n\t}\n\n\tif err != nil {\n\t\tcolor.Red(\"error generating SVG\")\n\t\treturn\n\t}\n\n\tcolor.Green(\"Successfully generated SVG at %s.svg!\", filename)\n}", "func (device Device) RenderToSVG(width int, height int) string {\n\tbuffer := new(bytes.Buffer)\n\n\tcenterX := int(width / 2)\n\tcenterY := int(height / 2)\n\n\tlineColor := \"#000000\"\n\n\tblazon := device.RenderToBlazon()\n\n\t/*\n\t\tblazonLength := len(blazon)\n\t\tblazonSize := \"10\"\n\n\t\tif blazonLength < 25 {\n\t\t\tblazonSize = \"28\"\n\t\t} else if blazonLength < 30 {\n\t\t\tblazonSize = \"26\"\n\t\t} else if blazonLength < 35 {\n\t\t\tblazonSize = \"20\"\n\t\t} else if blazonLength < 40 {\n\t\t\tblazonSize = \"18\"\n\t\t} else if blazonLength < 50 {\n\t\t\tblazonSize = \"14\"\n\t\t} else if blazonLength < 60 {\n\t\t\tblazonSize = \"12\"\n\t\t} else if blazonLength < 80 {\n\t\t\tblazonSize = \"11\"\n\t\t}\n\t*/\n\n\tcanvas := svg.New(buffer)\n\tcanvas.Start(width, height+50)\n\tcanvas.Title(blazon)\n\tcanvas.Def()\n\tcanvas.Mask(\"shieldmask\", 0, 0, width, height)\n\tcanvas.Path(\"m10.273 21.598v151.22c0 96.872 89.031 194.34 146.44 240.09 57.414-45.758 146.44-143.22 146.44-240.09v-151.22h-292.89z\", \"fill:#FFFFFF\")\n\tcanvas.MaskEnd()\n\tfor _, tincture := range device.AllTinctures {\n\t\tif tincture.Name == \"erminois\" {\n\t\t\tinsertErmine(canvas, \"erminois\")\n\t\t} else if tincture.Name == \"ermine\" {\n\t\t\tinsertErmine(canvas, \"ermine\")\n\t\t} else if tincture.Name == \"ermines\" {\n\t\t\tinsertErmine(canvas, \"ermines\")\n\t\t} else if tincture.Name == \"pean\" {\n\t\t\tinsertErmine(canvas, \"pean\")\n\t\t}\n\t}\n\tif device.Field.HasVariation {\n\t\tinsertVariationPattern(canvas, device.Field.Variation)\n\t}\n\tcanvas.DefEnd()\n\tcanvas.Group(\"mask='url(#shieldmask)'\")\n\n\tif device.Field.HasVariation {\n\t\tcanvas.Rect(0, 0, width, height, \"fill:url(#\"+device.Field.Variation.Name+\")\")\n\t} else {\n\t\tcanvas.Rect(0, 0, width, height, \"fill:\"+device.Field.Tincture.Hexcode)\n\t}\n\n\tswitch device.Field.Division.Name {\n\tcase \"plain\":\n\tcase \"pale\":\n\t\tcanvas.Rect(int(width/2), 0, int(width/2), height, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"fess\":\n\t\tcanvas.Rect(0, 0, width, int(height/2), \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"bend\":\n\t\tcanvas.Polygon([]int{0, 0, width}, []int{0, height, height}, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"bendsinister\":\n\t\tcanvas.Polygon([]int{0, width, 0}, []int{0, 0, height}, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"chevron\":\n\t\tcanvas.Polygon([]int{0, int(width / 2), width}, []int{height, int(height / 2), height}, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"quarterly\":\n\t\tcanvas.Rect(int(width/2), 0, int(width/2), int(height/2), \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\t\tcanvas.Rect(0, int(height/2), int(width/2), int(height/2), \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\tcase \"saltire\":\n\t\tcanvas.Polygon([]int{0, int(width / 2), 0}, []int{0, int(height / 2), height}, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\t\tcanvas.Polygon([]int{width, int(width / 2), width}, []int{0, int(height / 2), height}, \"fill:\"+device.Field.Division.Tincture.Hexcode)\n\t}\n\tfor _, chargeGroup := range device.ChargeGroups {\n\t\tif len(chargeGroup.Charges) == 2 {\n\t\t\tcanvas.Scale(0.5)\n\t\t} else if len(chargeGroup.Charges) == 3 {\n\t\t\tcanvas.Scale(0.5)\n\t\t}\n\t\tfor index, charge := range chargeGroup.Charges {\n\t\t\tif len(chargeGroup.Charges) == 2 {\n\t\t\t\tif charge.Identifier == \"pale\" {\n\t\t\t\t\tif index == 0 {\n\t\t\t\t\t\tcanvas.Translate(20, 0)\n\t\t\t\t\t} else if index == 1 {\n\t\t\t\t\t\tcanvas.Translate(300, 0)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif index == 0 {\n\t\t\t\t\t\tcanvas.Translate(20, 200)\n\t\t\t\t\t} else if index == 1 {\n\t\t\t\t\t\tcanvas.Translate(300, 200)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if len(chargeGroup.Charges) == 3 {\n\t\t\t\tif charge.Identifier == \"pale\" {\n\t\t\t\t\tif index == 0 {\n\t\t\t\t\t\tcanvas.Translate(-20, 0)\n\t\t\t\t\t} else if index == 1 {\n\t\t\t\t\t\tcanvas.Translate(160, 0)\n\t\t\t\t\t} else if index == 2 {\n\t\t\t\t\t\tcanvas.Translate(340, 00)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif index == 0 {\n\t\t\t\t\t\tcanvas.Translate(20, 80)\n\t\t\t\t\t} else if index == 1 {\n\t\t\t\t\t\tcanvas.Translate(300, 80)\n\t\t\t\t\t} else if index == 2 {\n\t\t\t\t\t\tcanvas.Translate(160, 400)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif chargeGroup.Tincture.Name == \"sable\" {\n\t\t\t\tlineColor = \"#FFFFFF\"\n\t\t\t}\n\t\t\tswitch charge.Identifier {\n\t\t\tcase \"pale\":\n\t\t\t\tif len(chargeGroup.Charges) > 1 {\n\t\t\t\t\tcanvas.Rect(int(width/3), 0, int(width/3), height*2, \"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\t\t} else {\n\t\t\t\t\tcanvas.Rect(int(width/3), 0, int(width/3), height, \"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\t\t}\n\t\t\tcase \"fess\":\n\t\t\t\tcanvas.Rect(0, int(height/3), width, int(height/3), \"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"cross\":\n\t\t\t\tcrossHalfWidth := 40\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{centerX - crossHalfWidth, centerX + crossHalfWidth, centerX + crossHalfWidth, width, width, centerX + crossHalfWidth, centerX + crossHalfWidth, centerX - crossHalfWidth, centerX - crossHalfWidth, 0, 0, centerX - crossHalfWidth},\n\t\t\t\t\t[]int{0, 0, centerY - crossHalfWidth, centerY - crossHalfWidth, centerY + crossHalfWidth, centerY + crossHalfWidth, height, height, centerY + crossHalfWidth, centerY + crossHalfWidth, centerY - crossHalfWidth, centerY - crossHalfWidth},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"bend\":\n\t\t\t\tcanvas.TranslateRotate(-100, 135, -45)\n\t\t\t\tcanvas.Rect(int(width/3), 0, int(width/3), height, \"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\t\tcanvas.Gend()\n\t\t\tcase \"saltire\":\n\t\t\t\tsaltireHalfWidth := 30\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{0, saltireHalfWidth, centerX, width - saltireHalfWidth, width, width, centerX + saltireHalfWidth, width, width, width - saltireHalfWidth, centerX, saltireHalfWidth, 0, 0, centerX - saltireHalfWidth, 0},\n\t\t\t\t\t[]int{0, 0, centerY - saltireHalfWidth, 0, 0, saltireHalfWidth, centerY, height - saltireHalfWidth, height, height, centerY + saltireHalfWidth, height, height, height - saltireHalfWidth, centerY, saltireHalfWidth},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"chevron\":\n\t\t\t\tchevronHalfWidth := 40\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{0, centerX, width, width, centerX, 0},\n\t\t\t\t\t[]int{height - int(height/4), height - int(height/3) - (3 * chevronHalfWidth), height - int(height/4), height - int(height/4) + (2 * chevronHalfWidth), height - int(height/3) - chevronHalfWidth, height - int(height/4) + (2 * chevronHalfWidth)},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"chief\":\n\t\t\t\tcanvas.Rect(0, 0, width, int(height/3), \"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"pile\":\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{0, width, int(width / 2)},\n\t\t\t\t\t[]int{0, 0, int(height / 2)},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"pall\":\n\t\t\t\tpallHalfWidth := 40\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{0, pallHalfWidth, centerX, width - pallHalfWidth, width, width, centerX + pallHalfWidth - int(pallHalfWidth/3), centerX + pallHalfWidth - int(pallHalfWidth/3), centerX - pallHalfWidth + int(pallHalfWidth/3), centerX - pallHalfWidth + int(pallHalfWidth/3), 0},\n\t\t\t\t\t[]int{0, 0, centerY - pallHalfWidth, 0, 0, pallHalfWidth, centerY + pallHalfWidth - int(pallHalfWidth/3), height, height, centerY + pallHalfWidth - int(pallHalfWidth/3), pallHalfWidth},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"bordure\":\n\t\t\t\trenderBordureToSvg(canvas, chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"lozenge\":\n\t\t\t\tlozengeHalfWidth := 80\n\t\t\t\tcanvas.Polygon(\n\t\t\t\t\t[]int{centerX, centerX + lozengeHalfWidth, centerX, centerX - lozengeHalfWidth},\n\t\t\t\t\t[]int{centerY - lozengeHalfWidth - int(lozengeHalfWidth/2), centerY, centerY + lozengeHalfWidth + int(lozengeHalfWidth/2), centerY},\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"roundel\":\n\t\t\t\troundelRadius := 100\n\t\t\t\tcanvas.Circle(\n\t\t\t\t\tint(width/2),\n\t\t\t\t\tint(height/2),\n\t\t\t\t\troundelRadius,\n\t\t\t\t\t\"fill:\"+chargeGroup.Tincture.Hexcode)\n\t\t\tcase \"eagle-displayed\":\n\t\t\t\trenderEagleDisplayedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"dragon-passant\":\n\t\t\t\trenderDragonPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"gryphon-passant\":\n\t\t\t\trenderGryphonPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"fox-passant\":\n\t\t\t\trenderFoxPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"antelope-passant\":\n\t\t\t\trenderAntelopePassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"antelope-rampant\":\n\t\t\t\trenderAntelopeRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bat-volant\":\n\t\t\t\trenderBatVolantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"battleaxe\":\n\t\t\t\trenderBattleaxeToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bear-head-couped\":\n\t\t\t\trenderBearHeadCoupedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bear-rampant\":\n\t\t\t\trenderBearRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bear-statant\":\n\t\t\t\trenderBearStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bee-volant\":\n\t\t\t\trenderBeeVolantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bell\":\n\t\t\t\trenderBellToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"boar-head-erased\":\n\t\t\t\trenderBoarHeadErasedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"boar-passant\":\n\t\t\t\trenderBoarPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"boar-rampant\":\n\t\t\t\trenderBoarRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bugle-horn\":\n\t\t\t\trenderBugleHornToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bull-passant\":\n\t\t\t\trenderBullPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"bull-rampant\":\n\t\t\t\trenderBullRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"castle\":\n\t\t\t\trenderCastleToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"cock\":\n\t\t\t\trenderCockToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"cockatrice\":\n\t\t\t\trenderCockatriceToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"crown\":\n\t\t\t\trenderCrownToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"dolphin-hauriant\":\n\t\t\t\trenderDolphinHauriantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"double-headed-eagle-displayed\":\n\t\t\t\trenderDoubleHeadedEagleDisplayedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"dragon-rampant\":\n\t\t\t\trenderDragonRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"eagles-head-erased\":\n\t\t\t\trenderEaglesHeadErasedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"fox-sejant\":\n\t\t\t\trenderFoxSejantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"gryphon-segreant\":\n\t\t\t\trenderGryphonSegreantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"hare-salient\":\n\t\t\t\trenderHareSalientToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"hare\":\n\t\t\t\trenderHareToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"heron\":\n\t\t\t\trenderHeronToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"horse-passant\":\n\t\t\t\trenderHorsePassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"horse-rampant\":\n\t\t\t\trenderHorseRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"leopard-passant\":\n\t\t\t\trenderLeopardPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"lion-passant\":\n\t\t\t\trenderLionPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"lion-rampant\":\n\t\t\t\trenderLionRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"lions-head-erased\":\n\t\t\t\trenderLionsHeadErasedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"owl\":\n\t\t\t\trenderOwlToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"pegasus-passant\":\n\t\t\t\trenderPegasusPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"pegasus-rampant\":\n\t\t\t\trenderPegasusRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"ram-rampant\":\n\t\t\t\trenderRamRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"ram-statant\":\n\t\t\t\trenderRamStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"rose\":\n\t\t\t\trenderRoseToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"sea-horse\":\n\t\t\t\trenderSeaHorseToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"serpent-nowed\":\n\t\t\t\trenderSerpentNowedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"squirrel\":\n\t\t\t\trenderSquirrelToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"stag-lodged\":\n\t\t\t\trenderStagLodgedToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"stag-statant\":\n\t\t\t\trenderStagStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"sun-in-splendor\":\n\t\t\t\trenderSunInSplendorToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"tiger-passant\":\n\t\t\t\trenderTigerPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"tiger-rampant\":\n\t\t\t\trenderTigerRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"tower\":\n\t\t\t\trenderTowerToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"two-axes-in-saltire\":\n\t\t\t\trenderTwoAxesInSaltireToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"two-bones-in-saltire\":\n\t\t\t\trenderTwoBonesInSaltireToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"unicorn-rampant\":\n\t\t\t\trenderUnicornRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"unicorn-statant\":\n\t\t\t\trenderUnicornStatantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"wolf-passant\":\n\t\t\t\trenderWolfPassantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"wolf-rampant\":\n\t\t\t\trenderWolfRampantToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\tcase \"wyvern\":\n\t\t\t\trenderWyvernToSvg(canvas, chargeGroup.Tincture.Hexcode, lineColor)\n\t\t\t}\n\t\t\tif len(chargeGroup.Charges) > 1 {\n\t\t\t\tcanvas.Gend()\n\t\t\t}\n\t\t}\n\t\tif len(chargeGroup.Charges) > 1 {\n\t\t\tcanvas.Gend()\n\t\t}\n\t}\n\n\tcanvas.Path(\"m10.273 21.598v151.22c0 96.872 89.031 194.34 146.44 240.09 57.414-45.758 146.44-143.22 146.44-240.09v-151.22h-292.89z\", \"stroke:#000000;stroke-width:4;fill:none\")\n\tcanvas.Gend()\n\t// canvas.Text(centerX, height+25, blazon, \"font-size:\"+blazonSize+\"px;text-anchor:middle\")\n\tcanvas.End()\n\n\treturn buffer.String()\n}", "func RenderSVG(\n\ts sdf.SDF2, // sdf2 to render\n\tmeshCells int, // number of cells on the longest axis. e.g 200\n\tpath string, // path to filename\n\tlineStyle string, // SVG line style\n) error {\n\t// work out the sampling resolution to use\n\tbbSize := s.BoundingBox().Size()\n\tresolution := bbSize.MaxComponent() / float64(meshCells)\n\tcells := bbSize.DivScalar(resolution).ToV2i()\n\n\tfmt.Printf(\"rendering %s (%dx%d, resolution %.2f)\\n\", path, cells[0], cells[1], resolution)\n\n\t// write the line segments to an SVG file\n\tvar wg sync.WaitGroup\n\toutput, err := WriteSVG(&wg, path, lineStyle)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// run marching squares to generate the line segments\n\tmarchingSquaresQuadtree(s, resolution, output)\n\n\t// stop the SVG writer reading on the channel\n\tclose(output)\n\t// wait for the file write to complete\n\twg.Wait()\n\treturn nil\n}", "func WriteSVG(wg *sync.WaitGroup, path, lineStyle string) (chan<- *Line, error) {\n\n\ts := NewSVG(path, lineStyle)\n\n\t// External code writes line segments to this channel.\n\t// This goroutine reads the channel and writes line segments to the file.\n\tc := make(chan *Line)\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor v := range c {\n\t\t\ts.Line(v[0], v[1])\n\t\t}\n\t\tif err := s.Save(); err != nil {\n\t\t\tfmt.Printf(\"%s\\n\", err)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn c, nil\n}", "func (s *SVG) Render(w io.Writer) error {\n\ttop := `<?xml version=\"1.0\"?>`\n\tif _, err := w.Write([]byte(top)); err != nil {\n\t\treturn err\n\t}\n\n\treturn s.render(w)\n}", "func SVGWriter(w io.Writer, t time.Time) {\n\tio.WriteString(w, svgStart)\n\tio.WriteString(w, bezel)\n\twriteHours(w, t)\n\twriteMins(w, t)\n\twriteSecs(w, t)\n\tio.WriteString(w, svgEnd)\n}", "func (s *SVG) Save() error {\n\tf, err := os.Create(s.filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twidth := s.max.X - s.min.X\n\theight := s.max.Y - s.min.Y\n\tcanvas := svg.New(f)\n\tcanvas.Start(width, height)\n\tfor i, p0 := range s.p0s {\n\t\tp1 := s.p1s[i]\n\t\tcanvas.Line(p0.X-s.min.X, s.max.Y-p0.Y, p1.X-s.min.X, s.max.Y-p1.Y, s.lineStyle)\n\t}\n\tcanvas.End()\n\treturn f.Close()\n}", "func SaveSVG(path, lineStyle string, mesh []*Line) error {\n\ts := NewSVG(path, lineStyle)\n\tfor _, v := range mesh {\n\t\ts.Line(v[0], v[1])\n\t}\n\tif err := s.Save(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *Renderer) Save(fileName string) {\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\tpng.Encode(file, flipper.FlipV(r.img))\n}", "func SVG(width, height int) (Renderer, error) {\n\tbuffer := bytes.NewBuffer([]byte{})\n\tcanvas := newCanvas(buffer)\n\tcanvas.Start(width, height)\n\treturn &vectorRenderer{\n\t\tb: buffer,\n\t\tc: canvas,\n\t\ts: &Style{},\n\t\tp: []string{},\n\t}, nil\n}", "func BuildAndWriteSVG(src io.Reader, dst io.Writer,\n\tsvgColorLightScheme, svgColorDarkScheme string) {\n\tsvg := buildSVG(src)\n\twriteBytes(dst, svg.String(svgColorLightScheme, svgColorDarkScheme))\n}", "func (b *BlockDAG) RenderSvg() ([]byte, error) {\n\t// Render the dag in graphviz dot format\n\tdot, err := b.RenderDot()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Render the graphviz DOT file as an SVG image\n\tsvg, err := soterutil.DotToSvg(dot)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn svg, nil\n}", "func svgEncode(w io.Writer, ii *IdentIcon, pixels int) error {\n\n\t// Padding is relative to the number of blocks.\n\tpadding := pixels / (ii.Size * MinSize)\n\tdrawableArea := pixels - (padding * 2)\n\tblockSize := drawableArea / ii.Size\n\n\t// Add the residue (pixels that won't be filled) to the padding.\n\t// Try to center the figure regardless when the drawable area is not\n\t// divisible by the block pixels.\n\tpadding += (drawableArea % ii.Size) / 2\n\n\tfillColor := colorToRGBAString(ii.FillColor)\n\tbackgroundColor := colorToRGBAString(ii.BackgroundColor)\n\n\tb, err := template.New(\"svg\").Parse(svgTemplate)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt := svgTmpl{\n\t\tPixels: pixels,\n\t\tBackgroundColor: backgroundColor,\n\t\tFillColor: fillColor,\n\t\tRects: make([]svgRect, ii.Canvas.FilledPoints),\n\t}\n\n\ti := 0\n\tfor y, mapX := range ii.Canvas.PointsMap {\n\t\tfor x := range mapX {\n\t\t\tt.Rects[i] = svgRect{\n\t\t\t\tblockSize*x + padding,\n\t\t\t\tblockSize*y + padding,\n\t\t\t\tblockSize,\n\t\t\t\tblockSize,\n\t\t\t\tfillColor,\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn b.Execute(w, t)\n}", "func handler(w http.ResponseWriter, r *http.Request) {\n\tconfig := make(map[string]string)\n\n\tw.Header().Set(\"Content-Type\", \"image/svg+xml\")\n\n\tif err := r.ParseForm(); err != nil {\n\t\tlog.Print(err)\n\t}\n\n\tfor k, v := range r.Form {\n\t\tconfig[k] = v[0]\n\t}\n\n\tsvg := svgplot.SVGPlotBuilder(config)\n\tsvg.Write(w)\n}", "func (s *SVG) RenderFragment(w io.Writer) error {\n\treturn s.render(w)\n}", "func main() {\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"image/svg+xml\")\n\t\tsvg(w)\n\t})\n\tlog.Fatal(http.ListenAndServe(\":8000\", nil))\n}", "func vizFileWrite(v *VizceralGraph) {\n\tvJson, _ := json.Marshal(*v)\n\tsJson := fmt.Sprintf(\"%s\", vJson)\n\n\tdf := os.Getenv(\"TRAFFIC_URL\")\n\tdataFile := string(\"/usr/src/app/dist/\" + df)\n\tcreateFile(dataFile)\n\tWriteFile(dataFile, sJson)\n}", "func drawCanvas(allStrings []string) (err error) {\n\t//Create and write to HTML file\n\tfile, err := os.OpenFile(BA_FILE, os.O_CREATE|os.O_WRONLY, 0664)\n\tfile.Write([]byte(\"<svg height=\\\"\" + strconv.Itoa(int(Settings.CanvasXMax)) + \"\\\" width=\\\"\" + strconv.Itoa(int(Settings.CanvasYMax)) + \"\\\">\\n\"))\n\tfor _, str := range allStrings {\n\t\tfile.Write([]byte(str))\n\t}\n\tfile.Write([]byte(\"</svg>\"))\n\tfile.Close()\n\tfmt.Println(\"Canvas can be seen at \", BA_FILE)\n\treturn nil\n}", "func (p *Path) ToSVG() string {\n\tsb := strings.Builder{}\n\tx, y := 0.0, 0.0\n\tif len(p.d) > 0 && p.d[0] != moveToCmd {\n\t\tfmt.Fprintf(&sb, \"M0 0\")\n\t}\n\tfor i := 0; i < len(p.d); {\n\t\tcmd := p.d[i]\n\t\tswitch cmd {\n\t\tcase moveToCmd:\n\t\t\tx, y = p.d[i+1], p.d[i+2]\n\t\t\tfmt.Fprintf(&sb, \"M%v %v\", num(x), num(y))\n\t\tcase lineToCmd:\n\t\t\txStart, yStart := x, y\n\t\t\tx, y = p.d[i+1], p.d[i+2]\n\t\t\tif equal(x, xStart) && equal(y, yStart) {\n\t\t\t\t// nothing\n\t\t\t} else if equal(x, xStart) {\n\t\t\t\tfmt.Fprintf(&sb, \"V%v\", num(y))\n\t\t\t} else if equal(y, yStart) {\n\t\t\t\tfmt.Fprintf(&sb, \"H%v\", num(x))\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(&sb, \"L%v %v\", num(x), num(y))\n\t\t\t}\n\t\tcase quadToCmd:\n\t\t\tx, y = p.d[i+3], p.d[i+4]\n\t\t\tfmt.Fprintf(&sb, \"Q%v %v %v %v\", num(p.d[i+1]), num(p.d[i+2]), num(x), num(y))\n\t\tcase cubeToCmd:\n\t\t\tx, y = p.d[i+5], p.d[i+6]\n\t\t\tfmt.Fprintf(&sb, \"C%v %v %v %v %v %v\", num(p.d[i+1]), num(p.d[i+2]), num(p.d[i+3]), num(p.d[i+4]), num(x), num(y))\n\t\tcase arcToCmd:\n\t\t\trx, ry := p.d[i+1], p.d[i+2]\n\t\t\trot := p.d[i+3] * 180.0 / math.Pi\n\t\t\tlargeArc, sweep := fromArcFlags(p.d[i+4])\n\t\t\tx, y = p.d[i+5], p.d[i+6]\n\t\t\tsLargeArc := \"0\"\n\t\t\tif largeArc {\n\t\t\t\tsLargeArc = \"1\"\n\t\t\t}\n\t\t\tsSweep := \"0\"\n\t\t\tif sweep {\n\t\t\t\tsSweep = \"1\"\n\t\t\t}\n\t\t\tif 90.0 <= rot {\n\t\t\t\trx, ry = ry, rx\n\t\t\t\trot -= 90.0\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"A%v %v %v %s %s %v %v\", num(rx), num(ry), num(rot), sLargeArc, sSweep, num(p.d[i+5]), num(p.d[i+6]))\n\t\tcase closeCmd:\n\t\t\tx, y = p.d[i+1], p.d[i+2]\n\t\t\tfmt.Fprintf(&sb, \"z\")\n\t\t}\n\t\ti += cmdLen(cmd)\n\t}\n\treturn sb.String()\n}", "func (m *BoundaryMap) AsSVG(attr string) (string, error) {\n\tvar (\n\t\tsvg = new(SVGStringBuilder)\n\t\tsvgpath = m.newSVGPath()\n\t\terr error\n\t)\n\n\tsvg.WriteTag(\"defs\", \"\", func(svg *SVGStringBuilder) error {\n\t\tsvg.WriteString(m.CSSTag())\n\t\treturn nil\n\t})\n\n\terr = svg.WriteTag(\n\t\t\"g\", Attr(map[string]string{\"id\": \"diagram\"}, \"\"),\n\t\tfunc(svg *SVGStringBuilder) error {\n\t\t\tif err := m.buildLayers(svgpath, svg); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err = m.writeCountry(svgpath, svg); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err = m.writeCutLine(svgpath, svg); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn SVGTag(\n\t\t\"svg\", Attr(map[string]string{\n\t\t\t\"viewBox\": svgpath.ViewBox(),\n\t\t\t\"xMidyMid\": \"meet\",\n\t\t\t\"version\": \"1.2\",\n\t\t\t\"baseProfile\": \"tiny\",\n\t\t\t\"xmlns\": \"http://www.w3.org/2000/svg\",\n\t\t}, attr),\n\t\tsvg.String(),\n\t), nil\n\n}", "func svgColor() {\n\tw, err := os.Create(\"file_33.svg\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tzmin, zmax := minmax()\n\t_, _ = fmt.Fprintf(w, \"<svg xmlns='http://www.w3.org/2000/svg' \"+\n\t\t\"style='stroke: grey; fill: white; stroke-width: 0.7' \"+\n\t\t\"width='%d' height='%d'>\", width, height)\n\tfor i := 0; i < cells; i++ {\n\t\tfor j := 0; j < cells; j++ {\n\t\t\tax, ay := corner(i+1, j)\n\t\t\tbx, by := corner(i, j)\n\t\t\tcx, cy := corner(i, j+1)\n\t\t\tdx, dy := corner(i+1, j+1)\n\t\t\tif math.IsNaN(ax) || math.IsNaN(ay) || math.IsNaN(bx) || math.IsNaN(by) || math.IsNaN(cx) || math.IsNaN(cy) || math.IsNaN(dx) || math.IsNaN(dy) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t_, _ = fmt.Fprintf(w, \"<polygon style='stroke: %s; fill: #222222' points='%g,%g %g,%g %g,%g %g,%g'/>\\n\",\n\t\t\t\tcolor(i, j, zmin, zmax), ax, ay, bx, by, cx, cy, dx, dy)\n\t\t}\n\t}\n\t_, _ = fmt.Fprintln(w, \"</svg>\")\n\terr = w.Close()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}", "func (vr *vectorRenderer) Save(w io.Writer) error {\n\tvr.c.End()\n\t_, err := w.Write(vr.b.Bytes())\n\treturn err\n}", "func (c *CanvasCairoFile) Write(filename string) error {\n\te := ErrorNew()\n\tfn := C.CString(filename)\n\tdefer C.free(unsafe.Pointer(fn))\n\tif C.gt_canvas_cairo_file_to_file(C.to_canvas_cairo_file_ptr(c.c.c), fn, e.e) != 0 {\n\t\treturn e.Get()\n\t}\n\treturn nil\n}", "func (c *container) SVG(x, y, w, h float64) *SVG {\n\tr := &SVG{Width: w, Height: h, X: x, Y: y, container: container{name: \"svg\"}}\n\n\tc.contents = append(c.contents, r)\n\n\treturn r\n}", "func PlotToPng(dev scope.Device, width, height int, traceParams map[scope.ChanID]scope.TraceParams, cols map[scope.ChanID]color.RGBA, outputFile string) error {\n\tplot, err := CreatePlot(dev, width, height, traceParams, cols)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(outputFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tpng.Encode(f, plot)\n\treturn nil\n}", "func (m *modules) Render() vdom.Element {\n\tengineUI := dspUI.MakeEngine(&m.dspEngine, 1400-m.state.vDividerPos-4, m.state.hDividerPos, &m.state.dspUIEngineState)\n\tfilePickerUI := dspUI.MakeFilePicker(&m.dspEngine, m.state.vDividerPos, m.state.hDividerPos, &m.state.dspUIFilePickerState)\n\tvSplit := vdomcomp.MakeLayoutVSplit(1200, m.state.hDividerPos, m.state.vDividerPos, 4, &m.state.vDividerMoving,\n\t\tfilePickerUI,\n\t\tengineUI,\n\t\tfunc(pos int) {\n\t\t\tif pos > 100 {\n\t\t\t\tm.state.vDividerPos = pos\n\t\t\t}\n\t\t},\n\t)\n\n\thSplit := vdomcomp.MakeLayoutHSplit(1400, 800, m.state.hDividerPos, 4, &m.state.hDividerMoving,\n\t\tvSplit, onscreenkeyboardUI.MakeKeyboard(&m.keyboard),\n\t\tfunc(pos int) {\n\t\t\tif pos > 100 {\n\t\t\t\tm.state.hDividerPos = pos\n\t\t\t}\n\t\t},\n\t)\n\n\telem := vdom.MakeElement(\"svg\",\n\t\t\"id\", \"root\",\n\t\t\"xmlns\", \"http://www.w3.org/2000/svg\",\n\t\t\"style\", \"width:100%;height:100%;position:fixed;top:0;left:0;bottom:0;right:0;\",\n\t\thSplit,\n\t)\n\n\treturn elem\n}", "func (s *Statistic) SaveToDiskFile(outPath string) error {\n\toutMap := map[string]interface{}{\n\t\t\"PeerId\": s.PeerId,\n\t\t\"NumBlockSend\": s.NumBlockSend,\n\t\t\"NumBlockRecv\":s.NumBlockRecv,\n\t\t\"NumDupBlock\": s.NumDupBlock,\n\t}\n\tjs := utils.Map2json(outMap)\n\t_, err := utils.WriteBytes(outPath, []byte(js))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func serialize(gnarkObject io.WriterTo, fileName string) {\n\tf, err := os.Create(fileName)\n\tassertNoError(err)\n\n\t_, err = gnarkObject.WriteTo(f)\n\tassertNoError(err)\n}", "func SVG(w io.Writer, key string, colors []color.RGBA, size int) {\n\tcanvas := svg.New(w)\n\tcanvas.Start(size, size)\n\n\tsquares := 6\n\tquadrantSize := size / squares\n\tmiddle := math.Ceil(float64(squares) / float64(2))\n\tcolorMap := make(map[int]color.RGBA)\n\tfor yQ := 0; yQ < squares; yQ++ {\n\t\ty := yQ * quadrantSize\n\t\tcolorMap = make(map[int]color.RGBA)\n\n\t\tfor xQ := 0; xQ < squares; xQ++ {\n\t\t\tx := xQ * quadrantSize\n\t\t\tif _, ok := colorMap[xQ]; !ok {\n\t\t\t\tif float64(xQ) < middle {\n\t\t\t\t\tcolorMap[xQ] = draw.PickColor(key, colors, xQ+3*yQ)\n\t\t\t\t} else if xQ < squares {\n\t\t\t\t\tcolorMap[xQ] = colorMap[squares-xQ-1]\n\t\t\t\t} else {\n\t\t\t\t\tcolorMap[xQ] = colorMap[0]\n\t\t\t\t}\n\t\t\t}\n\t\t\tcanvas.Rect(x, y, quadrantSize, quadrantSize, draw.FillFromRGBA(colorMap[xQ]))\n\t\t}\n\t}\n\tcanvas.End()\n}", "func (j *julia) ToPng(path string) error {\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := png.Encode(f, j.img); err != nil {\n\t\tf.Close()\n\t\treturn err\n\t}\n\n\tif err := f.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func PlotFile(metrics model.Matrix, title string, format string, name string) error {\n\tw, err := Plot(metrics, title, format)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif _, err = w.WriteTo(f); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (d *Diagram) SaveAs(filename string) error {\n\treturn saveAs(d, d.Style, filename)\n}", "func HttpAdapter(f func(w io.Writer)) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"image/svg+xml\")\n\t\tf(w)\n\t}\n}", "func (svgp *SvgPath) Draw(r *rasterx.Dasher, opacity float64) {\n\tsvgp.DrawTransformed(r, opacity, rasterx.Identity)\n}", "func writeFile(tmplStr, suffix string, spec *vfsSpec) error {\n\n\terrFmt := \"write file: %v\\n\"\n\n\tif suffix != \"\" {\n\t\tsuffix = \"_\" + suffix\n\t}\n\n\tfilename := fmt.Sprintf(\"%s/%s%s.go\", spec.Package, spec.Package, suffix)\n\n\tout, err := os.Create(filename)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\tdefer out.Close()\n\n\ttmpl, err := template.New(\"\").Funcs(fnMap).Parse(tmplStr)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\ttmpl, err = tmpl.Parse(publicInterfaceTmplStr)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tbuf := new(bytes.Buffer)\n\terr = tmpl.Execute(buf, spec)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tdata, err := format.Source(buf.Bytes())\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tif err := ioutil.WriteFile(filename, data, os.FileMode(0644)); err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tpwd, err := filepath.Abs(\".\")\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tfmt.Printf(\"ESSENCE: file written: %s/%s\\n\", pwd, filename)\n\n\treturn nil\n}", "func (me TxsdPresentationAttributesGraphicsShapeRendering) String() string {\n\treturn xsdt.String(me).String()\n}", "func DrawGraphTools(filename string, s spn.SPN) {\n\tfile, err := os.Create(filename)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error. Could not create file [%s].\\n\", filename)\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\n\toutname := utils.StringConcat(filename[0:len(filename)-len(filepath.Ext(filename))], \".png\")\n\n\tfmt.Fprintf(file, \"from graph_tool.all import *\\n\\n\")\n\tfmt.Fprintf(file, \"g = Graph(directed=True)\\n\")\n\tfmt.Fprintf(file, \"vcolors = g.new_vertex_property(\\\"string\\\")\\n\")\n\tfmt.Fprintf(file, \"vnames = g.new_vertex_property(\\\"string\\\")\\n\")\n\tfmt.Fprintf(file, \"enames = g.new_edge_property(\\\"string\\\")\\n\\n\")\n\tfmt.Fprintf(file, \"def add_node(name, type):\\n\\tv=g.add_vertex()\\n\\tvnames[v]=name\\n\\t\"+\n\t\t\"vcolors[v]=type\\n\\treturn v\\n\\n\")\n\tfmt.Fprintf(file, \"def add_edge(o, t, name):\\n\\te=g.add_edge(o, t)\\n\\tenames[e]=name\\n\\treturn e\\n\\n\")\n\tfmt.Fprintf(file, \"def add_edge_nameless(o, t):\\n\\te=g.add_edge(o, t)\\n\\treturn e\\n\\n\\n\")\n\n\t// If the SPN is itself an univariate distribution, create a graph with a single node.\n\tif s.Type() == \"leaf\" {\n\t\tfmt.Fprintf(file, \"add_node(\\\"X\\\")\\n\\n\")\n\t\tfmt.Fprintf(file, \"g.vertex_properties[\\\"name\\\"]=vnames\\n\")\n\t\tfmt.Fprintf(file, \"g.vertex_properties[\\\"color\\\"]=vcolors\\n\")\n\t\tfmt.Fprintf(file, \"\\ngraph_draw(g, vertex_text=g.vertex_properties[\\\"name\\\"], \"+\n\t\t\t\"edge_text=enames, vertex_fill_color=g.vertex_properties[\\\"color\\\"], output=\\\"%s\\\")\\n\",\n\t\t\toutname)\n\t\treturn\n\t}\n\n\t// Else, BFS the SPN and write nodes to filename.\n\tnvars, nsums, nprods := 0, 0, 0\n\tqueue := common.Queue{}\n\tqueue.Enqueue(&BFSPair{Spn: s, Pname: \"\", Weight: -1.0})\n\tfor !queue.Empty() {\n\t\tcurrpair := queue.Dequeue().(*BFSPair)\n\t\tcurr, pname, pw := currpair.Spn, currpair.Pname, currpair.Weight\n\t\tch := curr.Ch()\n\t\tnch := len(ch)\n\n\t\tname := \"N\"\n\t\tcurrt := curr.Type()\n\n\t\t// In case it is a sum node. Else product node.\n\t\tif currt == \"sum\" {\n\t\t\tname = fmt.Sprintf(\"S%d\", nsums)\n\t\t\tfmt.Fprintf(file, \"%s = add_node(\\\"+\\\", \\\"#ff3300\\\")\\n\", name)\n\t\t\tnsums++\n\t\t} else if currt == \"product\" {\n\t\t\tname = fmt.Sprintf(\"P%d\", nprods)\n\t\t\tfmt.Fprintf(file, \"%s = add_node(\\\"*\\\", \\\"#669900\\\")\\n\", name)\n\t\t\tnprods++\n\t\t}\n\n\t\t// If pname is empty, then it is the root node. Else, link parent node to current node.\n\t\tif pname != \"\" {\n\t\t\tif pw >= 0 {\n\t\t\t\tfmt.Fprintf(file, \"add_edge(%s, %s, \\\"%.3f\\\")\\n\", pname, name, pw)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(file, \"add_edge_nameless(%s, %s)\\n\", pname, name)\n\t\t\t}\n\t\t}\n\n\t\tvar w []float64\n\t\tif curr.Type() == \"sum\" {\n\t\t\tw = (curr.(*spn.Sum).Weights())\n\t\t}\n\t\t// For each children, run the BFS.\n\t\tfor i := 0; i < nch; i++ {\n\t\t\tc := ch[i]\n\n\t\t\t// If leaf, then simply write to the graphviz dot file. Else, recurse the BFS.\n\t\t\tif c.Type() == \"leaf\" {\n\t\t\t\tcname := fmt.Sprintf(\"X%d\", nvars)\n\t\t\t\tfmt.Fprintf(file, \"%s = add_node(\\\"X_%d\\\", \\\"#0066ff\\\")\\n\", cname, c.Sc()[0])\n\t\t\t\tnvars++\n\t\t\t\tif currt == \"sum\" {\n\t\t\t\t\tfmt.Fprintf(file, \"add_edge(%s, %s, \\\"%.3f\\\")\\n\", name, cname, w[i])\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(file, \"add_edge_nameless(%s, %s)\\n\", name, cname)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttw := -1.0\n\t\t\t\tif w != nil {\n\t\t\t\t\ttw = w[i]\n\t\t\t\t}\n\t\t\t\tqueue.Enqueue(&BFSPair{Spn: c, Pname: name, Weight: tw})\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Fprintf(file, \"g.vertex_properties[\\\"name\\\"]=vnames\\n\")\n\tfmt.Fprintf(file, \"g.vertex_properties[\\\"color\\\"]=vcolors\\n\")\n\t//fmt.Fprintf(file, \"\\ngraph_draw(g, vertex_text=g.vertex_properties[\\\"name\\\"], \"+\n\t//\"edge_text=enames, vertex_fill_color=g.vertex_properties[\\\"color\\\"], \"+\n\t//\"output_size=[16384, 16384], output=\\\"%s\\\", bg_color=[1, 1, 1, 1])\\n\", outname)\n\tfmt.Fprintf(file, \"\\ngraph_draw(g, \"+\n\t\t\"edge_text=enames, vertex_fill_color=g.vertex_properties[\\\"color\\\"], \"+\n\t\t\"output_size=[16384, 16384], output=\\\"%s\\\", bg_color=[1, 1, 1, 1])\\n\", outname)\n}", "func (w *viewBoxWriter) Write(p []byte) (n int, err error) {\n\t// just proxy to the original writer if we already sent the viewBox attribute\n\tif w.viewBoxSent {\n\t\treturn w.Target.Write(p)\n\t}\n\n\t// check if we already received the whole svg tag prefix\n\t// if not, then just cache the content and continue\n\tprefixLen := len(writeViewBoxAfter)\n\tnewBytes := append(w.sentBytes, p...)\n\tif len(newBytes) < prefixLen {\n\t\tw.sentBytes = newBytes\n\t\treturn 0, nil\n\t}\n\n\t// check if the received content is actually svg tag\n\tif !w.startsWith(newBytes, writeViewBoxAfter) {\n\t\treturn 0, errors.Errorf(\"expected content to start with '%s' to write viewBox SVG attribute, actual value: '%s'\", writeViewBoxAfter, newBytes)\n\t}\n\n\t// write part of the received content which ends after the tag name\n\tn, err = w.Target.Write(newBytes[0:prefixLen])\n\tif err != nil {\n\t\treturn n, err\n\t}\n\n\t// append the viewBox attribute\n\tviewBox := fmt.Sprintf(`viewBox=\"%d %d %d %d\" `, w.ViewBox[0], w.ViewBox[1], w.ViewBox[2], w.ViewBox[3])\n\tn, err = w.Target.Write([]byte(viewBox))\n\tif err != nil {\n\t\treturn n, err\n\t}\n\tw.viewBoxSent = true\n\n\t// write the rest of received content\n\treturn w.Target.Write(newBytes[prefixLen:])\n}", "func (render *Renderer) RenderToFile(id int) {\n\tcategory := render.indexer.getCategory(id)\n\n\tif category == nil {\n\t\treturn\n\t}\n\tf, err := os.Create(fmt.Sprintf(`%d.html`, id))\n\tdefer f.Close()\n\tcheckErr(err)\n\n\terr = render.t.Execute(f, category)\n\tif err != nil {\n\t\tfmt.Println(\"executing template:\", err)\n\t}\n}", "func Marshal(i interface{}, size float64) ([]byte, error) {\n\tif size <= 0 {\n\t\treturn nil, fmt.Errorf(\"kandinsky: invalid marshal size\")\n\t}\n\n\tvar b bytes.Buffer\n\n\ts := gosvg.NewSVG(size, size)\n\tg := s.Group()\n\te := &encodeState{Group: g, size: size}\n\n\terr := e.marshal(reflect.ValueOf(i))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.Render(&b)\n\n\treturn b.Bytes(), nil\n}", "func (m *Marker) SetSVGMarker(f SVGMarker) {\n\tm.drawSVG = f\n}", "func GenerateSvgBoxPath(data Coordinates, size float64, plotCoords chan<- Coordinate) {\n\n\tdefer close(plotCoords)\n\n\tminPoint, maxPoint := data.Extents()\n\n\timageSize := maxPoint.Minus(minPoint)\n\tscale := size / math.Max(imageSize.X, imageSize.Y)\n\n\tfmt.Println(\"SVG Min:\", minPoint, \"Max:\", maxPoint, \"Scale:\", scale)\n\n\tif imageSize.X*scale > (Settings.DrawingSurfaceMaxX_MM-Settings.DrawingSurfaceMinX_MM) || imageSize.Y*scale > (Settings.DrawingSurfaceMaxY_MM-Settings.DrawingSurfaceMinY_MM) {\n\t\tpanic(fmt.Sprint(\n\t\t\t\"SVG coordinates extend past drawable surface, as defined in setup. Scaled svg size was: \",\n\t\t\timageSize,\n\t\t\t\" And settings bounds are, X: \", Settings.DrawingSurfaceMaxX_MM, \" - \", Settings.DrawingSurfaceMinX_MM,\n\t\t\t\" Y: \", Settings.DrawingSurfaceMaxY_MM, \" - \", Settings.DrawingSurfaceMinY_MM))\n\t}\n\n\tplotCoords <- Coordinate{X: 0, Y: 0, PenUp: true}\n\tplotCoords <- Coordinate{X: 0, Y: 10, PenUp: true}\n\tplotCoords <- Coordinate{X: 0, Y: maxPoint.Y - minPoint.Y, PenUp: true}.Scaled(scale)\n\tplotCoords <- Coordinate{X: maxPoint.X - minPoint.X, Y: maxPoint.Y - minPoint.Y, PenUp: true}.Scaled(scale)\n\tplotCoords <- Coordinate{X: maxPoint.X - minPoint.X, Y: 0, PenUp: true}.Scaled(scale)\n\tplotCoords <- Coordinate{X: 0, Y: 0, PenUp: true}.Scaled(scale)\n\n\tfor index := 0; index < len(data); index++ {\n\t\tcurTarget := data[index]\n\t\tplotCoords <- curTarget.Minus(minPoint).Scaled(scale)\n\t}\n\n\tplotCoords <- Coordinate{X: 0, Y: 0, PenUp: true}\n}", "func save(img *image.RGBA, fileName string) {\n\tfileName = filepath.Join(os.TempDir(), fileName)\n\tlog.Println(\"Saving to \", fileName)\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer file.Close()\n\tpng.Encode(file, img)\n}", "func NewSVG(filename, lineStyle string) *SVG {\n\treturn &SVG{\n\t\tfilename: filename,\n\t\tlineStyle: lineStyle,\n\t}\n}", "func (svg *SVG) OpenXML(filename string) error {\n\tfi, err := os.Stat(filename)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tif fi.IsDir() {\n\t\terr := fmt.Errorf(\"svg.OpenXML: file is a directory: %v\\n\", filename)\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tfp, err := os.Open(filename)\n\tdefer fp.Close()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\treturn svg.ReadXML(fp)\n}", "func (tg *TurtleGraphics) SavePNG(filePath string) error {\n\tf, err := os.Create(filePath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer f.Close()\n\n\tb := bufio.NewWriter(f)\n\n\terr = png.Encode(b, tg.Image)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = b.Flush()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Calendar) SVG(w io.Writer, t *Theme) error {\n\tif t == nil {\n\t\tt = Default\n\t}\n\tsize := t.Length + t.Space // the size of one cell\n\n\t// Print headers\n\tw.Write([]byte(`<?xml version=\"1.0\" encoding=\"UTF-8\"?><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 ` +\n\t\tstrconv.Itoa(size*53-t.Space) +\n\t\t` ` +\n\t\tstrconv.Itoa(\n\t\t\tlen(c.Years)*(t.Title.Height+t.Title.Bottom+size*7)+\n\t\t\t\tt.HoverLines*t.Hover.Height) +\n\t\t`\" >`))\n\tdefer w.Write([]byte(`</svg>`))\n\n\tenc := xml.NewEncoder(w)\n\theight := 0\n\tfor _, y := range c.years() {\n\t\t// Print the title\n\t\tyc := c.Years[y]\n\t\theight += t.Title.Height\n\t\terr := enc.Encode(&text{\n\t\t\tY: height,\n\t\t\tStyle: t.Title.Style,\n\t\t\tText: y,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\theight += t.Title.Bottom\n\n\t\t// Print cells\n\t\tmax := yc.max()\n\t\toffset := int(time.Date(y, time.January, 1, 0, 0, 0, 0, c.location).Weekday())\n\t\toffset = (offset+6)%7 - 1\n\t\tfor i, d := range yc {\n\t\t\tif d.Date.IsZero() {\n\t\t\t\td.Date = time.Date(y, time.January, i+1, 0, 0, 0, 0, c.location)\n\t\t\t}\n\t\t\tfill := t.Colors[0]\n\t\t\tif d.Value != 0 {\n\t\t\t\tfill = t.Colors[d.Value*(len(t.Colors)-2)/max+1]\n\t\t\t}\n\t\t\terr = enc.Encode(&rect{\n\t\t\t\tX: (d.Date.YearDay() + offset) / 7 * size,\n\t\t\t\tY: height + int(d.Date.Weekday()+6)%7*size,\n\t\t\t\tWidth: t.Length,\n\t\t\t\tHeight: t.Length,\n\t\t\t\tRx: t.Round,\n\t\t\t\tRy: t.Round,\n\t\t\t\tFill: fill,\n\t\t\t\tData: d.Data,\n\t\t\t\tDate: d.Date,\n\t\t\t\tValue: d.Value,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\theight += size * 7\n\t}\n\n\tif t.HoverLines != 0 {\n\t\theight += t.Hover.Height\n\t\tenc.Encode(&text{\n\t\t\tY: height,\n\t\t\tStyle: t.Hover.Style,\n\t\t})\n\t\tenc.Encode(&script{Content: hover})\n\t}\n\n\treturn nil\n}", "func RenderPNG(inputFile, outputFile, imageFile, shape, effect string, scale float64) {\n\tcolor.Yellow(\"Reading image file...\")\n\n\timg, err := util.DecodeImage(imageFile)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcolor.Yellow(\"Reading input file...\")\n\tpoints, err := decodePoints(inputFile)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcolor.Yellow(\"Generating PNG...\")\n\tfilename := outputFile\n\n\tif !strings.HasSuffix(filename, \".png\") {\n\t\tfilename += \".png\"\n\t}\n\n\tvar writePNG func(string, normgeom.NormPointGroup, image.Data, float64) error\n\tvar writeEffectPNG func(string, normgeom.NormPointGroup, image.Data, float64, bool) error\n\n\tswitch shape {\n\tcase \"triangles\":\n\t\twritePNG = triangles.WritePNG\n\t\twriteEffectPNG = triangles.WriteEffectPNG\n\t\tbreak\n\tcase \"polygons\":\n\t\twritePNG = polygons.WritePNG\n\t\twriteEffectPNG = polygons.WriteEffectPNG\n\t\tbreak\n\tdefault:\n\t\tcolor.Red(\"invalid shape type\")\n\t\treturn\n\t}\n\n\tswitch e := strings.ToLower(effect); e {\n\tcase \"none\":\n\t\terr = writePNG(filename, points, img, scale)\n\tcase \"gradient\":\n\t\terr = writeEffectPNG(filename, points, img, scale, true)\n\tcase \"split\":\n\t\terr = writeEffectPNG(filename, points, img, scale, false)\n\tdefault:\n\t\tcolor.Red(\"unknown effect\")\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tcolor.Red(\"error generating PNG\")\n\t\treturn\n\t}\n\n\tcolor.Green(\"Successfully generated PNG at %s!\", filename)\n}", "func render(ctx Config, com Component, gfx *dot.Graph) *dot.Node {\n\n\timg := iconPath(ctx, com)\n\n\tif fc := strings.TrimSpace(com.FontColor); len(fc) == 0 {\n\t\tcom.FontColor = \"#000000ff\"\n\t}\n\n\tif imp := strings.TrimSpace(com.Impl); len(imp) == 0 {\n\t\tcom.Impl = \"&nbsp;\"\n\t}\n\n\tvar sb strings.Builder\n\tsb.WriteString(`<table border=\"0\" cellborder=\"0\">`)\n\tif ctx.showImpl {\n\t\tfmt.Fprintf(&sb, `<tr><td><font point-size=\"8\">%s</font></td></tr>`, com.Impl)\n\t}\n\n\tsb.WriteString(\"<tr>\")\n\tfmt.Fprintf(&sb, `<td fixedsize=\"true\" width=\"50\" height=\"50\"><img src=\"%s\" /></td>`, img)\n\tsb.WriteString(\"</tr>\")\n\n\tlabel := \"&nbsp;\"\n\tif s := strings.TrimSpace(com.Label); len(s) > 0 {\n\t\tlabel = s\n\t}\n\tfmt.Fprintf(&sb, `<tr><td><font point-size=\"7\">%s</font></td></tr>`, label)\n\tsb.WriteString(\"</table>\")\n\n\treturn node.New(gfx, com.ID,\n\t\tnode.Label(sb.String(), true),\n\t\tnode.FillColor(\"transparent\"),\n\t\tnode.Shape(\"plain\"),\n\t)\n}", "func (s *SVG) Str() string {\n\treturn s.header() + s.svgString + s.footer()\n}", "func (s *SVG) Path(str string, args map[string]interface{}) {\n\tpathStr := fmt.Sprintf(\"<path d='%s' %s />\", str, s.WriteArgs(args))\n\ts.svgString += pathStr\n}", "func (s *SVG) header() string {\n\treturn fmt.Sprintf(\"<svg xmlns='http://www.w3.org/2000/svg' width='%v' height='%v'>\", s.width, s.height)\n}", "func (c *ChromaHighlight) ToFile(filename string) (err error) {\n\treturn ioutil.WriteFile(filename, c.Output, os.ModePerm)\n}", "func save(img *image.RGBA, filePath string) {\n\t// filePath = \"screenshots/\" + filePath\n\t// file, err := os.Create(filePath)\n\t// if err != nil {\n\t// \tpanic(err)\n\t// }\n\t// defer file.Close()\n\t// png.Encode(file, img)\n\n\tbuf := new(bytes.Buffer)\n\tpng.Encode(buf, img)\n\tbase64Byte := buf.Bytes()\n\timgBase64Str := base64.StdEncoding.EncodeToString(base64Byte)\n\tsendScreenShot(imgBase64Str)\n\n}", "func save(fileName string, img image.Image) {\n\tfile, _ := os.Create(fileName)\n\tdefer file.Close()\n\tpng.Encode(file, img)\n}", "func (c *Canvas) printClose() {\n\tc.Println(\"</svg>\")\n}", "func (r *Renderer) Render(path string) error {\n\toutPath := outPath(path, r.OutDir, r.BaseDir)\n\n\tif err := os.MkdirAll(filepath.Dir(outPath), os.ModeDir); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create %s\", filepath.Dir(outPath))\n\t}\n\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to read %s\", path)\n\t}\n\n\tmarkdowned := blackfriday.MarkdownCommon(data)\n\n\t// we need document reader to modify markdowned html text, for example,\n\t// syntax highlight.\n\tdoc, err := goquery.NewDocumentFromReader(bytes.NewReader(markdowned))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to parse markdown contents of %s\", path)\n\t}\n\tr.highlightCode(doc)\n\tr.handleImage(doc, filepath.Dir(path))\n\n\tcontent, _ := doc.Html()\n\tcontent = strings.Replace(content, \"<html><head></head><body>\", \"\", 1)\n\tcontent = strings.Replace(content, \"</body></html>\", \"\", 1)\n\n\toutput := r.Template\n\toutput = strings.Replace(output, \"{{{style}}}\", r.Style, -1)\n\toutput = strings.Replace(output, \"{{{content}}}\", content, -1)\n\n\terr = ioutil.WriteFile(outPath, []byte(output), os.ModeAppend)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to write %s\", outPath)\n\t}\n\n\treturn nil\n}", "func (img *Image) WriteToFile(outputPath string) error {\n\tcimg := image.NewRGBA(img._Rect)\n\tdraw.Draw(cimg, img._Rect, img._Image, image.Point{}, draw.Over)\n\n\tfor y := 0; y < img.Height; y++ {\n\t\tfor x := 0; x < img.Width; x++ {\n\t\t\trowIndex, colIndex := y, x\n\t\t\tpixel := img.Pixels[rowIndex][colIndex]\n\t\t\tcimg.Set(x, y, color.RGBA{\n\t\t\t\tuint8(pixel.R),\n\t\t\t\tuint8(pixel.G),\n\t\t\t\tuint8(pixel.B),\n\t\t\t\tuint8(pixel.A),\n\t\t\t})\n\t\t}\n\t}\n\n\ts := strings.Split(outputPath, \".\")\n\timgType := s[len(s)-1]\n\n\tswitch imgType {\n\tcase \"jpeg\", \"jpg\", \"png\":\n\t\tfd, err := os.Create(outputPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch imgType {\n\t\tcase \"jpeg\", \"jpg\":\n\t\t\tjpeg.Encode(fd, cimg, nil)\n\t\tcase \"png\":\n\t\t\tpng.Encode(fd, cimg)\n\t\t}\n\tdefault:\n\t\treturn errors.New(\"unknown image type\")\n\t}\n\n\treturn nil\n}", "func (me TxsdPresentationAttributesGraphicsShapeRendering) ToXsdtString() xsdt.String {\n\treturn xsdt.String(me)\n}", "func Generate(name string) string {\n\tname = strings.ToLower(name)\n\tvar (\n\t\tr, g, b int\n\t)\n\tif len(name) > 0 {\n\t\tr = (int(name[0]) - 97) * 155 / 26\n\t}\n\tif len(name) > 1 {\n\t\tg = (int(name[1]) - 97) * 155 / 26\n\t}\n\tif len(name) > 2 {\n\t\tb = (int(name[2]) - 97) * 155 / 26\n\t}\n\ttext := initials(name)\n\tfontSize := int(500 / math.Pow(float64(len(text)), 0.7))\n\n\tdata := fmt.Sprintf(`<?xml version=\"1.0\"?>\n<svg width=\"1000\" height=\"1000\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n\t<circle cx=\"500\" cy=\"500\" r=\"500\" style=\"fill:rgb(%d,%d,%d)\" />\n\t<circle cx=\"500\" cy=\"500\" r=\"480\" style=\"fill:rgb(%d,%d,%d)\" />\n\t<text x=\"500\" y=\"500\" style=\"text-anchor:middle;font-size:%dpx;alignment-baseline:middle;font-family:Arial,Helvetica;fill:rgb(%d,%d,%d)\">%s</text>\n</svg>\n`, r, g, b, r+100, g+100, b+100, fontSize, r, g, b, text)\n\treturn data\n}", "func NewSVGSurface(filename string, widthInPoints, heightInPoints float64, version SVGVersion) *Surface {\n\tcs := C.CString(filename)\n\tdefer C.free(unsafe.Pointer(cs))\n\ts := C.cairo_svg_surface_create(cs, C.double(widthInPoints), C.double(heightInPoints))\n\tC.cairo_svg_surface_restrict_to_version(s, C.cairo_svg_version_t(version))\n\tsurface := &Surface{surface: s, context: C.cairo_create(s)}\n\treturn surface\n}", "func GenerateSvgCenterPath(data Coordinates, size float64, plotCoords chan<- Coordinate) {\n\n\tdefer close(plotCoords)\n\n\tminPoint, maxPoint := data.Extents()\n\n\timageSize := maxPoint.Minus(minPoint)\n\tscale := size / imageSize.X\n\n\tfmt.Println(\"SVG Min:\", minPoint, \"Max:\", maxPoint, \"Scale:\", scale)\n\n\tif imageSize.X*scale > (Settings.DrawingSurfaceMaxX_MM-Settings.DrawingSurfaceMinX_MM) || imageSize.Y*scale > (Settings.DrawingSurfaceMaxY_MM-Settings.DrawingSurfaceMinY_MM) {\n\t\tpanic(fmt.Sprint(\n\t\t\t\"SVG coordinates extend past drawable surface, as defined in setup. Scaled svg size was: \",\n\t\t\timageSize,\n\t\t\t\" And settings bounds are, X: \", Settings.DrawingSurfaceMaxX_MM, \" - \", Settings.DrawingSurfaceMinX_MM,\n\t\t\t\" Y: \", Settings.DrawingSurfaceMaxY_MM, \" - \", Settings.DrawingSurfaceMinY_MM))\n\t}\n\n\t// want to center the image horizontally, so need actual world space location of gondola at start\n\tpolarSystem := PolarSystemFromSettings()\n\tpreviousPolarPos := PolarCoordinate{LeftDist: Settings.StartingLeftDist_MM, RightDist: Settings.StartingRightDist_MM}\n\tstartingLocation := previousPolarPos.ToCoord(polarSystem)\n\tsurfaceWidth := Settings.DrawingSurfaceMaxX_MM - Settings.DrawingSurfaceMinX_MM\n\n\t// actual starting location - desired = offset\n\timageDistanceFromLeftMargin := (surfaceWidth - (imageSize.X * scale)) / 2\n\tcenteringOffset := Coordinate{X: startingLocation.X - imageDistanceFromLeftMargin}\n\tfmt.Println(\"Pen starting position:\", startingLocation, \"Drawing surface width:\", surfaceWidth, \"Centering Offset:\", centeringOffset)\n\n\tplotCoords <- Coordinate{X: 0, Y: 0, PenUp: true}\n\n\tfor index := 0; index < len(data); index++ {\n\t\tcurTarget := data[index]\n\t\tplotCoords <- curTarget.Minus(minPoint).Scaled(scale).Minus(centeringOffset)\n\t}\n\n\tplotCoords <- Coordinate{X: 0, Y: 0, PenUp: true}\n}", "func outputImg(dotPath string) error {\n\tpngPath := pathutil.TrimExt(dotPath) + \".png\"\n\tdbg.Printf(\"creating file %q\", pngPath)\n\tcmd := exec.Command(\"dot\", \"-Tpng\", \"-o\", pngPath, dotPath)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "func render(src string, dst string) {\n\tdefer wg.Done()\n\tmd, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\tprintErr(err)\n\t\treturn\n\t}\n\thtml := renderHtml(md)\n\tif stylefile != \"\" {\n\t\thtml = addStyle(html, stylecont)\n\t} else {\n\t\thtml = addStyle(html, CSS)\n\t}\n\n\terr = ioutil.WriteFile(dst, []byte(html), 0644)\n\tif err != nil {\n\t\tprintErr(err)\n\t}\n}", "func exportPNG(img image.Image, path string) {\n\tout, err := os.Create(path)\n\tdefer out.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpng.Encode(out, img)\n}", "func (l *GoLayout) RenderViewFile(fileName string, context interface{}) (string, error) {\n\tvar viewContents []byte\n\tvar err error\n\tvar viewTemplate *template.Template\n\tstringWriter := bytes.NewBufferString(\"\")\n\n\tl.renderLayout()\n\n\tif viewContents, err = ioutil.ReadFile(fileName); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"Unable to read the view file %s\", fileName)\n\t}\n\n\tif viewTemplate, err = l.layout.Parse(string(viewContents[:len(viewContents)])); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"Unable to parse the view file %s\", fileName)\n\t}\n\n\tif err = viewTemplate.Execute(stringWriter, context); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"Unable to render the file %s\", fileName)\n\t}\n\n\treturn stringWriter.String(), nil\n}", "func SVGTriangle(m Marker, b *bytes.Buffer) {\n\tw := int(m.size / 2)\n\th := w * 2\n\tc := int(float64(h) * 0.33)\n\n\tb.WriteString(fmt.Sprintf(\"<g id=\\\"%s\\\"><path d=\\\"M%d %d l%d 0 l-%d -%d l-%d %d Z\\\" fill=\\\"%s\\\" opacity=\\\"0.5\\\">\",\n\t\tm.id, int(m.x), int(m.y)+c, w, w, h, w, h, m.svgColour))\n\tb.WriteString(`<desc>` + m.label + `.</desc>`)\n\tb.WriteString(`<set attributeName=\"opacity\" from=\"0.5\" to=\"1\" begin=\"mouseover\" end=\"mouseout\" dur=\"2s\"/></path>`)\n\tb.WriteString(fmt.Sprintf(\"<path d=\\\"M%d %d l%d 0 l-%d -%d l-%d %d Z\\\" stroke=\\\"%s\\\" stroke-width=\\\"1\\\" fill=\\\"none\\\" opacity=\\\"1\\\" /></g>\",\n\t\tint(m.x), int(m.y)+c, w, w, h, w, h, m.svgColour))\n}", "func WriteFile(d *defs, fileName string, objName string, bflags attrVal) {\n objType, attrLen := getMaxAttr(objName)\n f, err := os.Create(fileName); if err != nil {\n fmt.Println(err)\n f.Close()\n return\n }\n defer func(){\n err := f.Close(); if err != nil {\n fmt.Println(\"Failed to close file \", err)\n }\n if bflags.Has(\"color\"){\n fmt.Printf(\"%vWrite%v: created a new config file '%v'\\n\",Green,RST,fileName)\n }else {\n fmt.Printf(\"Write: created a new config file '%v'\\n\",fileName)\n }\n }()\n // write nagios objects to a file\n for _, def := range *d {\n formatDef := formatObjDef(def, objType, attrLen)\n f.WriteString(formatDef)\n }\n}", "func DrawGraph(filename string, s spn.SPN) {\n\tfile, err := os.Create(filename)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error. Could not create file [%s].\\n\", filename)\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\n\tfmt.Fprintf(file, \"graph {\\n\")\n\n\t// If the SPN is itself an univariate distribution, create a graph with a single node.\n\tif s.Type() == \"leaf\" {\n\t\tfmt.Fprintf(file, \"X1 [label=<X<sub>1</sub>>,shape=circle];\\n\")\n\t\tfmt.Fprintf(file, \"}\")\n\t\tfile.Close()\n\t\treturn\n\t}\n\n\t// Else, BFS the SPN and write nodes to filename.\n\tnvars, nsums, nprods := 0, 0, 0\n\tqueue := common.Queue{}\n\tqueue.Enqueue(&BFSPair{Spn: s, Pname: \"\", Weight: -1.0})\n\tfor !queue.Empty() {\n\t\tcurrpair := queue.Dequeue().(*BFSPair)\n\t\tcurr, pname, pw := currpair.Spn, currpair.Pname, currpair.Weight\n\t\tch := curr.Ch()\n\t\tnch := len(ch)\n\n\t\tname := \"N\"\n\t\tcurrt := curr.Type()\n\n\t\t// In case it is a sum node. Else product node.\n\t\tif currt == \"sum\" {\n\t\t\tname = fmt.Sprintf(\"S%d\", nsums)\n\t\t\tfmt.Fprintf(file, \"%s [label=\\\"+\\\",shape=circle];\\n\", name)\n\t\t\tnsums++\n\t\t} else if currt == \"product\" {\n\t\t\tname = fmt.Sprintf(\"P%d\", nprods)\n\t\t\tfmt.Fprintf(file, \"%s [label=<&times;>,shape=circle];\\n\", name)\n\t\t\tnprods++\n\t\t}\n\n\t\t// If pname is empty, then it is the root node. Else, link parent node to current node.\n\t\tif pname != \"\" {\n\t\t\tif pw >= 0 {\n\t\t\t\tfmt.Fprintf(file, \"%s -- %s [label=\\\"%.3f\\\"];\\n\", pname, name, pw)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(file, \"%s -- %s\\n\", pname, name)\n\t\t\t}\n\t\t}\n\n\t\tvar w []float64\n\t\tif curr.Type() == \"sum\" {\n\t\t\tw = (curr.(*spn.Sum).Weights())\n\t\t}\n\t\t// For each children, run the BFS.\n\t\tfor i := 0; i < nch; i++ {\n\t\t\tc := ch[i]\n\n\t\t\t// If leaf, then simply write to the graphviz dot file. Else, recurse the BFS.\n\t\t\tif c.Type() == \"leaf\" {\n\t\t\t\tcname := fmt.Sprintf(\"X%d\", nvars)\n\t\t\t\tfmt.Fprintf(file, \"%s [label=<X<sub>%d</sub>>,shape=circle];\\n\", cname, c.Sc()[0])\n\t\t\t\tnvars++\n\t\t\t\tif currt == \"sum\" {\n\t\t\t\t\tfmt.Fprintf(file, \"%s -- %s [label=\\\"%.3f\\\"]\\n\", name, cname, w[i])\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(file, \"%s -- %s\\n\", name, cname)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttw := -1.0\n\t\t\t\tif w != nil {\n\t\t\t\t\ttw = w[i]\n\t\t\t\t}\n\t\t\t\tqueue.Enqueue(&BFSPair{Spn: c, Pname: name, Weight: tw})\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Fprintf(file, \"}\")\n}", "func (l *GoLayout) RenderViewFilef(writer http.ResponseWriter, fileName string, context interface{}) error {\n\tvar renderedContents string\n\tvar err error\n\n\tl.renderLayout()\n\n\tif renderedContents, err = l.RenderViewFile(fileName, context); err != nil {\n\t\treturn errors.Wrapf(err, \"Unable to render the view file %s\", fileName)\n\t}\n\n\thttpService.WriteHTML(writer, renderedContents, 200)\n\treturn nil\n}", "func (s *Spectrum) WriteFile(path string, fmt string, perm os.FileMode) error {\n\tvar strFunc func() string\n\tif fmt == \"ascii\" {\n\t\tstrFunc = s.String\n\t}\n\t// if fmt == \"tsv\" { strFunc = s.TSVString }\n\t// if fmt == \"csv\" { strFunc = s.CSVString }\n\t// if fmt == \"matlab\" { strFunc = s.MATLABString }\n\t// if fmt == \"json\" { strFunc = s.JSONString }\n\treturn ioutil.WriteFile(path, []byte(strFunc()), perm)\n}", "func PdfToImageCairo(w io.Writer, r io.Reader, contentType, size string) error {\n\timgtyp, ext := \"gif\", \"png\"\n\tif contentType != \"\" && strings.HasPrefix(contentType, \"image/\") {\n\t\timgtyp = contentType[6:]\n\t}\n\tif imgtyp == \"png\" || imgtyp == \"jpeg\" {\n\t\text = imgtyp\n\t}\n\targs := append(make([]string, 0, 8), \"-singlefile\", \"-\"+ext, \"-cropbox\")\n\tif size != \"\" {\n\t\ti := strings.IndexByte(size, 'x')\n\t\tif i <= 0 || size[:i] == size[i+1:] {\n\t\t\tif i > 0 {\n\t\t\t\tsize = size[:i]\n\t\t\t}\n\t\t\targs = append(args, \"-scale-to\", size)\n\t\t} else {\n\t\t\targs = append(args, \"-scale-to-x\", size[:i])\n\t\t\targs = append(args, \"-scale-to-y\", size[i+1:])\n\t\t}\n\t}\n\ttfh, err := ioutil.TempFile(\"\", \"PdfToImageGm-\")\n\tif err != nil {\n\t\tlogger.Error(\"msg\", \"cannot create temp file\", \"error\", err)\n\t\treturn err\n\t}\n\ttfh.Close()\n\t_ = os.Remove(tfh.Name())\n\tfn := tfh.Name()\n\targs = append(args, \"-\", fn)\n\tfn = fn + \".\" + ext // pdftocairo appends the .png\n\n\tcmd := exec.Command(\"pdftocairo\", args...)\n\tcmd.Stdin = r\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tlogger.Debug(\"msg\", \"PdfToImageCairo calls\", \"command\", cmd)\n\tif err = runWithTimeout(cmd); err != nil {\n\t\treturn err\n\t}\n\tif tfh, err = os.Open(fn); err != nil {\n\t\tlogger.Error(\"msg\", \"cannot open temp file\", \"file\", fn, \"error\", err)\n\t\treturn err\n\t}\n\t_ = os.Remove(fn)\n\n\tif imgtyp == \"png\" {\n\t\t_, err = io.Copy(w, tfh)\n\t\treturn err\n\t}\n\n\t// convert to the requested format\n\tcmd = exec.Command(*ConfGm, \"convert\", \"png:-\", imgtyp+\":-\")\n\tcmd.Stdin = tfh\n\tcmd.Stdout = w\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}", "func (f *Format) Render() error {\n\tmodules := sortModules(f.Config.GetSource())\n\tdocument, err := buildDocument(f.Config.ToolVersion, modules[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpackages, otherLicenses, err := f.buildPackages(modules)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err2 := os.Create(f.Config.Filename)\n\tif err2 != nil {\n\t\treturn err2\n\t}\n\t// todo organize file generation code below\n\t//Print DOCUMENT\n\tfile.WriteString(fmt.Sprintf(\"SPDXVersion: %s\\n\", document.SPDXVersion))\n\tfile.WriteString(fmt.Sprintf(\"DataLicense: %s\\n\", document.DataLicense))\n\tfile.WriteString(fmt.Sprintf(\"SPDXID: %s\\n\", document.SPDXID))\n\tfile.WriteString(fmt.Sprintf(\"DocumentName: %s\\n\", document.DocumentName))\n\tfile.WriteString(fmt.Sprintf(\"DocumentNamespace: %s\\n\", document.DocumentNamespace))\n\tfile.WriteString(fmt.Sprintf(\"Creator: %s\\n\", document.Creator))\n\tfile.WriteString(fmt.Sprintf(\"Created: %v\\n\\n\", document.Created))\n\t//Print Package\n\tfor _, pkg := range packages {\n\t\tfile.WriteString(fmt.Sprintf(\"##### Package representing the %s\\n\\n\", pkg.PackageName))\n\t\tgeneratePackage(file, pkg)\n\t\tif pkg.RootPackage {\n\t\t\tfile.WriteString(fmt.Sprintf(\"Relationship: %s DESCRIBES %s \\n\\n\", document.SPDXID, pkg.SPDXID))\n\t\t}\n\t\t//Print DEPS ON\n\t\tif len(pkg.DependsOn) > 0 {\n\t\t\tfor _, subPkg := range pkg.DependsOn {\n\t\t\t\tfile.WriteString(fmt.Sprintf(\"Relationship: %s DEPENDS_ON %s \\n\", pkg.SPDXID, subPkg.SPDXID))\n\t\t\t}\n\t\t\tfile.WriteString(\"\\n\")\n\t\t}\n\n\t}\n\n\t//Print Other Licenses\n\tif len(otherLicenses) > 0 {\n\t\tfile.WriteString(\"##### Non-standard license\\n\\n\")\n\t\tfor lic := range otherLicenses {\n\t\t\tfile.WriteString(fmt.Sprintf(\"LicenseID: LicenseRef-%s\\n\", lic))\n\t\t\tfile.WriteString(fmt.Sprintf(\"ExtractedText: %s\\n\", otherLicenses[lic].ExtractedText))\n\t\t\tfile.WriteString(fmt.Sprintf(\"LicenseName: %s\\n\", otherLicenses[lic].Name))\n\t\t\tfile.WriteString(fmt.Sprintf(\"LicenseComment: %s\\n\\n\", otherLicenses[lic].Comments))\n\t\t}\n\t}\n\n\t// Write to file\n\tfile.Sync()\n\n\treturn nil\n}", "func (dExt *DriverExt) saveScreenShot(raw *bytes.Buffer, fileName string) (string, error) {\n\t// notice: screenshot data is a stream, so we need to copy it to a new buffer\n\tcopiedBuffer := &bytes.Buffer{}\n\tif _, err := copiedBuffer.Write(raw.Bytes()); err != nil {\n\t\tlog.Error().Err(err).Msg(\"copy screenshot buffer failed\")\n\t}\n\n\timg, format, err := image.Decode(copiedBuffer)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"decode screenshot image failed\")\n\t}\n\n\tscreenshotPath := filepath.Join(fmt.Sprintf(\"%s.%s\", fileName, format))\n\tfile, err := os.Create(screenshotPath)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create screenshot image file failed\")\n\t}\n\tdefer func() {\n\t\t_ = file.Close()\n\t}()\n\n\tswitch format {\n\tcase \"png\":\n\t\terr = png.Encode(file, img)\n\tcase \"jpeg\":\n\t\terr = jpeg.Encode(file, img, nil)\n\tcase \"gif\":\n\t\terr = gif.Encode(file, img, nil)\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unsupported image format: %s\", format)\n\t}\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"encode screenshot image failed\")\n\t}\n\n\treturn screenshotPath, nil\n}", "func SaveAnalyzedGraph(graph chart.Chart, fileNamePrefix string) string {\n\tcollector := &chart.ImageWriter{}\n\tgraph.Render(chart.PNG, collector)\n\n\timage, err := collector.Image()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcurTime := time.Now()\n\tfileName := \"/tmp/\" + fileNamePrefix + \"-image-\" + curTime.Format(constants.IMAGE_FORMAT) + \".png\"\n\tf, _ := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE, 0600)\n\tdefer f.Close()\n\tpng.Encode(f, image)\n\treturn fileName\n}", "func RenderTemplateToFile(templateFP, destFP string, context ...interface{}) error {\n\t// Render the mustache file.\n\tcontents, err := mustache.RenderFile(templateFP, context...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write contents to the destination.\n\terr = os.Remove(destFP)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\tf, err := os.Create(destFP)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating file %s: %w\", destFP, err)\n\t}\n\tdefer f.Close()\n\tf.WriteString(contents)\n\treturn nil\n}", "func (t *ArtNodeMinerRPC) GetSvgStringRPC(args *shared.Args, reply *shared.GetSvgStringReply) error {\n\t_, ok := allShapes[args.ShapeHash]\n\tif !ok {\n\t\t// if does not exists return empty reply\n\t\treturn nil\n\t}\n\t// grab the SVG string for this shape\n\tthisShape := allShapes[args.ShapeHash]\n\treply.Data = thisShape.AppShapeOp\n\treply.Found = true\n\treturn nil\n}", "func NewSVG(width, height float64) *SVG {\n\treturn &SVG{\n\t\tWidth: width,\n\t\tHeight: height,\n\t\tcontainer: container{name: \"svg\"},\n\t}\n}", "func (ap *APNGModel) SavePNGData(path string) error {\n\n\tf, _ := os.Create(path)\n\n\t_, err := f.Write(ap.buffer)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tf.Close()\n\n\treturn err\n}", "func (x *xmlRender) Render(w io.Writer) error {\n\tif _, err := w.Write(xmlHeaderBytes); err != nil {\n\t\treturn err\n\t}\n\treturn xml.NewEncoder(w).Encode(x.Data)\n}", "func (s *SVG) footer() string {\n\treturn \"</svg>\"\n}", "func WritePNG(content []byte) (string, error) {\n\tfilename := fmt.Sprint(uuid.New().String(), \".png\")\n\tfile, err := os.OpenFile(\n\t\tfmt.Sprint(constants.TempDirectory, filename),\n\t\tos.O_WRONLY|os.O_TRUNC|os.O_CREATE,\n\t\tos.ModePerm,\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\n\t_, err = file.Write(content)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filename, nil\n}", "func Svg(raw []byte, limit uint32) bool {\n\treturn bytes.Contains(raw, []byte(\"<svg\"))\n}", "func (e *Eagle) WriteFile(filename string) error {\n\twrapped := &struct {\n\t\tEagle\n\t\tXMLName struct{} `xml:\"eagle\"`\n\t}{Eagle: *e}\n\txml, err := xml.MarshalIndent(wrapped, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tfile, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\tdefer file.Close()\n\theader := \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\\n\"\n\theader += \"<!DOCTYPE eagle SYSTEM \\\"eagle.dtd\\\">\\n\"\n\tif _, err := file.WriteString(header); err != nil {\n\t\treturn err\n\t}\n\tif _, err := file.Write(xml); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func getArreglo(w http.ResponseWriter, req *http.Request) {\n\tfmt.Println(\"\\n Generando un reporte del vector linealizado...\")\n\tdotArrayRoute := \"reporte.dot\"\n\n\tif len(array) <= 0 {\n\t\treturn\n\t}\n\ttext := \"digraph reporte {\\n\"\n\tfor i := 0; i < len(array); i++ {\n\n\t\tif array[i].List.head != nil {\n\t\t\tfmt.Println(array[i].List.head.data.Name)\n\t\t\ttext += array[i].List.GetGraphviz()\n\t\t} else {\n\t\t\ttext += \"\\tnode [ shape= rect label=\\\"Null\\\"] v\" + fmt.Sprint(i) + \";\\n\"\n\t\t}\n\t}\n\n\ttext += \"\\n}\"\n\t//fmt.Println(text)\n\n\tfile, err := os.Create(dotArrayRoute)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\n\tfile.WriteString(text)\n\n\tfmt.Println(\"\\n EL archivo reporte.svg se encuentra en la carpeta del proyecto.\")\n\n}", "func (sheet *Sheet) Execute(wr io.Writer, tplContext GridTemplateContext) error {\n\treturn sheet.svgTemplate.Execute(wr, tplContext)\n}", "func NewSVG() *SVG {\n\treturn &SVG{\n\t\twidth: 100,\n\t\theight: 100,\n\t\tContent: make([]SVGWriter, 0),\n\t}\n}", "func main() {\n\tcyan := color.RGBA{R: 0, G: 255, B: 255, A: 255}\n\tred := color.RGBA{R: 255, G: 0, B: 0, A: 255}\n\n\trectImg := image.NewRGBA(image.Rect(0, 0, rectXY, rectXY))\n\tdraw.Draw(rectImg, rectImg.Bounds(), &image.Uniform{C: cyan}, image.ZP, draw.Src)\n\n\t// Draw lines\n\tfor y := stepXY; y < rectXY; y += stepXY {\n\t\tfor x := 0; x < rectXY; x++ {\n\t\t\trectImg.Set(x, y, red) // horizontal\n\t\t\trectImg.Set(y, x, red) // vertical\n\t\t}\n\t}\n\n\t// Write file\n\tfile, err := os.Create(fileName)\n\tcheck(err, \"fatal\", \"Failed create file:\")\n\tdefer file.Close()\n\n\terr = png.Encode(file, rectImg)\n\tcheck(err, \"fatal\", \"Failed render image file:\")\n\n\tfmt.Println(\"Image file\", fileName, \"written successfully!\")\n}", "func (a *PDFApiService) SaveAsPNGFile(ctx _context.Context, pdfSaveAsPngParameters PdfSaveAsPngParameters) (*os.File, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/SaveAsPNGFile\"\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{\"application/json-patch+json\", \"application/json\", \"text/json\", \"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{\"text/plain\", \"application/json\", \"text/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 = &pdfSaveAsPngParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v *os.File\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 (script Script) RenderHTML() {\n\tsymbols := []string{}\n\ttemplateHTML := `\n<!DOCTYPE html>\n<html>\n <head>\n <title>Writing System</title>\n <style type=\"text/css\">\n body, html { font-size: 28px; }\n div.container { display: flex; flex-wrap: wrap; width: 1600px; margin: 1rem auto; }\n div.cell { width: 100px; height: 100px; margin: 1rem; text-align: center; font-weight: 700; }\n div.cell > img { display: block; }\n </style>\n </head>\n <body>\n\t\t<div class=\"container\">\n\t\t\t{{range $index, $element := .}}\n <div class=\"cell\">\n <img src=\"{{ $element }}.png\">\n <p>{{ $element }}</p>\n </div>\n {{end}}\n </div>\n </body>\n</html>\n`\n\n\twriter, err := os.Create(\"./output/index.html\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tt, err := template.New(\"htmlIndex\").Parse(templateHTML)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfor _, g := range script.Glyphs {\n\t\tsymbols = append(symbols, g.Representation)\n\t}\n\n\terr = t.Execute(writer, symbols)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tdefer writer.Close()\n}", "func (f *binaryRender) Render(w io.Writer) error {\n\tif f.Reader != nil {\n\t\tdefer ess.CloseQuietly(f.Reader)\n\t\t_, err := io.Copy(w, f.Reader)\n\t\treturn err\n\t}\n\n\tfile, err := os.Open(f.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer ess.CloseQuietly(file)\n\n\tfi, err := file.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif fi.IsDir() {\n\t\treturn fmt.Errorf(\"'%s' is a directory\", f.Path)\n\t}\n\n\t_, err = io.Copy(w, file)\n\treturn err\n}", "func (me TxsdPresentationAttributesGraphicsTextRendering) String() string {\n\treturn xsdt.String(me).String()\n}", "func renderDagHTML(h *rpctest.Harness) (string, error) {\n\tresult, err := h.Node.RenderDag()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to render dag: %s\", err)\n\t}\n\n\tsvg, err := soterutil.DotToSvg([]byte(result.Dot))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to convert dot to svg: %s\", err)\n\t}\n\n\tsvgEmbed, err := soterutil.StripSvgXmlDecl(svg)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to strip svg xml declaration tag: %s\", err)\n\t}\n\n\thtml, err := soterutil.RenderSvgHTML(svgEmbed, \"dag\")\n\n\tfh, err := ioutil.TempFile(\"\", \"dag_*.html\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = save(html, fh)\n\tif err != nil {\n\t\treturn fh.Name(), err\n\t}\n\n\treturn fh.Name(), err\n}", "func RenderSVGSlow(\n\ts sdf.SDF2, // sdf2 to render\n\tmeshCells int, // number of cells on the longest axis. e.g 200\n\tpath string, // path to filename\n\tlineStyle string, // SVG line style\n) error {\n\t// work out the region we will sample\n\tbb0 := s.BoundingBox()\n\tbb0Size := bb0.Size()\n\tmeshInc := bb0Size.MaxComponent() / float64(meshCells)\n\tbb1Size := bb0Size.DivScalar(meshInc)\n\tbb1Size = bb1Size.Ceil().AddScalar(1)\n\tcells := bb1Size.ToV2i()\n\tbb1Size = bb1Size.MulScalar(meshInc)\n\tbb := sdf.NewBox2(bb0.Center(), bb1Size)\n\n\tfmt.Printf(\"rendering %s (%dx%d)\\n\", path, cells[0], cells[1])\n\n\t// run marching squares to generate the line segments\n\tm := marchingSquares(s, bb, meshInc)\n\treturn SaveSVG(path, lineStyle, m)\n}", "func (d deck) saveTofile(filename string) error {\n\treturn ioutil.WriteFile(filename, []byte(d.toString()), 0666)\n}", "func (d *DriverFile) Write(folder string) {\n\ttag := \"NikuDataBus\"\n\tif folder == constant.FolderDebug {\n\t\ttag = \"XOGOutput\"\n\t}\n\tr, _ := regexp.Compile(\"(?s)<\" + tag + \"(.*)</\" + tag + \">\")\n\tstr := r.FindString(d.xogXML)\n\tif str == constant.Undefined {\n\t\tstr = d.xogXML\n\t}\n\tioutil.WriteFile(folder+d.Type+\"/\"+d.Path, []byte(str), os.ModePerm)\n}", "func (rf RendererFunc) Render(w io.Writer, v interface{}) error { return rf(w, v) }", "func (r *RSS) Render(path string) error {\n\tfeed := r.getFeedXML()\n\n\treturn ioutil.WriteFile(path, feed, os.ModePerm)\n}", "func sendFile(w http.ResponseWriter, r *http.Request, file string) {\n\tfilepath := \"./assets/\" + file\n\tlog.Printf(\"Serving file %s\", filepath)\n\thttp.ServeFile(w, r, filepath)\n}", "func (l Poset) ToGraphViz(svg string, colors map[string]string) error {\n\tbuf, err := gviz.Compile(l, svg, colors)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := ioutil.WriteFile(\"g.gv\", buf, os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\treturn gviz.Dot(\"g.gv\", svg)\n}" ]
[ "0.6718539", "0.66789246", "0.6487193", "0.6272151", "0.6267421", "0.61351657", "0.6050372", "0.584832", "0.58023566", "0.5525576", "0.5492239", "0.5447316", "0.53317386", "0.52356464", "0.5182851", "0.514774", "0.50849193", "0.5077104", "0.50698155", "0.4960823", "0.4909119", "0.49049547", "0.48848492", "0.48305932", "0.48094544", "0.46850306", "0.4628972", "0.45920798", "0.4584947", "0.4584474", "0.45717597", "0.45701075", "0.45452893", "0.45402372", "0.45290372", "0.44926894", "0.44590524", "0.44548154", "0.4451958", "0.44471154", "0.44441527", "0.4436863", "0.44205302", "0.44141233", "0.4393971", "0.43759632", "0.43672645", "0.43507984", "0.43411747", "0.43379277", "0.43345818", "0.43217844", "0.43191364", "0.4310346", "0.43056744", "0.42980325", "0.4264561", "0.4262561", "0.4258784", "0.42493972", "0.42493215", "0.42491496", "0.4241297", "0.42147595", "0.42098966", "0.42074695", "0.42051065", "0.42049405", "0.42012444", "0.42008755", "0.41972753", "0.41954362", "0.41711834", "0.41612762", "0.4135643", "0.4134989", "0.41335848", "0.41288203", "0.41285425", "0.41247082", "0.41201672", "0.41187966", "0.41152114", "0.41116676", "0.41045296", "0.4103105", "0.40962365", "0.40782622", "0.4069605", "0.40653017", "0.4063443", "0.40616438", "0.40580684", "0.40570307", "0.40258783", "0.40231624", "0.40113887", "0.4010135", "0.40053234", "0.39942357" ]
0.86594194
0
GetSurgeDir returns the surge dir
func GetSurgeDir() string { return os.Getenv("APPDATA") + string(os.PathSeparator) + "Surge" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetGoPathDir() string {\n\troseDir := GetRosieDir()\n\treturn path.Join(roseDir, goPathDirName)\n}", "func GetDir() string {\n\t_, filename, _, _ := runtime.Caller(1)\n\treturn path.Dir(filename)\n}", "func getDir(location string) string {\n\tdir := viper.GetString(DirFlag)\n\tif dir[len(dir)-1] != '/' {\n\t\tdir = filepath.Join(dir, \"/\")\n\t}\n\treturn os.ExpandEnv(filepath.Join(dir, location))\n}", "func getDir(dirPath string) (*fs.Dir, error) {\n\tcmd := mybase.NewCommand(\"dumpertest\", \"\", \"\", nil)\n\tutil.AddGlobalOptions(cmd)\n\tworkspace.AddCommandOptions(cmd)\n\tcmd.AddArg(\"environment\", \"production\", false)\n\tcfg := &mybase.Config{\n\t\tCLI: &mybase.CommandLine{Command: cmd},\n\t}\n\treturn fs.ParseDir(dirPath, cfg)\n}", "func getRepoPath() (string, error) {\n\t// Set default base path and directory name\n\tdirectoryName := \".saturn\"\n\n\t// Join the path and directory name, then expand the home path\n\tfullPath, err := homedir.Expand(filepath.Join(\"~\", directoryName))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Return the shortest lexical representation of the path\n\treturn filepath.Clean(fullPath), nil\n}", "func GameDir() (string, error) {\n\texePath, err := os.Executable()\n\tif err != nil {\n\t\treturn \"\", errors.WithStack(err)\n\t}\n\tgameDir := filepath.Dir(exePath)\n\treturn gameDir, nil\n}", "func GlideWD(dir string) (string, error) {\n\tfullpath := filepath.Join(dir, GlideFile)\n\n\tif _, err := os.Stat(fullpath); err == nil {\n\t\treturn dir, nil\n\t}\n\n\tbase := filepath.Dir(dir)\n\tif base == dir {\n\t\treturn \"\", fmt.Errorf(\"Cannot resolve parent of %s\", base)\n\t}\n\n\treturn GlideWD(base)\n}", "func WorkDir() string { return workDir }", "func GetPassDir() (d string, err error) {\n\td, ok := os.LookupEnv(PASSGODIR)\n\tif !ok {\n\t\thome, err := GetHomeDir()\n\t\tif err == nil {\n\t\t\td = filepath.Join(home, \".passgo\")\n\t\t}\n\t}\n\treturn\n}", "func (c *client) GetTKGDirectory() (string, error) {\n\tif c.configDir == \"\" {\n\t\treturn \"\", errors.New(\"tkg config directory is empty\")\n\t}\n\treturn c.configDir, nil\n}", "func GetWD() (string, error) {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn dir, err\n}", "func (b *KRMBlueprintTest) GetBuildDir() string {\n\tif b.buildDir == \"\" {\n\t\tb.t.Fatalf(\"unable to get a valid build directory\")\n\t}\n\n\treturn b.buildDir\n}", "func (w *Writer) GetDirectory() store.Directory {\n\t// return the original directory the user supplied, unwrapped.\n\treturn w.directoryOrig\n}", "func Getwd() (string, error)", "func Dir() string {\n\tsrcdir := os.Getenv(\"TEST_SRCDIR\")\n\treturn filepath.Join(\n\t\tsrcdir, os.Getenv(\"TEST_WORKSPACE\"),\n\t\t\"go\", \"tools\", \"gazelle\", \"testdata\",\n\t)\n}", "func (s *Site) SourceDir() string { return s.cfg.Source }", "func CurrentDir(L *lua.LState) string {\n\t// same: debug.getinfo(2,'S').source\n\tvar dbg *lua.Debug\n\tvar err error\n\tvar ok bool\n\n\tdbg, ok = L.GetStack(1)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\t_, err = L.GetInfo(\"S\", dbg, lua.LNil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn filepath.Dir(dbg.Source)\n}", "func SelfDir() string {\n\treturn filepath.Dir(SelfPath())\n}", "func SelfDir() string {\n\treturn filepath.Dir(SelfPath())\n}", "func SelfDir() string {\n\treturn filepath.Dir(SelfPath())\n}", "func getPluginDir(v *viper.Viper) (string, error) {\n\tpluginDir := GetExpandedString(v, v.GetString(PluginDirKey))\n\n\tif v.IsSet(PluginDirKey) {\n\t\t// If the flag was given, assert it exists and is a directory\n\t\tinfo, err := os.Stat(pluginDir)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"plugin dir %q not found: %w\", pluginDir, err)\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\treturn \"\", fmt.Errorf(\"%w: %q\", errPluginDirNotADirectory, pluginDir)\n\t\t}\n\t} else {\n\t\t// If the flag wasn't given, make sure the default location exists.\n\t\tif err := os.MkdirAll(pluginDir, perms.ReadWriteExecute); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to create plugin dir at %s: %w\", pluginDir, err)\n\t\t}\n\t}\n\n\treturn pluginDir, nil\n}", "func GetRootlessDir() string {\n\treturn rootlessDir\n}", "func WorkDir() string {\n\treturn wd\n}", "func goPath() string {\n\tgpDefault := build.Default.GOPATH\n\tgps := filepath.SplitList(gpDefault)\n\n\treturn gps[0]\n}", "func GetGoRootDir() string {\n\troseDir := GetRosieDir()\n\treturn path.Join(roseDir, goDirName)\n}", "func (v *Module) GetDirectory() (o string) {\n\tif v != nil {\n\t\to = v.Directory\n\t}\n\treturn\n}", "func Dir() string {\n\t// At first, Check the $HOME environment variable\n\tusrHome := os.Getenv(\"HOME\")\n\tif usrHome != \"\" {\n\t\treturn filepath.FromSlash(usrHome)\n\t}\n\n\t// TODO(zchee): In Windows OS, which of $HOME and these checks has priority?\n\t// Respect the USERPROFILE environment variable because Go stdlib uses it for default GOPATH in the \"go/build\" package.\n\tif usrHome = os.Getenv(\"USERPROFILE\"); usrHome == \"\" {\n\t\tusrHome = os.Getenv(\"HOMEDRIVE\") + os.Getenv(\"HOMEPATH\")\n\t}\n\n\treturn filepath.FromSlash(usrHome)\n}", "func (l *Locator) DestDir() string {\n\treturn l.dest\n}", "func GetCurrentDirPath() string {\n\tdirPath := filepath.Dir(os.Args[0])\n\treturn dirPath\n}", "func (at AssetType) DirPath() string {\n\tinvPath := env.InvestigationsPath()\n\tswitch at {\n\tcase AssetTypeGCPAnalysis:\n\t\treturn filepath.Join(invPath, \"gcp-analyses\")\n\tcase AssetTypeIBMAnalysis:\n\t\treturn filepath.Join(invPath, \"ibm-analyses\")\n\tcase AssetTypeAudio:\n\t\treturn filepath.Join(invPath, \"audio\")\n\tcase AssetTypeRecognition:\n\t\treturn filepath.Join(invPath, \"recognitions\")\n\tcase AssetTypeTranscript:\n\t\treturn filepath.Join(invPath, \"transcripts\")\n\tcase AssetTypeVideo:\n\t\treturn filepath.Join(invPath, \"videos\")\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func GetSnapshotDir(snapshotID string) string {\n\treturn filepath.Join(SnapshotsDirname, snapshotID)\n}", "func (e *Engine) WorkDir() string {\n\treturn e.dirs.work\n}", "func (l *Locator) SourceDir() string {\n\treturn l.src\n}", "func GetProfileDir(lc logger.LoggingClient, profileDir string) string {\n\tenvValue := os.Getenv(envProfile)\n\tif len(envValue) > 0 {\n\t\tprofileDir = envValue\n\t\tlogEnvironmentOverride(lc, \"-p/-profile\", envProfile, envValue)\n\t}\n\n\tif len(profileDir) > 0 {\n\t\tprofileDir += \"/\"\n\t}\n\n\treturn profileDir\n}", "func (a Aferox) Getwd() string {\n\treturn a.Fs.Getwd()\n}", "func gitPathDir() string {\n\tgcd := trim(cmdOutput(\"git\", \"rev-parse\", \"--git-path\", \".\"))\n\tresult, err := filepath.Abs(gcd)\n\tif err != nil {\n\t\tdief(\"%v\", err)\n\t}\n\treturn result\n}", "func (gw *Gateway) GetWalletDir() (string, error) {\n\tif !gw.Config.EnableWalletAPI {\n\t\treturn \"\", wallet.ErrWalletAPIDisabled\n\t}\n\treturn gw.v.Config.WalletDirectory, nil\n}", "func (il *IL) DirPath() string {\n\treturn il.dirPath\n}", "func getCurrentDirectory() string {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tdir = \"\"\n\t}\n\treturn strings.Replace(dir, \"\\\\\", \"/\", -1)\n}", "func getGarbledCodeOutputDir() (string, error) {\n\n\toutputDir := os.Getenv(\"CODE_OUT_DIR\")\n\n\t// The real reason we create a new directory here,\n\t// is because if garble build was run twice using the same output directory\n\t// for source files, it would tend to hang, using lots of cpu like it was stuck\n\t// in a loop. Not sure why, so might as well just create a new dir each time,\n\t// and might as well use the salt as the name.\n\tif outputDir != \"\" {\n\t\tsalt := os.Getenv(\"SALT\")\n\n\t\tfinalOutputDir := filepath.Join(outputDir, salt)\n\n\t\terr := os.MkdirAll(finalOutputDir, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn finalOutputDir, nil\n\t}\n\n\t// since they didn't pass a dir, we use a temp dir\n\ttempDir, err := ioutil.TempDir(\"\", \"garble-build-\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// clean up temp dir later\n\tdeferred = append(deferred, func() error {\n\t\treturn os.RemoveAll(tempDir)\n\t})\n\n\treturn tempDir, nil\n}", "func (p *param) Dir() string {\n\treturn os.Getenv(\"HOME\") + \"/.config/teonet/teol0/\"\n}", "func locateWorkDir() (string, error) {\n\t// 1. Use work directory if explicitly passed in as an env var.\n\tif v, ok := os.LookupEnv(EnvTestgroundWorkDir); ok {\n\t\treturn v, ensureDir(v)\n\t}\n\n\t// 2. Use \"$HOME/.testground\" as the work directory.\n\n\thome, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tp := path.Join(home, \".testground\")\n\treturn p, ensureDir(p)\n}", "func OutDir(det *pb.Detection) (string, error) {\n\tswitch det.GetRequest().(type) {\n\tcase *pb.Detection_ImgManipReq:\n\t\treturn det.GetImgManipReq().GetOutDir(), nil\n\tcase *pb.Detection_VidManipReq:\n\t\treturn det.GetVidManipReq().GetOutDir(), nil\n\tcase *pb.Detection_ImgSpliceReq:\n\t\treturn det.GetImgSpliceReq().GetOutDir(), nil\n\tcase *pb.Detection_ImgCamMatchReq:\n\t\treturn det.GetImgCamMatchReq().GetOutDir(), nil\n\tdefault:\n\t\treturn \"\", errors.Errorf(\"unknown request type: %T\", det.GetRequest())\n\t}\n}", "func trunkDir() string {\n\t// TODO(derat): Should probably check that we're actually in the chroot first.\n\treturn filepath.Join(os.Getenv(\"HOME\"), \"trunk\")\n}", "func (o *EditorSettings) GetSettingsDir() gdnative.String {\n\t//log.Println(\"Calling EditorSettings.GetSettingsDir()\")\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(\"EditorSettings\", \"get_settings_dir\")\n\n\t// Call the parent method.\n\t// String\n\tretPtr := gdnative.NewEmptyString()\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.NewStringFromPointer(retPtr)\n\treturn ret\n}", "func Dir() string {\n\tdir, _ := os.Getwd()\n\treturn dir\n}", "func (e *Engine) SourceDir() string {\n\treturn e.dirs.src\n}", "func locateWorkDir() (string, error) {\n\t// 1. Use work directory if explicitly passed in as an env var.\n\tif v, ok := os.LookupEnv(EnvTestgroundWorkDir); ok {\n\t\treturn v, ensureDir(v)\n\t}\n\n\t// 2. Use \"$HOME/.testground\" as the work directory.\n\thome, ok := os.LookupEnv(\"HOME\")\n\tif !ok {\n\t\treturn \"\", errors.New(\"$HOME env variable not declared; cannot calculate work directory\")\n\t}\n\tp := path.Join(home, \".testground\")\n\treturn p, ensureDir(p)\n}", "func (builder *Builder) GetBuildDir(build string) string {\n\treturn filepath.Join(builder.BuildDir, build)\n}", "func GetRemoteFolder() (string, error) {\n\thomedir, _ := windows.KnownFolderPath(windows.FOLDERID_Downloads, 0)\n\treturn homedir + string(os.PathSeparator) + \"surge_downloads\", nil\n}", "func getWorkDirPath(dir string) (string, error) {\n\tpath, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%s%c%s\", path, os.PathSeparator, dir), nil\n}", "func (c *CmdReal) GetDir() string {\n\treturn c.cmd.Dir\n}", "func CurrentDir() string {\n\t_, f, _, _ := runtime.Caller(1)\n\treturn filepath.Dir(f)\n}", "func WorkDir() string {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn usr.HomeDir\n}", "func currentDir() string {\n\tdir, _ := filepath.Abs(filepath.Dir(os.Args[0]))\n\treturn dir\n}", "func (c *client) GetTKGCompatibilityDirectory() (string, error) {\n\ttkgDir, err := c.GetTKGDirectory()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(tkgDir, constants.LocalCompatibilityFolderName), nil\n}", "func currentDir() (wdStr string) {\n\twdStr, _ = filepath.Abs(\".\")\n\treturn\n}", "func (fs *FileSystem) Getwd() (dir string, err error) {\n\treturn fs.cwd, nil\n}", "func GetCurrentDirectory() string {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\treturn dir\n}", "func WorkDir() string {\n\tworkDirOnce.Do(func() {\n\t\tworkDir = os.Getenv(\"GOGS_WORK_DIR\")\n\t\tif workDir != \"\" {\n\t\t\treturn\n\t\t}\n\n\t\tworkDir = filepath.Dir(AppPath())\n\t})\n\n\treturn workDir\n}", "func UserConfigDir() (string, error)", "func getCurrentPath() string {\n\tpath, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn path\n}", "func (a SecondLifeClient) GetDirectory() (string, error) {\n\t// Directory detection took from indra/llvfs/lldir_win32.cpp\n\tenvParam := os.Getenv(\"APPDATA\")\n\tif envParam != \"\" {\n\t\treturn fmt.Sprintf(\"%s\\\\%s\", envParam, a), nil\n\t}\n\n\tknownPath, err := windows.KnownFolderPath(windows.FOLDERID_RoamingAppData, 0)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to retrieve application data path: %w\", err)\n\t}\n\n\treturn fmt.Sprintf(\"%s\\\\%s\", knownPath, a), nil\n}", "func FusionOutDir(fus *pb.Fusion) (string, error) {\n\tswitch fus.GetRequest().(type) {\n\tcase *pb.Fusion_ImgManipReq:\n\t\treturn fus.GetImgManipReq().GetOutDir(), nil\n\tcase *pb.Fusion_VidManipReq:\n\t\treturn fus.GetVidManipReq().GetOutDir(), nil\n\tcase *pb.Fusion_ImgSpliceReq:\n\t\treturn fus.GetImgSpliceReq().GetOutDir(), nil\n\tcase *pb.Fusion_ImgCamMatchReq:\n\t\treturn fus.GetImgCamMatchReq().GetOutDir(), nil\n\tdefault:\n\t\treturn \"\", errors.Errorf(\"unknown request type: %T\", fus.GetRequest())\n\t}\n}", "func (sf SuiteFile) RelDir() string {\n\tdir, _ := filepath.Rel(sf.BaseDir, filepath.Dir(sf.Path))\n\treturn dir\n}", "func TracingDir() string {\n\tmounts := Mounts()\n\n\t// Look for an existing tracefs\n\tfor _, m := range mounts {\n\t\tif m.FilesystemType == \"tracefs\" {\n\t\t\tglog.V(1).Infof(\"Found tracefs at %s\", m.MountPoint)\n\t\t\treturn m.MountPoint\n\t\t}\n\t}\n\n\t// If no mounted tracefs has been found, look for it as a\n\t// subdirectory of the older debugfs\n\tfor _, m := range mounts {\n\t\tif m.FilesystemType == \"debugfs\" {\n\t\t\td := filepath.Join(m.MountPoint, \"tracing\")\n\t\t\ts, err := os.Stat(filepath.Join(d, \"events\"))\n\t\t\tif err == nil && s.IsDir() {\n\t\t\t\tglog.V(1).Infof(\"Found debugfs w/ tracing at %s\", d)\n\t\t\t\treturn d\n\t\t\t}\n\n\t\t\treturn m.MountPoint\n\t\t}\n\t}\n\n\treturn \"\"\n}", "func getDirectoryName() string {\n\tflag.Parse() //parse flags\n\treturn *dirFlag //after flag.Parse(), *fileFlag is now user's --file= input\n}", "func (c *ConfHolder) Dir() string {\n\treturn os.Getenv(\"HOME\") + \"/.config/teonet/teoroom/\"\n}", "func GetCurrFileDir() string {\n\t// get this file path\n\t_, file, _, ok := runtime.Caller(1)\n\tif !ok {\n\t\tpanic(fmt.Errorf(\"Unable to access the current file path\"))\n\t}\n\treturn filepath.Dir(file)\n}", "func TracingDir() string {\n\tmounts := HostProcFS().Mounts()\n\n\t// Look for an existing tracefs\n\tfor _, m := range mounts {\n\t\tif m.FilesystemType == \"tracefs\" {\n\t\t\tglog.V(1).Infof(\"Found tracefs at %s\", m.MountPoint)\n\t\t\treturn m.MountPoint\n\t\t}\n\t}\n\n\t// If no mounted tracefs has been found, look for it as a\n\t// subdirectory of the older debugfs\n\tfor _, m := range mounts {\n\t\tif m.FilesystemType == \"debugfs\" {\n\t\t\td := filepath.Join(m.MountPoint, \"tracing\")\n\t\t\ts, err := os.Stat(filepath.Join(d, \"events\"))\n\t\t\tif err == nil && s.IsDir() {\n\t\t\t\tglog.V(1).Infof(\"Found debugfs w/ tracing at %s\", d)\n\t\t\t\treturn d\n\t\t\t}\n\n\t\t\treturn m.MountPoint\n\t\t}\n\t}\n\n\treturn \"\"\n}", "func (c *client) GetTKGProvidersDirectory() (string, error) {\n\ttkgDir, err := c.GetTKGDirectory()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(tkgDir, constants.LocalProvidersFolderName), nil\n}", "func (testFile *TestFile) GetPath() string {\n\treturn filepath.Dir(testFile.filePath)\n}", "func (o *os) GetUserDataDir() gdnative.String {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetUserDataDir()\")\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_user_data_dir\")\n\n\t// Call the parent method.\n\t// String\n\tretPtr := gdnative.NewEmptyString()\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.NewStringFromPointer(retPtr)\n\treturn ret\n}", "func Srcdir() string {\n\treturn filepath.Join(Gopath(), srcDirName)\n}", "func locateGreenplumInstallationDirectory() string {\n\t// rpm usually installs the software in /usr/local\n\t// we need to check what is the directory name it has taken\n\tbaseDir := \"/usr/local/\"\n\tfolders, _ := FilterDirsGlob(baseDir, fmt.Sprintf(\"*%s*\", cmdOptions.Version))\n\tif len(folders) > 0 {\n\t\t// We found one\n\t\treturn folders[0]\n\t} else {\n\t\tFatalf(fmt.Sprintf(\"Cannot locate the directory name at %s where the version %s is installed\", baseDir, cmdOptions.Version))\n\t}\n\n\treturn \"\"\n}", "func GetRuntimeDir() (string, error) {\n\treturn \"\", errors.New(\"this function is not implemented for windows\")\n}", "func (s *Signatures) Dir() (dir string) {\n\tsignatures.Lock()\n\tdefer signatures.Unlock()\n\n\treturn signatures.dir\n}", "func (c *Config) RewardDir() string {\n\tif len(c.rewardDir) == 0 {\n\t\tc.rewardDir = path.Join(\"rewards\", c.Name)\n\t}\n\n\treturn c.rewardDir\n}", "func postsDir() string {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn filepath.Join(wd, \"posts\")\n}", "func getHomeDir() (string, error) {\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\t// If for some reason the above doesn't work, let's see what the standard library\n\t\t// can do for us here. If this doesn't work, something is wrong and we should\n\t\t// cut out at this point.\n\t\tcurrentUser, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn currentUser.HomeDir, nil\n\t}\n\treturn home, nil\n}", "func (c *Config) RoundDir() string {\n\tif len(c.roundDir) == 0 {\n\t\tc.roundDir = path.Join(c.RewardDir(), c.Round)\n\t}\n\n\treturn c.roundDir\n}", "func GetTunnelProviderPath() string {\n\tveryFlagInput()\n\treturn providerPath\n}", "func GetProfilesDir() (string, error) {\n\tprofilesDir := os.Getenv(profilesDirEnvVariable)\n\tif profilesDir == \"\" {\n\t\tuser, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tprofilesDir = user.HomeDir + \"/go-http-cli\"\n\t}\n\treturn profilesDir, nil\n}", "func UserHomeDir() (string, error)", "func (l LoadedNotaryRepository) GetGUN() data.GUN {\n\treturn data.GUN(\"signed-repo\")\n}", "func Dir() string {\n\treturn configDir\n}", "func (s *scpSession) GetDir(remoteDir, localDir string) error {\n\tlocalDir = filepath.Clean(localDir)\n\tremoteDir = filepath.Clean(remoteDir)\n\n\treturn s.execSCPSession(SCPGETDIR, remoteDir, func() error {\n\t\treturn s.getDir(localDir)\n\t})\n}", "func Dir() string {\n\t_, filename, _, _ := runtime.Caller(1)\n\n\treturn filepath.Dir(filename)\n}", "func gradeDir(ctx *grader.Context, runID int64) string {\n\treturn path.Join(\n\t\tctx.Config.Grader.V1.RuntimeGradePath,\n\t\tfmt.Sprintf(\"%02d/%02d/%d\", runID%100, (runID%10000)/100, runID),\n\t)\n}", "func (o TriggerBuildStepOutput) Dir() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TriggerBuildStep) *string { return v.Dir }).(pulumi.StringPtrOutput)\n}", "func (s *Site) DestDir() string {\n\tif filepath.IsAbs(s.cfg.Destination) {\n\t\treturn s.cfg.Destination\n\t}\n\treturn filepath.Join(s.cfg.Source, s.cfg.Destination)\n}", "func getDir(t *testing.T, dirPath string, cliArgs ...string) *fs.Dir {\n\tt.Helper()\n\tcmd := mybase.NewCommand(\"lintertest\", \"\", \"\", nil)\n\tutil.AddGlobalOptions(cmd)\n\tworkspace.AddCommandOptions(cmd)\n\tAddCommandOptions(cmd)\n\tcmd.AddArg(\"environment\", \"production\", false)\n\tcommandLine := \"lintertest\"\n\tif len(cliArgs) > 0 {\n\t\tcommandLine = fmt.Sprintf(\"lintertest %s\", strings.Join(cliArgs, \" \"))\n\t}\n\tcfg := mybase.ParseFakeCLI(t, cmd, commandLine)\n\tdir, err := fs.ParseDir(dirPath, cfg)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error parsing dir %s: %s\", dirPath, err)\n\t}\n\treturn dir\n}", "func projectDir() string {\n\t_, filename, _, _ := runtime.Caller(1)\n\treturn path.Dir(filename)\n}", "func GetInstallDir(pluginName, v string) (string, error) {\n\tallPluginsInstallDir, err := common.GetPluginsInstallDir(pluginName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpluginDir := filepath.Join(allPluginsInstallDir, pluginName)\n\tif v != \"\" {\n\t\tpluginDir = filepath.Join(pluginDir, v)\n\t} else {\n\t\tlatestPlugin, err := pluginInfo.GetLatestInstalledPlugin(pluginDir)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpluginDir = latestPlugin.Path\n\t}\n\treturn pluginDir, nil\n}", "func fileDir() string {\n\n\t_, filename, _, _ := runtime.Caller(0)\n\treturn path.Dir(filename)\n}", "func CurrentDir() (string, error) {\n\treturn filepath.Abs(filepath.Dir(os.Args[0]))\n}", "func (env *LocalTestEnv) Directory() string {\n\treturn env.TmpPath\n}", "func getCertsDir() (string, *probe.Error) {\n\tp, err := getMcConfigDir()\n\tif err != nil {\n\t\treturn \"\", err.Trace()\n\t}\n\treturn filepath.Join(p, globalMCCertsDir), nil\n}", "func configDirPath() string {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlogging.LogFatal(\"config/configDirPath() - Can't find current user: \", err)\n\t}\n\n\t// println(\"usr.HomeDir: \", usr.HomeDir)\n\tconfigDirPath := paths.GetFilePath(usr.HomeDir, configDirName)\n\n\treturn configDirPath\n}", "func TestFileDir() string {\n\t_, file, _, ok := runtime.Caller(1)\n\tif ok {\n\t\treturn filepath.Dir(file)\n\t}\n\tpanic(\"cannot determine test file directory\")\n}" ]
[ "0.6091041", "0.596902", "0.5848043", "0.5813174", "0.57255304", "0.566004", "0.5532455", "0.55257356", "0.5516977", "0.54708016", "0.5470233", "0.5463827", "0.54617167", "0.5458734", "0.54428273", "0.544068", "0.5408417", "0.5401757", "0.5401757", "0.5401757", "0.5400922", "0.54002124", "0.5395629", "0.5379109", "0.5335753", "0.53286713", "0.5319004", "0.53076404", "0.5294469", "0.52930206", "0.52866334", "0.52844995", "0.52835137", "0.5280958", "0.5276639", "0.52480865", "0.5244679", "0.52365965", "0.5234222", "0.522688", "0.517204", "0.5156489", "0.51556444", "0.51499754", "0.51392525", "0.513619", "0.51289093", "0.5127436", "0.5126184", "0.51165473", "0.5112752", "0.5107246", "0.5105798", "0.5103727", "0.5103095", "0.5101411", "0.5097689", "0.5091164", "0.5079894", "0.5078943", "0.5062645", "0.5062517", "0.5052615", "0.5049789", "0.5045129", "0.5034105", "0.5034007", "0.5031993", "0.5030156", "0.5029972", "0.5027188", "0.50200135", "0.50182617", "0.5016539", "0.50093746", "0.50066394", "0.5004677", "0.4994238", "0.4993412", "0.49852756", "0.49847525", "0.49838933", "0.4979967", "0.49794805", "0.49698865", "0.49695963", "0.49619302", "0.4958976", "0.49432603", "0.49406815", "0.49368805", "0.49293917", "0.49248913", "0.49197802", "0.49088246", "0.49068904", "0.49025157", "0.49016318", "0.48998743", "0.4898638" ]
0.84099966
0
GetRemoteFolder returns the download dir
func GetRemoteFolder() (string, error) { homedir, _ := windows.KnownFolderPath(windows.FOLDERID_Downloads, 0) return homedir + string(os.PathSeparator) + "surge_downloads", nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b *Binary) RemotePath() string {\n\treturn b.file.RemotePath()\n}", "func getRemoteFolder(uid string) (*grizzly.Resource, error) {\n\tclient := new(http.Client)\n\th := FolderHandler{}\n\tif uid == \"General\" || uid == \"general\" {\n\t\tfolder := Folder{\n\t\t\t\"id\": 0.0,\n\t\t\t\"uid\": uid,\n\t\t\t\"title\": \"General\",\n\t\t}\n\t\tresource := grizzly.NewResource(h.APIVersion(), h.Kind(), uid, folder)\n\t\treturn &resource, nil\n\t}\n\tgrafanaURL, err := getGrafanaURL(\"api/folders/\" + uid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", grafanaURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif grafanaToken, ok := getGrafanaToken(); ok {\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+grafanaToken)\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tswitch {\n\tcase resp.StatusCode == http.StatusNotFound:\n\t\treturn nil, fmt.Errorf(\"couldn't fetch folder '%s' from remote: %w\", uid, grizzly.ErrNotFound)\n\tcase resp.StatusCode >= 400:\n\t\treturn nil, errors.New(resp.Status)\n\t}\n\n\tdata, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar f Folder\n\tif err := json.Unmarshal(data, &f); err != nil {\n\t\treturn nil, grizzly.APIErr{Err: err, Body: data}\n\t}\n\tresource := grizzly.NewResource(h.APIVersion(), h.Kind(), uid, f)\n\treturn &resource, nil\n}", "func (s *scpSession) GetDir(remoteDir, localDir string) error {\n\tlocalDir = filepath.Clean(localDir)\n\tremoteDir = filepath.Clean(remoteDir)\n\n\treturn s.execSCPSession(SCPGETDIR, remoteDir, func() error {\n\t\treturn s.getDir(localDir)\n\t})\n}", "func DownloadDir(remoteHost, remoteDir, sourceDir string) error {\n\t_, _, err := Exec(\"rsync\", \"\", \"\", \"-acrv\", \"--rsh=ssh\", remoteHost+\":\"+remoteDir+\"/\", sourceDir+\"/\")\n\treturn err\n}", "func (k *Klient) RemoteMountFolder(r req.MountFolder) (string, error) {\n\tresp, err := k.Tell(\"remote.mountFolder\", r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar warning string\n\t// TODO: Ignore the nil unmarshal error, but return others.\n\tresp.Unmarshal(&warning)\n\n\treturn warning, nil\n}", "func (g *goGetter) Download(remoteURL, destPath string) (string, error) {\n\n\tzap.S().Debugf(\"download with remote url: %q, destination dir: %q\",\n\t\tremoteURL, destPath)\n\n\t// validations: remote url or destination dir path cannot be empty\n\tif remoteURL == \"\" || destPath == \"\" {\n\t\tzap.S().Error(ErrEmptyURLDest)\n\t\treturn \"\", ErrEmptyURLDest\n\t}\n\n\t// get repository url, subdir from given remote url\n\tURLWithType, subDir, err := g.GetURLSubDir(remoteURL, destPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// downloading from remote addr\n\tclient := getter.Client{\n\t\tSrc: URLWithType,\n\t\tDst: destPath,\n\t\tPwd: destPath,\n\t\tMode: getter.ClientModeDir,\n\t\tDetectors: goGetterNoDetectors,\n\t\tDecompressors: goGetterDecompressors,\n\t\tGetters: goGetterGetters,\n\t}\n\terr = client.Get()\n\tif err != nil {\n\t\tzap.S().Errorf(\"failed to download %q. error: '%v'\", URLWithType, err)\n\t\treturn \"\", err\n\t}\n\n\t// Our subDir string can contain wildcards until this point, so that\n\t// e.g. a subDir of * can expand to one top-level directory in a .tar.gz\n\t// archive. Now that we've expanded the archive successfully we must\n\t// resolve that into a concrete path.\n\tfinalDir := destPath\n\tif subDir != \"\" {\n\t\tfinalDir, err = getter.SubdirGlob(destPath, subDir)\n\t\tif err != nil {\n\t\t\tzap.S().Errorf(\"failed to expand %q to %q\", subDir, finalDir)\n\t\t\treturn \"\", err\n\t\t}\n\t\tzap.S().Debugf(\"expanded %q to %q\", subDir, finalDir)\n\t}\n\n\t// If we got this far then we have apparently succeeded in downloading\n\t// the requested object!\n\treturn filepath.Clean(finalDir), nil\n}", "func (o *Object) remotePath() string {\n\treturn o.fs.slashRootSlash + o.remote\n}", "func (g *goGetter) GetURLSubDir(remoteURL, destPath string) (string, string, error) {\n\n\t// get subDir, if present\n\trepoURL, subDir := SplitAddrSubdir(remoteURL)\n\tzap.S().Debugf(\"downloading %q to %q\", repoURL, destPath)\n\n\t// check if a detector is present for the given url with type\n\tURLWithType, err := getter.Detect(repoURL, destPath, goGetterDetectors)\n\tif err != nil {\n\t\tzap.S().Errorf(\"failed to detect url with type for %q. error: '%v'\", remoteURL, err)\n\t\treturn \"\", \"\", err\n\t}\n\tzap.S().Debugf(\"remote URL: %q; url with type: %q\", remoteURL, URLWithType)\n\n\t// get actual subDir path\n\tURLWithType, realSubDir := SplitAddrSubdir(URLWithType)\n\tif realSubDir != \"\" {\n\t\tsubDir = filepath.Join(realSubDir, subDir)\n\t}\n\n\tif URLWithType != repoURL {\n\t\tzap.S().Debugf(\"detector rewrote %q to %q\", repoURL, URLWithType)\n\t}\n\n\t// successful\n\treturn URLWithType, subDir, nil\n}", "func getDirDownloads(c suitetalk.HTTPClient, src string, dest string) (downloads, dirs []FileTransfer) {\n\tres, err := suitetalk.ListFiles(c, src)\n\tif err != nil {\n\t\tlib.PrFatalf(\"%s\\n\", err.Error())\n\t}\n\tfor _, r := range res {\n\t\tp := filepath.Clean(strings.Replace(r.Path, src, string(filepath.Separator), 1))\n\t\tif !r.IsDir {\n\t\t\tdownloads = append(downloads, FileTransfer{Path: p, Dest: dest, Src: r.Path})\n\t\t} else {\n\t\t\tdirs = append(dirs, FileTransfer{Path: p, Dest: dest, Src: r.Path})\n\t\t}\n\t}\n\treturn downloads, dirs\n}", "func getRemoteBackup(r *Restore, conf *config.Config) {\n\tr.LocalFilePath = fmt.Sprintf(\"%v/%v\", conf.TmpDir, r.RestorePath)\n\n\tlocalFileDir := filepath.Dir(r.LocalFilePath)\n\n\terr := os.MkdirAll(localFileDir, 0755)\n\tif err != nil {\n\t\tlog.Fatalf(\"[ERR] Unable to create local restore directory!: %v\", err)\n\t}\n\n\toutFile, err := os.Create(r.LocalFilePath)\n\tif err != nil {\n\t\tlog.Fatalf(\"[ERR] Unable to create local restore temp file!: %v\", err)\n\t}\n\n\tif len(string(conf.GCSBucket)) < 1 {\n\t\tgetRemoteBackupS3(r, conf, outFile)\n\t} else {\n\t\tgetRemoteBackupGoogleStorage(r, conf, outFile)\n\t}\n\toutFile.Close()\n\tlog.Print(\"[INFO] Download completed\")\n}", "func (p *Part) RemotePath(prefix string) string {\n\tfor strings.HasSuffix(prefix, \"/\") {\n\t\tprefix = prefix[:len(prefix)-1]\n\t}\n\treturn fmt.Sprintf(\"%s/%s/%016X_%016X_%016X\", prefix, p.Path, p.FileSize, p.Offset, p.Size)\n}", "func (o *Object) Remote() string {\n\torigFileName, _, _, err := processFileName(o.Object.Remote())\n\tif err != nil {\n\t\tfs.Errorf(o, \"Could not get remote path for: %s\", o.Object.Remote())\n\t\treturn o.Object.Remote()\n\t}\n\treturn origFileName\n}", "func (_DappboxManager *DappboxManagerSession) ReturnRemoteFolderInfo(dappboxAddress common.Address, folderNameHash string) (common.Address, common.Address, error) {\n\treturn _DappboxManager.Contract.ReturnRemoteFolderInfo(&_DappboxManager.CallOpts, dappboxAddress, folderNameHash)\n}", "func (o *Object) Remote() string {\n\tnewPath, err := o.u.pathAdjustment.do(o.Object.String())\n\tif err != nil {\n\t\tfs.Errorf(o.Object, \"Bad object: %v\", err)\n\t\treturn err.Error()\n\t}\n\treturn newPath\n}", "func GetRemoteFile(url string) string {\n\tresp, err := http.Get(url)\n\tReportError(err, \"Cannot fetch remote file..., Please check your internet connection!\")\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tReportError(err, \"Cannot read from response..., Please check your internet connection!\")\n\treturn string(body)\n}", "func (resource *GitResource) DownloadRemoteResource(fileSystem filemanager.FileSystem, downloadPath string) (err error, result *remoteresource.DownloadResult) {\n\tlog := resource.context.Log()\n\tif downloadPath == \"\" {\n\t\tdownloadPath = appconfig.DownloadRoot\n\t}\n\n\terr = fileSystem.MakeDirs(downloadPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot create download path %s: %v\", downloadPath, err.Error()), nil\n\t}\n\n\tlog.Debug(\"Destination path to download into - \", downloadPath)\n\n\tauthMethod, err := resource.Handler.GetAuthMethod(log)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\t// Clone first into a random directory to safely collect downloaded files. There may already be other files in the\n\t// download directory which must be avoided\n\ttempCloneDir, err := fileSystem.CreateTempDir(downloadPath, \"tempCloneDir\")\n\tif err != nil {\n\t\treturn log.Errorf(\"Cannot create temporary directory to clone into: %s\", err.Error()), nil\n\t}\n\tdefer func() {\n\t\tdeleteErr := fileSystem.DeleteDirectory(tempCloneDir)\n\t\tif deleteErr != nil {\n\t\t\tlog.Warnf(\"Cannot remove temporary directory: %s\", deleteErr.Error())\n\t\t}\n\t}()\n\n\trepository, err := resource.Handler.CloneRepository(log, authMethod, tempCloneDir)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\tif err := resource.Handler.PerformCheckout(core.NewGitRepository(repository)); err != nil {\n\t\treturn err, nil\n\t}\n\n\tresult = &remoteresource.DownloadResult{}\n\tresult.Files, err = collectFilesAndRebaseFunction(tempCloneDir, downloadPath)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\terr = moveFilesFunction(tempCloneDir, downloadPath)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\treturn nil, result\n}", "func (f *FFS) GetFolder(ctx context.Context, ipfsRevProxyAddr string, c cid.Cid, outputDir string) error {\n\ttoken := ctx.Value(AuthKey).(string)\n\tipfs, err := newDecoratedIPFSAPI(ipfsRevProxyAddr, token)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating decorated IPFS client: %s\", err)\n\t}\n\tn, err := ipfs.Unixfs().Get(ctx, ipfspath.IpfsPath(c))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting folder DAG from IPFS: %s\", err)\n\t}\n\terr = files.WriteTo(n, outputDir)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"saving folder DAG to output folder: %s\", err)\n\t}\n\treturn nil\n}", "func (downloader FileDownloader) GetRemoteContents(URL string) ([]byte, error) {\n\tvar buffer bytes.Buffer\n\tif err := download(downloader.context, downloader.client, URL, &buffer); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer.Bytes(), nil\n}", "func (_DappboxManager *DappboxManagerCallerSession) ReturnRemoteFolderInfo(dappboxAddress common.Address, folderNameHash string) (common.Address, common.Address, error) {\n\treturn _DappboxManager.Contract.ReturnRemoteFolderInfo(&_DappboxManager.CallOpts, dappboxAddress, folderNameHash)\n}", "func (o *ObjectInfo) Remote() string {\n\torigFileName, _, _, err := processFileName(o.ObjectInfo.Remote())\n\tif err != nil {\n\t\tfs.Errorf(o, \"Could not get remote path for: %s\", o.ObjectInfo.Remote())\n\t\treturn o.ObjectInfo.Remote()\n\t}\n\treturn origFileName\n}", "func GetRemoteDownloadURL(version string) (v string, filename string, url string, err error) {\n\t_, err = semver.NewVersion(version)\n\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", errors.WithStack(err)\n\t}\n\n\tfilename, err = GetRemoteTarFilename(version)\n\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", errors.WithStack(err)\n\t}\n\n\tdownloadURL := fmt.Sprintf(\"https://github.com/denoland/deno/releases/download/%s/%s\", version, filename)\n\n\treturn version, filename, downloadURL, nil\n}", "func getDroneDownloadsPath() string {\n\treturn path.Join(getDronePath(), \"downloads\")\n}", "func downloadRemoteFile(from, user, pwd string) (string, error) {\n\t//download content from remote http url.\n\tclient := http.Client{\n\t\tTimeout: time.Duration(120 * time.Second),\n\t}\n\n\trequest, err := http.NewRequest(\"GET\", from, nil)\n\tif err != nil {\n\t\tblog.Errorf(\"http NewRequest %s error %s\", from, err.Error())\n\t\treturn \"\", err\n\t}\n\n\tif len(user) != 0 {\n\t\trequest.SetBasicAuth(user, pwd)\n\t}\n\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\tblog.Errorf(\"download remote file %s error %s\", from, err.Error())\n\t\treturn \"\", err\n\t}\n\tdefer response.Body.Close()\n\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tblog.Errorf(\"read url %s response body error %s\", from, err.Error())\n\t\treturn \"\", err\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\tblog.Errorf(\"request url %s response statuscode %d body %s\", from, response.StatusCode, string(data))\n\t\treturn \"\", fmt.Errorf(\"request url %s response statuscode %d body %s\", from, response.StatusCode, string(data))\n\t}\n\n\treturn string(data), nil\n}", "func (s3 *S3Resource) DownloadRemoteResource(filesys filemanager.FileSystem, destPath string) (err error, result *remoteresource.DownloadResult) {\n\tvar fileURL *url.URL\n\tvar unescapedURL string\n\tvar folders []string\n\tvar localFilePath string\n\n\tlog := s3.context.Log()\n\tresult = &remoteresource.DownloadResult{}\n\n\tisDirTypeDownloaded := true\n\tif destPath == \"\" {\n\t\tdestPath = appconfig.DownloadRoot\n\t}\n\tlog.Info(\"Downloading S3 artifacts from path - \", s3.Info.Path)\n\n\t// Change from '+' to '%20' is made as a workaround because s3 uses + for spaces in its URL instead of %20\n\t// This makes the differentiation between '+' and ' ' impossible when we try to manipulate the path of files to download\n\t// Since %20 is the universal escaping for ' ', s3 accepts that as well.\n\t// https://s3.amazonaws.com/aws-executecommand-test/scripts/hello%2Bworld/spaces+file.sh\n\t// new path - https://s3.amazonaws.com/aws-executecommand-test/scripts/hello%2Bworld/spaces%20file.sh\n\ts3.Info.Path = strings.Replace(s3.Info.Path, \"+\", \"%20\", -1)\n\n\tif fileURL, err = url.Parse(s3.Info.Path); err != nil {\n\t\treturn err, nil\n\t}\n\tlog.Debug(\"File URL - \", fileURL.String())\n\n\ts3.s3Object = s3util.ParseAmazonS3URL(log, fileURL)\n\tlog.Debug(\"S3 object - \", s3.s3Object.String())\n\n\tif !s3.s3Object.IsValidS3URI {\n\t\treturn fmt.Errorf(\"invalid S3 path parameter\"), nil\n\t}\n\n\t// Create an object for the source URL. This can be used to list the objects in the folder\n\tif folders, err = dep.ListS3Directory(s3.context, s3.s3Object); err != nil {\n\t\tif isPathType(s3.s3Object.Key) {\n\t\t\treturn err, nil\n\t\t}\n\n\t\tlog.Infof(\"Attempting s3 download while assuming s3Object '%s' is a file\", s3.s3Object.Key)\n\t\tfolders = []string{}\n\t}\n\n\tif len(folders) == 0 {\n\t\t// In case of a file download, append the filename to folders\n\t\tisDirTypeDownloaded = false\n\t\tfolders = append(folders, s3.s3Object.Key)\n\t}\n\n\t// The URL till the bucket name will be concatenated with the prefix in the loop\n\t// responsible for download\n\tfor _, files := range folders {\n\t\tlog.Debug(\"Name of file - \", files)\n\n\t\tif !isPathType(files) { //Only download in case the URL is a file\n\t\t\tsubFolderPath := strings.TrimPrefix(files, s3.s3Object.Key)\n\t\t\tvar bucketURL *url.URL\n\t\t\tif bucketURL, err = s3.getS3BucketURLString(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"error while obtaining URL parsing - %v\", bucketURL), nil\n\t\t\t}\n\t\t\tif bucketURL == nil {\n\t\t\t\treturn errors.New(\"URL obtained is nil\"), nil\n\t\t\t}\n\t\t\tlog.Debug(\"S3 bucket URL -\", bucketURL.String())\n\t\t\tvar input artifact.DownloadInput\n\n\t\t\t// Obtain the full URL for the file before download\n\n\t\t\tbucketURL.Path += \"/\" + files\n\t\t\tinput.SourceURL = bucketURL.String()\n\n\t\t\t// When s3 object returns the Path, it has + for '+', and %20 for ' ', because of the workaround above.\n\t\t\t// Since we are sending this URL for download, S3 manipulates the + to be a space.\n\t\t\t// Change from '+' to '%2B' which is the encoding for '+' so that s3 has to interpret %20 to be a space and %2B\n\t\t\t// to be a '+'\n\t\t\t// https://s3.amazonaws.com/aws-executecommand-test/scripts/hello+world/spaces%20file.sh\n\t\t\t// https://s3.amazonaws.com/aws-executecommand-test/scripts/hello%2Bworld/spaces%20file.sh\n\t\t\tinput.SourceURL = strings.Replace(input.SourceURL, \"+\", \"%2B\", -1)\n\t\t\tlog.Debug(\"SourceURL \", input.SourceURL)\n\t\t\tif unescapedURL, err = url.QueryUnescape(input.SourceURL); err != nil {\n\t\t\t\treturn err, nil\n\t\t\t}\n\t\t\tlog.Debug(\"UnescapedURL \", unescapedURL)\n\t\t\tdestinationFile := filepath.Base(unescapedURL)\n\n\t\t\t//when the s3 key has sub-folders leading to files, those sub-folders need to be created as well\n\t\t\tlocalFilePath = fileutil.BuildPath(destPath, filepath.Dir(subFolderPath))\n\t\t\tif !isDirTypeDownloaded {\n\t\t\t\t// if the file path provided exists as a directory or if it is in the format,\n\t\t\t\t// that would be the localFilePath\n\t\t\t\tif filesys.Exists(destPath) && filesys.IsDirectory(destPath) || isPathType(destPath) {\n\t\t\t\t\tlocalFilePath = destPath\n\t\t\t\t} else {\n\t\t\t\t\tlocalFilePath = filepath.Dir(destPath)\n\t\t\t\t\tdestinationFile = filepath.Base(destPath)\n\t\t\t\t}\n\t\t\t}\n\t\t\tinput.DestinationDirectory = localFilePath\n\t\t\tdownloadOutput, err := dep.Download(s3.context, input)\n\t\t\tif err != nil {\n\t\t\t\treturn err, nil\n\t\t\t}\n\n\t\t\tif err = system.RenameFile(log, filesys, downloadOutput.LocalFilePath, destinationFile); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Something went wrong when trying to access downloaded content. It is \"+\n\t\t\t\t\t\t\"possible that the content was not downloaded because the path provided is wrong. %v\", err),\n\t\t\t\t\tnil\n\t\t\t}\n\n\t\t\tresult.Files = append(result.Files, filepath.Join(input.DestinationDirectory, destinationFile))\n\t\t}\n\t}\n\treturn nil, result\n}", "func (_DappboxManager *DappboxManagerCaller) ReturnRemoteFolderInfo(opts *bind.CallOpts, dappboxAddress common.Address, folderNameHash string) (common.Address, common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t\tret1 = new(common.Address)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t}\n\terr := _DappboxManager.contract.Call(opts, out, \"returnRemoteFolderInfo\", dappboxAddress, folderNameHash)\n\treturn *ret0, *ret1, err\n}", "func LocalRepoDir(croniclePath string, repoURL string) (string, error) {\n\tdotCronicleRepos := path.Join(\".cronicle\", \"repos\")\n\treposDir := path.Join(croniclePath, dotCronicleRepos)\n\tu, err := url.Parse(repoURL)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tlocalRepoDir := path.Join(reposDir, u.Path)\n\n\treturn localRepoDir, nil\n}", "func (_DappboxManager *DappboxManagerCaller) IsRemoteFolder(opts *bind.CallOpts, dappboxAddress common.Address, remoteFolderAddress common.Address) (bool, common.Address, *big.Int, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t\tret1 = new(common.Address)\n\t\tret2 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _DappboxManager.contract.Call(opts, out, \"isRemoteFolder\", dappboxAddress, remoteFolderAddress)\n\treturn *ret0, *ret1, *ret2, err\n}", "func setDownloadFolder() string {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(\"Trouble looking up username!\")\n\t}\n\n\tdirLocation := usr.HomeDir + \"/4tools_downloads\"\n\tos.MkdirAll(dirLocation, 0755)\n\tos.Chdir(dirLocation)\n\n\treturn dirLocation\n}", "func (a SecondLifeClient) GetDirectory() (string, error) {\n\t// Directory detection took from indra/llvfs/lldir_win32.cpp\n\tenvParam := os.Getenv(\"APPDATA\")\n\tif envParam != \"\" {\n\t\treturn fmt.Sprintf(\"%s\\\\%s\", envParam, a), nil\n\t}\n\n\tknownPath, err := windows.KnownFolderPath(windows.FOLDERID_RoamingAppData, 0)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to retrieve application data path: %w\", err)\n\t}\n\n\treturn fmt.Sprintf(\"%s\\\\%s\", knownPath, a), nil\n}", "func (client *Client) DownloadDirectory(ctx context.Context, bucket *storage.BucketHandle, destPath string, filter FilesFilter) error {\n\tif bucket == nil {\n\t\treturn ErrorNilBucket\n\t}\n\n\tfiles, err := ListRemoteFiles(ctx, bucket, filter)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// return err if dir already exists\n\texists, err := fsutil.Exists(destPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif exists {\n\t\treturn fmt.Errorf(\"destination path %q already exists\", destPath)\n\t}\n\n\terr = os.MkdirAll(destPath, 0750)\n\tif err != nil && !os.IsExist(err) {\n\t\treturn err\n\t}\n\n\tfor _, file := range files {\n\t\terr = client.downloadFile(ctx, bucket, file.FullPath, file.PathTrimmed)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (f *Fs) DownloadRemoteFile(url string, name string) error {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := f.AferoFs.Create(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\n\treturn err\n}", "func (_DappboxManager *DappboxManagerSession) IsRemoteFolder(dappboxAddress common.Address, remoteFolderAddress common.Address) (bool, common.Address, *big.Int, error) {\n\treturn _DappboxManager.Contract.IsRemoteFolder(&_DappboxManager.CallOpts, dappboxAddress, remoteFolderAddress)\n}", "func getRemoteArtifactWorker(artDetails *jfauth.ServiceDetails, chFolder chan string, chFile chan<- string) {\n\trmtBaseURL := \"api/storage\"\n\tfor f := range chFolder {\n\t\trmtPath := \"\"\n\t\tif f[0] != '/' {\n\t\t\trmtPath = \"/\" + f\n\t\t} else {\n\t\t\trmtPath = f\n\t\t}\n\t\trmtURL := rmtBaseURL + rmtPath\n\n\t\t//fmt.Printf(\"accumulated files : %d, remaining folders : %d, checking : %s\\n\", files.Len(), folders.Len(), rmtURL)\n\n\t\tresp, err := getHttpResp(artDetails, rmtURL)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"GET HTTP failed for url : %s\\n\", rmtURL)\n\t\t\tjflog.Error(fmt.Sprintf(\"GET HTTP failed for url : %s\", rmtURL))\n\t\t}\n\t\t//fmt.Printf(\"getHttpResp() done : %s\\n\", f)\n\t\tArtiInfo := &ArtifactInfo{}\n\t\tif err := json.Unmarshal(resp, &ArtiInfo); err != nil {\n\t\t\tfmt.Printf(\"Unable to fetch file and folders for url : %s\\n\", rmtURL)\n\t\t\tjflog.Error(fmt.Sprintf(\"Unable to fetch file and folders for url : %s\", rmtURL))\n\t\t\tcontinue\n\t\t}\n\t\t//fmt.Printf(\"json.Unmarshal done, count of items in folder : %d\\n\", len(ArtiInfo.Children))\n\t\tfor _, c := range ArtiInfo.Children {\n\t\t\tif c.Folder == true {\n\t\t\t\tchFolder <- rmtPath + c.Uri\n\t\t\t} else {\n\t\t\t\tchFile <- rmtPath + c.Uri\n\t\t\t}\n\t\t}\n\t\t//fmt.Printf(\"completed folder : %s\\n\", f)\n\t}\n}", "func (c *cache) GetRemote(ctx context.Context, hash string) ([]byte, error) {\n\tif !c.fs.useRemote {\n\t\treturn c.Get(ctx, hash)\n\t}\n\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tvar err error\n\tcachedBlob, ok, err := c.blobsCache.Get(hash)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cache failed: %v\", err)\n\t}\n\tlogger.Printf(\"[remote] downloading %s from remote\", hash)\n\tvar data []byte\n\tif ok {\n\t\tdata = cachedBlob\n\t} else {\n\t\tobj, err := s3util.NewBucket(c.fs.s3, c.fs.profile.RemoteConfig.Bucket).GetObject(hash)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\teblob := s3util.NewEncryptedBlob(obj, c.fs.key)\n\t\tdata, err = eblob.PlainText()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := c.blobsCache.Add(hash, data); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add to cache: %v\", err)\n\t\t}\n\t}\n\n\treturn data, nil\n}", "func (l *Locator) DestDir() string {\n\treturn l.dest\n}", "func getRemoteURL(config *gitcfg.Config, name string) string {\n\tif config.Remotes != nil {\n\t\treturn firstRemoteURL(config.Remotes[name])\n\t}\n\n\treturn \"\"\n}", "func (_DappboxManager *DappboxManagerSession) ReturnAllDappboxRemoteFolders(dappboxAddress common.Address, index *big.Int) (string, common.Address, common.Address, bool, bool, error) {\n\treturn _DappboxManager.Contract.ReturnAllDappboxRemoteFolders(&_DappboxManager.CallOpts, dappboxAddress, index)\n}", "func (_DappboxManager *DappboxManagerCallerSession) IsRemoteFolder(dappboxAddress common.Address, remoteFolderAddress common.Address) (bool, common.Address, *big.Int, error) {\n\treturn _DappboxManager.Contract.IsRemoteFolder(&_DappboxManager.CallOpts, dappboxAddress, remoteFolderAddress)\n}", "func getRemoteRepository(remote RemoteRepository, doUpdate bool, isShallow bool) {\n\tremoteURL := remote.URL()\n\tlocal := LocalRepositoryFromURL(remoteURL)\n\n\tpath := local.FullPath\n\tnewPath := false\n\n\t_, err := os.Stat(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tnewPath = true\n\t\t\terr = nil\n\t\t}\n\t\tutils.PanicIf(err)\n\t}\n\n\tif newPath {\n\t\tutils.Log(\"clone\", fmt.Sprintf(\"%s -> %s\", remoteURL, path))\n\n\t\tvcs := remote.VCS()\n\t\tif vcs == nil {\n\t\t\tutils.Log(\"error\", fmt.Sprintf(\"Could not find version control system: %s\", remoteURL))\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tvcs.Clone(remoteURL, path, isShallow)\n\t} else {\n\t\tif doUpdate {\n\t\t\tutils.Log(\"update\", path)\n\t\t\tlocal.VCS().Update(path)\n\t\t} else {\n\t\t\tutils.Log(\"exists\", path)\n\t\t}\n\t}\n}", "func FetchRemoteFile() {\n\n}", "func getFilesAtRemotePath(path string, recursive, includeBase,\n\tmustExist bool) map[string]*drive.File {\n\texistingFiles := make(map[string]*drive.File)\n\tfile, err := getDriveFile(path)\n\tif err != nil {\n\t\tif !mustExist {\n\t\t\treturn existingFiles\n\t\t}\n\t\tprintErrorAndExit(fmt.Errorf(\"skicka: %v\\n\", err))\n\t}\n\n\tif isFolder(file) {\n\t\terr := getFolderContents(path, file, recursive, existingFiles)\n\t\tif err != nil {\n\t\t\tprintErrorAndExit(fmt.Errorf(\"skicka: %v\\n\", err))\n\t\t}\n\t\tif includeBase {\n\t\t\texistingFiles[path] = file\n\t\t}\n\t} else {\n\t\texistingFiles[path] = file\n\t}\n\ttimeDelta(\"Get file descriptors from Google Drive\")\n\treturn existingFiles\n}", "func (_DappboxManager *DappboxManagerCallerSession) ReturnAllDappboxRemoteFolders(dappboxAddress common.Address, index *big.Int) (string, common.Address, common.Address, bool, bool, error) {\n\treturn _DappboxManager.Contract.ReturnAllDappboxRemoteFolders(&_DappboxManager.CallOpts, dappboxAddress, index)\n}", "func (k *Klient) RemoteGetPathSize(opts req.GetPathSizeOptions) (uint64, error) {\n\tvar size uint64\n\n\tkRes, err := k.Tell(\"remote.getPathSize\", opts)\n\tif err != nil {\n\t\treturn size, err\n\t}\n\n\treturn size, kRes.Unmarshal(&size)\n}", "func getRemoteBuildDataFS(repo, commitID string) (rwvfs.FileSystem, string, sourcegraph.RepoRevSpec, error) {\n\tif repo == \"\" {\n\t\terr := errors.New(\"getRemoteBuildDataFS: repo cannot be empty\")\n\t\treturn nil, \"\", sourcegraph.RepoRevSpec{}, err\n\t}\n\tcl := NewAPIClientWithAuthIfPresent()\n\trrepo, _, err := cl.Repos.Get(sourcegraph.RepoSpec{URI: repo}, nil)\n\tif err != nil {\n\t\treturn nil, \"\", sourcegraph.RepoRevSpec{}, err\n\t}\n\n\trepoRevSpec := sourcegraph.RepoRevSpec{RepoSpec: rrepo.RepoSpec(), Rev: commitID, CommitID: commitID}\n\tfs, err := cl.BuildData.FileSystem(repoRevSpec)\n\treturn fs, fmt.Sprintf(\"remote repository (URI %s, commit %s)\", rrepo.URI, commitID), repoRevSpec, err\n}", "func (k *Klient) RemoteCache(r req.Cache, cb func(par *dnode.Partial)) error {\n\tcacheReq := struct {\n\t\treq.Cache\n\t\tProgress dnode.Function `json:\"progress\"`\n\t}{\n\t\tCache: r,\n\t}\n\n\tif cb != nil {\n\t\tcacheReq.Progress = dnode.Callback(cb)\n\t}\n\n\t// No response from cacheFolder currently.\n\t_, err := k.Tell(\"remote.cacheFolder\", cacheReq)\n\treturn err\n}", "func getRemote(project string) string {\n\tsession := sh.NewSession()\n\tsession.SetDir(project)\n\tremote, err := session.Command(\"git\", \"remote\").Command(\"head\", \"-n\", \"1\").Output()\n\t// pipe makes this code unreachable\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn strings.TrimSpace(string(remote))\n}", "func getRemoteBackupS3(r *Restore, conf *config.Config, outFile *os.File) {\n\ts3Conn := session.New(&aws.Config{Region: aws.String(string(conf.S3Region))})\n\n\t// Create the params to pass into the actual downloader\n\tparams := &s3.GetObjectInput{\n\t\tBucket: &conf.S3Bucket,\n\t\tKey: &r.RestorePath,\n\t}\n\n\tlog.Printf(\"[INFO] Downloading %v%v from S3 in %v\", string(conf.S3Bucket), r.RestorePath, string(conf.S3Region))\n\tdownloader := s3manager.NewDownloader(s3Conn)\n\t_, err := downloader.Download(outFile, params)\n\tif err != nil {\n\t\tlog.Fatalf(\"[ERR] Could not download file from S3!: %v\", err)\n\t}\n}", "func (o *OverrideRemote) Remote() string {\n\treturn o.remote\n}", "func (downloader *DatabaseDownloader) RemoteChecksum() (string, error) {\n\n\tresp, err := downloader.doGETRequest(downloader.ChecksumURL)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tresult, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(result), nil\n\n}", "func Remote(user, host, path string) string {\n\treturn fmt.Sprintf(\"ssh://%s@%s/%s\", user, host, path)\n}", "func (client *Client) CopyRemoteDir(ctx context.Context, fromBucket *storage.BucketHandle, from string, toBucket *storage.BucketHandle, to string) error {\n\tif toBucket == nil || fromBucket == nil {\n\t\treturn ErrorNilBucket\n\t}\n\n\tfiles, err := ListRemoteFiles(ctx, fromBucket, FilesFilter{Prefix: from})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar ch = make(chan File, len(files))\n\tvar wg sync.WaitGroup\n\twg.Add(maxThreads)\n\n\tfor i := 0; i < maxThreads; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tfile, ok := <-ch\n\t\t\t\tif !ok {\n\t\t\t\t\twg.Done()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := client.RemoteCopy(ctx, file, fromBucket, toBucket, to); err != nil {\n\t\t\t\t\tlog.Printf(\"failed to copy files between buckets: err: %s\\n\", err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor _, file := range files {\n\t\tch <- file\n\t}\n\n\tclose(ch)\n\twg.Wait()\n\n\treturn nil\n}", "func (g *getter) getRemoteRepository(remote RemoteRepository, branch string) error {\n\tremoteURL := remote.URL()\n\tlocal, err := LocalRepositoryFromURL(remoteURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar (\n\t\tfpath = local.FullPath\n\t\tnewPath = false\n\t)\n\n\t_, err = os.Stat(fpath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tnewPath = true\n\t\t\terr = nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tswitch {\n\tcase newPath:\n\t\tif remoteURL.Scheme == \"codecommit\" {\n\t\t\tlogger.Log(\"clone\", fmt.Sprintf(\"%s -> %s\", remoteURL.Opaque, fpath))\n\t\t} else {\n\t\t\tlogger.Log(\"clone\", fmt.Sprintf(\"%s -> %s\", remoteURL, fpath))\n\t\t}\n\t\tvar (\n\t\t\tlocalRepoRoot = fpath\n\t\t\trepoURL = remoteURL\n\t\t)\n\t\tvcs, ok := vcsRegistry[g.vcs]\n\t\tif !ok {\n\t\t\tvcs, repoURL, err = remote.VCS()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif l := detectLocalRepoRoot(remoteURL.Path, repoURL.Path); l != \"\" {\n\t\t\tlocalRepoRoot = filepath.Join(local.RootPath, remoteURL.Hostname(), l)\n\t\t}\n\n\t\tif remoteURL.Scheme == \"codecommit\" {\n\t\t\trepoURL, _ = url.Parse(remoteURL.Opaque)\n\t\t}\n\t\tif getRepoLock(localRepoRoot) {\n\t\t\treturn vcs.Clone(&vcsGetOption{\n\t\t\t\turl: repoURL,\n\t\t\t\tdir: localRepoRoot,\n\t\t\t\tshallow: g.shallow,\n\t\t\t\tsilent: g.silent,\n\t\t\t\tbranch: branch,\n\t\t\t\trecursive: g.recursive,\n\t\t\t\tbare: g.bare,\n\t\t\t})\n\t\t}\n\t\treturn nil\n\tcase g.update:\n\t\tlogger.Log(\"update\", fpath)\n\t\tvcs, localRepoRoot := local.VCS()\n\t\tif vcs == nil {\n\t\t\treturn fmt.Errorf(\"failed to detect VCS for %q\", fpath)\n\t\t}\n\t\tif getRepoLock(localRepoRoot) {\n\t\t\treturn vcs.Update(&vcsGetOption{\n\t\t\t\tdir: localRepoRoot,\n\t\t\t\tsilent: g.silent,\n\t\t\t\trecursive: g.recursive,\n\t\t\t})\n\t\t}\n\t\treturn nil\n\t}\n\tlogger.Log(\"exists\", fpath)\n\treturn nil\n}", "func RemoteRepo(url, path string) (*Repo, error) {\n\trr, err := vcs.RepoRootForImportPath(url, *verbose)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Repo{\n\t\tPath: path,\n\t\tMaster: rr,\n\t}, nil\n}", "func (o *Object) Remote() string {\n\treturn o.remote\n}", "func (o *Object) Remote() string {\n\treturn o.remote\n}", "func (o *Object) Remote() string {\n\treturn o.remote\n}", "func (o *Object) Remote() string {\n\treturn o.remote\n}", "func (c *Config) GetRemoteHost() string {\n\tif c.sandboxMode {\n\t\treturn fmt.Sprintf(\"sandbox.payfast.co.za\")\n\t}\n\n\treturn fmt.Sprintf(\"www.payfast.co.za\")\n}", "func getRemoteParts() []string {\n\tvar (\n\t\tcmdOut []byte\n\t\terr error\n\t)\n\tif cmdOut, err = exec.Command(\"git\", \"remote\", \"get-url\", \"origin\").Output(); err != nil {\n\t\tlog.Fatal(\"Error executing git command: \", err)\n\t}\n\n\tr := strings.TrimSpace(string(cmdOut))\n\treplaced := replaceString(r)\n\n\t// naive implementation assuming no path to gitlab host\n\ts := strings.Split(replaced, \"/\")\n\tbase := s[:3]\n\tpath := s[3:]\n\treturn []string{strings.Join(base, \"/\"), strings.Join(path, \"/\")}\n}", "func (d Driver) getSecureDiffPath(id, parent string, canBeRemote bool) string {\n\tvar diffDirName string\n\n\tif parent == \"\" || d.isParent(id, parent) {\n\t\tdiffDirName = \"diff\"\n\t} else {\n\t\tdiffDirName = fmt.Sprintf(\"%s-%s\", \"diff\", parent)\n\t}\n\n\tlocalSecureDiffPath := path.Join(d.dir(id), constSecureBaseDirName, diffDirName)\n\tremoteSecureDiffPath := path.Join(d.options.remoteDir, id, constSecureBaseDirName, diffDirName)\n\tlogrus.Debugf(\"secureoverlay2: getSecureDiffPath %s. localSecureDiffPath %s remoteSecureDiffPath\", localSecureDiffPath, remoteSecureDiffPath)\n\tdiffPath := localSecureDiffPath\n\t// remote only \"wins\" if local does not exist and remote exists\n\tif canBeRemote && d.options.remoteDir != \"\" {\n\t\tif b, _ := exists(localSecureDiffPath); !b {\n\t\t\tif b, _ := exists(remoteSecureDiffPath); b {\n\t\t\t\tdiffPath = remoteSecureDiffPath\n\t\t\t}\n\t\t}\n\t}\n\tlogrus.Debugf(\"secureoverlay2: getSecureDiffPath w. id: %s, parent: %s, canBeRemote: %v returns %s\",\n\t\tid, parent, canBeRemote, diffPath)\n\n\treturn diffPath\n}", "func (fs FileStorageSettings) Dir() string {\n\tpath := \"\"\n\tif fs.Type == FileStorageTypeLocal {\n\t\tpath = fs.Local.Path\n\t} else if fs.Type == FileStorageTypeS3 {\n\t\tpath = fs.S3.Key\n\t}\n\treturn filepath.Dir(path)\n}", "func (m *DPAPIMonitorEntry) Remote() string {\n\treturn m.remote\n}", "func (o GetVolumeDataProtectionReplicationOutput) RemoteVolumeLocation() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVolumeDataProtectionReplication) string { return v.RemoteVolumeLocation }).(pulumi.StringOutput)\n}", "func (g *gcs) GetLocation(ctx context.Context, remotePath string) (url string, err error) {\n\tattributes, err := g.bucket.Object(remotePath).Attrs(g.context)\n\tif err != nil {\n\t\treturn\n\t}\n\n\turl = attributes.MediaLink\n\n\treturn\n}", "func getCacheDir() string {\n\tcacheRoot := os.ExpandEnv(\"$HOME/.cache\")\n\tif xdgCache, ok := os.LookupEnv(\"XDG_CACHE_HOME\"); ok {\n\t\tcacheRoot = xdgCache\n\t}\n\treturn filepath.Join(cacheRoot, \"barista\", \"http\")\n}", "func (g *GitLocal) GetRemoteUrl(config *gitcfg.Config, name string) string {\n\treturn g.GitCLI.GetRemoteUrl(config, name)\n}", "func (o *SoftwarerepositoryLocalMachineAllOf) GetDownloadUrl() string {\n\tif o == nil || o.DownloadUrl == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DownloadUrl\n}", "func Dir() string {\n\tif ForceDir != \"\" {\n\t\treturn ForceDir\n\t}\n\tdir := os.Getenv(\"XDG_DATA_HOME\")\n\tif dir != \"\" {\n\t\treturn dir\n\t}\n\tusr, _ := user.Current()\n\tif usr != nil {\n\t\treturn filepath.Join(usr.HomeDir, \".local\", \"share\")\n\t}\n\treturn \"\"\n}", "func (f *Fs) findSharedFolder(ctx context.Context, name string) (id string, err error) {\n\tentries, err := f.listSharedFolders(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor _, entry := range entries {\n\t\tif entry.(*fs.Dir).Remote() == name {\n\t\t\treturn entry.(*fs.Dir).ID(), nil\n\t\t}\n\t}\n\treturn \"\", fs.ErrorDirNotFound\n}", "func GetFolderUrl(folderUid string, slug string) string {\n\treturn fmt.Sprintf(\"/dashboards/f/%s/%s\", folderUid, slug)\n}", "func Dir(strinput2 string, tc net.Conn) string {\n\tnetwork.SendDataMessage(&tc, 4, 7, Responseport, strinput2)\n\ttime.Sleep(100 * time.Millisecond)\n\ttcpconn1, err := tcplisten.Accept()\n\tif err != nil {\n\t\tfmt.Println(\"receive dir error\")\n\t\treturn \"\"\n\t}\n\treadinfo := make([]byte, 30)\n\tfmt.Println(\"begin read from client\")\n\tn, _ := tcpconn1.Read(readinfo)\n\ttcpconn1.Close()\n\tfmt.Println(\"dir now have:\" + network.MessageDealer(readinfo[:n]).Str)\n\treturn network.MessageDealer(readinfo[:n]).Str\n}", "func getMcConfigDir() (string, error) {\n\tif mcCustomConfigDir != \"\" {\n\t\treturn mcCustomConfigDir, nil\n\t}\n\tu, err := user.Current()\n\tif err != nil {\n\t\treturn \"\", NewIodine(iodine.New(err, nil))\n\t}\n\t// For windows the path is slightly different\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\treturn filepath.Join(u.HomeDir, mcConfigWindowsDir), nil\n\tdefault:\n\t\treturn filepath.Join(u.HomeDir, mcConfigDir), nil\n\t}\n}", "func (s *scpSession) GetFile(remoteFile, localFile string) error {\n\tlocalFile = filepath.Clean(localFile)\n\tremoteFile = filepath.Clean(remoteFile)\n\n\tlocalFolder := path.Dir(localFile)\n\tremoteFilename := path.Base(remoteFile)\n\n\t// Check whether the localFile exists.\n\t// If not, we create systematically all parent directories.\n\t// If yes, we check if localFile is a directory or not.\n\t// If it is a directory then, the localFile will be a\n\t// concatenation of directory + remoteFile's filename.\n\t// If not, localFile remains as it is.\n\tfileInfo, err := os.Stat(localFile)\n\tif os.IsNotExist(err) {\n\t\terr := os.MkdirAll(localFolder, 0755)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif fileInfo.IsDir() {\n\t\t\tlocalFile = localFolder + \"/\" + remoteFilename\n\t\t}\n\t}\n\n\treturn s.execSCPSession(SCPGETFILE, remoteFile, func() error {\n\t\treturn s.getFile(localFile)\n\t})\n}", "func (sf SuiteFile) RelDir() string {\n\tdir, _ := filepath.Rel(sf.BaseDir, filepath.Dir(sf.Path))\n\treturn dir\n}", "func (pr LocalPackageReference) FolderPath() string {\n\treturn path.Join(pr.group, pr.version)\n}", "func GetDashboardFolderUrl(isFolder bool, uid string, slug string) string {\n\tif isFolder {\n\t\treturn GetFolderUrl(uid, slug)\n\t}\n\n\treturn GetDashboardUrl(uid, slug)\n}", "func (dp *DevPortal) Download(url, folder string) error {\n\n\t// proxy, insecure are null because we override the client below\n\tdownloader := NewDownload(\n\t\tdp.config.Proxy,\n\t\tdp.config.Insecure,\n\t\tdp.config.SkipAll,\n\t\tdp.config.ResumeAll,\n\t\tdp.config.RestartAll,\n\t\tfalse,\n\t\tdp.config.Verbose,\n\t)\n\t// use authenticated client\n\tdownloader.client = dp.Client\n\n\tdestName := getDestName(url, dp.config.RemoveCommas)\n\tdestName = filepath.Join(filepath.Clean(folder), filepath.Base(destName))\n\n\tif _, err := os.Stat(destName); os.IsNotExist(err) {\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"file\": destName,\n\t\t}).Info(\"Downloading\")\n\n\t\t// download file\n\t\tdownloader.URL = url\n\t\tdownloader.DestName = destName\n\n\t\terr = downloader.Do()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to download file: %v\", err)\n\t\t}\n\n\t} else {\n\t\tlog.Warnf(\"file already exists: %s\", destName)\n\t}\n\n\treturn nil\n}", "func (p *FileInf) DlFolders() error {\r\n\tif p.Progress {\r\n\t\tif p.ShowFileInf {\r\n\t\t\tfmt.Printf(\"File finformation is retrieved from a folder '%s'.\\n\", p.FileName)\r\n\t\t} else {\r\n\t\t\tfmt.Printf(\"Files are downloaded from a folder '%s'.\\n\", p.FileName)\r\n\t\t}\r\n\t\tfmt.Println(\"Getting values to download.\")\r\n\t}\r\n\tfolT := &folderTree{}\r\n\tif p.getOwner() {\r\n\t\tq := \"mimeType='application/vnd.google-apps.folder' and trashed=false\"\r\n\t\tfields := \"files(id,mimeType,name,parents,size),nextPageToken\"\r\n\t\tfm := p.GetListLoop(q, fields)\r\n\t\tfT1 := &folderTr{Search: p.FileID}\r\n\t\tfolT = createFolderTreeID(fm, p.FileID, []string{}, fT1).getDlFoldersS(p.FileName)\r\n\t} else {\r\n\t\tfT2 := &folderTr{Search: p.FileID}\r\n\t\tfolT = p.getAllfoldersRecursively(p.FileID, []string{}, fT2).getDlFoldersS(p.FileName)\r\n\t}\r\n\tfileList := p.getFilesFromFolder(folT)\r\n\tp.dupChkFoldersFiles(fileList)\r\n\tif p.ShowFileInf {\r\n\t\tp.FolderTree = fileList\r\n\t\tp.Msgar = append(p.Msgar, fmt.Sprintf(\"File list in folder '%s' was retrieved.\", p.FileName))\r\n\t\treturn nil\r\n\t}\r\n\tp.Msgar = append(p.Msgar, fmt.Sprintf(\"Files were downloaded from folder '%s'.\", p.FileName))\r\n\tdlres := p.initDownload(fileList)\r\n\tif dlres != nil {\r\n\t\treturn dlres\r\n\t}\r\n\treturn nil\r\n}", "func (k *Kluster) Dir() string {\n\treturn filepath.Dir(k.path)\n}", "func GetInstallDir(pluginName, v string) (string, error) {\n\tallPluginsInstallDir, err := common.GetPluginsInstallDir(pluginName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpluginDir := filepath.Join(allPluginsInstallDir, pluginName)\n\tif v != \"\" {\n\t\tpluginDir = filepath.Join(pluginDir, v)\n\t} else {\n\t\tlatestPlugin, err := pluginInfo.GetLatestInstalledPlugin(pluginDir)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpluginDir = latestPlugin.Path\n\t}\n\treturn pluginDir, nil\n}", "func (o DatasetAzureBlobOutput) Folder() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DatasetAzureBlob) pulumi.StringPtrOutput { return v.Folder }).(pulumi.StringPtrOutput)\n}", "func (u *uploader) getDirectory(req mcstoreapi.DirectoryRequest) (string, error) {\n\tvar (\n\t\tdirID string\n\t\terr error\n\t)\n\tif dirID, err = u.serverAPI.GetDirectory(req); err != nil {\n\t\tapp.Log.Errorf(\"Failed creating directory: %#v/%s\", req, err)\n\t\treturn \"\", err\n\t}\n\treturn dirID, nil\n}", "func (o GetVolumeGroupSapHanaVolumeDataProtectionReplicationOutput) RemoteVolumeLocation() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVolumeGroupSapHanaVolumeDataProtectionReplication) string { return v.RemoteVolumeLocation }).(pulumi.StringOutput)\n}", "func (_DappboxManager *DappboxManagerCaller) ReturnAllDappboxRemoteFolders(opts *bind.CallOpts, dappboxAddress common.Address, index *big.Int) (string, common.Address, common.Address, bool, bool, error) {\n\tvar (\n\t\tret0 = new(string)\n\t\tret1 = new(common.Address)\n\t\tret2 = new(common.Address)\n\t\tret3 = new(bool)\n\t\tret4 = new(bool)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t\tret3,\n\t\tret4,\n\t}\n\terr := _DappboxManager.contract.Call(opts, out, \"returnAllDappboxRemoteFolders\", dappboxAddress, index)\n\treturn *ret0, *ret1, *ret2, *ret3, *ret4, err\n}", "func GetRemoteForURL(repoDir string, remoteURL string, gitter Gitter) (string, error) {\n\t_, config, err := gitter.FindGitConfigDir(repoDir)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to load git config in %s\", repoDir)\n\t}\n\n\tcfg := gitcfg.NewConfig()\n\tdata, err := ioutil.ReadFile(config)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to read git config in %s\", repoDir)\n\t}\n\n\terr = cfg.Unmarshal(data)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to parse git config in %s\", repoDir)\n\t}\n\n\tfor _, remote := range cfg.Remotes {\n\t\tfor _, url := range remote.URLs {\n\t\t\tif url == remoteURL {\n\t\t\t\treturn remote.Name, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", nil\n}", "func (o VolumeDataProtectionReplicationOutput) RemoteVolumeLocation() pulumi.StringOutput {\n\treturn o.ApplyT(func(v VolumeDataProtectionReplication) string { return v.RemoteVolumeLocation }).(pulumi.StringOutput)\n}", "func (o VolumeGroupSapHanaVolumeDataProtectionReplicationOutput) RemoteVolumeLocation() pulumi.StringOutput {\n\treturn o.ApplyT(func(v VolumeGroupSapHanaVolumeDataProtectionReplication) string { return v.RemoteVolumeLocation }).(pulumi.StringOutput)\n}", "func GetRemoteArtifactFiles(artDetails *jfauth.ServiceDetails, repos *[]string) (*list.List, error) {\n\tfolders := make(chan string, 4096)\n\tfiles := make(chan string, 1024)\n\trtfacts := list.New()\n\n\tvar workerg sync.WaitGroup\n\tconst numWorkers = 8\n\tworkerg.Add(numWorkers)\n\tfor i := 0; i < numWorkers; i++ {\n\t\tgo func() {\n\t\t\tgetRemoteArtifactWorker(artDetails, folders, files)\n\t\t\tworkerg.Done()\n\t\t}()\n\t}\n\tjflog.Info(fmt.Sprintf(\"Created %d getRemoteArtifactWorker() go routines\", numWorkers))\n\n\tgo func(rl *[]string, chFolder chan<- string) {\n\t\tfor _, r := range *rl {\n\t\t\tchFolder <- r\n\t\t}\n\t}(repos, folders)\n\tjflog.Info(fmt.Sprintf(\"Pushed initial remote repo's\"))\n\n\tconst getArtiTimeout = 60\n\tvar collectorg sync.WaitGroup\n\tcollectorg.Add(1)\n\tgo func() {\n\t\tdefer collectorg.Done()\n\t\tfor {\n\t\t\ttimeout := time.After(getArtiTimeout * time.Second)\n\t\t\tselect {\n\t\t\tcase f := <-files:\n\t\t\t\trtfacts.PushBack(f)\n\t\t\t\tjflog.Debug(f)\n\t\t\t\tif rtfacts.Len()%1000 == 0 {\n\t\t\t\t\tjflog.Info(fmt.Sprintf(\"collector_goroutine() artifact : %s, rt-count = %d\", f, rtfacts.Len()))\n\t\t\t\t}\n\t\t\tcase <-timeout:\n\t\t\t\tfmt.Printf(\"Timeout after %d seconds\\n\", getArtiTimeout)\n\t\t\t\tjflog.Info(fmt.Printf(\"Timeout after %d seconds\", getArtiTimeout))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tcollectorg.Wait()\n\tjflog.Info(fmt.Sprintf(\"All results collected, collector_goroutine() done, closing folders channel\"))\n\tclose(folders)\n\tworkerg.Wait()\n\tjflog.Info(fmt.Sprintf(\"All getRemoteArtifactWorker() completed, closing files channel\"))\n\tclose(files)\n\n\treturn rtfacts, nil\n}", "func DownloadDir(ctx context.Context, logger log.Logger, bkt BucketReader, originalSrc, src, dst string, options ...DownloadOption) error {\n\tif err := os.MkdirAll(dst, 0750); err != nil {\n\t\treturn errors.Wrap(err, \"create dir\")\n\t}\n\topts := applyDownloadOptions(options...)\n\n\t// The derived Context is canceled the first time a function passed to Go returns a non-nil error or the first\n\t// time Wait returns, whichever occurs first.\n\tg, ctx := errgroup.WithContext(ctx)\n\tg.SetLimit(opts.concurrency)\n\n\tvar downloadedFiles []string\n\tvar m sync.Mutex\n\n\terr := bkt.Iter(ctx, src, func(name string) error {\n\t\tg.Go(func() error {\n\t\t\tdst := filepath.Join(dst, filepath.Base(name))\n\t\t\tif strings.HasSuffix(name, DirDelim) {\n\t\t\t\tif err := DownloadDir(ctx, logger, bkt, originalSrc, name, dst, options...); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tm.Lock()\n\t\t\t\tdownloadedFiles = append(downloadedFiles, dst)\n\t\t\t\tm.Unlock()\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfor _, ignoredPath := range opts.ignoredPaths {\n\t\t\t\tif ignoredPath == strings.TrimPrefix(name, string(originalSrc)+DirDelim) {\n\t\t\t\t\tlevel.Debug(logger).Log(\"msg\", \"not downloading again because a provided path matches this one\", \"file\", name)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err := DownloadFile(ctx, logger, bkt, name, dst); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tm.Lock()\n\t\t\tdownloadedFiles = append(downloadedFiles, dst)\n\t\t\tm.Unlock()\n\t\t\treturn nil\n\t\t})\n\t\treturn nil\n\t})\n\n\tif err == nil {\n\t\terr = g.Wait()\n\t}\n\n\tif err != nil {\n\t\tdownloadedFiles = append(downloadedFiles, dst) // Last, clean up the root dst directory.\n\t\t// Best-effort cleanup if the download failed.\n\t\tfor _, f := range downloadedFiles {\n\t\t\tif rerr := os.RemoveAll(f); rerr != nil {\n\t\t\t\tlevel.Warn(logger).Log(\"msg\", \"failed to remove file on partial dir download error\", \"file\", f, \"err\", rerr)\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func getFolderDestination(fname string) string {\n\tf, err := os.Open(fname)\n\tdefer f.Close()\n\tmanageErrors(err)\n\n\tx, err := exif.Decode(f)\n\tmanageErrors(err)\n\n\tt, err := x.DateTime()\n\tmanageErrors(err)\n\n\treturn RootPath + string(os.PathSeparator) + t.Format(\"2006\") + string(os.PathSeparator) + t.Format(\"01\") + string(os.PathSeparator) + t.Format(\"02\")\n}", "func getDir(location string) string {\n\tdir := viper.GetString(DirFlag)\n\tif dir[len(dir)-1] != '/' {\n\t\tdir = filepath.Join(dir, \"/\")\n\t}\n\treturn os.ExpandEnv(filepath.Join(dir, location))\n}", "func (p *Pebble) DirectoryURL() string {\n\treturn fmt.Sprintf(\"https://%s/dir\", p.config.Pebble.ListenAddress)\n}", "func (f *RPCFile) GetRemoteSize() uint64 {\n\treturn f.file.SizeOnDisk\n}", "func (o *RenamedObjectInfo) Remote() string {\n\treturn o.remote\n}", "func (s *Store) GetRemote(aciURL string) (*Remote, error) {\n\tvar remote *Remote\n\n\terr := s.db.Do(func(tx *sql.Tx) error {\n\t\tvar err error\n\n\t\tremote, err = GetRemote(tx, aciURL)\n\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn remote, nil\n}", "func getURLChecksum(dlURL, tempFile string) (_ string, errOut error) {\n\tif tempFile == \"\" {\n\t\tdownloadDir, err := os.MkdirTemp(\"\", \"bindown\")\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\ttempFile = filepath.Join(downloadDir, \"download\")\n\t\tdefer deferErr(&errOut, func() error {\n\t\t\treturn os.RemoveAll(downloadDir)\n\t\t})\n\t}\n\treturn downloadFile(tempFile, dlURL)\n}", "func computeProgramDirectory() string {\n\tlocation := js.Global().Get(\"location\")\n\turl := location.Get(\"href\").String()\n\turl = filepath.Dir(url)\n\turl = strings.TrimPrefix(url, \"file:/\")\n\tif strings.HasPrefix(url, \"http:/\") {\n\t\turl = strings.TrimPrefix(url, \"http:/\")\n\t\turl = \"http://\" + url\n\t}\n\tif strings.HasPrefix(url, \"https:/\") {\n\t\turl = strings.TrimPrefix(url, \"https:/\")\n\t\turl = \"https://\" + url\n\t}\n\treturn url\n}", "func (f *File) IsRemote() bool {\n\treturn strings.HasPrefix(f.Url, \"http\")\n}", "func (v Video) GetLocation() (string, bool) {\n\tif v.Path != \"\" {\n\t\treturn fmt.Sprintf(\"%v/%v\", v.Path, storage.MasterPlaylistName), false\n\t}\n\treturn v.RemotePath, true\n}", "func GetConfigFolder() string {\n\treturn filepath.Join(helper.Home(), configPath)\n}" ]
[ "0.6257538", "0.62270194", "0.6118162", "0.61103785", "0.6055305", "0.60033774", "0.59513587", "0.59404033", "0.5792233", "0.5764929", "0.5625382", "0.55947894", "0.5577834", "0.5553884", "0.55104315", "0.54651415", "0.543813", "0.5415896", "0.5412922", "0.53885454", "0.5342559", "0.5282548", "0.5280333", "0.52580965", "0.5255199", "0.5222709", "0.52176803", "0.5176079", "0.516546", "0.5158633", "0.51513374", "0.5077285", "0.50643754", "0.5060353", "0.5057381", "0.50439745", "0.50293654", "0.50124073", "0.49906716", "0.49845442", "0.49203748", "0.49162287", "0.48987576", "0.4882279", "0.4879235", "0.48761013", "0.48663983", "0.48636085", "0.48483765", "0.48431948", "0.48429933", "0.48366874", "0.48280406", "0.48242015", "0.48242015", "0.48242015", "0.48242015", "0.48193234", "0.4811392", "0.4799097", "0.4795757", "0.4793973", "0.47765052", "0.4770897", "0.47672588", "0.47647008", "0.4751165", "0.4747598", "0.47352543", "0.4735207", "0.47344807", "0.47307408", "0.47097442", "0.47072062", "0.47068435", "0.47010738", "0.4693825", "0.4689445", "0.468486", "0.4683113", "0.46790114", "0.46775058", "0.46729192", "0.46694174", "0.46668303", "0.46445253", "0.4625746", "0.46240106", "0.46005687", "0.45986557", "0.45984685", "0.45969433", "0.4594736", "0.45890945", "0.4580493", "0.45730245", "0.4572869", "0.45643535", "0.45632696", "0.45625034" ]
0.8045053
0
Retrieves information about the specified version of the specified managed policy, including the policy document. Policies returned by this operation are URLencoded compliant with RFC 3986 ( . You can use a URL decoding method to convert the policy back to plain JSON text. For example, if you use Java, you can use the decode method of the java.net.URLDecoder utility class in the Java SDK. Other languages and SDKs provide similar functionality. To list the available versions for a policy, use ListPolicyVersions . This operation retrieves information about managed policies. To retrieve information about an inline policy that is embedded in a user, group, or role, use GetUserPolicy , GetGroupPolicy , or GetRolePolicy . For more information about the types of policies, see Managed policies and inline policies ( in the IAM User Guide. For more information about managed policy versions, see Versioning for managed policies ( in the IAM User Guide.
func (c *Client) GetPolicyVersion(ctx context.Context, params *GetPolicyVersionInput, optFns ...func(*Options)) (*GetPolicyVersionOutput, error) { if params == nil { params = &GetPolicyVersionInput{} } result, metadata, err := c.invokeOperation(ctx, "GetPolicyVersion", params, optFns, c.addOperationGetPolicyVersionMiddlewares) if err != nil { return nil, err } out := result.(*GetPolicyVersionOutput) out.ResultMetadata = metadata return out, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *ManagedAppPolicy) GetVersion()(*string) {\n return m.version\n}", "func (e *Enforcer) GetPolicy(ctx context.Context) ([][]string, error) {\n\tres, err := e.client.remoteClient.GetPolicy(ctx, &pb.EmptyRequest{Handler: e.handler})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn replyTo2DSlice(res), nil\n}", "func (c *controller) GetPolicy(ctx context.Context, id int64) (*policyModels.Schema, error) {\n\treturn c.pManager.Get(ctx, id)\n}", "func (ps *PolicyStore) GetPolicy(name string) (*Policy, error) {\n\tdefer metrics.MeasureSince([]string{\"policy\", \"get_policy\"}, time.Now())\n\tif ps.lru != nil {\n\t\t// Check for cached policy\n\t\tif raw, ok := ps.lru.Get(name); ok {\n\t\t\treturn raw.(*Policy), nil\n\t\t}\n\t}\n\n\t// Special case the root policy\n\tif name == \"root\" {\n\t\tp := &Policy{Name: \"root\"}\n\t\tif ps.lru != nil {\n\t\t\tps.lru.Add(p.Name, p)\n\t\t}\n\t\treturn p, nil\n\t}\n\n\t// Load the policy in\n\tout, err := ps.view.Get(name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read policy: %v\", err)\n\t}\n\tif out == nil {\n\t\treturn nil, nil\n\t}\n\n\t// In Vault 0.1.X we stored the raw policy, but in\n\t// Vault 0.2 we switch to the PolicyEntry\n\tpolicyEntry := new(PolicyEntry)\n\tvar policy *Policy\n\tif err := out.DecodeJSON(policyEntry); err == nil {\n\t\t// Parse normally\n\t\tp, err := Parse(policyEntry.Raw)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse policy: %v\", err)\n\t\t}\n\t\tp.Name = name\n\t\tpolicy = p\n\n\t} else {\n\t\t// On error, attempt to use V1 parsing\n\t\tp, err := Parse(string(out.Value))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse policy: %v\", err)\n\t\t}\n\t\tp.Name = name\n\n\t\t// V1 used implicit glob, we need to do a fix-up\n\t\tfor _, pp := range p.Paths {\n\t\t\tpp.Glob = true\n\t\t}\n\t\tpolicy = p\n\t}\n\n\tif ps.lru != nil {\n\t\t// Update the LRU cache\n\t\tps.lru.Add(name, policy)\n\t}\n\n\treturn policy, nil\n}", "func PolicyGET(g *gin.Context) {\n\tg.JSON(http.StatusOK, gin.H{\"messge\": \"OK\", \"policy\": conf.VISUAL_NAVIGATION_MOD_POLICY})\n}", "func (c *Client) Policy() (*www.PolicyReply, error) {\n\tresponseBody, err := c.makeRequest(http.MethodGet,\n\t\twww.PoliteiaWWWAPIRoute, www.RoutePolicy, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pr www.PolicyReply\n\terr = json.Unmarshal(responseBody, &pr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshal PolicyReply: %v\", err)\n\t}\n\n\tif c.cfg.Verbose {\n\t\terr := prettyPrintJSON(pr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &pr, nil\n}", "func PolicyGet(client *golangsdk.ServiceClient, clusterId string) (r PolicyResult) {\n\t_, r.Err = client.Get(policyURL(client, clusterId), &r.Body, nil)\n\treturn\n}", "func getPolicy(policyPath string) (policyContent, error) {\n\tvar policyContentStruct policyContent\n\tpolicyContent, err := os.ReadFile(policyPath)\n\tif err != nil {\n\t\treturn policyContentStruct, fmt.Errorf(\"unable to read policy file: %w\", err)\n\t}\n\tif err := json.Unmarshal(policyContent, &policyContentStruct); err != nil {\n\t\treturn policyContentStruct, fmt.Errorf(\"could not parse trust policies from %s: %w\", policyPath, err)\n\t}\n\treturn policyContentStruct, nil\n}", "func (c *Client) GetPolicy(name string) (*Policy, error) {\n\tif name == \"\" {\n\t\treturn nil, errored.Errorf(\"Policy invalid: empty string for name\")\n\t}\n\n\tresp, err := c.etcdClient.Get(context.Background(), c.policy(name), nil)\n\tif err != nil {\n\t\treturn nil, errors.EtcdToErrored(err)\n\t}\n\n\ttc := NewPolicy()\n\tif err := json.Unmarshal([]byte(resp.Node.Value), tc); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttc.Name = name\n\n\terr = tc.Validate()\n\treturn tc, err\n}", "func (r *PolicyRequest) Get(ctx context.Context) (resObj *Policy, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}", "func (m *GroupPolicyDefinition) GetVersion()(*string) {\n val, err := m.GetBackingStore().Get(\"version\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o AclTokenPolicyAttachmentOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AclTokenPolicyAttachment) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}", "func (r *Repository) GetOne(id string, version uint) (*domain.Policy, error) {\n\tm := &model.Policy{}\n\tcondition := \"id = ?\"\n\targs := []interface{}{id}\n\tif version != 0 {\n\t\tcondition = \"id = ? AND version = ?\"\n\t\targs = append(args, version)\n\t}\n\n\tconds := append([]interface{}{condition}, args...)\n\tif err := r.db.Order(\"version desc\").First(m, conds...).Error; err != nil {\n\t\tif err == gorm.ErrRecordNotFound {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tp, err := m.ToDomain()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}", "func (e *CachedEnforcer) GetPolicy() [][]string {\n\treturn e.api.GetPolicy()\n}", "func (o *SnapmirrorCreateRequest) Policy() string {\n\tvar r string\n\tif o.PolicyPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.PolicyPtr\n\treturn r\n}", "func (p *Policy) Get() ([]byte, error) {\n\tresult, err := json.Marshal(p)\n\treturn result, err\n}", "func (c *Client) GetPolicyDocument(input *PolicyDocumentInput) (*PolicyDocument, error) {\n\tvar policyDocument PolicyDocument\n\n\tvar inputBody map[string]interface{} = make(map[string]interface{})\n\n\tif input.ActionsForServices != nil {\n\t\tif input.ActionsForServices.Read != nil && len(input.ActionsForServices.Read) > 0 {\n\t\t\tinputBody[\"service-read\"] = input.ActionsForServices.Read\n\t\t}\n\t\tif input.ActionsForServices.Write != nil && len(input.ActionsForServices.Write) > 0 {\n\t\t\tinputBody[\"service-write\"] = input.ActionsForServices.Write\n\t\t}\n\t\tif input.ActionsForServices.Tagging != nil && len(input.ActionsForServices.Tagging) > 0 {\n\t\t\tinputBody[\"service-tagging\"] = input.ActionsForServices.Tagging\n\t\t}\n\t\tif input.ActionsForServices.PermissionsManagement != nil && len(input.ActionsForServices.PermissionsManagement) > 0 {\n\t\t\tinputBody[\"service-permissions-management\"] = input.ActionsForServices.PermissionsManagement\n\t\t}\n\t\tif input.ActionsForServices.List != nil && len(input.ActionsForServices.List) > 0 {\n\t\t\tinputBody[\"service-list\"] = input.ActionsForServices.List\n\t\t}\n\t\tif input.ActionsForServices.SingleActions != nil && len(input.ActionsForServices.SingleActions) > 0 {\n\t\t\tinputBody[\"single-actions\"] = input.ActionsForServices.SingleActions\n\t\t}\n\t}\n\n\tif input.ActionsForResources != nil {\n\t\tif input.ActionsForResources.Read != nil && len(input.ActionsForResources.Read) > 0 {\n\t\t\tinputBody[\"read\"] = input.ActionsForResources.Read\n\t\t}\n\t\tif input.ActionsForResources.Write != nil && len(input.ActionsForResources.Write) > 0 {\n\t\t\tinputBody[\"write\"] = input.ActionsForResources.Write\n\t\t}\n\t\tif input.ActionsForResources.Tagging != nil && len(input.ActionsForResources.Tagging) > 0 {\n\t\t\tinputBody[\"tagging\"] = input.ActionsForResources.Tagging\n\t\t}\n\t\tif input.ActionsForResources.PermissionsManagement != nil && len(input.ActionsForResources.PermissionsManagement) > 0 {\n\t\t\tinputBody[\"permissions-management\"] = input.ActionsForResources.PermissionsManagement\n\t\t}\n\t\tif input.ActionsForResources.List != nil && len(input.ActionsForResources.List) > 0 {\n\t\t\tinputBody[\"list\"] = input.ActionsForResources.List\n\t\t}\n\t}\n\n\tif input.Overrides != nil {\n\t\tif input.Overrides.SkipResourceConstraints != nil && len(input.Overrides.SkipResourceConstraints) > 0 {\n\t\t\tinputBody[\"skip-resource-constraints\"] = input.Overrides.SkipResourceConstraints\n\t\t}\n\t}\n\n\tif len(input.ExcludeActions) > 0 {\n\t\tinputBody[\"exclude-actions\"] = input.ExcludeActions\n\t}\n\n\tfmt.Println(inputBody)\n\n\trequestBody, err := json.Marshal(inputBody)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := c.newRequest(requestBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresBody, err := c.doRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(resBody, &policyDocument)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &policyDocument, nil\n}", "func (client IdentityClient) getPolicy(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/policies/{policyId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response GetPolicyResponse\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 ReadPolicy(src io.Reader) (*policyv1.Policy, error) {\n\tpolicy := &policyv1.Policy{}\n\tif err := util.ReadJSONOrYAML(src, policy); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn policy, nil\n}", "func GetPolicy(serviceName string, baseUrl string) (*Service, error) {\n\tclient := http.Client{}\n\treq, err := http.NewRequest(\"GET\", baseUrl + policyEndpoint + serviceName, nil)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Request to Apache Ranger failed\", err)\n\t\treturn nil, err\n\t}\n\n\tparams := req.URL.Query()\n\tparams.Add(pluginId, serviceName + string(\"@bla\"))\n\n\treq.URL.RawQuery = params.Encode()\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Request to Apache Ranger failed\", err)\n\t\treturn nil, err\n\t}\n\n\tdata, _ := ioutil.ReadAll(resp.Body)\n\n\tvar service Service\n\n\terr = json.Unmarshal(data, &service)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Could not unmarshal json data\", err)\n\t\treturn nil, err\n\t}\n\n\treturn &service, nil\n}", "func (client IdentityClient) GetPolicy(ctx context.Context, request GetPolicyRequest) (response GetPolicyResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.getPolicy, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = GetPolicyResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = GetPolicyResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(GetPolicyResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into GetPolicyResponse\")\n\t}\n\treturn\n}", "func (e *SyncedEnforcer) GetPolicy() [][]string {\n\te.m.RLock()\n\tdefer e.m.RUnlock()\n\treturn e.Enforcer.GetPolicy()\n}", "func (m *InformationProtection) GetPolicy()(InformationProtectionPolicyable) {\n val, err := m.GetBackingStore().Get(\"policy\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(InformationProtectionPolicyable)\n }\n return nil\n}", "func (o BucketOutput) Policy() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Bucket) pulumi.StringPtrOutput { return v.Policy }).(pulumi.StringPtrOutput)\n}", "func (c *PolicyService) GetPolicy(opt *GetPolicyOptions, options ...OptionFunc) ([]*Policy, *Response, error) {\n\n\treq, err := c.client.newRequest(\"GET\", \"core/credentials/Policy\", opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif opt.ProductKey == nil {\n\t\treturn nil, nil, ErrMissingProductKey\n\t}\n\n\treq.Header.Set(\"Api-Version\", CredentialsAPIVersion)\n\treq.Header.Set(\"X-Product-Key\", *opt.ProductKey)\n\n\tvar policyGetResponse []*Policy\n\n\tresp, err := c.client.Do(req, &policyGetResponse)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\t// Set ProductKey\n\tfor _, policy := range policyGetResponse {\n\t\tpolicy.ProductKey = *opt.ProductKey\n\t}\n\treturn policyGetResponse, resp, err\n}", "func (p *SdkPolicyManager) Update(\n\tctx context.Context,\n\treq *api.SdkOpenStoragePolicyUpdateRequest,\n) (*api.SdkOpenStoragePolicyUpdateResponse, error) {\n\tif req.GetStoragePolicy().GetName() == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Must supply a Storage Policy Name\")\n\t}\n\n\tif req.GetStoragePolicy().GetPolicy() == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Must supply Volume Specs\")\n\t}\n\n\t// Get Existing details to check access\n\toldPolicy, err := p.Inspect(ctx,\n\t\t&api.SdkOpenStoragePolicyInspectRequest{\n\t\t\tName: req.GetStoragePolicy().GetName(),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// update user must have write acess\n\tif !oldPolicy.GetStoragePolicy().IsPermitted(ctx, api.Ownership_Write) {\n\t\treturn nil, status.Errorf(codes.PermissionDenied, \"Cannot update storage policy\")\n\t}\n\n\tm := jsonpb.Marshaler{OrigName: true}\n\tupdateStr, err := m.MarshalToString(req.GetStoragePolicy())\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"Json Marshal failed for policy %s: %v\", req.GetStoragePolicy().GetName(), err)\n\t}\n\n\t// check ownership update is request\n\tif req.GetStoragePolicy().GetOwnership() != nil {\n\t\tif oldPolicy.StoragePolicy.Ownership == nil {\n\t\t\toldPolicy.StoragePolicy.Ownership = &api.Ownership{}\n\t\t}\n\t\tuser, _ := auth.NewUserInfoFromContext(ctx)\n\t\t// we run through ownership for update to check whether given user\n\t\t// is administrator, only admin can update ownership details\n\t\tif err := oldPolicy.StoragePolicy.Ownership.Update(req.GetStoragePolicy().GetOwnership(), user); err != nil {\n\t\t\tlogrus.Errorf(\"Error updating ownership: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t_, err = kvdb.Instance().Update(prefixWithName(req.GetStoragePolicy().GetName()), updateStr, 0)\n\tif err == kvdb.ErrNotFound {\n\t\treturn nil, status.Errorf(codes.NotFound, \"Storage Policy %s not found\", req.GetStoragePolicy().GetPolicy())\n\t} else if err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"Failed to update storage policy: %v\", err)\n\t}\n\n\tlogrus.Infof(\"Storage Policy %v is updated\", req.GetStoragePolicy().GetName())\n\treturn &api.SdkOpenStoragePolicyUpdateResponse{}, nil\n}", "func (o *VolumeExportAttributesType) Policy() string {\n\tvar r string\n\tif o.PolicyPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.PolicyPtr\n\treturn r\n}", "func (o ReplicaExternalKeyOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReplicaExternalKey) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}", "func (s *Storage) GetPolicy(ctx context.Context, ID int64) (*Policy, error) {\n\tvar policy Policy\n\terr := s.db.QueryRowContext(ctx, `SELECT query_policy($1);`, ID).Scan(&policy)\n\tif err != nil {\n\t\treturn nil, s.database.ProcessError(err)\n\t}\n\n\treturn &policy, nil\n}", "func (c *Client) GetPolicy(ctx context.Context, r ResourceWithPolicy) (*Policy, error) {\n\tu, v, body, err := r.GetPolicy(c.Config.BasePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := dcl.SendRequest(ctx, c.Config, v, u, body, c.Config.RetryProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Response.Body.Close()\n\tb, err := ioutil.ReadAll(resp.Response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp := &Policy{}\n\tif err := json.Unmarshal(b, p); err != nil {\n\t\treturn nil, err\n\t}\n\tp.Resource = r\n\treturn p, nil\n}", "func PolicyVersionForDomain(domain string) (string, error) {\n\t// Check TXT record.\n\tts, err := lookupTXT(txtHost + \".\" + domain)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor _, t := range ts {\n\t\tkv := map[string]string{}\n\t\tfor _, p := range strings.Split(t, \";\") {\n\t\t\tp := strings.TrimSpace(p)\n\t\t\tps := strings.SplitN(p, \"=\", 2)\n\t\t\tif len(ps) != 2 {\n\t\t\t\t// Every pair should be key=value.\n\t\t\t\terr = fmt.Errorf(\"invalid format (%v)\", p)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, ok := kv[ps[0]]; ok {\n\t\t\t\t// Duplicate key.\n\t\t\t\terr = fmt.Errorf(\"duplicate key (%v)\", ps[0])\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tkv[ps[0]] = strings.TrimSpace(ps[1])\n\t\t}\n\t\tif kv[\"v\"] != allowedVersion {\n\t\t\t// Wrong version.\n\t\t\terr = fmt.Errorf(`invalid or missing version (\"%v\")`, kv[\"v\"])\n\t\t\tcontinue\n\t\t}\n\t\tif id, ok := kv[\"id\"]; !ok {\n\t\t\t// Missing ID.\n\t\t\terr = fmt.Errorf(`missing \"id\"`)\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn id, nil\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn \"\", fmt.Errorf(\"no policy found\")\n}", "func (c readOnlyAuthorizationCache) GetPolicy(ctx kapi.Context, name string) (*authorizationapi.Policy, error) {\n\tnamespace, _ := kapi.NamespaceFrom(ctx)\n\n\tif namespaceRefersToCluster(namespace) {\n\t\tclusterPolicy, err := c.ReadOnlyClusterPolicies().Get(name)\n\t\tif err != nil {\n\t\t\treturn &authorizationapi.Policy{}, err\n\t\t}\n\t\treturn authorizationapi.ToPolicy(clusterPolicy), nil\n\t} else {\n\t\tpolicy, err := c.ReadOnlyPolicies(namespace).Get(name)\n\t\tif err != nil {\n\t\t\treturn &authorizationapi.Policy{}, err\n\t\t}\n\t\treturn policy, nil\n\t}\n}", "func (r *Bucket) Policy() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"policy\"])\n}", "func (f *Factory) GetPolicyStatement() (string, error) {\n\t// Perform checks\n\tif len(f.accountID) == 0 {\n\t\treturn \"\", errors.New(AccountIDMissingErr)\n\t}\n\n\tif len(f.region) == 0 {\n\t\treturn \"\", errors.New(RegionMissingErr)\n\t}\n\n\tif len(f.partition) == 0 {\n\t\treturn \"\", errors.New(PartitionMissingErr)\n\t}\n\n\t// Replace AWS placeholders\n\tt := fmt.Sprintf(iamTemplate, strings.Join(f.policies, \",\"))\n\tt = strings.ReplaceAll(t, \"${AWS::Partition}\", f.partition)\n\tt = strings.ReplaceAll(t, \"${AWS::Region}\", f.region)\n\tt = strings.ReplaceAll(t, \"${AWS::AccountId}\", f.accountID)\n\n\t// Return the policy document\n\treturn t, nil\n}", "func (o UserPolicyOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *UserPolicy) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}", "func (o *SSHAuthorizationPolicy) Version() int {\n\n\treturn 1\n}", "func (m *MockClient) GetPolicyVersion(input *iam.GetPolicyVersionInput) (*iam.GetPolicyVersionOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPolicyVersion\", input)\n\tret0, _ := ret[0].(*iam.GetPolicyVersionOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (csapr ContainersSetAccessPolicyResponse) Version() string {\n\treturn csapr.rawResponse.Header.Get(\"x-ms-version\")\n}", "func (p *PolicyService) List() (policies *PolicyListResult, err error) {\n\terr = p.client.magicRequestDecoder(\"GET\", \"/policies\", nil, &policies)\n\treturn\n}", "func (*GetPolicyResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_policy_proto_rawDescGZIP(), []int{3}\n}", "func (c *Clientset) Policy() policyv1beta1.PolicyV1beta1Interface {\n\treturn c.PolicyV1beta1()\n}", "func (km KeyValueMap) Policy() string {\n\treturn km[kmPolicy]\n}", "func (s *DefaultStore) GetPolicy(policyGen object.Generation) (*lang.Policy, object.Generation, error) {\n\t// todo should we use RWMutex for get/update policy?\n\tpolicyData, err := s.GetPolicyData(policyGen)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn s.getPolicyFromData(policyData)\n}", "func explainPolicy(userCred mcclient.TokenCredential, policyReq jsonutils.JSONObject, policyData *sPolicyData) ([]string, rbacutils.SPolicyResult, rbacutils.SPolicyResult, error) {\n\t_, request, result, userResult, err := explainPolicyInternal(userCred, policyReq, policyData)\n\treturn request, result, userResult, err\n}", "func (e *Enforcer) GetPolicy() [][]string {\n\treturn e.GetNamedPolicy(\"p\")\n}", "func (opa *client) EvaluatePolicy(policy string, input []byte) (*EvaluatePolicyResponse, error) {\n\tlog := opa.logger.Named(\"Evalute Policy\")\n\n\trequest, err := json.Marshal(&EvalutePolicyRequest{Input: input})\n\tif err != nil {\n\t\tlog.Error(\"failed to encode OPA input\", zap.Error(err), zap.String(\"input\", string(input)))\n\t\treturn nil, fmt.Errorf(\"failed to encode OPA input: %s\", err)\n\t}\n\n\thttpResponse, err := opa.httpClient.Post(opa.getDataQueryURL(getOpaPackagePath(policy)), \"application/json\", bytes.NewReader(request))\n\tif err != nil {\n\t\tlog.Error(\"http request to OPA failed\", zap.Error(err))\n\t\treturn nil, fmt.Errorf(\"http request to OPA failed: %s\", err)\n\t}\n\tif httpResponse.StatusCode != http.StatusOK {\n\t\tlog.Error(\"http response status from OPA not OK\", zap.Any(\"status\", httpResponse.Status))\n\t\treturn nil, fmt.Errorf(\"http response status not OK\")\n\t}\n\n\tresponse := &EvaluatePolicyResponse{}\n\terr = json.NewDecoder(httpResponse.Body).Decode(&response)\n\tif err != nil {\n\t\tlog.Error(\"failed to decode OPA result\", zap.Error(err))\n\t\treturn nil, fmt.Errorf(\"failed to decode OPA result: %s\", err)\n\t}\n\n\treturn response, nil\n}", "func (*PolicyResponse) Descriptor() ([]byte, []int) {\n\treturn file_interservice_license_control_license_control_proto_rawDescGZIP(), []int{3}\n}", "func (o CloudConfigurationRuleOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CloudConfigurationRule) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}", "func (o TopicPolicyOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *TopicPolicy) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}", "func (c *applicationUsecaseImpl) DetailPolicy(ctx context.Context, app *model.Application, policyName string) (*apisv1.DetailPolicyResponse, error) {\n\tvar policy = model.ApplicationPolicy{\n\t\tAppPrimaryKey: app.PrimaryKey(),\n\t\tName: policyName,\n\t}\n\terr := c.ds.Get(ctx, &policy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &apisv1.DetailPolicyResponse{\n\t\tPolicyBase: *c.converPolicyModelToBase(&policy),\n\t}, nil\n}", "func (nri *NodeReportItem) GetPolicyWithRev() string {\n\n\tif nri.Policy == \"\" {\n\t\treturn \"no policy\"\n\t}\n\n\treturn fmt.Sprintf(\"%s (rev %s)\", nri.Policy, nri.PolicyRev)\n}", "func (a *ACL) GetPolicy(args *structs.ACLPolicyResolveLegacyRequest, reply *structs.ACLPolicyResolveLegacyResponse) error {\n\tif done, err := a.srv.forward(\"ACL.GetPolicy\", args, args, reply); done {\n\t\treturn err\n\t}\n\n\t// Verify we are allowed to serve this request\n\tif a.srv.config.ACLDatacenter != a.srv.config.Datacenter {\n\t\treturn acl.ErrDisabled\n\t}\n\n\t// Get the policy via the cache\n\tparent := a.srv.config.ACLDefaultPolicy\n\n\tpolicy, err := a.srv.acls.GetMergedPolicyForToken(args.ACL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// translates the structures internals to most closely match what could be expressed in the original rule language\n\tpolicy = policy.ConvertToLegacy()\n\n\t// Generate an ETag\n\tetag := makeACLETag(parent, policy)\n\n\t// Setup the response\n\treply.ETag = etag\n\treply.TTL = a.srv.config.ACLTokenTTL\n\ta.srv.setQueryMeta(&reply.QueryMeta)\n\n\t// Only send the policy on an Etag mis-match\n\tif args.ETag != etag {\n\t\treply.Parent = parent\n\t\treply.Policy = policy\n\t}\n\treturn nil\n}", "func Policy() status.Policy {\n\treturn status.Policy{\n\t\tDeps: status.Dependencies{\n\t\t\tConfigReader: config.NewGitconfigDataSource(gitconfig.NewDataSource()),\n\t\t\tStateReader: state.NewGitConfigDataSource(gitconfig.NewDataSource()),\n\t\t\tActivationValidator: activation.NewGitConfigDataSource(gitconfig.NewDataSource()),\n\t\t},\n\t}\n}", "func (nri *NodeReportItem) GetPolicy() string {\n\n\tif nri.Policy == \"\" {\n\t\treturn \"no policy\"\n\t}\n\n\treturn nri.Policy\n}", "func (pg *PolicyGroup) GetPolicy() *api.Policy {\n\treturn pg.Policy\n}", "func (r *DeviceManagementExchangeOnPremisesPolicyRequest) Get(ctx context.Context) (resObj *DeviceManagementExchangeOnPremisesPolicy, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}", "func (o *MicrosoftGraphWindows10CompliancePolicy) GetVersion() int32 {\n\tif o == nil || o.Version == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (*Policy) Descriptor() ([]byte, []int) {\n\treturn file_interservice_license_control_license_control_proto_rawDescGZIP(), []int{4}\n}", "func (o ArgoCDSpecRbacOutput) Policy() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecRbac) *string { return v.Policy }).(pulumi.StringPtrOutput)\n}", "func (s PolicyVersion) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *policies) Read(ctx context.Context, policyID string) (*Policy, error) {\n\tif !validStringID(&policyID) {\n\t\treturn nil, ErrInvalidPolicyID\n\t}\n\n\tu := fmt.Sprintf(\"policies/%s\", url.QueryEscape(policyID))\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := &Policy{}\n\terr = req.Do(ctx, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, err\n}", "func GetPolicyList(id string) *PolicyList {\n\tpolicyList := PolicyList{ID: id}\n\texisted, err := ormManager.engine.Get(&policyList)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif existed {\n\t\treturn &policyList\n\t}\n\treturn nil\n}", "func (c *Clientset) PolicyV1() policyv1.PolicyV1Interface {\n\treturn c.policyV1\n}", "func (c *VaultController) reconcilePolicy(vPolicy *policyapi.VaultPolicy, pClient policy.Policy) error {\n\t// create or update policy\n\t// its safe to call multiple times\n\n\tdoc := vPolicy.Spec.PolicyDocument\n\tif vPolicy.Spec.PolicyDocument == \"\" && vPolicy.Spec.Policy != nil {\n\t\tdata, err := json.Marshal(vPolicy.Spec.Policy)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to serialize VaultPolicy %s/%s. Reason: %v\", vPolicy.Namespace, vPolicy.Name, err)\n\t\t}\n\t\tdoc = string(data)\n\t}\n\n\terr := pClient.EnsurePolicy(vPolicy.PolicyName(), doc)\n\tif err != nil {\n\t\t_, err2 := patchutil.UpdateVaultPolicyStatus(\n\t\t\tcontext.TODO(),\n\t\t\tc.extClient.PolicyV1alpha1(),\n\t\t\tvPolicy.ObjectMeta,\n\t\t\tfunc(status *policyapi.VaultPolicyStatus) *policyapi.VaultPolicyStatus {\n\t\t\t\tstatus.Phase = policyapi.PolicyFailed\n\t\t\t\tstatus.Conditions = kmapi.SetCondition(status.Conditions, kmapi.Condition{\n\t\t\t\t\tType: kmapi.ConditionFailed,\n\t\t\t\t\tStatus: core.ConditionTrue,\n\t\t\t\t\tReason: \"FailedToPutPolicy\",\n\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t})\n\t\t\t\treturn status\n\t\t\t},\n\t\t\tmetav1.UpdateOptions{},\n\t\t)\n\t\treturn utilerrors.NewAggregate([]error{err2, err})\n\t}\n\n\t// update status\n\t_, err = patchutil.UpdateVaultPolicyStatus(\n\t\tcontext.TODO(),\n\t\tc.extClient.PolicyV1alpha1(),\n\t\tvPolicy.ObjectMeta,\n\t\tfunc(status *policyapi.VaultPolicyStatus) *policyapi.VaultPolicyStatus {\n\t\t\tstatus.ObservedGeneration = vPolicy.Generation\n\t\t\tstatus.Phase = policyapi.PolicySuccess\n\t\t\tstatus.Conditions = kmapi.RemoveCondition(status.Conditions, kmapi.ConditionFailed)\n\t\t\tstatus.Conditions = kmapi.SetCondition(status.Conditions, kmapi.Condition{\n\t\t\t\tType: kmapi.ConditionAvailable,\n\t\t\t\tStatus: core.ConditionTrue,\n\t\t\t\tReason: \"Provisioned\",\n\t\t\t\tMessage: \"policy is ready to use\",\n\t\t\t})\n\t\t\treturn status\n\t\t},\n\t\tmetav1.UpdateOptions{},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Successfully processed VaultPolicy: %s/%s\", vPolicy.Namespace, vPolicy.Name)\n\treturn nil\n}", "func (o ArgoCDSpecRbacPtrOutput) Policy() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecRbac) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Policy\n\t}).(pulumi.StringPtrOutput)\n}", "func (c *controller) GetPolicyByName(ctx context.Context, projectID int64, name string) (*policyModels.Schema, error) {\n\treturn c.pManager.GetByName(ctx, projectID, name)\n}", "func newPolicy() *Policy {\n\tp := &Policy{ContractMD: *interop.NewContractMD(policyName)}\n\n\tp.ContractID = policyContractID\n\tp.Manifest.Features |= smartcontract.HasStorage\n\n\tdesc := newDescriptor(\"getMaxTransactionsPerBlock\", smartcontract.IntegerType)\n\tmd := newMethodAndPrice(p.getMaxTransactionsPerBlock, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getMaxBlockSize\", smartcontract.IntegerType)\n\tmd = newMethodAndPrice(p.getMaxBlockSize, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getFeePerByte\", smartcontract.IntegerType)\n\tmd = newMethodAndPrice(p.getFeePerByte, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getBlockedAccounts\", smartcontract.ArrayType)\n\tmd = newMethodAndPrice(p.getBlockedAccounts, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getMaxBlockSystemFee\", smartcontract.IntegerType)\n\tmd = newMethodAndPrice(p.getMaxBlockSystemFee, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"setMaxBlockSize\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setMaxBlockSize, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"setMaxTransactionsPerBlock\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setMaxTransactionsPerBlock, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"setFeePerByte\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setFeePerByte, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"setMaxBlockSystemFee\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setMaxBlockSystemFee, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"blockAccount\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"account\", smartcontract.Hash160Type))\n\tmd = newMethodAndPrice(p.blockAccount, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"unblockAccount\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"account\", smartcontract.Hash160Type))\n\tmd = newMethodAndPrice(p.unblockAccount, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"name\", smartcontract.StringType)\n\tmd = newMethodAndPrice(nameMethod(policyName), 0, smartcontract.NoneFlag)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"onPersist\", smartcontract.VoidType)\n\tmd = newMethodAndPrice(getOnPersistWrapper(p.OnPersist), 0, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"postPersist\", smartcontract.VoidType)\n\tmd = newMethodAndPrice(getOnPersistWrapper(postPersistBase), 0, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\treturn p\n}", "func (*GetPolicyRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_policy_proto_rawDescGZIP(), []int{2}\n}", "func (o NetworkPolicyOutput) ApiVersion() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NetworkPolicy) pulumi.StringOutput { return v.ApiVersion }).(pulumi.StringOutput)\n}", "func (r *Referrer) GetPolicy() Policy {\n\treturn r.policy\n}", "func (m *GovernancePolicy) GetNotificationPolicy()(GovernanceNotificationPolicyable) {\n val, err := m.GetBackingStore().Get(\"notificationPolicy\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(GovernanceNotificationPolicyable)\n }\n return nil\n}", "func (mgr *LocalHashMapDBMgr) Policy() string {\n\treturn mgr.policy\n}", "func ExampleProtectionPoliciesClient_Get_getAzureIaasVmProtectionPolicyDetails() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armrecoveryservicesbackup.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewProtectionPoliciesClient().Get(ctx, \"NetSDKTestRsVault\", \"SwaggerTestRg\", \"testPolicy1\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.ProtectionPolicyResource = armrecoveryservicesbackup.ProtectionPolicyResource{\n\t// \tName: to.Ptr(\"testPolicy1\"),\n\t// \tType: to.Ptr(\"Microsoft.RecoveryServices/vaults/backupPolicies\"),\n\t// \tID: to.Ptr(\"/Subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/SwaggerTestRg/providers/Microsoft.RecoveryServices/vaults/NetSDKTestRsVault/backupPolicies/testPolicy1\"),\n\t// \tProperties: &armrecoveryservicesbackup.AzureIaaSVMProtectionPolicy{\n\t// \t\tBackupManagementType: to.Ptr(\"AzureIaasVM\"),\n\t// \t\tProtectedItemsCount: to.Ptr[int32](0),\n\t// \t\tRetentionPolicy: &armrecoveryservicesbackup.LongTermRetentionPolicy{\n\t// \t\t\tRetentionPolicyType: to.Ptr(\"LongTermRetentionPolicy\"),\n\t// \t\t\tDailySchedule: &armrecoveryservicesbackup.DailyRetentionSchedule{\n\t// \t\t\t\tRetentionDuration: &armrecoveryservicesbackup.RetentionDuration{\n\t// \t\t\t\t\tCount: to.Ptr[int32](1),\n\t// \t\t\t\t\tDurationType: to.Ptr(armrecoveryservicesbackup.RetentionDurationTypeDays),\n\t// \t\t\t\t},\n\t// \t\t\t\tRetentionTimes: []*time.Time{\n\t// \t\t\t\t\tto.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2018-01-24T02:00:00Z\"); return t}())},\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\tSchedulePolicy: &armrecoveryservicesbackup.SimpleSchedulePolicy{\n\t// \t\t\t\tSchedulePolicyType: to.Ptr(\"SimpleSchedulePolicy\"),\n\t// \t\t\t\tScheduleRunFrequency: to.Ptr(armrecoveryservicesbackup.ScheduleRunTypeDaily),\n\t// \t\t\t\tScheduleRunTimes: []*time.Time{\n\t// \t\t\t\t\tto.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2018-01-24T02:00:00Z\"); return t}())},\n\t// \t\t\t\t\tScheduleWeeklyFrequency: to.Ptr[int32](0),\n\t// \t\t\t\t},\n\t// \t\t\t\tTimeZone: to.Ptr(\"Pacific Standard Time\"),\n\t// \t\t\t},\n\t// \t\t}\n}", "func ExampleProtectionPoliciesClient_Get_getAzureIaasVmEnhancedProtectionPolicyDetails() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armrecoveryservicesbackup.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewProtectionPoliciesClient().Get(ctx, \"NetSDKTestRsVault\", \"SwaggerTestRg\", \"v2-daily-sample\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.ProtectionPolicyResource = armrecoveryservicesbackup.ProtectionPolicyResource{\n\t// \tName: to.Ptr(\"v2-daily-sample\"),\n\t// \tType: to.Ptr(\"Microsoft.RecoveryServices/vaults/backupPolicies\"),\n\t// \tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/SwaggerTestRg/providers/Microsoft.RecoveryServices/vaults/NetSDKTestRsVault/backupPolicies/v2-daily-sample\"),\n\t// \tProperties: &armrecoveryservicesbackup.AzureIaaSVMProtectionPolicy{\n\t// \t\tBackupManagementType: to.Ptr(\"AzureIaasVM\"),\n\t// \t\tProtectedItemsCount: to.Ptr[int32](0),\n\t// \t\tInstantRpRetentionRangeInDays: to.Ptr[int32](30),\n\t// \t\tPolicyType: to.Ptr(armrecoveryservicesbackup.IAASVMPolicyTypeV2),\n\t// \t\tRetentionPolicy: &armrecoveryservicesbackup.LongTermRetentionPolicy{\n\t// \t\t\tRetentionPolicyType: to.Ptr(\"LongTermRetentionPolicy\"),\n\t// \t\t\tDailySchedule: &armrecoveryservicesbackup.DailyRetentionSchedule{\n\t// \t\t\t\tRetentionDuration: &armrecoveryservicesbackup.RetentionDuration{\n\t// \t\t\t\t\tCount: to.Ptr[int32](1),\n\t// \t\t\t\t\tDurationType: to.Ptr(armrecoveryservicesbackup.RetentionDurationTypeDays),\n\t// \t\t\t\t},\n\t// \t\t\t\tRetentionTimes: []*time.Time{\n\t// \t\t\t\t\tto.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2018-01-24T02:00:00Z\"); return t}())},\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\tSchedulePolicy: &armrecoveryservicesbackup.SimpleSchedulePolicyV2{\n\t// \t\t\t\tSchedulePolicyType: to.Ptr(\"SimpleSchedulePolicyV2\"),\n\t// \t\t\t\tDailySchedule: &armrecoveryservicesbackup.DailySchedule{\n\t// \t\t\t\t\tScheduleRunTimes: []*time.Time{\n\t// \t\t\t\t\t\tto.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2018-01-24T10:00:00Z\"); return t}())},\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tScheduleRunFrequency: to.Ptr(armrecoveryservicesbackup.ScheduleRunTypeDaily),\n\t// \t\t\t\t},\n\t// \t\t\t\tTimeZone: to.Ptr(\"Pacific Standard Time\"),\n\t// \t\t\t},\n\t// \t\t}\n}", "func (reg *defaultRegistry) GetLastRevisionForPolicy(policyGen runtime.Generation) (*engine.Revision, error) {\n\t// TODO: this method is slow, needs indexes\n\tvar revision *engine.Revision\n\terr := reg.store.Find(engine.TypeRevision.Kind, &revision, store.WithKey(engine.RevisionKey), store.WithWhereEq(\"PolicyGen\", policyGen), store.WithGetLast())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn revision, nil\n}", "func (o ApplicationStatusPtrOutput) Policy() ApplicationStatusPolicyArrayOutput {\n\treturn o.ApplyT(func(v *ApplicationStatus) []ApplicationStatusPolicy {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Policy\n\t}).(ApplicationStatusPolicyArrayOutput)\n}", "func GetPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *PolicyState, opts ...pulumi.ResourceOption) (*Policy, error) {\n\tvar resource Policy\n\terr := ctx.ReadResource(\"aws-native:iot:Policy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (a *SyncApiService) GetTargetPolicy(ctx context.Context, targetPolicyId string) (TargetPolicies, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t \tsuccessPayload TargetPolicies\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/platform/1/sync/target/policies/{TargetPolicyId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"TargetPolicyId\"+\"}\", fmt.Sprintf(\"%v\", targetPolicyId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn successPayload, localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\n\n\treturn successPayload, localVarHttpResponse, err\n}", "func (r policyResult) Extract() (*Policy, error) {\n\tvar s struct {\n\t\tPolicy *Policy `json:\"policy\"`\n\t}\n\terr := r.ExtractInto(&s)\n\treturn s.Policy, err\n}", "func GetPolicy(file []byte) (clusterPolicies []*v1.ClusterPolicy, errors []error) {\n\tpolicies, err := SplitYAMLDocuments(file)\n\tif err != nil {\n\t\terrors = append(errors, err)\n\t\treturn clusterPolicies, errors\n\t}\n\n\tfor _, thisPolicyBytes := range policies {\n\t\tpolicyBytes, err := yaml.ToJSON(thisPolicyBytes)\n\t\tif err != nil {\n\t\t\terrors = append(errors, fmt.Errorf(fmt.Sprintf(\"failed to convert json. error: %v\", err)))\n\t\t\tcontinue\n\t\t}\n\n\t\tpolicy := &v1.ClusterPolicy{}\n\t\tif err := json.Unmarshal(policyBytes, policy); err != nil {\n\t\t\terrors = append(errors, fmt.Errorf(fmt.Sprintf(\"failed to decode policy. error: %v\", err)))\n\t\t\tcontinue\n\t\t}\n\n\t\tif !(policy.TypeMeta.Kind == \"ClusterPolicy\" || policy.TypeMeta.Kind == \"Policy\") {\n\t\t\terrors = append(errors, fmt.Errorf(fmt.Sprintf(\"resource %v is not a policy/clusterPolicy\", policy.Name)))\n\t\t\tcontinue\n\t\t}\n\t\tclusterPolicies = append(clusterPolicies, policy)\n\t}\n\n\treturn clusterPolicies, errors\n}", "func ExampleManagementPoliciesClient_Get() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armstorage.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewManagementPoliciesClient().Get(ctx, \"res6977\", \"sto2527\", armstorage.ManagementPolicyNameDefault, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.ManagementPolicy = armstorage.ManagementPolicy{\n\t// \tName: to.Ptr(\"DefaultManagementPolicy\"),\n\t// \tType: to.Ptr(\"Microsoft.Storage/storageAccounts/managementPolicies\"),\n\t// \tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/res7231/providers/Microsoft.Storage/storageAccounts/sto288/managementPolicies/default\"),\n\t// \tProperties: &armstorage.ManagementPolicyProperties{\n\t// \t\tLastModifiedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2018-06-08T03:01:55.7168089Z\"); return t}()),\n\t// \t\tPolicy: &armstorage.ManagementPolicySchema{\n\t// \t\t\tRules: []*armstorage.ManagementPolicyRule{\n\t// \t\t\t\t{\n\t// \t\t\t\t\tName: to.Ptr(\"olcmtest\"),\n\t// \t\t\t\t\tType: to.Ptr(armstorage.RuleTypeLifecycle),\n\t// \t\t\t\t\tDefinition: &armstorage.ManagementPolicyDefinition{\n\t// \t\t\t\t\t\tActions: &armstorage.ManagementPolicyAction{\n\t// \t\t\t\t\t\t\tBaseBlob: &armstorage.ManagementPolicyBaseBlob{\n\t// \t\t\t\t\t\t\t\tDelete: &armstorage.DateAfterModification{\n\t// \t\t\t\t\t\t\t\t\tDaysAfterModificationGreaterThan: to.Ptr[float32](1000),\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\tTierToArchive: &armstorage.DateAfterModification{\n\t// \t\t\t\t\t\t\t\t\tDaysAfterModificationGreaterThan: to.Ptr[float32](90),\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\tTierToCool: &armstorage.DateAfterModification{\n\t// \t\t\t\t\t\t\t\t\tDaysAfterModificationGreaterThan: to.Ptr[float32](30),\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\tSnapshot: &armstorage.ManagementPolicySnapShot{\n\t// \t\t\t\t\t\t\t\tDelete: &armstorage.DateAfterCreation{\n\t// \t\t\t\t\t\t\t\t\tDaysAfterCreationGreaterThan: to.Ptr[float32](30),\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\tFilters: &armstorage.ManagementPolicyFilter{\n\t// \t\t\t\t\t\t\tBlobTypes: []*string{\n\t// \t\t\t\t\t\t\t\tto.Ptr(\"blockBlob\")},\n\t// \t\t\t\t\t\t\t\tPrefixMatch: []*string{\n\t// \t\t\t\t\t\t\t\t\tto.Ptr(\"olcmtestcontainer\")},\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\tEnabled: to.Ptr(true),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t}\n}", "func (p *policy) String() string {\n\treturn fmt.Sprintf(policyDocument,\n\t\tp.Expiration,\n\t\tp.Bucket,\n\t\tp.Key,\n\t\tp.O.MaxFileSize,\n\t\tp.Credential,\n\t\tp.Date,\n\t)\n}", "func (policy *PolicySvc) deletePolicy(id uint64) (interface{}, error) {\n\t// TODO do we need this to be transactional or not ... case can be made for either.\n\terr := policy.store.inactivatePolicy(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpolicyDoc, err := policy.store.getPolicy(id, true)\n\tlog.Printf(\"Found policy for ID %d: %s (%v)\", id, policyDoc, err)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thosts, err := policy.client.ListHosts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif policyDoc.ExternalID == \"\" {\n\t\t// TODO\n\t\t// Important! This should really be done in policy agent.\n\t\t// Only done here as temporary measure.\n\t\texternalId := makeId(policyDoc.AppliedTo, policyDoc.Name)\n\t\tlog.Printf(\"Constructing internal policy name = %s\", externalId)\n\t\tpolicyDoc.ExternalID = externalId\n\t}\n\n\terrStr := make([]string, 0)\n\tfor _, host := range hosts {\n\t\t// TODO make schema configurable\n\t\turl := fmt.Sprintf(\"http://%s:%d/policies\", host.Ip, host.AgentPort)\n\t\tresult := make(map[string]interface{})\n\t\terr = policy.client.Delete(url, policyDoc, result)\n\t\tlog.Printf(\"Agent at %s returned %v\", host.Ip, result)\n\t\tif err != nil {\n\t\t\terrStr = append(errStr, fmt.Sprintf(\"Error deleting policy %d (%s) from host %s: %v. \", id, policyDoc.Name, host.Ip, err))\n\t\t}\n\t}\n\tif len(errStr) > 0 {\n\t\treturn nil, common.NewError500(errStr)\n\t}\n\terr = policy.store.deletePolicy(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpolicyDoc.Datacenter = nil\n\treturn policyDoc, nil\n}", "func (a *HyperflexApiService) GetHyperflexSoftwareVersionPolicyList(ctx context.Context) ApiGetHyperflexSoftwareVersionPolicyListRequest {\n\treturn ApiGetHyperflexSoftwareVersionPolicyListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (p *SdkPolicyManager) Inspect(\n\tctx context.Context,\n\treq *api.SdkOpenStoragePolicyInspectRequest,\n) (*api.SdkOpenStoragePolicyInspectResponse, error) {\n\tif req.GetName() == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Must supply a Storage Policy Name\")\n\t}\n\n\tkvp, err := kvdb.Instance().Get(prefixWithName(req.GetName()))\n\tif err == kvdb.ErrNotFound {\n\t\treturn nil, status.Errorf(codes.NotFound, \"Policy %s not found\", req.GetName())\n\t} else if err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"Failed to get policy %s information: %v\", req.GetName(), err)\n\t}\n\n\tstorPolicy := &api.SdkStoragePolicy{}\n\terr = jsonpb.UnmarshalString(string(kvp.Value), storPolicy)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"Json Unmarshal failed for policy %s: %v\", req.GetName(), err)\n\t}\n\n\tif !storPolicy.IsPermitted(ctx, api.Ownership_Read) {\n\t\treturn nil, status.Errorf(codes.PermissionDenied, \"Access denied to storage policy %s\", storPolicy.GetName())\n\t}\n\n\treturn &api.SdkOpenStoragePolicyInspectResponse{\n\t\tStoragePolicy: storPolicy,\n\t}, nil\n}", "func (ssp StorageServiceProperties) Version() string {\n\treturn ssp.rawResponse.Header.Get(\"x-ms-version\")\n}", "func (s *MockSupport) Policy(channelID, ns, coll string) (privdata.CollectionAccessPolicy, error) {\n\treturn s.CollPolicy, s.Err\n}", "func (client IdentityClient) updatePolicy(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPut, \"/policies/{policyId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response UpdatePolicyResponse\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 (p *PolicyResource) GetAll(params GetAllParams) (*PolicyList, error) {\n\tvar (\n\t\tpath = \"/policies\"\n\t\tpolicyList PolicyList\n\t)\n\n\tqrStr := params.QueryString()\n\n\tresp, err := p.client.DoRequest(\"GET\", path, qrStr, nil, nil)\n\tif err != nil {\n\t\treturn &policyList, err\n\t}\n\n\terr = json.Unmarshal(resp, &policyList)\n\tif err != nil {\n\t\treturn &policyList, err\n\t}\n\n\treturn &policyList, nil\n}", "func (Recommendations) Policy() ent.Policy {\n\t/*return authz.NewPolicy(\n\t\tauthz.WithMutationRules(\n\t\t\tauthz.AssuranceTemplatesWritePolicyRule(),\n\t\t),\n\t)*/\n\treturn authz.NewPolicy(\n\t\tauthz.WithMutationRules(\n\t\t\tprivacy.AlwaysAllowRule(),\n\t\t),\n\t)\n}", "func (bgpr BlobsGetPropertiesResponse) Version() string {\n\treturn bgpr.rawResponse.Header.Get(\"x-ms-version\")\n}", "func NewPolicy() *Policy {\n\treturn &Policy{}\n}", "func (s *SignedPolicy) Verify(pkp pubkey.Provider) error {\n\n\tif s.SignedPolicyData == nil {\n\t\treturn errors.New(\"no policy data\")\n\t}\n\n\t// verify expires\n\tif s.SignedPolicyData.Expires == nil {\n\t\treturn errors.New(\"policy without expiry\")\n\t}\n\tif s.SignedPolicyData.Expires.Time.Sub(fastime.Now()) <= 0 {\n\t\t// when the {expires: \"invalid string\"}, s.SignedPolicyData.Expires is Time{}\n\t\treturn fmt.Errorf(\"policy already expired at %s\", s.SignedPolicyData.Expires.Time.String())\n\t}\n\n\t// verify signed policy data\n\tver := pkp(pubkey.EnvZTS, s.KeyId)\n\tif ver == nil {\n\t\treturn errors.New(\"zts key not found\")\n\t}\n\tspd, err := json.Marshal(s.SignedPolicyData)\n\tif err != nil {\n\t\treturn errors.New(\"error marshal signed policy data\")\n\t}\n\tif err := ver.Verify((string)(spd), s.Signature); err != nil {\n\t\t//if err := ver.Verify(*(*string)(unsafe.Pointer(s.SignedPolicyData)), s.Signature); err != nil {\n\t\treturn errors.Wrap(err, \"error verify signature\")\n\t}\n\n\t// verify policy data\n\tver = pkp(pubkey.EnvZMS, s.SignedPolicyData.ZmsKeyId)\n\tif ver == nil {\n\t\treturn errors.New(\"zms key not found\")\n\t}\n\tpd, err := json.Marshal(s.SignedPolicyData.PolicyData)\n\tif err != nil {\n\t\treturn errors.New(\"error marshal policy data\")\n\t}\n\tif err := ver.Verify((string)(pd), s.SignedPolicyData.ZmsSignature); err != nil {\n\t\treturn errors.Wrap(err, \"error verify zms signature\")\n\t}\n\treturn nil\n}", "func GetPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *PolicyState, opts ...pulumi.ResourceOption) (*Policy, error) {\n\tvar resource Policy\n\terr := ctx.ReadResource(\"gcp:organizations/policy:Policy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {\n\turl := rootURL(c)\n\n\tif opts != nil {\n\t\tquery, err := opts.ToPolicyListQuery()\n\t\tif err != nil {\n\t\t\treturn pagination.Pager{Err: err}\n\t\t}\n\t\turl += query\n\t}\n\n\treturn pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page {\n\t\treturn PolicyPage{pagination.LinkedPageBase{PageResult: r}}\n\t})\n}", "func (h *httpJSONRPCClient) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) {\n\tres, err := h.call(\"SessionState.GetConfigPolicy\", []interface{}{})\n\tif err != nil {\n\t\tlogger.WithFields(log.Fields{\n\t\t\t\"_block\": \"GetConfigPolicy\",\n\t\t\t\"result\": fmt.Sprintf(\"%+v\", res),\n\t\t\t\"error\": err,\n\t\t}).Error(\"error getting config policy\")\n\t\treturn nil, err\n\t}\n\tif len(res.Result) == 0 {\n\t\treturn nil, errors.New(res.Error)\n\t}\n\tvar cpr plugin.GetConfigPolicyReply\n\terr = h.encoder.Decode(res.Result, &cpr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cpr.Policy, nil\n}", "func (m *GraphBaseServiceClient) Policies()(*i4ac7f0a844871066493521918f268cafe2a25c71c28a98221ea3f22d5153090f.PoliciesRequestBuilder) {\n return i4ac7f0a844871066493521918f268cafe2a25c71c28a98221ea3f22d5153090f.NewPoliciesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Policies()(*i4ac7f0a844871066493521918f268cafe2a25c71c28a98221ea3f22d5153090f.PoliciesRequestBuilder) {\n return i4ac7f0a844871066493521918f268cafe2a25c71c28a98221ea3f22d5153090f.NewPoliciesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (o *SparseSSHAuthorizationPolicy) Version() int {\n\n\treturn 1\n}", "func (a *HyperflexApiService) GetHyperflexSoftwareVersionPolicyByMoid(ctx context.Context, moid string) ApiGetHyperflexSoftwareVersionPolicyByMoidRequest {\n\treturn ApiGetHyperflexSoftwareVersionPolicyByMoidRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}" ]
[ "0.64794177", "0.6166629", "0.6142629", "0.60333997", "0.6007773", "0.59438336", "0.59017044", "0.58497113", "0.579923", "0.57853687", "0.5713539", "0.5689446", "0.5642515", "0.55955076", "0.55911833", "0.5583373", "0.55813783", "0.55767983", "0.55475533", "0.5528939", "0.55241054", "0.5518599", "0.5470575", "0.54704297", "0.5460751", "0.54594666", "0.544908", "0.54342794", "0.5431726", "0.5416564", "0.53991795", "0.53861815", "0.5379222", "0.5362879", "0.5361444", "0.53401107", "0.53281176", "0.5324194", "0.5320466", "0.52965814", "0.5285168", "0.52831143", "0.5278509", "0.5259573", "0.5252329", "0.52423775", "0.5234109", "0.52230144", "0.52222574", "0.52221215", "0.52127796", "0.52018255", "0.51842445", "0.5183614", "0.5183299", "0.51832527", "0.51798284", "0.5161651", "0.51372474", "0.513501", "0.51202345", "0.5102662", "0.51000416", "0.5098747", "0.50920564", "0.5091889", "0.5088525", "0.5081146", "0.5071772", "0.5068149", "0.5061502", "0.5045936", "0.50457793", "0.5036874", "0.5035211", "0.5022842", "0.50191534", "0.50078416", "0.49933013", "0.49916893", "0.4989379", "0.49884602", "0.49799928", "0.4977776", "0.4974214", "0.4972279", "0.49647516", "0.49623862", "0.49491003", "0.4938462", "0.49362388", "0.49328914", "0.4928567", "0.4916707", "0.49139085", "0.49125507", "0.4910764", "0.4910764", "0.49025214", "0.4902327" ]
0.64694965
1
NewConfig returns a new Config pointer that can be chained with builder methods to set multiple configuration values inline without using pointers. c := simplebackupec2.NewConfig().WithRegion("apnortheast1").WithCredentials(creds)
func NewConfig(region string) *aws.Config { return &aws.Config{Region: aws.String(region)} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewConfig(credentials *Credentials) *Config {\n\treturn &Config{\n\t\tCredentials: credentials,\n\t\tRegion: Region[\"bj\"],\n\t}\n}", "func New() *Config {\n\treturn &Config{\n\t\tEncryptor: &encryption.KMSEncryptor{\n\t\t\tKMS: kms.New(session.New(), &aws.Config{Region: aws.String(os.Getenv(\"EC2_REGION\"))}),\n\t\t},\n\t\tdata: (unsafe.Pointer)(&configData{\n\t\t\tbody: new(sjson.Json),\n\t\t\tdecrypted: make(map[uint64]*sjson.Json),\n\t\t}),\n\t\tobservers: make([]chan bool, 0),\n\t}\n}", "func newConfig() (*config, error) {\n\tec2Metadata := ec2metadata.New(session.Must(session.NewSession()))\n\tregion, err := ec2Metadata.Region()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get region from ec2 metadata\")\n\t}\n\n\tinstanceID, err := ec2Metadata.GetMetadata(\"instance-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get instance id from ec2 metadata\")\n\t}\n\n\tmac, err := ec2Metadata.GetMetadata(\"mac\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get mac from ec2 metadata\")\n\t}\n\n\tsecurityGroups, err := ec2Metadata.GetMetadata(\"security-groups\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get security groups from ec2 metadata\")\n\t}\n\n\tinterfaces, err := ec2Metadata.GetMetadata(\"network/interfaces/macs\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get interfaces from ec2 metadata\")\n\t}\n\n\tsubnet, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/subnet-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get subnet from ec2 metadata\")\n\t}\n\n\tvpc, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/vpc-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get vpc from ec2 metadata\")\n\t}\n\n\treturn &config{region: region,\n\t\tsubnet: subnet,\n\t\tindex: int64(len(strings.Split(interfaces, \"\\n\"))),\n\t\tinstanceID: instanceID,\n\t\tsecurityGroups: strings.Split(securityGroups, \"\\n\"),\n\t\tvpc: vpc,\n\t}, nil\n}", "func NewConfig(\n\trollupCfg *rollup.Config,\n\tl2Genesis *params.ChainConfig,\n\tl1Head common.Hash,\n\tl2Head common.Hash,\n\tl2OutputRoot common.Hash,\n\tl2Claim common.Hash,\n\tl2ClaimBlockNum uint64,\n) *Config {\n\treturn &Config{\n\t\tRollup: rollupCfg,\n\t\tL2ChainConfig: l2Genesis,\n\t\tL1Head: l1Head,\n\t\tL2Head: l2Head,\n\t\tL2OutputRoot: l2OutputRoot,\n\t\tL2Claim: l2Claim,\n\t\tL2ClaimBlockNumber: l2ClaimBlockNum,\n\t\tL1RPCKind: sources.RPCKindBasic,\n\t}\n}", "func New() *Config {\n\tc := &Config{\n\t\tTargets: make([]string, 0),\n\t}\n\tsetDefaultValues(c)\n\n\treturn c\n}", "func NewConfig() *Config {\r\n\t//config := Config{}\r\n\treturn &Config{\r\n\t\tInsteon: Credential{BaseURL: \"http://192.168.1.1:25105\", Username: \"fobar\", Password: \"password\"},\r\n\t\tWifiInterface: \"wlan0\",\r\n\t\tSSID: \"ssid_to_track\",\r\n\t\tGarageID: \"A3BF45\",\r\n\t\tLogfile: \"/var/log/opensesame.log\",\r\n\t}\r\n}", "func newConfig(opts ...Option) config {\n\tc := config{\n\t\tMeterProvider: otel.GetMeterProvider(),\n\t}\n\tfor _, opt := range opts {\n\t\topt.apply(&c)\n\t}\n\treturn c\n}", "func NewConfig(newServices []services.ServiceConfig, newGroups []services.ServiceGroupConfig) Config {\n\tlog.Printf(\"Creating new config with %d services and %d groups.\\n\", len(newServices), len(newGroups))\n\n\t// Find Env settings common to all services\n\tvar allEnvSlices [][]string\n\tfor _, s := range newServices {\n\t\tallEnvSlices = append(allEnvSlices, s.Env)\n\t}\n\tenv := stringSliceIntersect(allEnvSlices)\n\n\t// Remove common settings from services\n\tvar svcs []services.ServiceConfig\n\tfor _, s := range newServices {\n\t\ts.Env = stringSliceRemoveCommon(env, s.Env)\n\t\tsvcs = append(svcs, s)\n\t}\n\n\tcfg := Config{\n\t\tEnv: env,\n\t\tServices: svcs,\n\t\tGroups: []GroupDef{},\n\t}\n\n\tcfg.AddGroups(newGroups)\n\n\tlog.Printf(\"Config created: %v\", cfg)\n\n\treturn cfg\n}", "func New() (Config, error) {\n\tconfig := Config{}\n\tif err := env.Parse(&config); err != nil {\n\t\treturn config, errors.Wrap(err, \"failed to load enviroment variables\")\n\t}\n\n\tconfig.Baker.Blacklist = cleanList(config.Baker.Blacklist)\n\tconfig.Baker.DexterLiquidityContracts = cleanList(config.Baker.DexterLiquidityContracts)\n\n\tif config.Notifications.Twilio.To != nil {\n\t\tconfig.Notifications.Twilio.To = cleanList(config.Notifications.Twilio.To)\n\t}\n\n\terr := validator.New().Struct(&config)\n\tif err != nil {\n\t\treturn config, errors.Wrap(err, \"invalid input\")\n\t}\n\n\treturn config, nil\n}", "func New(p Provider) (*Config, error) {\n\tm, err := p.Provide()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &Config{\n\t\tm: m,\n\t}\n\treturn c, nil\n}", "func NewConfig(data map[string]string) (settings *Config) {\n cfg := &Config{\n ConsumerKey: data[\"consumer_key\"],\n ConsumerSecret: data[\"consumer_secret\"],\n }\n\n // save access token if defined\n if atoken, ok := data[\"access_token\"]; ok {\n cfg.AccessToken = atoken\n }\n\n // save access token secret if defined\n if asecret, ok := data[\"access_secret\"]; ok {\n cfg.AccessSecret = asecret\n }\n\n // save debug flag if defined\n if debug, ok := data[\"debug\"]; ok && debug == \"on\" {\n cfg.Debug = true\n }\n\n return cfg\n}", "func newConfig() Config {\n\treturn Config{\n\t\tDefaultContainerConfig: newDefaultContainerConfig(),\n\t\tContainersConfig: map[string]ContainerConfig{},\n\t\tExclude: []string{},\n\t}\n}", "func NewConfig(username, password string) (Config, error) {\n\talias := os.Getenv(\"CLC_ALIAS\")\n\tagent := userAgentDefault\n\tif v := os.Getenv(\"CLC_USER_AGENT\"); v != \"\" {\n\t\tagent = v\n\t}\n\tbase := baseUriDefault\n\tif v := os.Getenv(\"CLC_BASE_URL\"); v != \"\" {\n\t\tbase = v\n\t}\n\turi, err := url.Parse(base)\n\treturn Config{\n\t\tUser: User{\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t},\n\t\tAlias: alias,\n\t\tBaseURL: uri,\n\t\tUserAgent: agent,\n\t}, err\n}", "func newConfig() (*rest.Config, error) {\n // try in cluster config first, it should fail quickly on lack of env vars\n cfg, err := inClusterConfig()\n if err != nil {\n cfg, err = clientcmd.BuildConfigFromFlags(\"\", clientcmd.RecommendedHomeFile)\n if err != nil {\n return nil, errors.Wrap(err, \"failed to get InClusterConfig and Config from kube_config\")\n }\n }\n return cfg, nil\n}", "func NewClientConfiguration(pfmServicesEnabled bool, isAutomaticBatchUpdateEnabled bool, isDevelopmentModeEnabled bool, isNonEuroAccountsSupported bool, isAutoCategorizationEnabled bool, mandatorLicense MandatorLicense, preferredConsentType PreferredConsentType, userNotificationCallbackUrl NullableString, userSynchronizationCallbackUrl NullableString, refreshTokensValidityPeriod int32, userAccessTokensValidityPeriod int32, clientAccessTokensValidityPeriod int32, maxUserLoginAttempts int32, transactionImportLimitation int32, isUserAutoVerificationEnabled bool, isMandatorAdmin bool, isWebScrapingEnabled bool, isXs2aEnabled bool, pinStorageAvailableInWebForm bool, paymentsEnabled bool, isStandalonePaymentsEnabled bool, availableBankGroups []string, products []Product, applicationName NullableString, finTSProductRegistrationNumber NullableString, storeSecretsAvailableInWebForm bool, supportSubjectDefault NullableString, supportEmail NullableString, aisWebFormMode WebFormMode, pisWebFormMode WebFormMode, pisStandaloneWebFormMode WebFormMode, betaBanksEnabled bool, categoryRestrictions []Category, autoDismountWebForm bool, corsAllowedOrigins []string, ) *ClientConfiguration {\n\tthis := ClientConfiguration{}\n\tthis.PfmServicesEnabled = pfmServicesEnabled\n\tthis.IsAutomaticBatchUpdateEnabled = isAutomaticBatchUpdateEnabled\n\tthis.IsDevelopmentModeEnabled = isDevelopmentModeEnabled\n\tthis.IsNonEuroAccountsSupported = isNonEuroAccountsSupported\n\tthis.IsAutoCategorizationEnabled = isAutoCategorizationEnabled\n\tthis.MandatorLicense = mandatorLicense\n\tthis.PreferredConsentType = preferredConsentType\n\tthis.UserNotificationCallbackUrl = userNotificationCallbackUrl\n\tthis.UserSynchronizationCallbackUrl = userSynchronizationCallbackUrl\n\tthis.RefreshTokensValidityPeriod = refreshTokensValidityPeriod\n\tthis.UserAccessTokensValidityPeriod = userAccessTokensValidityPeriod\n\tthis.ClientAccessTokensValidityPeriod = clientAccessTokensValidityPeriod\n\tthis.MaxUserLoginAttempts = maxUserLoginAttempts\n\tthis.TransactionImportLimitation = transactionImportLimitation\n\tthis.IsUserAutoVerificationEnabled = isUserAutoVerificationEnabled\n\tthis.IsMandatorAdmin = isMandatorAdmin\n\tthis.IsWebScrapingEnabled = isWebScrapingEnabled\n\tthis.IsXs2aEnabled = isXs2aEnabled\n\tthis.PinStorageAvailableInWebForm = pinStorageAvailableInWebForm\n\tthis.PaymentsEnabled = paymentsEnabled\n\tthis.IsStandalonePaymentsEnabled = isStandalonePaymentsEnabled\n\tthis.AvailableBankGroups = availableBankGroups\n\tthis.Products = products\n\tthis.ApplicationName = applicationName\n\tthis.FinTSProductRegistrationNumber = finTSProductRegistrationNumber\n\tthis.StoreSecretsAvailableInWebForm = storeSecretsAvailableInWebForm\n\tthis.SupportSubjectDefault = supportSubjectDefault\n\tthis.SupportEmail = supportEmail\n\tthis.AisWebFormMode = aisWebFormMode\n\tthis.PisWebFormMode = pisWebFormMode\n\tthis.PisStandaloneWebFormMode = pisStandaloneWebFormMode\n\tthis.BetaBanksEnabled = betaBanksEnabled\n\tthis.CategoryRestrictions = categoryRestrictions\n\tthis.AutoDismountWebForm = autoDismountWebForm\n\tthis.CorsAllowedOrigins = corsAllowedOrigins\n\treturn &this\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tHosts: []string{\"localhost:10101\"},\n\t\tGenerate: true,\n\t\tVerify: \"update\",\n\t\tPrefix: \"imaginary-\",\n\t\tThreadCount: 0, // if unchanged, uses workloadspec.threadcount\n\t\t// if workloadspec.threadcount is also unset, defaults to 1\n\t}\n}", "func New() *Config {\n\treturn &Config{}\n}", "func New() *Config {\n\treturn &Config{}\n}", "func NewConfig(claimSpec *v1alpha1.DeviceClaimSpec, client client.Client) *Config {\n\tisManualSelection := false\n\tif claimSpec.BlockDeviceName != \"\" {\n\t\tisManualSelection = true\n\t}\n\tc := &Config{\n\t\tClient: client,\n\t\tClaimSpec: claimSpec,\n\t\tManualSelection: isManualSelection,\n\t}\n\treturn c\n}", "func NewConfig(userAgent string,\n\tclientID string,\n\tclientSecret string,\n\tusername string,\n\tpassword string,\n) (*Config, error) {\n\n\tswitch {\n\tcase clientID == \"\":\n\t\treturn nil, errors.Wrap(ErrMalformedParam, \"clientID\")\n\tcase clientSecret == \"\":\n\t\treturn nil, errors.Wrap(ErrMalformedParam, \"clientSecret\")\n\tcase username == \"\":\n\t\treturn nil, errors.Wrap(ErrMalformedParam, \"username\")\n\tcase password == \"\":\n\t\treturn nil, errors.Wrap(ErrMalformedParam, \"password\")\n\t}\n\n\treturn &Config{userAgent: userAgent,\n\t\tclientID: clientID,\n\t\tclientSecret: clientSecret,\n\t\tusername: username,\n\t\tpassword: password,\n\t}, nil\n}", "func CreateConfig(id, secret, token string) *aws.Config {\n\tAnonymousCredentials := credentials.NewStaticCredentials(id, secret, token)\n\tconfig := &aws.Config{\n\t\tRegion: aws.String(\"ap-southeast-1\"),\n\t\tCredentials: AnonymousCredentials,\n\t}\n\treturn config\n}", "func (c *config) newConfig(redirect string) *oauth2.Config {\n\treturn &oauth2.Config{\n\t\tClientID: c.Client,\n\t\tClientSecret: c.Secret,\n\t\tEndpoint: oauth2.Endpoint{\n\t\t\tAuthURL: fmt.Sprintf(\"%s/site/oauth2/authorize\", c.URL),\n\t\t\tTokenURL: fmt.Sprintf(\"%s/site/oauth2/access_token\", c.URL),\n\t\t},\n\t\tRedirectURL: fmt.Sprintf(\"%s/authorize\", redirect),\n\t}\n}", "func NewConfig(cfg map[string]interface{}) Config {\n\treturn Config{Data: cfg}\n}", "func newConfig() *config {\n\treturn &config{\n\t\tAddr: \":80\",\n\t\tCacheSize: 1000,\n\t\tLogLevel: \"info\",\n\t\tRequestTimeout: 3000,\n\t\tTargetAddr: \"https://places.aviasales.ru\",\n\t}\n}", "func NewConfig(opts ...Option) *Config {\n\tc := Config{\n\t\ttree: make(tree),\n\t\tParms: &Parms{\n\t\t\tDex: list{RWMutex: &sync.RWMutex{}, entry: make(entry)},\n\t\t\tExc: list{RWMutex: &sync.RWMutex{}, entry: make(entry)},\n\t\t},\n\t}\n\tfor _, opt := range opts {\n\t\topt(&c)\n\t}\n\treturn &c\n}", "func NewConfig(config *Config) *aws.Config {\n\t// combine many providers in case some is missing\n\tcreds := credentials.NewChainCredentials([]credentials.Provider{\n\t\t// use static access key & private key if available\n\t\t&credentials.StaticProvider{\n\t\t\tValue: credentials.Value{\n\t\t\t\tAccessKeyID: config.AccessKey,\n\t\t\t\tSecretAccessKey: config.SecretKey,\n\t\t\t},\n\t\t},\n\t\t// fallback to default aws environment variables\n\t\t&credentials.EnvProvider{},\n\t\t// read aws config file $HOME/.aws/credentials\n\t\t&credentials.SharedCredentialsProvider{},\n\t})\n\n\tawsConfig := aws.NewConfig()\n\tawsConfig.WithCredentials(creds)\n\tawsConfig.WithRegion(config.Region)\n\n\treturn awsConfig\n}", "func NewConfig(fns ...OptionFunc) *Config {\n\tconf := &Config{\n\t\tTransform: &TransformConfig{},\n\t\tReadable: &ReadableConfig{},\n\t\tWritable: &WritableConfig{},\n\t}\n\n\tfor _, fn := range fns {\n\t\tfn(conf)\n\t}\n\n\treturn conf\n}", "func NewConfig(loc string) (cfg *Config, err error) {\n\tvar c Config\n\tif _, err = toml.DecodeFile(loc, &c); err != nil {\n\t\treturn\n\t}\n\n\tif err = c.loadIncludes(); err != nil {\n\t\treturn\n\t}\n\n\tif c.Dir == \"\" {\n\t\tc.Dir = \"./\"\n\t}\n\n\tif c.Environment == nil {\n\t\tc.Environment = make(map[string]string)\n\t}\n\n\tc.populateFromOSEnv()\n\tcfg = &c\n\treturn\n}", "func NewConfig(opts ...Option) Config {\n\tvar config Config\n\tfor _, o := range opts {\n\t\tconfig = o.applyInstrument(config)\n\t}\n\treturn config\n}", "func New() *Config {\n\treturn new(Config)\n}", "func ConfigNew() *Config {\n\tc := Config{\n\t\tHosts: map[string]*ConfigHost{},\n\t}\n\treturn &c\n}", "func New(name string) *Config {\n\treturn &Config{name: name}\n}", "func New() *Config {\n\treturn &Config{\n\t\tMode: ModeDevelopment,\n\t\tconfigs: make([]map[string]string, 3),\n\t}\n}", "func NewConfig(base string) (config *Config) {\n\tconfig = &Config{}\n\tconfig.Base = base\n\tconfig.Entries = make(map[string]ConfigEntry)\n\treturn\n}", "func NewConfig(name string, client kubernetes.Interface) *Config {\n\treturn &Config{\n\t\tName: name,\n\t\tClient: client,\n\t}\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tEnable: true,\n\t\tAddress: \"0.0.0.0:30003\",\n\t}\n}", "func NewConfig(cfg map[string]interface{}) *Config {\n\tif cfg == nil {\n\t\tcfg = make(map[string]interface{})\n\t}\n\treturn &Config{\n\t\tm: cfg,\n\t}\n}", "func New() *Config {\n\treturn &Config{\n\t\tdevices: make([]Device, 0),\n\t}\n}", "func NewConfig(username, password, BaseURL string) *oauthPassword.Config {\n\tc := oauthPassword.Config{}\n\tc.Username = username\n\tc.Password = password\n\tc.Endpoint = Endpoint(BaseURL)\n\treturn &c\n}", "func NewConfig(configFile string) (*Config, error) {\n\n\tcfg := &Config{\n\t\tHost: \"0.0.0.0\",\n\t\tPort: 8080,\n\t\tAllowEmptyClientSecret: false,\n\t\tScopes: []string{\"openid\", \"profile\", \"email\", \"offline_access\"},\n\t\tUsernameClaim: \"nickname\",\n\t\tEmailClaim: \"\",\n\t\tServeTLS: false,\n\t\tCertFile: \"/etc/gangway/tls/tls.crt\",\n\t\tKeyFile: \"/etc/gangway/tls/tls.key\",\n\t\tClusterCAPath: \"/var/run/secrets/kubernetes.io/serviceaccount/ca.crt\",\n\t\tHTTPPath: \"\",\n\t}\n\n\tif configFile != \"\" {\n\t\tdata, err := ioutil.ReadFile(configFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\terr = yaml.Unmarshal([]byte(data), cfg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\terr := envconfig.Process(\"gangway\", cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = cfg.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check for trailing slash on HTTPPath and remove\n\tcfg.HTTPPath = strings.TrimRight(cfg.HTTPPath, \"/\")\n\n\treturn cfg, nil\n}", "func New() (*Config, error) {\n\tc := &Config{}\n\terr := env.Parse(c)\n\treturn c, err\n}", "func newConfig() *bqConfig {\n\treturn &bqConfig{\n\t\tarenaSize: cDefaultArenaSize,\n\t\tmaxInMemArenas: cMinMaxInMemArenas,\n\t}\n}", "func NewConfig(address string) *Config {\n\treturn &Config{\n\t\tAddress: address,\n\t\tNamespace: \"\",\n\t\tInsecure: false,\n\t}\n}", "func New() *Config {\n\tcfg := new(Config)\n\treturn cfg\n}", "func New() *Config {\n\treturn &Config{\n\t\tOptions: AppConfig{\n\t\t\tHoldtime: 12 * time.Hour, // do not retry a successful device backup before this holdtime\n\t\t\tScanInterval: 10 * time.Minute, // interval for scanning device table\n\t\t\tMaxConcurrency: 20, // limit for concurrent backup jobs\n\t\t\tMaxConfigFiles: 120, // limit for per-device saved files\n\t\t\tMaxConfigLoadSize: 10000000, // 10M limit max config file size for loading to memory\n\t\t},\n\t\tDevices: []DevConfig{},\n\t}\n}", "func NewConfig(fns []ConfigFunc) *Config {\n\t// TODO: This function returns a pointer while most of the other returns values. Decide which way to do it.\n\tconfig := &Config{}\n\tfor _, fn := range fns {\n\t\tfn(config)\n\t}\n\treturn config\n}", "func NewConfigWithParams(accessKeyID, secretAccessKey, region string) *Config {\n\treturn &Config{\n\t\tCredentials: &Credentials{\n\t\t\tAccessKeyID: accessKeyID,\n\t\t\tSecretAccessKey: secretAccessKey,\n\t\t},\n\t\tRegion: Region[region],\n\t}\n}", "func NewConfig() *Config {\n\treturn &Config{v: make(map[string]string)}\n}", "func NewConfig(configFile string) (conf *ProjectConfig, err error) {\n\tif os.Getenv(\"ZARUBA_HOME\") == \"\" {\n\t\texecutable, err := os.Executable()\n\t\tif err != nil {\n\t\t\treturn conf, err\n\t\t}\n\t\tos.Setenv(\"ZARUBA_HOME\", filepath.Dir(executable))\n\t}\n\tconf, err = loadConfigRecursively(configFile)\n\tconf.Kwargs = map[string]string{}\n\tconf.IconGenerator = iconer.NewGenerator()\n\tconf.Decoration = logger.NewDecoration()\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\tconf.generateProperties()\n\tconf.fillTaskAndEnv()\n\treturn conf, err\n}", "func New(pathname string, setters ...ConfigSetter) (*Config, error) {\n\tvar err error\n\n\tc := &Config{pathname: pathname}\n\n\tfor _, setter := range setters {\n\t\tif err := setter(c); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcgms := []congomap.Setter{congomap.Lookup(c.lookupSection())}\n\tif c.ttl > 0 {\n\t\tcgms = append(cgms, congomap.TTL(c.ttl))\n\t}\n\tc.cgm, err = congomap.NewSyncAtomicMap(cgms...) // relatively few config sections\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func New(c context.Context) (config.Interface, error) {\n\tsettings, err := FetchCachedSettings(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif settings.ConfigServiceURL == \"\" {\n\t\treturn nil, ErrNotConfigured\n\t}\n\n\tc = client.UseServiceAccountTransport(c, nil, nil)\n\tcfg := remote.New(c, settings.ConfigServiceURL+\"/_ah/api/config/v1/\")\n\tif settings.CacheExpirationSec != 0 {\n\t\tf := NewCacheFilter(c, time.Duration(settings.CacheExpirationSec)*time.Second)\n\t\tcfg = f(c, cfg)\n\t}\n\treturn cfg, nil\n}", "func NewConfig() Config {\n\treturn Config{\n\t\t0.0, 0.0,\n\t\t4.0, 4.0,\n\t\t1000, 1000,\n\t\t512,\n\t\t\"ramp.json\",\n\t\t\"default.gob\",\n\t\t\"output.jpg\",\n\t\t\"000000\",\n\t\t0.0, 0.0}\n}", "func (client *HTTPClient) NewConfig(config *Config) {\n\tclient.sendRequest(\"POST\", config, nil, &HTTPClientMetrics{NewConfig: true})\n}", "func New(opts ...Option) *Config {\n\tcfg := &Config{\n\t\tWindowWidth: 800,\n\t\tWindowHeight: 600,\n\t\tSize: 5,\n\t\tSquareSize: 48,\n\t\tDotRadius: 16,\n\t\tColor: &sdl.Color{R: 168, G: 168, B: 168, A: 255},\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(cfg)\n\t}\n\n\treturn cfg\n}", "func New(name string, desc string, cfg interface{}) *Config {\n\treturn NewWithCommand(\n\t\t&cobra.Command{\n\t\t\tUse: name,\n\t\t\tLong: desc,\n\t\t\tRun: func(cmd *cobra.Command, args []string) {},\n\t\t}, cfg)\n}", "func NewConfig(args []string) (*Config, error) {\n\tconfig := &Config{}\n\tif len(args) == 0 {\n\t\treturn config, errors.New(\"arguments cannot be empty\")\n\t}\n\n\t// load default config values\n\tconfig.FlagPort = defaultHTTPPort\n\tconfig.FlagGetRequestTimeout = defaultGETRequestTimeout\n\n\tflagSet := flag.NewFlagSet(dcosLog, flag.ContinueOnError)\n\tconfig.setFlags(flagSet)\n\n\t// override with user provided arguments\n\tif err := flagSet.Parse(args[1:]); err != nil {\n\t\treturn config, err\n\t}\n\n\t// read config file if exists.\n\tif err := readAndUpdateConfigFile(config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set debug level\n\tif config.FlagVerbose {\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t\tlogrus.Debug(\"Using debug level\")\n\t}\n\n\treturn config, validateConfigStruct(config)\n}", "func New() *Config {\n\treturn &Config{\n\t\tJenkinsOptions: jenkins.NewDevopsOptions(),\n\t\tKubernetesOptions: k8s.NewKubernetesOptions(),\n\t\tAuthMode: AuthModeToken,\n\t\tAuthenticationOptions: authoptions.NewAuthenticateOptions(),\n\t}\n}", "func NewConfig() *Config {\n\treturn &Config{values: map[string]string{}, Color: &Color{colorSettings{}, colorFuncs{}}}\n}", "func New() (*Config, error) {\n\tflags := pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)\n\tcfg := &Config{\n\t\tFlags: flags,\n\t\tHTTPAddr: flags.StringP(\"http-addr\", \"l\", \":8080\", \"http listen address\"),\n\t\tHTTPReadHeaderTimeout: flags.DurationP(\"http-timeout\", \"h\", 1*time.Second, \"http timeout for reading request headers\"),\n\t\tCallTimeout: flags.DurationP(\"call-timeout\", \"t\", 0*time.Second, \"function call timeout\"),\n\t\tReadLimit: flags.Int64(\"read-limit\", -1, \"limit the amount of data which can be contained in a requests body\"),\n\t\tFramer: flags.StringP(\"framer\", \"f\", \"\", \"afterburn framer to use: line, json or http\"),\n\t\tBuffer: flags.BoolP(\"buffer\", \"b\", false, \"buffer output before writing\"),\n\t}\n\tif err := cfg.parseCommandline(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := cfg.parseEnvironment(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg, nil\n}", "func NewIntegrationTestConfig(t *testing.T) config.Config {\n\tenvPersonalAPIKey := os.Getenv(\"NEW_RELIC_API_KEY\")\n\tenvInsightsInsertKey := os.Getenv(\"NEW_RELIC_INSIGHTS_INSERT_KEY\")\n\tenvLicenseKey := os.Getenv(\"NEW_RELIC_LICENSE_KEY\")\n\tenvRegion := os.Getenv(\"NEW_RELIC_REGION\")\n\tenvLogLevel := os.Getenv(\"NEW_RELIC_LOG_LEVEL\")\n\n\tif envPersonalAPIKey == \"\" {\n\t\tt.Skipf(\"acceptance testing requires NEW_RELIC_API_KEY\")\n\t}\n\n\tcfg := config.New()\n\n\t// Set some defaults\n\tif envLogLevel != \"\" {\n\t\tcfg.LogLevel = envLogLevel\n\t} else {\n\t\tcfg.LogLevel = LogLevel\n\t}\n\tcfg.Logger = cfg.GetLogger()\n\n\t// HTTP Settings\n\ttimeout := HTTPTimeout\n\tcfg.Timeout = &timeout\n\tcfg.UserAgent = UserAgent\n\n\t// Auth\n\tcfg.PersonalAPIKey = envPersonalAPIKey\n\tcfg.InsightsInsertKey = envInsightsInsertKey\n\tcfg.LicenseKey = envLicenseKey\n\n\tif envRegion != \"\" {\n\t\tregName, err := region.Parse(envRegion)\n\t\tassert.NoError(t, err)\n\n\t\treg, err := region.Get(regName)\n\t\tassert.NoError(t, err)\n\n\t\terr = cfg.SetRegion(reg)\n\t\tassert.NoError(t, err)\n\t}\n\n\treturn cfg\n}", "func NewConfig(opts ...Option) (Config, error) {\n\treturn newConfig(opts...)\n}", "func NewConfig(locator resource.ReadLocator, renderAPI render.API, shaders ShaderCollection) *Config {\n\treturn &Config{\n\t\tlocator: locator,\n\t\trenderAPI: renderAPI,\n\t\tshaders: shaders,\n\t}\n}", "func newConfiguration() *configuration {\n\treturn &configuration{\n\t\tUseSSL: true,\n\t\tLocation: \"us-east-1\",\n\t\tMaxBackups: 5,\n\t\tBackupPrefix: \"backup-\",\n\t}\n}", "func New(file string) (conf *Config, err error) {\n\tconf = &Config{\n\t\tLogLevel: \"info\",\n\t\tSite: \"default\",\n\t\taudit: []auditors.Auditor{},\n\t}\n\n\trawconf, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not read config file %s\", file)\n\t}\n\n\terr = json.Unmarshal(rawconf, conf)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not parse config file %s\", file)\n\t}\n\n\tccfg, err := cconf.NewConfig(conf.ChoriaConfigFile)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not parse choria config %s\", conf.ChoriaConfigFile)\n\t}\n\n\tccfg.LogFile = conf.LogFile\n\tccfg.LogLevel = conf.LogLevel\n\tccfg.RPCAuthorization = false\n\n\t// by definition these are clients who do not have security credentials, verification is based on the JWT\n\tccfg.DisableSecurityProviderVerify = true\n\n\tconf.fw, err = choria.NewWithConfig(ccfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not configure choria\")\n\t}\n\n\terr = configureAuthenticator(conf)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not configure %s authenticator\", conf.AuthenticatorType)\n\t}\n\n\terr = configureSigner(conf)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not configure %s signer\", conf.SignerType)\n\t}\n\n\treturn conf, nil\n}", "func New() *Config {\n\tcfg := &Config{}\n\tcfg.SetDefaults()\n\tcfg.ChangedCH = make(chan bool)\n\treturn cfg\n}", "func newConfigV1() *configV1 {\n\tconf := new(configV1)\n\tconf.Version = mcPreviousConfigVersion\n\t// make sure to allocate map's otherwise Golang\n\t// exits silently without providing any errors\n\tconf.Hosts = make(map[string]*hostConfig)\n\tconf.Aliases = make(map[string]string)\n\treturn conf\n}", "func NewConfig(appName string) *Config {\n\tref := uuid.New()\n\n\treturn &Config{\n\t\treference: ref.String(),\n\t\tlevel: INFO,\n\t\tfilePathSize: SHORT,\n\t\tappName: appName,\n\t}\n}", "func New(file ...string) *Config {\n\tname := DefaultConfigFile\n\tif len(file) > 0 {\n\t\tname = file[0]\n\t} else {\n\t\t// Custom default configuration file name from command line or environment.\n\t\tif customFile := gcmd.GetOptWithEnv(commandEnvKeyForFile).String(); customFile != \"\" {\n\t\t\tname = customFile\n\t\t}\n\t}\n\tc := &Config{\n\t\tdefaultName: name,\n\t\tsearchPaths: garray.NewStrArray(true),\n\t\tjsonMap: gmap.NewStrAnyMap(true),\n\t}\n\t// Customized dir path from env/cmd.\n\tif customPath := gcmd.GetOptWithEnv(commandEnvKeyForPath).String(); customPath != \"\" {\n\t\tif gfile.Exists(customPath) {\n\t\t\t_ = c.SetPath(customPath)\n\t\t} else {\n\t\t\tif errorPrint() {\n\t\t\t\tglog.Errorf(\"[gcfg] Configuration directory path does not exist: %s\", customPath)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Dir path of working dir.\n\t\tif err := c.AddPath(gfile.Pwd()); err != nil {\n\t\t\tintlog.Error(context.TODO(), err)\n\t\t}\n\n\t\t// Dir path of main package.\n\t\tif mainPath := gfile.MainPkgPath(); mainPath != \"\" && gfile.Exists(mainPath) {\n\t\t\tif err := c.AddPath(mainPath); err != nil {\n\t\t\t\tintlog.Error(context.TODO(), err)\n\t\t\t}\n\t\t}\n\n\t\t// Dir path of binary.\n\t\tif selfPath := gfile.SelfDir(); selfPath != \"\" && gfile.Exists(selfPath) {\n\t\t\tif err := c.AddPath(selfPath); err != nil {\n\t\t\t\tintlog.Error(context.TODO(), err)\n\t\t\t}\n\t\t}\n\t}\n\treturn c\n}", "func NewConfig(region string) aws.Config {\n\tcfg, err := config.LoadDefaultConfig(context.Background(), config.WithRegion(region))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cfg\n}", "func NewConfig(cfg config.Config) *oauth2.Config {\n\tconf := &oauth2.Config{\n\t\tClientID: cfg.ClientID,\n\t\tScopes: []string{\"authorization_code\"},\n\t\tEndpoint: oauth2.Endpoint{\n\t\t\tTokenURL: config.TokenURL,\n\t\t\tAuthURL: config.AuthURL,\n\t\t},\n\t}\n\treturn conf\n}", "func NewConfig(data []byte) (*Config, error) {\n\tvar config Config\n\tif err := json.Unmarshal(data, &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal configuration: %v\", err)\n\t}\n\treturn &config, nil\n}", "func NewProvider() *ProviderConfig {\n\tproviderConfig := &ProviderConfig{\n\t\tAlibaba: make(map[string]*models.AlibabaCloudSpec),\n\t\tAnexia: make(map[string]*models.AnexiaCloudSpec),\n\t\tAws: make(map[string]*models.AWSCloudSpec),\n\t\tAzure: make(map[string]*models.AzureCloudSpec),\n\t\tDigitalocean: make(map[string]*models.DigitaloceanCloudSpec),\n\t\tFake: make(map[string]*models.FakeCloudSpec),\n\t\tGcp: make(map[string]*models.GCPCloudSpec),\n\t\tHetzner: make(map[string]*models.HetznerCloudSpec),\n\t\tKubevirt: make(map[string]*models.KubevirtCloudSpec),\n\t\tOpenstack: make(map[string]*models.OpenstackCloudSpec),\n\t\tPacket: make(map[string]*models.PacketCloudSpec),\n\t\tVsphere: make(map[string]*models.VSphereCloudSpec),\n\t}\n\n\tproviderConfig.Alibaba[\"Alibaba\"] = newAlibabaCloudSpec()\n\tproviderConfig.Anexia[\"Anexia\"] = newAnexiaCloudSpec()\n\tproviderConfig.Aws[\"Aws\"] = newAWSCloudSpec()\n\tproviderConfig.Azure[\"Azure\"] = newAzureCloudSpec()\n\tproviderConfig.Digitalocean[\"Digitalocean\"] = newDigitaloceanCloudSpec()\n\tproviderConfig.Fake[\"Fake\"] = newFakeCloudSpec()\n\tproviderConfig.Gcp[\"Gcp\"] = newGCPCloudSpec()\n\tproviderConfig.Hetzner[\"Hetzner\"] = newHetznerCloudSpec()\n\tproviderConfig.Kubevirt[\"Kubevirt\"] = newKubevirtCloudSpec()\n\tproviderConfig.Openstack[\"Openstack\"] = newOpenstackCloudSpec()\n\tproviderConfig.Packet[\"Packet\"] = newPacketCloudSpec()\n\tproviderConfig.Vsphere[\"Vsphere\"] = newVSphereCloudSpec()\n\n\treturn providerConfig\n}", "func newConfig(appName string, pathToKeybase string, log Log, ignoreSnooze bool) (*config, error) {\n\tcfg := newDefaultConfig(appName, pathToKeybase, log, ignoreSnooze)\n\terr := cfg.load()\n\treturn &cfg, err\n}", "func New() *Config {\n\treturn &Config{\n\t\tChecks: []*checkInstance{},\n\t}\n}", "func newConfig(envParams envParams) error {\n\t// Initialize server config.\n\tsrvCfg := newServerConfigV14()\n\n\t// If env is set for a fresh start, save them to config file.\n\tif globalIsEnvCreds {\n\t\tsrvCfg.SetCredential(envParams.creds)\n\t}\n\n\tif globalIsEnvBrowser {\n\t\tsrvCfg.SetBrowser(envParams.browser)\n\t}\n\n\t// Create config path.\n\tif err := createConfigDir(); err != nil {\n\t\treturn err\n\t}\n\n\t// hold the mutex lock before a new config is assigned.\n\t// Save the new config globally.\n\t// unlock the mutex.\n\tserverConfigMu.Lock()\n\tserverConfig = srvCfg\n\tserverConfigMu.Unlock()\n\n\t// Save config into file.\n\treturn serverConfig.Save()\n}", "func NewConfig() *component {\n\treturn &component{\n\t\tEnableDefaultStorageClass: true,\n\t\tEnableVolumeScheduling: true,\n\t\tEnableVolumeResizing: true,\n\t\tEnableVolumeSnapshot: true,\n\t\tReclaimPolicy: \"Retain\",\n\t}\n}", "func New(client, secret string) remote.Remote {\n\treturn &config{\n\t\tAPI: DefaultAPI,\n\t\tURL: DefaultURL,\n\t\tClient: client,\n\t\tSecret: secret,\n\t}\n}", "func newConfigV101() *configV1 {\n\tconf := new(configV1)\n\tconf.Version = mcCurrentConfigVersion\n\t// make sure to allocate map's otherwise Golang\n\t// exits silently without providing any errors\n\tconf.Hosts = make(map[string]*hostConfig)\n\tconf.Aliases = make(map[string]string)\n\n\tlocalHostConfig := new(hostConfig)\n\tlocalHostConfig.AccessKeyID = \"\"\n\tlocalHostConfig.SecretAccessKey = \"\"\n\n\ts3HostConf := new(hostConfig)\n\ts3HostConf.AccessKeyID = globalAccessKeyID\n\ts3HostConf.SecretAccessKey = globalSecretAccessKey\n\n\t// Your example host config\n\texampleHostConf := new(hostConfig)\n\texampleHostConf.AccessKeyID = globalAccessKeyID\n\texampleHostConf.SecretAccessKey = globalSecretAccessKey\n\n\tplayHostConfig := new(hostConfig)\n\tplayHostConfig.AccessKeyID = \"\"\n\tplayHostConfig.SecretAccessKey = \"\"\n\n\tdlHostConfig := new(hostConfig)\n\tdlHostConfig.AccessKeyID = \"\"\n\tdlHostConfig.SecretAccessKey = \"\"\n\n\tconf.Hosts[exampleHostURL] = exampleHostConf\n\tconf.Hosts[\"localhost:*\"] = localHostConfig\n\tconf.Hosts[\"127.0.0.1:*\"] = localHostConfig\n\tconf.Hosts[\"s3*.amazonaws.com\"] = s3HostConf\n\tconf.Hosts[\"play.minio.io:9000\"] = playHostConfig\n\tconf.Hosts[\"dl.minio.io:9000\"] = dlHostConfig\n\n\taliases := make(map[string]string)\n\taliases[\"s3\"] = \"https://s3.amazonaws.com\"\n\taliases[\"play\"] = \"https://play.minio.io:9000\"\n\taliases[\"dl\"] = \"https://dl.minio.io:9000\"\n\taliases[\"localhost\"] = \"http://localhost:9000\"\n\tconf.Aliases = aliases\n\n\treturn conf\n}", "func NewConfig() Config {\n\treturn Config{\n\t\tType: TypeNone,\n\t\tJaeger: NewJaegerConfig(),\n\t\tNone: struct{}{},\n\t}\n}", "func NewConfig(clientID, clientSecret string) *Config {\n\treturn &Config{\n\t\tClientID: clientID,\n\t\tClientSecret: clientSecret,\n\t}\n}", "func New() *Config {\n\tc := &Config{\n\t\tAgent: &AgentConfig{\n\t\t\tEventReceiverCount: 5,\n\t\t\tEventQueueLimit: 50,\n\t\t\tHealthCheckPort: 10240,\n\t\t\tLogLevel: \"info\",\n\t\t},\n\t\tPlugins: make([]*pluginrunner.PluginRunner, 0),\n\t\tEventKinds: make(map[events.EventKind]bool),\n\t}\n\treturn c\n}", "func New(config Config) (*Values, error) {\n\tif config.K8sClient == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.K8sClient 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\n\tr := &Values{\n\t\t// Dependencies.\n\t\tk8sClient: config.K8sClient,\n\t\tlogger: config.Logger,\n\t}\n\n\treturn r, nil\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tMode: \t\t gin.ReleaseMode,\n\t\tMiddlewares: []string{},\n\t\tHealthz: \t true,\n\t}\n}", "func New(version, commit, date, env string) *Config {\n\tc := &Config{\n\t\tName: \"Colligo\",\n\t\tVersion: version,\n\t\tCommit: commit,\n\t\tDate: date,\n\t\tEnvironment: env,\n\t}\n\n\t// Get Working Dir\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tc.WD = wd\n\n\t// Get Env Vars\n\ttw := Service{\n\t\tKey: os.Getenv(\"TWITTER_KEY\"),\n\t\tSecret: os.Getenv(\"TWITTER_SECRET\"),\n\t}\n\tc.Twitter = tw\n\n\treturn c\n}", "func NewConfig(config *configuration.Data, setTemplateRepoInfo TemplateRepoInfoSetter, clusterUser, clusterToken, clusterURL string) Config {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: config.APIServerInsecureSkipTLSVerify(),\n\t\t},\n\t}\n\n\tconf := Config{\n\t\tOriginalConfig: config,\n\t\tConsoleURL: config.GetConsoleURL(),\n\t\tHTTPTransport: tr,\n\t\tMasterUser: clusterUser,\n\t\tToken: clusterToken,\n\t\tMasterURL: clusterURL,\n\t}\n\treturn setTemplateRepoInfo(conf)\n}", "func NewConfig(args ...interface{}) (*Config, error) {\n\t// Implementation note: This factory is written with future\n\t// extensibility in mind. Only specific types are supported as\n\t// input, but in the future more might be added.\n\t//\n\t// This constructor ensures that callers can't construct\n\t// invalid Config values.\n\tvar c Config\n\tfor _, arg := range args {\n\t\tif afs, ok := arg.(AccessFSSet); ok {\n\t\t\tif !c.handledAccessFS.isEmpty() {\n\t\t\t\treturn nil, errors.New(\"only one AccessFSSet may be provided\")\n\t\t\t}\n\t\t\tif !afs.valid() {\n\t\t\t\treturn nil, errors.New(\"unsupported AccessFSSet value; upgrade go-landlock?\")\n\t\t\t}\n\t\t\tc.handledAccessFS = afs\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"unknown argument %v; only AccessFSSet-type argument is supported\", arg)\n\t\t}\n\t}\n\treturn &c, nil\n}", "func NewConfig(cmd *cobra.Command, prefix string) *Config {\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\toverrides := &clientcmd.ConfigOverrides{}\n\tcfg := &Config{\n\t\tloadingRules: loadingRules,\n\t\toverrides: overrides,\n\t}\n\tcmd.PersistentFlags().StringVar(&loadingRules.ExplicitPath, prefix+\"kubeconfig\", \"\", \"Path to a kubeconfig file. Alternative to env var $KUBECONFIG.\")\n\tcmd.PersistentFlags().IntVar(&cfg.qps, prefix+\"client-qps\", 0, \"QPS to use for K8s client, 0 for default\")\n\tcmd.PersistentFlags().IntVar(&cfg.burst, prefix+\"client-burst\", 0, \"Burst to use for K8s client, 0 for default\")\n\tcmd.PersistentFlags().Int64Var(&cfg.ListPageSize, prefix+\"list-page-size\", 1000, \"Maximum number of responses per page to return for a list call. 0 for no limit\")\n\tclientcmd.BindOverrideFlags(overrides, cmd.PersistentFlags(), clientcmd.ConfigOverrideFlags{\n\t\tAuthOverrideFlags: clientcmd.RecommendedAuthOverrideFlags(prefix),\n\t\tTimeout: clientcmd.FlagInfo{\n\t\t\tLongName: prefix + clientcmd.FlagTimeout,\n\t\t\tDefault: \"0\",\n\t\t\tDescription: \"The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests.\"},\n\t})\n\treturn cfg\n}", "func NewConfig() Config {\n\treturn Config{}\n}", "func NewConfig() Config {\n\treturn Config{}\n}", "func NewConfig(file string) (c *Config, err error) {\r\n\tvar gconf = goconf.New()\r\n\tc = &Config{}\r\n\tif err = gconf.Parse(file); err != nil {\r\n\t\treturn\r\n\t}\r\n\tif err = gconf.Unmarshal(c); err != nil {\r\n\t\treturn\r\n\t}\r\n\tc.setDefault()\r\n\treturn\r\n}", "func NewConfig(name string, logr klog.Logger, caller bool, callDepth int) *Config {\n\treturn &Config{\n\t\tName: name,\n\t\tLogger: logr,\n\t\tCaller: caller,\n\t\tCallDepth: callDepth,\n\t}\n}", "func NewConfig(apiDomain, apiKey string) *Config {\n\treturn &Config{apiDomain, apiKey}\n}", "func newConfig() *Config {\n\treturn &Config{\n\t\tgeneral{\n\t\t\tVerbose: false,\n\t\t},\n\t\tserver{\n\t\t\tType: \"http\",\n\t\t\tHost: \"0.0.0.0\",\n\t\t},\n\t\tmongo{\n\t\t\tHost: \"0.0.0.0:27017\",\n\t\t\tDatabase: \"etlog\",\n\t\t\tCollection: \"logs\",\n\t\t},\n\t}\n}", "func NewConfig() (c *Config, err error) {\n\tif config == nil {\n\t\t// Look for config file using environment variable\n\t\t// And if unset, use the current working directory\n\t\tn := os.Getenv(\"VROPSBOT_CONFIG_JSON\")\n\t\tif n == \"\" {\n\t\t\tn = configFilename\n\t\t}\n\n\t\tf, err := os.Open(n)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tdefer f.Close()\n\n\t\tif err := json.NewDecoder(f).Decode(&config); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tc = config\n\n\treturn\n}", "func NewConfig(impostersPath, host string, port int, opts ...ConfigOpt) (Config, error) {\n\tcfg := Config{\n\t\tImpostersPath: impostersPath,\n\t\tHost: host,\n\t\tPort: port,\n\t}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(&cfg); err != nil {\n\t\t\treturn Config{}, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}", "func NewConfig(r io.Reader, filename string, values map[string]string) (*Config, error) {\n\tc, err := newConfig(r, filename, values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, c.resolve()\n}", "func NewConfig(readUnits, writeUnits, readWorkers, writeWorkers int) Config {\n\treturn Config{\n\t\treadCapacityUnits: int64(readUnits),\n\t\twriteCapacityUnits: int64(writeUnits),\n\t\treadWorkers: readWorkers,\n\t\twriteWorkers: writeWorkers,\n\t}\n}", "func NewConfig(ver string) (Config, error) {\n\tif ver == \"\" {\n\t\treturn Config{}, errors.New(\"version is required\")\n\t}\n\n\treturn Config{Version: ver}, nil\n}", "func NewConfig() *TestProjectConfig {\n\tconfig := &TestProjectConfig{\n\t\tAccountID: \"accountId\",\n\t\tAnonymizeIP: true,\n\t\tAttributeKeyToIDMap: make(map[string]string),\n\t\tAudienceMap: map[string]entities.Audience{},\n\t\tAttributeMap: make(map[string]entities.Attribute),\n\t\tBotFiltering: true,\n\t\tExperimentKeyToIDMap: make(map[string]string),\n\t\tExperimentMap: make(map[string]entities.Experiment),\n\t\tEventMap: make(map[string]entities.Event),\n\t\tFeatureMap: make(map[string]entities.Feature),\n\t\tProjectID: \"projectId\",\n\t\tRevision: \"revision\",\n\t\tRolloutMap: make(map[string]entities.Rollout),\n\t\tSegments: []string{},\n\t\tIntegrations: []entities.Integration{},\n\t\tflagVariationsMap: make(map[string][]entities.Variation),\n\t\tPublicKeyForODP: \"publicKeyForODP\",\n\t\tHostForODP: \"hostForODP\",\n\t\tsdkKey: \"sdkKey\",\n\t}\n\n\treturn config\n}", "func ExampleNewConfig() {\n\t// Check for CORS config from cors.yml or config/cors.yml.\n\tconfig, err := ezcors.NewConfig()\n\tif err != nil {\n\t\tpanic(\"don't panic\")\n\t}\n\n\tfmt.Println(\"dev allowed origins:\", config[\"dev\"].AllowedOrigins)\n\tfmt.Println(\"dev allowed methods:\", config[\"dev\"].AllowedMethods)\n\tfmt.Println(\"dev allow credentials:\", config[\"dev\"].AllowCredentials)\n\tfmt.Println(\"dev debug:\", config[\"dev\"].Debug)\n\n\tfmt.Println(\"test allowed origins:\", config[\"test\"].AllowedOrigins)\n\tfmt.Println(\"test allowed methods:\", config[\"test\"].AllowedMethods)\n\tfmt.Println(\"test allow credentials:\", config[\"test\"].AllowCredentials)\n\tfmt.Println(\"test debug:\", config[\"test\"].Debug)\n\n\tfmt.Println(\"stage allowed origins:\", config[\"stage\"].AllowedOrigins)\n\tfmt.Println(\"prod allowed origins:\", config[\"prod\"].AllowedOrigins)\n\n\t// Check for CORS config from testdata/cors.yml.\n\tconfig, err = ezcors.NewConfig(ezcors.Option{\n\t\tPath: \"testdata/cors.yml\",\n\t})\n\tif err != nil {\n\t\tpanic(\"don't panic\")\n\t}\n\n\tfmt.Println(\"-----------\")\n\tfmt.Println(\"Custom Path\")\n\tfmt.Println(\"test allowed origins:\", config[\"test\"].AllowedOrigins)\n\tfmt.Println(\"stage allowed origins:\", config[\"stage\"].AllowedOrigins)\n\tfmt.Println(\"prod allowed origins:\", config[\"prod\"].AllowedOrigins)\n\n\t// Output:\n\t// dev allowed origins: [*]\n\t// dev allowed methods: [GET POST PUT PATCH DELETE]\n\t// dev allow credentials: false\n\t// dev debug: true\n\t// test allowed origins: [http://127.0.0.2 http://testhost.com]\n\t// test allowed methods: [POST]\n\t// test allow credentials: true\n\t// test debug: true\n\t// stage allowed origins: [http://127.0.0.3 http://stagehost.com]\n\t// prod allowed origins: [http://127.0.0.4 http://prodhost.com]\n\t// -----------\n\t// Custom Path\n\t// test allowed origins: [http://127.0.0.2 http://testhostcustom.com]\n\t// stage allowed origins: [http://127.0.0.3 http://stagehostcustom.com]\n\t// prod allowed origins: [http://127.0.0.4 http://prodhostcustom.com]\n}" ]
[ "0.7341069", "0.68238413", "0.6640498", "0.65082395", "0.6468099", "0.6457817", "0.6428905", "0.64268625", "0.64227784", "0.6390573", "0.6385709", "0.63830554", "0.63791794", "0.6338361", "0.62751126", "0.62710613", "0.62594914", "0.62594914", "0.6257439", "0.62159497", "0.6201112", "0.6199947", "0.6190151", "0.6189006", "0.61668235", "0.61481535", "0.61477906", "0.6143704", "0.6132998", "0.61318886", "0.61311454", "0.6125778", "0.6110274", "0.61087775", "0.6108314", "0.6102808", "0.60977334", "0.6085109", "0.6075581", "0.60748523", "0.6074124", "0.6069406", "0.6068997", "0.606882", "0.60593003", "0.6044744", "0.60420465", "0.6032742", "0.6026215", "0.602613", "0.60237056", "0.6016889", "0.600754", "0.5997907", "0.5995798", "0.5987797", "0.5974574", "0.59744453", "0.5974153", "0.59725165", "0.5964471", "0.5960625", "0.59485453", "0.59467506", "0.5941068", "0.5929946", "0.5919486", "0.5919028", "0.5917817", "0.59131515", "0.5912134", "0.5911972", "0.5909033", "0.590581", "0.58977187", "0.58962023", "0.58821714", "0.58804584", "0.5879189", "0.5878142", "0.5875919", "0.5875844", "0.587484", "0.58713907", "0.58659756", "0.5863936", "0.58627063", "0.58623594", "0.58623594", "0.5861261", "0.5859133", "0.5858822", "0.5854389", "0.58486354", "0.5847085", "0.58467364", "0.5845733", "0.58441585", "0.5838007", "0.5833194" ]
0.6419964
9
NewService creates a new instance of the EC2 client with a session.
func NewService(c *aws.Config) (*Service, error) { sess, err := session.NewSession(c) if err != nil { return nil, errors.Wrap(err, "failed to create new session") } return &Service{ec2.New(sess)}, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c PGClient) NewService(name string, binsIB int64, host string, port int, typeService string, runSTR string, projects []string, owner string) (err error) {\n\t_, err = c.DB.Query(\"select new_service_function($1,$2,$3,$4,$5,$6,$7,$8)\", name, binsIB, host, port, typeService, runSTR, pg.Array(projects), owner)\n\treturn err\n}", "func newService() *service {\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\treturn &service{\n\t\tctx: ctx,\n\t\tctxCancel: cancel,\n\t}\n}", "func newService(namespace, name string) *v1.Service {\n\treturn &v1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labelMap(),\n\t\t},\n\t\tSpec: v1.ServiceSpec{\n\t\t\tSelector: labelMap(),\n\t\t\tPorts: []v1.ServicePort{\n\t\t\t\t{Name: \"port-1338\", Port: 1338, Protocol: \"TCP\", TargetPort: intstr.FromInt(1338)},\n\t\t\t\t{Name: \"port-1337\", Port: 1337, Protocol: \"TCP\", TargetPort: intstr.FromInt(1337)},\n\t\t\t},\n\t\t},\n\t}\n\n}", "func newService(cr *argoprojv1a1.ArgoCD) *corev1.Service {\n\treturn &corev1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: argoutil.LabelsForCluster(cr),\n\t\t},\n\t}\n}", "func newService(serviceName string) *Service {\n\treturn &Service{\n\t\tpluginDir: serverless.PluginDir,\n\t\tname: serviceName,\n\t\tinterf: nil,\n\t}\n}", "func newService(c *onet.Context) (onet.Service, error) {\n\ts := &ServiceState{\n\t\tServiceProcessor: onet.NewServiceProcessor(c),\n\t}\n\thelloMsg := network.RegisterMessage(HelloMsg{})\n\tstopMsg := network.RegisterMessage(StopProtocol{})\n\tconnMsg := network.RegisterMessage(ConnectionRequest{})\n\tdisconnectMsg := network.RegisterMessage(DisconnectionRequest{})\n\n\tc.RegisterProcessorFunc(helloMsg, s.HandleHelloMsg)\n\tc.RegisterProcessorFunc(stopMsg, s.HandleStop)\n\tc.RegisterProcessorFunc(connMsg, s.HandleConnection)\n\tc.RegisterProcessorFunc(disconnectMsg, s.HandleDisconnection)\n\n\tif err := s.tryLoad(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn s, nil\n}", "func NewService(serv ServiceInterface) (*Service, error) {\n\tif serv == nil {\n\t\treturn nil, errors.New(\"coor must be non nil\")\n\t}\n\n\tstockRuntimeClient, err := NewStockRuntimeServiceClient()\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"failed to create new stock runtime service client\")\n\t\treturn nil, err\n\t}\n\n\tstockImageClient, err := NewStockImageServiceClient()\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"failed to create new stock image service client\")\n\t\treturn nil, err\n\t}\n\n\tcs := &Service{\n\t\tstockRuntimeClient: stockRuntimeClient,\n\t\tstockImageClient: stockImageClient,\n\t\tserv: serv,\n\t}\n\n\treturn cs, nil\n}", "func NewService(networkScope scope.NetworkScope) *Service {\n\treturn &Service{\n\t\tscope: networkScope,\n\t\tEC2Client: scope.NewEC2Client(networkScope, networkScope, networkScope, networkScope.InfraCluster()),\n\t}\n}", "func NewService(serviceName string) *ServiceObject {\n\tserviceObject := ServiceObject{}\n\tserviceObject.serviceName = serviceName\n\tserviceObject.serviceStatusHandle = 0\n\tserviceObject.serviceExit = make(chan bool)\n\treturn &serviceObject\n}", "func NewService(client *clients.Client) *Service {\n\treturn &Service{\n\t\tclient: client,\n\t}\n}", "func NewService(name, version string, store store.KeyValueStore) (*Service, error) {\n\tlog.Debugf(\"[Azure CNS] Going to create a service object with name: %v. version: %v.\", name, version)\n\n\tsvc := &Service{\n\t\tName: name,\n\t\tVersion: version,\n\t\tOptions: make(map[string]interface{}),\n\t\tStore: store,\n\t}\n\n\tlog.Debugf(\"[Azure CNS] Finished creating service object with name: %v. version: %v.\", name, version)\n\treturn svc, nil\n}", "func NewService(args []string, p person.Service, ns serializer.Serializer) error {\n\tcli := service{args, p, ns}\n\tif err := cli.checkArgs(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := cli.runArgs(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewService(config Config) *Service {\n\n\treturn &Service{\n\t\tclient: NewClient(config),\n\t}\n}", "func NewService(kv Store, configs ...ServiceConfig) *Service {\n\ts := &Service{\n\t\tLogger: zap.NewNop(),\n\t\tIDGenerator: snowflake.NewIDGenerator(),\n\t\t// Seed the random number generator with the current time\n\t\tOrgBucketIDs: rand.NewOrgBucketID(time.Now().UnixNano()),\n\t\tTokenGenerator: rand.NewTokenGenerator(64),\n\t\tHash: &Bcrypt{},\n\t\tkv: kv,\n\t\tTimeGenerator: influxdb.RealTimeGenerator{},\n\t}\n\n\tif len(configs) > 0 {\n\t\ts.Config = configs[0]\n\t} else {\n\t\ts.Config.SessionLength = influxdb.DefaultSessionLength\n\t}\n\n\treturn s\n}", "func NewService(c *config.Config) (*OSC, error) {\n\tvar o OSC\n\taddr := \"127.0.0.1:8765\"\n\to.server = &xosc.Server{Addr: addr}\n\n\treturn &o, nil\n}", "func newService(m *influxdatav1alpha1.Influxdb) *corev1.Service {\n\tls := labelsForInfluxdb(m.Name)\n\n\treturn &corev1.Service{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"Service\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: m.Name + \"-svc\",\n\t\t\tNamespace: m.Namespace,\n\t\t\tLabels: ls,\n\t\t},\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tSelector: ls,\n\t\t\tType: \"ClusterIP\",\n\t\t\tPorts: newServicePorts(m),\n\t\t},\n\t}\n}", "func NewService(http webreq.HTTP, secret string) Service {\n\treturn Service{\n\t\thttp: http,\n\t\tsecret: secret,\n\t}\n}", "func New() *service {\n\treturn &service{}\n}", "func NewService(cfg aws.Config) *Service {\n\treturn &Service{\n\t\tacm: acm.NewFromConfig(cfg), // v2\n\t\trds: rds.NewFromConfig(cfg), // v2\n\t\tiam: iam.NewFromConfig(cfg), // v2\n\t\ts3: s3.NewFromConfig(cfg), // v2\n\t\troute53: route53.NewFromConfig(cfg), // v2\n\t\tsecretsManager: secretsmanager.NewFromConfig(cfg), // v2\n\t\tresourceGroupsTagging: resourcegroupstaggingapi.NewFromConfig(cfg), // v2\n\t\tec2: ec2.NewFromConfig(cfg), // v2\n\t\tkms: kms.NewFromConfig(cfg), // v2\n\t\tdynamodb: dynamodb.NewFromConfig(cfg), // v2\n\t\tsts: sts.NewFromConfig(cfg), // v2\n\t\teks: eks.NewFromConfig(cfg), // v2\n\t\telb: newElasticLoadbalancerFromConfig(cfg),\n\t}\n}", "func NewService(name string, options types.ServiceCreateOptions) (*Service, error) {\n\tuuid, err := generateEntityID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\turls := strings.Split(options.URLs, \",\")\n\n\tfor _, u := range urls {\n\t\tu = strings.Trim(u, \" \")\n\t}\n\n\ts := Service{\n\t\tID: uuid,\n\t\tName: name,\n\t\tURLs: urls,\n\t\tTargetVersion: \"\",\n\t\tBalancingMethod: options.Balancing,\n\t\tIsEnabled: options.Enable,\n\t}\n\n\treturn &s, nil\n}", "func NewService(cfg *Config) (*AWSSNS, error) {\n\tsess, err := session.NewSession(\n\t\t&aws.Config{\n\t\t\tRegion: &cfg.Region,\n\t\t\tCredentials: credentials.NewStaticCredentials(cfg.AccessKey, cfg.Secret, \"\"),\n\t\t\tHTTPClient: cfg.HTTPClient,\n\t\t},\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsvc := sns.New(sess)\n\n\tawssns := &AWSSNS{\n\t\tcfg: cfg,\n\t\tsns: svc,\n\t}\n\n\treturn awssns, nil\n}", "func New(c *conf.Config) (s *Service) {\n\ts = &Service{\n\t\tc: c,\n\t}\n\tcardRPC, err := v1.NewClient(c.CardClient)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ts.cardRPC = cardRPC\n\treturn\n}", "func New(conf Config) (*Service, error) {\n\tvar service Service\n\n\t// launch server\n\tserver, err := transport.Launch(conf.Addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// prepare backend and configure logger\n\tbackend := newBackend(conf)\n\tbackend.Logger = service.eventHandler\n\n\t// prepare engine\n\tengine := broker.NewEngine(backend)\n\n\t// prepare server client for publishing outbox to device\n\tserverClient := client.New()\n\tcid := fmt.Sprintf(\"%s-%d\", serverClientID, time.Now().Unix())\n\t_, err = serverClient.Connect(client.NewConfigWithClientID(conf.Addr, cid))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tengine.Accept(server)\n\n\t// compose service\n\tservice.config = conf\n\tservice.client = serverClient\n\tservice.stats.ActiveClients = map[string]time.Time{}\n\tservice.activeClientFn = func(string) {}\n\tservice.closeFn = func() error {\n\t\tif err = serverClient.Disconnect(); err != nil {\n\t\t\treturn fmt.Errorf(\"closing client error\")\n\t\t}\n\n\t\tif !backend.Close(2 * time.Second) {\n\t\t\treturn fmt.Errorf(\"closing backend timed-out\")\n\t\t}\n\n\t\tif err = server.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tengine.Close()\n\t\treturn nil\n\t}\n\treturn &service, nil\n}", "func NewService(client *gophercloud.ProviderClient, clientOpts *clientconfig.ClientOpts, logger logr.Logger) (*Service, error) {\n\tidentityClient, err := openstack.NewIdentityV3(client, gophercloud.EndpointOpts{\n\t\tRegion: \"\",\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create identity service client: %v\", err)\n\t}\n\n\tcomputeClient, err := openstack.NewComputeV2(client, gophercloud.EndpointOpts{\n\t\tRegion: clientOpts.RegionName,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create compute service client: %v\", err)\n\t}\n\n\tnetworkingClient, err := openstack.NewNetworkV2(client, gophercloud.EndpointOpts{\n\t\tRegion: clientOpts.RegionName,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create networking service client: %v\", err)\n\t}\n\n\timagesClient, err := openstack.NewImageServiceV2(client, gophercloud.EndpointOpts{\n\t\tRegion: clientOpts.RegionName,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create image service client: %v\", err)\n\t}\n\n\tif clientOpts.AuthInfo == nil {\n\t\treturn nil, fmt.Errorf(\"failed to get project id: authInfo must be set\")\n\t}\n\n\tprojectID := clientOpts.AuthInfo.ProjectID\n\tif projectID == \"\" && clientOpts.AuthInfo.ProjectName != \"\" {\n\t\tprojectID, err = provider.GetProjectID(client, clientOpts.AuthInfo.ProjectName)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error retrieveing project id: %v\", err)\n\t\t}\n\t}\n\tif projectID == \"\" {\n\t\treturn nil, fmt.Errorf(\"failed to get project id\")\n\t}\n\n\tnetworkingService, err := networking.NewService(client, clientOpts, logger)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create networking service: %v\", err)\n\t}\n\n\treturn &Service{\n\t\tprovider: client,\n\t\tprojectID: projectID,\n\t\tidentityClient: identityClient,\n\t\tcomputeClient: computeClient,\n\t\tnetworkClient: networkingClient,\n\t\tnetworkingService: networkingService,\n\t\timagesClient: imagesClient,\n\t\tlogger: logger,\n\t}, nil\n}", "func NewService(ctx context.Context, client *http.Client) (*Service, error) {\n\tmsClient := NewClient(ctx, client)\n\tsvc := &Service{\n\t\tctx: ctx,\n\t\tclient: msClient,\n\t}\n\treturn svc, nil\n}", "func New(pairs ...*types.Pair) (s *Service, err error) {\n\tconst errorMessage = \"%s New: %w\"\n\n\ts = &Service{}\n\n\topt, err := parseServicePairNew(pairs...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(errorMessage, s, err)\n\t}\n\n\tcredProtocol, cred := opt.Credential.Protocol(), opt.Credential.Value()\n\tif credProtocol != credential.ProtocolHmac {\n\t\treturn nil, fmt.Errorf(errorMessage, s, err)\n\t}\n\n\tmac := qbox.NewMac(cred[0], cred[1])\n\tcfg := &qs.Config{}\n\ts.service = qs.NewBucketManager(mac, cfg)\n\treturn\n}", "func NewService(ctx context.Context) (*Service, error) {\n\tclient, _, err := htransport.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsvc := &Service{client: client, BasePath: basePath}\n\tsvc.API = New(svc)\n\n\treturn svc, nil\n}", "func NewService() Service {\n\treturn Service{}\n}", "func newService(name, project, image string, envs map[string]string, options options) *runapi.Service {\n\tvar envVars []*runapi.EnvVar\n\tfor k, v := range envs {\n\t\tenvVars = append(envVars, &runapi.EnvVar{Name: k, Value: v})\n\t}\n\n\tsvc := &runapi.Service{\n\t\tApiVersion: \"serving.knative.dev/v1\",\n\t\tKind: \"Service\",\n\t\tMetadata: &runapi.ObjectMeta{\n\t\t\tAnnotations: make(map[string]string),\n\t\t\tName: name,\n\t\t\tNamespace: project,\n\t\t},\n\t\tSpec: &runapi.ServiceSpec{\n\t\t\tTemplate: &runapi.RevisionTemplate{\n\t\t\t\tMetadata: &runapi.ObjectMeta{\n\t\t\t\t\tName: generateRevisionName(name, 0),\n\t\t\t\t\tAnnotations: make(map[string]string),\n\t\t\t\t},\n\t\t\t\tSpec: &runapi.RevisionSpec{\n\t\t\t\t\tContainerConcurrency: int64(options.Concurrency),\n\t\t\t\t\tContainers: []*runapi.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tImage: image,\n\t\t\t\t\t\t\tEnv: envVars,\n\t\t\t\t\t\t\tResources: optionsToResourceRequirements(options),\n\t\t\t\t\t\t\tPorts: []*runapi.ContainerPort{optionsToContainerSpec(options)},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tForceSendFields: nil,\n\t\t\t\tNullFields: nil,\n\t\t\t},\n\t\t},\n\t}\n\n\tapplyMeta(svc.Metadata, image)\n\tapplyMeta(svc.Spec.Template.Metadata, image)\n\tapplyScaleMeta(svc.Spec.Template.Metadata, \"maxScale\", options.MaxInstances)\n\n\treturn svc\n}", "func NewService(conf config.Config) *Service {\n\ttoken := tokenModule.New(conf.LoadPrivateKey(), conf.LoadPublicKey(), 12*time.Hour)\n\n\tservice := new(Service)\n\tservice.conf = conf\n\tservice.token = token\n\treturn service\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 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 New(pairs ...*types.Pair) (s *Service, err error) {\n\tconst errorMessage = \"%s New: %w\"\n\n\ts = &Service{}\n\n\topt, err := parseServicePairNew(pairs...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(errorMessage, s, err)\n\t}\n\n\tcredProtocol, cred := opt.Credential.Protocol(), opt.Credential.Value()\n\tif credProtocol != credential.ProtocolHmac {\n\t\treturn nil, fmt.Errorf(errorMessage, s, credential.ErrUnsupportedProtocol)\n\t}\n\tep := opt.Endpoint.Value()\n\n\ts.service, err = oss.New(ep.String(), cred[0], cred[1])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(errorMessage, s, err)\n\t}\n\treturn\n}", "func NewService(region, bucket, accessKeyID, secret string) (*Service, error) {\n\tsess, err := session.NewSession(&aws.Config{\n\t\tRegion: &region,\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secret, \"\"),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := s3.New(sess)\n\tuploader := s3manager.NewUploader(sess)\n\n\treturn &Service{\n\t\tclient: client,\n\t\tBucket: bucket,\n\t\tuploader: uploader,\n\t}, nil\n}", "func NewService(m map[string]interface{}) Service {\n\treturn m\n}", "func NewService(ctx *pulumi.Context,\n\tname string, args *ServiceArgs, opts ...pulumi.ResourceOption) (*Service, error) {\n\tif args == nil {\n\t\targs = &ServiceArgs{}\n\t}\n\n\tvar resource Service\n\terr := ctx.RegisterResource(\"aws:vpclattice/service:Service\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewService(cli helmcli.Client) Service {\n\treturn Service{cli}\n}", "func New() Service {\n\treturn &service{}\n}", "func New() Service {\n\treturn &service{}\n}", "func NewService(config *Config, pastelClient pastel.Client, nodeClient node.Client) *Service {\n\treturn &Service{\n\t\tconfig: config,\n\t\tpastelClient: pastelClient,\n\t\tnodeClient: nodeClient,\n\t\tWorker: task.NewWorker(),\n\t}\n}", "func NewService() Service {\n\treturn Service{\n\t\tclient: &http.Client{\n\t\t\t// TODO Make timeout configurable.\n\t\t\tTimeout: 10 * time.Second,\n\t\t},\n\t\tauthURL: authURL,\n\t\tregistryURL: registryURL,\n\t\tserviceURL: serviceURL,\n\t}\n}", "func New() *Service {\n\ts := new(Service)\n\ts.GoRoutines = sdk.NewGoRoutines(context.Background())\n\treturn s\n}", "func NewService() *Service {\n\treturn &Service{\n\t\tclients: make(map[Client]bool),\n\t\tregister: make(chan Client),\n\t\tunregister: make(chan Client),\n\t\tbroadcast: make(chan *payload),\n\t}\n}", "func NewService(ctx *pulumi.Context,\n\tname string, args *ServiceArgs, opts ...pulumi.ResourceOption) (*Service, error) {\n\tif args == nil {\n\t\targs = &ServiceArgs{}\n\t}\n\tvar resource Service\n\terr := ctx.RegisterResource(\"aws:servicediscovery/service:Service\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func New(name string) *Service {\n\tctx, cancel := context.WithCancel(context.Background())\n\treturn &Service{\n\t\tctx: ctx,\n\t\tname: name,\n\t\tcancel: cancel,\n\t\tstate: Idle,\n\t\tshutdown: make(chan struct{}),\n\t\tdone: make(chan struct{}),\n\t}\n}", "func NewService(config Config) *Service {\n\treturn &Service{\n\t\tinstances: new(sync.Map),\n\t\tconfig: config,\n\t}\n}", "func New(c *rpc.ClientConfig) (s *Service) {\n\ts = &Service{}\n\ts.client = rpc.NewDiscoveryCli(_appid, c)\n\treturn\n}", "func NewService(spotifyUser string) *Service {\n\tsc := spotify.NewClient(spotifyUser)\n\tsgc := seatgeek.NewClient()\n\treturn &Service{\n\t\tSpotify: sc,\n\t\tSeatGeek: sgc}\n}", "func NewService(secret []byte) Service {\n\treturn &basicService{secret: secret}\n}", "func NewService(savedPath string) *Service {\n\treturn &Service{\n\t\tsavedPath: savedPath,\n\t}\n}", "func New(c config.Service, pm *procman.ProcessManager) (svc *Service, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = r.(error)\n\t\t}\n\t}()\n\tsvc = &Service{\n\t\tAutoStart: c.AutoStart,\n\t\tProxy: c.Proxy,\n\t\tCommand: pm.Process(c),\n\t\tTimeout: config.ParseDuration(c.Timeout, config.DefaultTimeout),\n\t\tStopAfter: config.ParseDuration(c.StopAfter, config.DefaultStopAfter),\n\t}\n\treturn\n}", "func NewService(host, dockerAPIVersion string, defaultHeaders map[string]string) *Service {\n\tclient, err := client.NewClient(host, dockerAPIVersion, nil, defaultHeaders)\n\tif err != nil {\n\t\tfmt.Printf(\"Something went wrong when tries to connect on the docker host: %s\", err.Error())\n\t}\n\n\treturn &Service{\n\t\thost,\n\t\tclient,\n\t}\n}", "func NewService(key string) *Service {\n\treturn &Service{\n\t\tURLFormat: defaultURLFormat,\n\t\tKey: key,\n\t\tTimeout: defaultTimeout,\n\t}\n}", "func NewService(g *Greeter) *Service {\n\treturn &Service{greeter: g}\n}", "func NewService(ci CIServer, r Repository) *Service {\n\treturn &Service{ci, r}\n}", "func New(cl hue.Client) (*Service, error) {\n\tif cl == nil {\n\t\treturn nil, errors.New(\"required Philips Hue client was no supplied\")\n\t}\n\n\treturn &Service{\n\t\thue: cl,\n\t}, nil\n}", "func New() *Service {\n\treturn &Service{}\n}", "func New() *Service {\n\treturn &Service{}\n}", "func New() *Service {\n\treturn &Service{}\n}", "func (c *Client) NewService(name string, fn func(cc *grpc.ClientConn) (interface{}, error)) error {\n\tif _, ok := c.services[name]; ok {\n\t\treturn fmt.Errorf(\"service %s client has existed\", name)\n\t}\n\tsvc, err := fn(c.conn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.services[name] = svc\n\n\treturn nil\n}", "func New(d database.Service, passphrase string) (*client, error) {\n\t// immediately return if a nil database Service is provided\n\tif d == nil {\n\t\treturn nil, fmt.Errorf(\"empty Database client passed to native secret engine\")\n\t}\n\n\t// create the client object\n\tclient := &client{\n\t\tNative: d,\n\t\tpassphrase: passphrase,\n\t}\n\n\treturn client, nil\n}", "func New(c service.GapidClient) service.Service {\n\treturn &client{c, func() error { return nil }}\n}", "func newService(c *onet.Context) (onet.Service, error) {\n\ts := &Service{\n\t\tServiceProcessor: onet.NewServiceProcessor(c),\n\t}\n\ts.RegisterProcessorFunc(cosiSendRawID, s.HandleRaw)\n\t_, err := c.ProtocolRegister(protoName, s.NewDefaultProtocol)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := s.RegisterHandlers(s.GenesisTx, s.Setup, s.TreesBLSCoSi, s.MemoryAllocated); err != nil {\n\t\treturn nil, errors.New(\"Couldn't register messages\")\n\t}\n\n\ts.propagateF, s.mypi, err = propagate.NewPropagationFunc(c, \"Propagate\", s.propagateHandler, -1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.trees = make(map[onet.TreeID]*onet.Tree)\n\ts.coinToAtomic = make(map[string]int)\n\ts.atomicCoinReserved = make([]int32, 0)\n\n\tdb, bucketNameTx := s.GetAdditionalBucket([]byte(\"Tx\"))\n\t_, bucketNameLastTx := s.GetAdditionalBucket([]byte(\"LastTx\"))\n\ts.bucketNameTx = bucketNameTx\n\ts.bucketNameLastTx = bucketNameLastTx\n\ts.db = db\n\treturn s, nil\n}", "func NewService(c *Config) *Service {\n\ts := &Service{\n\t\taddr: c.BindAddress,\n\t\ttls: c.UseTls,\n\t\tcertFile: c.CertFile,\n\t\tkeyFile: c.KeyFile,\n\t\terr: make(chan error),\n\t\thlr: api.NewNegHandler(),\n\t}\n\treturn s\n}", "func NewService(cred interfaces.IAWSCredentials, region *regions.Region) *KinesisService {\n\treturn &KinesisService{cred, region, \"https://\" + ServiceName + \".\" + region.Name() + \".amazonaws.com\"}\n}", "func New(client *http.Client) (*Service, error) {\n\tif client == nil {\n\t\treturn nil, errors.New(\"client is nil\")\n\t}\n\ts := &Service{client: client, BasePath: basePath}\n\ts.LicenseAssignments = NewLicenseAssignmentsService(s)\n\treturn s, nil\n}", "func NewService(driver neo4j.Driver) *Service {\n\treturn &Service{\n\t\tdriver: driver,\n\t}\n}", "func NewService(name, url string) Service {\n\treturn Service{\n\t\tName: name,\n\t\tURL: url,\n\t}\n}", "func NewService() (service.Service, error) {\n\treturn &Service{}, nil\n}", "func NewService(addr string) *Service {\n\treturn &Service{\n\t\taddr: addr,\n\t}\n}", "func NewService(r repository, e event) *Service {\n\treturn &Service{r, e}\n}", "func New() Service {\n\tvar svc Service\n\t{\n\t\tsvc = NewBasicService()\n\t}\n\treturn svc\n}", "func NewService(clusterScope cloud.ClusterScoper, opts ...ServiceOption) *Service {\n\tsvc := &Service{\n\t\tscope: clusterScope,\n\t\telbClient: scope.NewELBClient(clusterScope, clusterScope, clusterScope, clusterScope.InfraCluster()),\n\t\telbv2Client: scope.NewELBv2Client(clusterScope, clusterScope, clusterScope, clusterScope.InfraCluster()),\n\t\tresourceTaggingClient: scope.NewResourgeTaggingClient(clusterScope, clusterScope, clusterScope, clusterScope.InfraCluster()),\n\t\tec2Client: scope.NewEC2Client(clusterScope, clusterScope, clusterScope, clusterScope.InfraCluster()),\n\t\tcleanupFuncs: ResourceCleanupFuncs{},\n\t\tcollectFuncs: ResourceCollectFuncs{},\n\t}\n\taddDefaultCleanupFuncs(svc)\n\n\tfor _, opt := range opts {\n\t\topt(svc)\n\t}\n\n\treturn svc\n}", "func NewService() *Service {\n\ts := &Service{\n\t\tch: make(chan bool),\n\t\twaitGroup: &sync.WaitGroup{},\n\t}\n\ts.waitGroup.Add(1)\n\treturn s\n}", "func NewService(subscriptionID string) *Service {\n\treturn &Service{\n\t\tDisksClient: compute.NewDisksClient(subscriptionID),\n\t\tVirtualMachinesClient: compute.NewVirtualMachinesClient(subscriptionID),\n\t\tctx: context.Background(),\n\t}\n}", "func New() endly.Service {\n\tvar result = &service{\n\t\tAbstractService: endly.NewAbstractService(ServiceID),\n\t}\n\tresult.AbstractService.Service = result\n\tresult.registerRoutes()\n\treturn result\n}", "func New() endly.Service {\n\tvar result = &service{\n\t\tAbstractService: endly.NewAbstractService(ServiceID),\n\t}\n\tresult.AbstractService.Service = result\n\tresult.registerRoutes()\n\treturn result\n}", "func New() endly.Service {\n\tvar result = &service{\n\t\tAbstractService: endly.NewAbstractService(ServiceID),\n\t}\n\tresult.AbstractService.Service = result\n\tresult.registerRoutes()\n\treturn result\n}", "func NewService(scope VMScope, skuCache *resourceskus.Cache) *Service {\n\treturn &Service{\n\t\tScope: scope,\n\t\tClient: NewClient(scope),\n\t\tInterfacesClient: networkinterfaces.NewClient(scope),\n\t\tPublicIPsClient: publicips.NewClient(scope),\n\t\tResourceSKUCache: skuCache,\n\t}\n}", "func New() endly.Service {\n\tvar result = &service{\n\t\tjdkService: &jdkService{},\n\t\tgoService: &goService{},\n\t\tnodeService: &nodeService{},\n\t\tAbstractService: endly.NewAbstractService(ServiceID),\n\t}\n\tresult.AbstractService.Service = result\n\tresult.registerRoutes()\n\treturn result\n}", "func NewService(vendor string, product string, version string, url string) (*Service, error) {\n\ts := Service{\n\t\tvendor: vendor,\n\t\tproduct: product,\n\t\tversion: version,\n\t\turl: url,\n\t\tinterfaces: make(map[string]dispatcher),\n\t\tdescriptions: make(map[string]string),\n\t}\n\terr := s.RegisterInterface(orgvarlinkserviceNew())\n\n\treturn &s, err\n}", "func NewService(host, port, book, samhost, samport string, subs []string, useh bool) {\n\ts, err := NewServerFromOptions(\n\t\tSetServerHost(host),\n\t\tSetServerPort(port),\n\t\tSetServerAddressBookPath(book),\n\t\tSetServerUseHelper(useh),\n\t\tSetServerJumpHelperHost(samhost),\n\t\tSetServerJumpHelperPort(samport),\n\t\tSetServerSubscription(subs),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err, \"Error starting server\")\n\t}\n\tgo s.Serve()\n}", "func NewService() *Service {\n\treturn &Service{}\n}", "func NewService() *Service {\n\treturn &Service{}\n}", "func NewService() *Service {\n\treturn &Service{}\n}", "func NewService() *Service {\n\treturn &Service{}\n}", "func NewService(name string) *Service {\n\treturn &Service{\n\t\tname: name,\n\t}\n}", "func New(selfPeer *p2p.Peer, shardID uint32, GetNodeIDs func() []libp2p_peer.ID, GetAccountBalance func(common.Address) (*big.Int, error)) *Service {\n\treturn &Service{\n\t\tIP: selfPeer.IP,\n\t\tPort: selfPeer.Port,\n\t\tShardID: shardID,\n\t\tGetNodeIDs: GetNodeIDs,\n\t\tGetAccountBalance: GetAccountBalance,\n\t}\n}", "func NewService(scope scope.ScopeInterface) *Service {\n\treturn &Service{\n\t\tClient: getVipPoolsClient(scope.GetCloudAgentFqdn(), scope.GetAuthorizer()),\n\t\tScope: scope,\n\t}\n}", "func New(awsConfig client.ConfigProvider, logger *zap.SugaredLogger) (*Service, error) {\n\t// set up database\n\tdb, err := database.New(awsConfig, logger)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to init database: %s\", err.Error())\n\t}\n\n\t// create service\n\treturn &Service{\n\t\tl: logger.Named(\"service\"),\n\t\tdb: db,\n\t}, nil\n}", "func New() *Service {\n\ts := new(Service)\n\ts.GoRoutines = sdk.NewGoRoutines(context.Background())\n\ts.Router = &api.Router{\n\t\tMux: mux.NewRouter(),\n\t}\n\treturn s\n}", "func NewService(coreConfig *core.Config, basefs *basefs.BaseFS) *Service {\n\n\tserviceConfig := Config{}\n\tlog.Println(\"Initializing\", pname, \"service\")\n\tlog.Println(\"Source config:\", coreConfig.Source)\n\n\terr := coreutil.ParseConfig(coreConfig.Source, &serviceConfig)\n\tif err != nil {\n\t\terrlog.Fatalf(\"Unable to read <source>: %v\", err)\n\t}\n\t// Initialize cloud service here\n\tm := mega.New()\n\tm.Login(serviceConfig.Credentials.Email, serviceConfig.Credentials.Password)\n\n\treturn &Service{m, basefs}\n\n}", "func New(config ServiceConfig) *Service {\n\n\ts := &Service{\n\t\tPeerAdded: make(chan string),\n\t\tPeerRemoved: make(chan string),\n\t\tstopChan: make(chan interface{}),\n\t\tpeers: make(peerMap),\n\t\tconfig: config,\n\t}\n\n\t// Spawn a new goroutine for managing peers.\n\tgo s.run()\n\n\treturn s\n}", "func NewService() Service {\n\treturn &service{}\n}", "func NewService() Service {\n\treturn &service{}\n}", "func NewService() Service {\n\treturn &service{}\n}", "func NewService(server string) (Service, error) {\n\tif strings.HasPrefix(server, \"ssh://\") {\n\t\treturn NewSSHService(server)\n\t}\n\n\tif strings.HasPrefix(server, \"mrt://\") {\n\t\treturn NewMarathonService(server)\n\t}\n\n\treturn nil, ErrServiceNotFound\n}", "func NewService(\n\tlc fx.Lifecycle,\n\tcfg *config.Config,\n\tcfgManager *config.DynamicConfigManager,\n\tcustomProvider *region.DataProvider,\n\tetcdClient *clientv3.Client,\n\tpdClient *pd.Client,\n\tdb *dbstore.DB,\n\ttidbClient *tidb.Client,\n) *Service {\n\ts := &Service{\n\t\tstatus: utils.NewServiceStatus(),\n\t\tconfig: cfg,\n\t\tcfgManager: cfgManager,\n\t\tcustomProvider: customProvider,\n\t\tetcdClient: etcdClient,\n\t\tpdClient: pdClient,\n\t\tdb: db,\n\t\ttidbClient: tidbClient,\n\t}\n\n\tlc.Append(s.managerHook())\n\n\treturn s\n}", "func NewService(config ServiceConfig) (*Service, error) {\n\t// Dependencies.\n\tif config.IDService == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"ID service must not be empty\")\n\t}\n\tif config.PeerCollection == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"peer collection must not be empty\")\n\t}\n\n\tID, err := config.IDService.New()\n\tif err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\n\tnewService := &Service{\n\t\t// Dependencies.\n\t\tpeer: config.PeerCollection,\n\n\t\t// Internals.\n\t\tbootOnce: sync.Once{},\n\t\tcloser: make(chan struct{}, 1),\n\t\tmetadata: map[string]string{\n\t\t\t\"id\": ID,\n\t\t\t\"kind\": \"read/information/sequence\",\n\t\t\t\"name\": \"clg\",\n\t\t\t\"type\": \"service\",\n\t\t},\n\t\tshutdownOnce: sync.Once{},\n\t}\n\n\treturn newService, nil\n}", "func NewService(name string) (*Service, error) {\n\tserviceLock.Lock()\n\tdefer serviceLock.Unlock()\n\n\tif _, ok := services[name]; ok {\n\t\treturn nil, errors.New(fmt.Sprintf(\"service '%s' already exists\", name))\n\t}\n\n\tservices[name] = &Service{\n\t\tName: name,\n\t\tEnabled: false,\n\t\tRole: ROLE_WEBSERVER,\n\t\tListeners: make(map[string]*ServiceListener),\n\t}\n\n\tgo services[name].requestPump()\n\n\treturn services[name], nil\n}" ]
[ "0.6918659", "0.6759272", "0.6732525", "0.66946626", "0.6669318", "0.66284686", "0.6610021", "0.660634", "0.660149", "0.65938777", "0.6586359", "0.6562283", "0.6554421", "0.65464216", "0.65458965", "0.6543939", "0.65203875", "0.65024567", "0.6498615", "0.64954954", "0.6478836", "0.6474353", "0.6471865", "0.6464784", "0.64505124", "0.6449364", "0.64332736", "0.64319396", "0.6422049", "0.64134526", "0.6412306", "0.63856304", "0.6380337", "0.6379009", "0.6373996", "0.6368671", "0.63646865", "0.63505113", "0.63505113", "0.6347347", "0.6346613", "0.63403666", "0.6335919", "0.632442", "0.63225293", "0.6307239", "0.63055784", "0.63029313", "0.6299762", "0.62848073", "0.6281245", "0.6276933", "0.6274459", "0.62741727", "0.6273308", "0.62729776", "0.62668043", "0.62668043", "0.62668043", "0.6261062", "0.6256187", "0.6250331", "0.62449145", "0.6243279", "0.6222379", "0.6221408", "0.6212739", "0.6208672", "0.6207981", "0.620754", "0.62069875", "0.62063366", "0.62022525", "0.61976814", "0.6192017", "0.61843663", "0.61843663", "0.61843663", "0.6177791", "0.6177379", "0.61726564", "0.61640173", "0.61595833", "0.61595833", "0.61595833", "0.61595833", "0.61493367", "0.61478627", "0.6145264", "0.61376333", "0.6136763", "0.61302924", "0.61228484", "0.6120342", "0.6120342", "0.6120342", "0.6117582", "0.61160874", "0.6114506", "0.61105955" ]
0.7535344
0
FetchLatestAmiInfo is request to aws api, and fetch latest ami information.
func (s *Service) FetchLatestAmiInfo() (amiInfo *ec2.Image, err error) { params := &ec2.DescribeImagesInput{ Owners: []*string{ aws.String("amazon"), }, Filters: []*ec2.Filter{ { Name: aws.String("image-type"), Values: []*string{ aws.String("machine"), }, }, { Name: aws.String("architecture"), Values: []*string{ aws.String("x86_64"), }, }, {Name: aws.String("root-device-type"), Values: []*string{aws.String("ebs")}}, {Name: aws.String("virtualization-type"), Values: []*string{ aws.String("hvm"), }, }, { Name: aws.String("state"), Values: []*string{ aws.String("available"), }, }, }, } resp, err := s.DescribeImages(params) if err != nil { return } var amis []*ec2.Image for _, v := range resp.Images { if m := strings.HasPrefix(*v.ImageLocation, "amazon/amzn-ami-hvm"); m { amis = append(amis, v) } } sort.Slice(amis, func(i, j int) bool { return *amis[i].CreationDate > *amis[j].CreationDate }) amiInfo = amis[0] return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *API) fetchLatestBlock() (*Block, error) {\n\tb := &Block{}\n\tif err := net.GetJSON(\"https://blockchain.info/latestblock\", b); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}", "func (s *ReplicationJob) SetLatestAmiId(v string) *ReplicationJob {\n\ts.LatestAmiId = &v\n\treturn s\n}", "func LatestImage(level int) (image.Image, error) {\n\tvar (\n\t\terr error\n\t\tcode int\n\t\ttry int\n\t\tbody []byte\n\t\tlatest = new(latestInfo)\n\t)\n\tlog.Println(\"Fetching latest image info\")\n\tfor (err != nil || code != 200) && try <= config.HTTPRetryTimes {\n\t\ttry++\n\t\tcode, body, err = fasthttp.GetTimeout(nil, LatestInfoURL, config.HTTPTimesout)\n\t}\n\tif err != nil || code != 200 {\n\t\tlog.Printf(\"fetch latest image info from %s failed, code: %d err: %v\",\n\t\t\tLatestInfoURL, code, err)\n\t\treturn nil, fmt.Errorf(\"fetch latest info failed\")\n\t}\n\terr = json.Unmarshal(body, latest)\n\tif err != nil {\n\t\tlog.Printf(\"unmarshal JSON %s failed, err: %v\",\n\t\t\tstring(body), err)\n\t\treturn nil, fmt.Errorf(\"decode latest info failed\")\n\t}\n\tlog.Printf(\"Latest version: %v\", latest.Date.Local())\n\treturn buildImage(level, time.Time(latest.Date.Time))\n}", "func (c *Client) Latest(ctx context.Context) (Comic, error) {\n\treturn c.do(ctx, fmt.Sprintf(\"/info.0.json\"))\n}", "func FetchAWSMetadata() {\n\tdefer trace()()\n\t//get EC2 metadata\n\tsess := session.Must(session.NewSession(&aws.Config{\n\t\tRegion: aws.String(conf.UCMConfig.MetadataReporting.AWSRegion),\n\t}))\n\tsvc := ec2metadata.New(sess)\n\tif svc.Available() {\n\t\t//\t\tiddoc, err := svc.GetInstanceIdentityDocument()\n\t\tresp, err := svc.GetDynamicData(\"instance-identity/document\")\n\t\tif err != nil {\n\t\t\tlog.Errorln(\"EC2Metadata Request Error. Failed to get EC2 Identity document.\", err)\n\t\t\treturn\n\t\t}\n\n\t\tvar doc interface{}\n\t\terr = json.NewDecoder(strings.NewReader(resp)).Decode(&doc)\n\t\tif err != nil {\n\t\t\tlog.Errorln(\"EC2Metadata Request Error. Failed to decode EC2 instance identity document.\", err)\n\t\t\treturn\n\t\t}\n\n\t\tm := doc.(map[string]interface{})\n\t\tfor k, v := range m {\n\t\t\tswitch vv := v.(type) {\n\t\t\tcase string:\n\t\t\t\tlabels[k] = v.(string)\n\t\t\tcase int:\n\t\t\t\tlabels[k] = strconv.Itoa(v.(int))\n\t\t\tcase []interface{}:\n\t\t\t\tlabels[k] = strings.Join(v.([]string), \";\")\n\t\t\tdefault:\n\t\t\t\tlog.Infoln(\"Found an unknown type\", vv)\n\t\t\t}\n\t\t}\n\t}\n}", "func (sc *snapshotInfoContainer) GetLatest() SnapshotInfo {\n\te := sc.snapshotList.Front()\n\n\tif e == nil {\n\t\treturn nil\n\t} else {\n\t\treturn e.Value.(SnapshotInfo)\n\t}\n}", "func GetLatestAccountInfo(bic string, iban string) (*model.AccountInfo, error) {\n\tpath := fmt.Sprintf(\"%s/%s/%s\",\n\t\tconfig.Configuration.Seaweed.AccountFolder,\n\t\tbic,\n\t\tiban)\n\tdirectory, err := filer.ReadDirectory(path, \"\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(directory.Files) == 0 {\n\t\treturn nil, fmt.Errorf(\"There is no latest accountInfo for %s\", path)\n\t}\n\n\tlatestAccountInfoFileName := directory.Files[len(directory.Files)-1].Name\n\tlatestAccountInfoJSON, err := filer.Read(latestAccountInfoFileName, path)\n\n\taccountInfo, err := parseAccountInfo(latestAccountInfoJSON)\n\n\tif err != nil {\n\n\t\treturn nil, err\n\t}\n\n\treturn accountInfo, nil\n}", "func (a *API) fetchAddressInfo(address string, pLimit int, pOffset int) (*AddressInfo, error) {\n\turl := fmt.Sprintf(\"https://blockchain.info/rawaddr/%s?n=%d&offset=%d\", address, pLimit, pOffset)\n\tad := &AddressInfo{}\n\tif err := net.GetJSON(url, ad); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ad, nil\n}", "func (sii SortedImageInfos) Latest() (image.Info, bool) {\n\tif len(sii) > 0 {\n\t\treturn sii[0], true\n\t}\n\treturn image.Info{}, false\n}", "func (c *Client) Latest(page int) ([]Manga, error) {\n\tres, err := c.get(c.base+\"/mrs_latest\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar mangas []Manga\n\tif err := json.Unmarshal(res, &mangas); err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not unmarshal latest mangas\")\n\t}\n\tids := make([]string, len(mangas))\n\tfor i, manga := range mangas {\n\t\tids[i] = manga.ID\n\t}\n\tmangas, err = c.mangasByIDs(ids)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not get latest mangas by ids\")\n\t}\n\treturn c.addAuthors(mangas)\n}", "func (br *BlockRepository) RetrieveLatest() (*types.Block, *rTypes.Error) {\n\trf := &recordFile{}\n\tif br.dbClient.Raw(selectLatestWithIndex).Scan(rf).RecordNotFound() {\n\t\treturn nil, errors.Errors[errors.BlockNotFound]\n\t}\n\n\treturn br.constructBlockResponse(rf, rf.BlockIndex), nil\n}", "func FindLatestLog(apiName string) *structs.TApiCalledLog {\r\n\tdbmap, e := dbConnect()\r\n\tif e != nil {\r\n\t\tlog.Println(e)\r\n\t\treturn &structs.TApiCalledLog{}\r\n\t}\r\n\r\n\tdefer dbmap.Db.Close()\r\n\r\n\tvar dto structs.TApiCalledLog\r\n\r\n\t// 過去6レコードの平均値を取得する\r\n\terr := dbmap.SelectOne(&dto,\r\n\t\t`\r\n\t\tselect\r\n\t\t\tt1.API_NAME\r\n\t\t\t, t1.operation_result\r\n\t\t\t, t1.INS_DATE \r\n\t\tfrom\r\n\t\t\tT_API_CALLED_LOG t1 \r\n\t\t\tinner join ( \r\n\t\t\t\tselect\r\n\t\t\t\t\tmax(api.ID) id \r\n\t\t\t\tfrom\r\n\t\t\t\t\tT_API_CALLED_LOG api \r\n\t\t\t\twhere\r\n\t\t\t\t\tapi.API_NAME = ?\r\n\t\t\t\t) t2 \r\n\t\t\ton t1.ID = t2.id\r\n\t\t`, apiName)\r\n\r\n\tif err != nil {\r\n\t\tfmt.Println(err)\r\n\t}\r\n\r\n\treturn &dto\r\n}", "func (a *AliyunInstanceAttribute) fetchAttributes(targetReader TargetReader, nodeName string) {\n\ta.ShootName = GetFromTargetInfo(targetReader, \"shootTechnicalID\")\n\tvar err error\n\tif a.FlagProviderID != \"\" {\n\t\ta.InstanceID = a.FlagProviderID\n\t} else {\n\t\ta.InstanceID, err = fetchAlicloudInstanceIDByNodeName(nodeName)\n\t\tcheckError(err)\n\t}\n\n\tres, err := ExecCmdReturnOutput(\"bash\", \"-c\", \"aliyun ecs DescribeInstanceAttribute --InstanceId=\"+a.InstanceID)\n\tcheckError(err)\n\tdecodedQuery := decodeAndQueryFromJSONString(res)\n\n\ta.RegionID, err = decodedQuery.String(\"RegionId\")\n\tcheckError(err)\n\ta.ZoneID, err = decodedQuery.String(\"ZoneId\")\n\tcheckError(err)\n\ta.VpcID, err = decodedQuery.String(\"VpcAttributes\", \"VpcId\")\n\tcheckError(err)\n\ta.VSwitchID, err = decodedQuery.String(\"VpcAttributes\", \"VSwitchId\")\n\tcheckError(err)\n\ta.ImageID, err = decodedQuery.String(\"ImageId\")\n\tcheckError(err)\n\tips, err := decodedQuery.ArrayOfStrings(\"VpcAttributes\", \"PrivateIpAddress\", \"IpAddress\")\n\tcheckError(err)\n\ta.PrivateIP = ips[0]\n\ta.BastionSecurityGroupName = a.ShootName + \"-bsg\"\n\ta.BastionInstanceName = a.ShootName + \"-bastion\"\n\n\ta.InstanceChargeType = \"PostPaid\"\n\ta.InternetChargeType = \"PayByTraffic\"\n\ta.InternetMaxBandwidthIn = \"10\"\n\ta.InternetMaxBandwidthOut = \"100\"\n\ta.IoOptimized = \"optimized\"\n\ta.InstanceType = a.getMinimumInstanceSpec()\n}", "func GetLatestSnapshotInfo(c context.Context) (*SnapshotInfo, error) {\n\treport := durationReporter(c, latestSnapshotInfoDuration)\n\tlogging.Debugf(c, \"Fetching AuthDB snapshot info from the datastore\")\n\tc = ds.WithoutTransaction(defaultNS(c))\n\tinfo := SnapshotInfo{}\n\tswitch err := ds.Get(c, &info); {\n\tcase err == ds.ErrNoSuchEntity:\n\t\treport(\"SUCCESS\")\n\t\treturn nil, nil\n\tcase err != nil:\n\t\treport(\"ERROR_TRANSIENT\")\n\t\treturn nil, transient.Tag.Apply(err)\n\tdefault:\n\t\treport(\"SUCCESS\")\n\t\treturn &info, nil\n\t}\n}", "func (api *API) fetchInfo(w http.ResponseWriter, r *http.Request) {\n\tdata := struct {\n\t\tAppVersion string `json:\"app_version\"`\n\t}{\n\t\tAppVersion: api.AppVersion,\n\t}\n\trenderJSON(w, data, http.StatusOK)\n}", "func (m *MockHandler) GetLatestOsImage(arg0 string) (*models.OsImage, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetLatestOsImage\", arg0)\n\tret0, _ := ret[0].(*models.OsImage)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c Provider) Latest(name string) (r *results.Result, s results.Status) {\n\t// Query the APIDownloadURL\n\tmodule, s := nameToModule(name)\n\tif s != results.OK {\n\t\treturn\n\t}\n\tresp, err := http.Get(fmt.Sprintf(APIDownloadURL, module))\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err.Error())\n\t\ts = results.Unavailable\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\t// Translate Status Code\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\ts = results.OK\n\tcase 404:\n\t\ts = results.NotFound\n\tdefault:\n\t\ts = results.Unavailable\n\t}\n\n\t// Fail if not OK\n\tif s != results.OK {\n\t\treturn\n\t}\n\n\tdec := json.NewDecoder(resp.Body)\n\trs := &Release{}\n\terr = dec.Decode(rs)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err.Error())\n\t\ts = results.Unavailable\n\t\treturn\n\t}\n\tif len(rs.Error) > 0 {\n\t\ts = results.NotFound\n\t\treturn\n\t}\n\tr = rs.Convert(name)\n\tif r == nil {\n\t\ts = results.NotFound\n\t}\n\treturn\n}", "func FetchLatestTag() (string, error) {\n\tklog.V(4).Infof(\"Fetching latest tag from GitHub\")\n\tresponse, err := http.Get(versionURL)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"could not GET the latest release\")\n\t}\n\tdefer response.Body.Close()\n\tif response.StatusCode != http.StatusOK {\n\t\treturn \"\", errors.Errorf(\"expected HTTP status 200 OK, got %s\", response.Status)\n\t}\n\n\tvar res struct {\n\t\tTag string `json:\"tag_name\"`\n\t}\n\tklog.V(4).Infof(\"Parsing response from GitHub\")\n\tif err := json.NewDecoder(response.Body).Decode(&res); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"could not parse the response from GitHub\")\n\t}\n\tklog.V(4).Infof(\"Fetched latest tag name (%s) from GitHub\", res.Tag)\n\treturn res.Tag, nil\n}", "func (a API) GetMempoolInfoWait(cmd *None) (out *btcjson.GetMempoolInfoResult, e error) {\n\tRPCHandlers[\"getmempoolinfo\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetMempoolInfoRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func GetLatestDeployed(projectID string, location string, modelName string) (*automlpb.Model, error) {\n\t// projectID := \"my-project-id\"\n\t// location := \"us-central1\"\n\n\tctx := context.Background()\n\tclient, err := automl.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewClient: %v\", err)\n\t}\n\tdefer client.Close()\n\n\treq := &automlpb.ListModelsRequest{\n\t\tParent: fmt.Sprintf(\"projects/%s/locations/%s\", projectID, location),\n\t}\n\n\tit := client.ListModels(ctx, req)\n\treturn getLatestDeployedFromIt(it, modelName)\n}", "func (p *Processor) RetrieveInfo(fullInfo chan resource.Resource, wg *sync.WaitGroup, image resource.Resource) {\n\tdefer wg.Done()\n\n\tfullInfo <- image\n}", "func (s *Store) GetACI(name types.ACIdentifier, labels types.Labels) (string, error) {\n\tvar curaciinfo *ACIInfo\n\tversionRequested := false\n\tif _, ok := labels.Get(\"version\"); ok {\n\t\tversionRequested = true\n\t}\n\n\tvar aciinfos []*ACIInfo\n\terr := s.db.Do(func(tx *sql.Tx) error {\n\t\tvar err error\n\t\taciinfos, _, err = GetACIInfosWithName(tx, name.String())\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\nnextKey:\n\tfor _, aciinfo := range aciinfos {\n\t\tim, err := s.GetImageManifest(aciinfo.BlobKey)\n\t\tif err != nil {\n\t\t\treturn \"\", errwrap.Wrap(errors.New(\"error getting image manifest\"), err)\n\t\t}\n\n\t\t// The image manifest must have all the requested labels\n\t\tfor _, l := range labels {\n\t\t\tok := false\n\t\t\tfor _, rl := range im.Labels {\n\t\t\t\tif l.Name == rl.Name && l.Value == rl.Value {\n\t\t\t\t\tok = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\tcontinue nextKey\n\t\t\t}\n\t\t}\n\n\t\tif curaciinfo != nil {\n\t\t\t// If no version is requested prefer the acis marked as latest\n\t\t\tif !versionRequested {\n\t\t\t\tif !curaciinfo.Latest && aciinfo.Latest {\n\t\t\t\t\tcuraciinfo = aciinfo\n\t\t\t\t\tcontinue nextKey\n\t\t\t\t}\n\t\t\t\tif curaciinfo.Latest && !aciinfo.Latest {\n\t\t\t\t\tcontinue nextKey\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If multiple matching image manifests are found, choose the latest imported in the cas.\n\t\t\tif aciinfo.ImportTime.After(curaciinfo.ImportTime) {\n\t\t\t\tcuraciinfo = aciinfo\n\t\t\t}\n\t\t} else {\n\t\t\tcuraciinfo = aciinfo\n\t\t}\n\t}\n\n\tif curaciinfo != nil {\n\t\treturn curaciinfo.BlobKey, nil\n\t}\n\treturn \"\", ACINotFoundError{name: name, labels: labels}\n}", "func (xratesKit *XRatesKit) GetLatest(currencyCode string, coinCodes *CoinCodes) *XRates {\n\n\tdata, err := xratesKit.ipfsHandler.GetLatestXRates(currencyCode, coinCodes.toStringArray())\n\n\tif err != nil {\n\n\t\t// Get data from CoinPaprika\n\t\tdata, err = xratesKit.coinPaprika.GetLatestXRates(currencyCode, coinCodes.toStringArray())\n\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\t//---------- Cache Data -------------------\n\n\txratesKit.cacheService.SetLatest(data)\n\n\t//-----------------------------------------\n\n\tlog.Println(data)\n\n\tvar result = make([]XRate, len(data))\n\tfor i, xrate := range data {\n\t\tresult[i] = XRate(xrate)\n\t}\n\treturn &XRates{result}\n}", "func getTopAnime(w http.ResponseWriter, r *http.Request) {\n\ttopType, _ := strconv.Atoi(r.URL.Query().Get(\"type\"))\n\tpage, _ := strconv.Atoi(r.URL.Query().Get(\"page\"))\n\n\tif page == 0 {\n\t\tpage = 1\n\t}\n\n\tparser, err := MalService.GetTopAnime(topType, page)\n\n\tif err != nil {\n\t\tview.RespondWithJSON(w, parser.ResponseCode, err.Error(), nil)\n\t} else {\n\t\tview.RespondWithJSON(w, parser.ResponseCode, parser.ResponseMessage.Error(), parser.Data)\n\t}\n}", "func DBFetchXTopRatingAnime(skipN int, limitN int) ([]projectModels.StructureAnime, int, error) {\n\n\tresCountQuery, err := r.Table(\"animes\").OrderBy(r.Desc(\"Score\")).Count().Run(dbSession)\n\tif err != nil {\n\t\treturn []projectModels.StructureAnime{}, 0, err\n\t}\n\tif resCountQuery.IsNil() {\n\t\treturn []projectModels.StructureAnime{}, 0, errors.New(\"Empty Result\")\n\t}\n\n\tvar resCount int\n\n\terr = resCountQuery.One(&resCount)\n\tif err != nil {\n\t\treturn []projectModels.StructureAnime{}, 0, err\n\t}\n\n\terr = resCountQuery.Close()\n\tcommon.CheckErrorAndPanic(err)\n\n\tres, err := r.Table(\"animes\").OrderBy(r.Desc(\"Score\")).Skip(skipN).Limit(limitN).Run(dbSession)\n\tif err != nil {\n\t\treturn []projectModels.StructureAnime{}, 0, err\n\t}\n\n\t// Not working: https://github.com/dancannon/gorethink/issues/326\n\tif res.IsNil() {\n\t\treturn []projectModels.StructureAnime{}, 0, errors.New(\"Empty Result\")\n\t}\n\n\tvar animelist []projectModels.StructureAnime\n\tif err = res.All(&animelist); err != nil {\n\t\treturn []projectModels.StructureAnime{}, 0, err\n\t}\n\n\terr = res.Close()\n\tcommon.CheckErrorAndPanic(err)\n\n\tif len(animelist) == 0 {\n\t\treturn []projectModels.StructureAnime{}, 0, errors.New(\"Empty Result\")\n\t}\n\treturn animelist, resCount, nil\n}", "func latest(urltemplate string) (string, error) {\n\tyear, month, _ := time.Now().Date()\n\tsnapshotURL := fmt.Sprintf(urltemplate, year, month)\n\tresp, err := retryablehttp.Get(snapshotURL)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbody := resp.Body\n\tdefer body.Close()\n\tcontent, err := io.ReadAll(body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmatches := reSnapshot.FindAll(content, -1)\n\tif len(matches) == 0 {\n\t\treturn \"\", errors.Errorf(\"No snapshots found at %q\", snapshotURL)\n\t} else if len(matches) == 1 {\n\t\treturn string(matches[0]), nil\n\t} else {\n\t\treturn string(matches[len(matches)-2]), nil\n\t}\n}", "func (i EC2Instance) AMI() string {\n\treturn utils.Config(\"partitions.\" + i.partition + \".ami\").Self()\n}", "func (a API) GetMiningInfoWait(cmd *None) (out *btcjson.GetMiningInfoResult, e error) {\n\tRPCHandlers[\"getmininginfo\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetMiningInfoRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func GetLatest(currency string) (time.Time, error) {\n\tif !common.ValidateCurrency(currency) {\n\t\treturn time.Time{}, errors.New(\"invalid currency\")\n\t}\n\trow := db.QueryRowx(fmt.Sprintf(`\n\t\tSELECT effective_date\n\t\tFROM %s\n\t\tORDER BY effective_date DESC\n\t\tLIMIT 1\n\t`, currency))\n\tar := common.ArchiveRow{}\n\terr := row.StructScan(&ar)\n\treturn ar.Date, err\n}", "func (c *Client) LatestData() (AirData, error) {\n\tvar ad AirData\n\tresp, err := http.Get(fmt.Sprintf(\"http://%s/air-data/latest\", c.Addr))\n\tif err != nil {\n\t\treturn ad, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tdec := json.NewDecoder(resp.Body)\n\n\terr = dec.Decode(&ad)\n\treturn ad, err\n}", "func (f *Frontend) fetchImage(i *img.Image) (*img.Image, error) {\n\tvar err error\n\n\t// go through image proxy to resize and cache the image\n\tkey := hmacKey(i.ID)\n\tu := fmt.Sprintf(\"%v/image/225x,s%v/%v\", f.Host, key, i.ID)\n\tfmt.Println(u)\n\n\tresp, err := f.Images.Client.Get(u)\n\tif err != nil {\n\t\treturn i, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbdy, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn i, err\n\t}\n\n\ti.Base64 = base64.StdEncoding.EncodeToString(bdy)\n\treturn i, err\n}", "func (b *BotCommands) latest(m *tb.Message) {\n\tvar page int\n\tsplit := strings.Split(m.Text, \" \")\n\tif len(split) == 2 {\n\t\tpage, _ = strconv.Atoi(split[1])\n\t} else {\n\t\tpage = 1\n\t}\n\tresult := scraper.FindAnime(fmt.Sprintf(\"https://nyaa.si/?p=%v\", page))\n\tb.Bot.Reply(\n\t\tm, fmt.Sprintf(\"Found %v Results ...\", len(result)),\n\t)\n\tfor i := 0; i < len(result); i += limit {\n\t\tbatch := result[i:min(i+limit, len(result))]\n\t\tres := markDownify(batch)\n\t\tb.Bot.Reply(\n\t\t\tm, res,\n\t\t)\n\t}\n}", "func DBFetchXPopularAnime(skipN, limitN int) ([]projectModels.StructureAnime, int, error) {\n\n\tresCountQuery, err := r.Table(\"cache_popular_animes\").Count().Run(dbSession)\n\tif err != nil {\n\t\treturn []projectModels.StructureAnime{}, 0, err\n\t}\n\n\tif resCountQuery.IsNil() {\n\t\treturn []projectModels.StructureAnime{}, 0, errors.New(\"Empty Result\")\n\t}\n\n\tvar resCount int\n\terr = resCountQuery.One(&resCount)\n\tif err != nil {\n\t\treturn []projectModels.StructureAnime{}, 0, err\n\t}\n\n\terr = resCountQuery.Close()\n\tcommon.CheckErrorAndPanic(err)\n\n\tresp, err := r.Table(\"cache_popular_animes\").OrderBy(\"id\").Skip(skipN).Limit(limitN).Run(dbSession)\n\tif err != nil {\n\t\treturn []projectModels.StructureAnime{}, 0, err\n\t}\n\n\tif resp.IsNil() {\n\t\treturn []projectModels.StructureAnime{}, 0, errors.New(\"Empty Result\")\n\t}\n\n\tvar popularAnimeIDs []map[string]interface{}\n\tif err = resp.All(&popularAnimeIDs); err != nil {\n\t\treturn []projectModels.StructureAnime{}, 0, err\n\t}\n\n\terr = resp.Close()\n\tcommon.CheckErrorAndPanic(err)\n\n\tvar animelist []projectModels.StructureAnime\n\tfor _, v := range popularAnimeIDs {\n\t\tres, err := r.Table(\"animes\").Filter(map[string]interface{}{\n\t\t\t\"id\": v[\"malID\"].(string),\n\t\t}).Run(dbSession)\n\t\tif err != nil {\n\t\t\treturn []projectModels.StructureAnime{}, 0, err\n\t\t}\n\t\tif res.IsNil() {\n\t\t\treturn []projectModels.StructureAnime{}, 0, errors.New(\"Empty Result\")\n\t\t}\n\t\tvar anime projectModels.StructureAnime\n\t\tif err = res.One(&anime); err != nil {\n\t\t\treturn []projectModels.StructureAnime{}, 0, err\n\t\t}\n\t\terr = res.Close()\n\t\tcommon.CheckErrorAndPanic(err)\n\n\t\tanimelist = append(animelist, anime)\n\t}\n\tif len(animelist) == 0 {\n\t\treturn []projectModels.StructureAnime{}, 0, errors.New(\"Empty Result\")\n\t}\n\treturn animelist, resCount, nil\n}", "func (r Virtual_Guest) GetLatestNetworkMonitorIncident() (resp datatypes.Network_Monitor_Version1_Incident, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getLatestNetworkMonitorIncident\", nil, &r.Options, &resp)\n\treturn\n}", "func fetchData(url string) (*info, error) {\r\n\r\n\t// Throttle the data request rate\r\n\ttime.Sleep(100 * time.Millisecond)\r\n\r\n\tresp, _ := http.Get(source + url)\r\n\tdefer resp.Body.Close()\r\n\r\n\tresult, err := ioutil.ReadAll(resp.Body)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tvar i info\r\n\terr = json.Unmarshal(result, &i)\r\n\tif err != nil {\r\n\t\t//log.Println(err, err.Error())\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\ttotalRequest++\r\n\t//fmt.Printf(\"%v\\n\\n\", i)\r\n\treturn &i, nil\r\n}", "func (a API) GetMempoolInfo(cmd *None) (e error) {\n\tRPCHandlers[\"getmempoolinfo\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (ds *DataSource) GetLatestInfo(ctx context.Context, unitPath, modulePath string) (latest internal.LatestInfo, err error) {\n\tdefer derrors.Wrap(&err, \"GetLatestInfo(ctx, %q, %q)\", unitPath, modulePath)\n\n\tum, err := ds.GetUnitMeta(ctx, unitPath, internal.UnknownModulePath, internal.LatestVersion)\n\tif err != nil {\n\t\treturn latest, err\n\t}\n\tlatest.MinorVersion = um.Version\n\tlatest.MinorModulePath = um.ModulePath\n\n\tlatest.MajorModulePath, latest.MajorUnitPath, err = ds.getLatestMajorVersion(ctx, unitPath, modulePath)\n\tif err != nil {\n\t\treturn latest, err\n\t}\n\t// Do not try to discover whether the unit is in the latest minor version; assume it is.\n\tlatest.UnitExistsAtMinor = true\n\treturn latest, nil\n}", "func (p *Processor) RetrieveInfo(fullInfo chan resource.Resource, wg *sync.WaitGroup, vm resource.Resource) {\n\tdefer wg.Done()\n\n\tid, err := vm.ID()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"error\": err}).Fatal(\"error get virtual machine id\")\n\t}\n\n\tv, err := p.reader.RetrieveVirtualMachineInfo(id)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"error\": err}).Fatal(\"error retrieve virtual machine info\")\n\t}\n\n\tfullInfo <- v\n}", "func (m *MalService) GetTopAnime(params ...int) (top.AnimeParser, error) {\n\treturn top.InitAnimeParser(m.Config, params...)\n}", "func (a API) GetInfoWait(cmd *None) (out *btcjson.InfoChainResult0, e error) {\n\tRPCHandlers[\"getinfo\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetInfoRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func (c *Client) LatestObservationForStationLastRetrieved(id string) time.Time {\n\t// return zero time if station does not exist in obeservations map\n\treturn c.observations[id].observationLastRetrieved\n}", "func (fl *MCPMFileList) GetLatest() *MCPMFile {\n\treturn fl.a[0]\n}", "func fetchNetworkInterface(conn *ec2.EC2, ifaceID string) (*ec2.NetworkInterface, error) {\n\tlog.Printf(\"[DEBUG] Fetching information for interface ID %s\", ifaceID)\n\tdniParams := &ec2.DescribeNetworkInterfacesInput{\n\t\tNetworkInterfaceIds: aws.StringSlice([]string{ifaceID}),\n\t}\n\n\tdniResp, err := conn.DescribeNetworkInterfaces(dniParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dniResp.NetworkInterfaces[0], nil\n}", "func (book *Book) GetLatest() []Book {\n\tvar books []Book\n\tdb := utils.OpenDB()\n\tdefer db.Close()\n\tdb.Order(\"created_at desc\").Limit(8).Find(&books)\n\tbookdetailsub(books)\n\treturn books\n}", "func (c Provider) Latest(name string) (r *results.Result, s results.Status) {\n\trs, s := c.GetReleases(name, 100)\n\tif s != results.OK {\n\t\treturn\n\t}\n\tr = rs.Last()\n\tif r == nil {\n\t\ts = results.NotFound\n\t}\n\treturn\n}", "func (ad *AWSData) getAWSInfo() error {\n\tlog.Trace(\"GetInfo Start\")\n\tchange := sets.NewSet()\n\tfor _, zid := range ad.zones {\n\t\tdata, err := GetAWSZoneInfo(ad.r53, ad.dnsfilters, zid)\n\t\tif err != nil {\n\t\t\tlog.Warn(\"Problems reading from zone:{}, {}\", zid, err)\n\t\t\treturn err\n\t\t} else {\n\t\t\tfor host, s := range data {\n\t\t\t\tar := khostdns.CreateArecord(host, s)\n\t\t\t\tif cips, ok := ad.awsHosts.Load(host); ok {\n\t\t\t\t\tcipsl := cips.(khostdns.Arecord).GetIps()\n\t\t\t\t\tif !cmp.Equal(cipsl, s) {\n\t\t\t\t\t\tlog.Trace(\"Found host change:{} ips:{}\", host, s)\n\t\t\t\t\t\tchange.Add(ar)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Trace(\"Found new host:{} ips:{}\", host, s)\n\t\t\t\t\tchange.Add(ar)\n\t\t\t\t}\n\t\t\t\tad.awsHosts.Store(host, ar)\n\t\t\t}\n\t\t}\n\t}\n\tif change.Cardinality() > 0 {\n\t\tchange.Each(func(i interface{}) bool {\n\t\t\tar2 := i.(khostdns.Arecord)\n\t\t\tlog.Trace(\"notify changes:{} ips:{}\", ar2.GetHostname(), ar2.GetIps())\n\t\t\tad.notifyChannel <- ar2\n\t\t\treturn false\n\t\t})\n\t}\n\tlog.Trace(\"GetInfo End\")\n\treturn nil\n}", "func getLatestUserInfo(bot *eb.Bot, user *model.EtternaUser) error {\n\tetternaUser, err := bot.API.GetByUsername(user.Username)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser.Avatar = etternaUser.AvatarURL\n\tuser.MSDOverall = util.RoundToPrecision(etternaUser.Overall, 2)\n\tuser.MSDStream = util.RoundToPrecision(etternaUser.Stream, 2)\n\tuser.MSDJumpstream = util.RoundToPrecision(etternaUser.Jumpstream, 2)\n\tuser.MSDHandstream = util.RoundToPrecision(etternaUser.Handstream, 2)\n\tuser.MSDStamina = util.RoundToPrecision(etternaUser.Stamina, 2)\n\tuser.MSDJackSpeed = util.RoundToPrecision(etternaUser.JackSpeed, 2)\n\tuser.MSDChordjack = util.RoundToPrecision(etternaUser.Chordjack, 2)\n\tuser.MSDTechnical = util.RoundToPrecision(etternaUser.Technical, 2)\n\tuser.RankOverall = etternaUser.Rank.Overall\n\tuser.RankStream = etternaUser.Rank.Stream\n\tuser.RankJumpstream = etternaUser.Rank.Jumpstream\n\tuser.RankHandstream = etternaUser.Rank.Handstream\n\tuser.RankStamina = etternaUser.Rank.Stamina\n\tuser.RankJackSpeed = etternaUser.Rank.JackSpeed\n\tuser.RankChordjack = etternaUser.Rank.Chordjack\n\tuser.RankTechnical = etternaUser.Rank.Technical\n\n\treturn nil\n}", "func GetLatestPrice(w http.ResponseWriter, r *http.Request) {\n\tuserName := r.Header.Get(\"userName\")\n\tif !checkQueryLimit(userName) {\n\t\tutility.ResponseWithJSON(w, http.StatusForbidden, utility.Response{Message: \"over the query limit\", Result: utility.ResFailed})\n\t\treturn\n\t}\n\tresult := make(map[string]models.Price)\n\tservices := strings.Split(mux.Vars(r)[\"service\"], \",\")\n\tfor _, service := range services {\n\t\tvalue, err := db.RedisGet(db.NSLatestAPI + \":\" + service)\n\t\tif err != nil {\n\t\t\tlogrus.Infof(\"redis get error %s\", service)\n\t\t\tcontinue\n\t\t}\n\t\tvar price models.Price\n\t\terr = json.Unmarshal([]byte(value), &price)\n\t\tif err != nil {\n\t\t\tlogrus.Infof(\"json decode error %s\", value)\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := result[service]; !ok {\n\t\t\tresult[service] = price\n\t\t}\n\t}\n\tif len(result) == 0 {\n\t\tutility.ResponseWithJSON(w, http.StatusBadRequest, utility.Response{Message: \"no active service or service not exsit\", Result: utility.ResFailed})\n\t\treturn\n\t}\n\tutility.ResponseWithJSON(w, http.StatusOK, utility.Response{Result: utility.ResSuccess, Data: result})\n\tincreaseQueryLimit(userName)\n}", "func (r *HumioClusterReconciler) getLatestHumioCluster(ctx context.Context, hc *humiov1alpha1.HumioCluster) error {\n\treturn r.Get(ctx, types.NamespacedName{\n\t\tName: hc.Name,\n\t\tNamespace: hc.Namespace,\n\t}, hc)\n}", "func (c Provider) Latest(params []string) (r *results.Result, err error) {\n\trs, err := c.Releases(params)\n\tif err == nil {\n\t\tr = rs.Last()\n\t}\n\treturn\n}", "func (c Provider) Latest(params []string) (r *results.Result, err error) {\n\trs, err := c.Releases(params)\n\tif err == nil {\n\t\tr = rs.Last()\n\t}\n\treturn\n}", "func (c Provider) Latest(params []string) (r *results.Result, err error) {\n\trs, err := c.Releases(params)\n\tif err == nil {\n\t\tr = rs.Last()\n\t}\n\treturn\n}", "func (o *Avi) FetchApplicationProfile() (byName map[string]string, byUUID map[string]string, err error) {\r\n\tbyName = make(map[string]string)\r\n\tbyUUID = make(map[string]string)\r\n\tavi := new(tmavi.Avi)\r\n\tavi.Client = o.Client\r\n\tresp, err := avi.GetAllApplicationProfile()\r\n\tif err != nil {\r\n\t\treturn\r\n\t}\r\n\tfor _, v := range resp {\r\n\t\tbyName[*v.Name] = *v.UUID\r\n\t\tbyUUID[*v.UUID] = *v.Name\r\n\t}\r\n\treturn\r\n}", "func (c *Client) GetLatestTag(image string) (string, error) {\n\ttags, err := c.ListTags(image)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn tags[0].Name, nil\n}", "func GetLatest(coll string) bson.D {\n\tfmt.Println(\"controllers: get latest invoked\")\n\tpipeline := []bson.M{\n\t\t{\"$limit\": 1},\n\t\t{\"$sort\": bson.M{\"createdat\": -1}},\n\t\t{\"$project\": bson.M{\"_id\": 0}},\n\t}\n\n\treturn runAggregate(pipeline, db.Collection(coll))\n}", "func GetLatestVersion() (string, error) {\n\tclient := &http.Client{Timeout: 2 * time.Second}\n\tresponse, err := client.Get(config.Settings.Uris.LatestVersion)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode == 200 {\n\t\tbodyBytes, err := io.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn string(bodyBytes), nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"Status code %d\", response.StatusCode)\n}", "func (c *Client) GetLatestBlock() (resp *LatestBlock, e error) {\n\tresp = &LatestBlock{}\n\treturn resp, c.Do(\"/latestblock\", resp, nil)\n}", "func GetImageDetail(request *model.RequestImageDetail) ([]model.ImageDetail, error) {\n\tlog.Printf(\"call GetImageDetail:%v\", request)\n\tvar err error\n\tvar imageTags []swagger.DetailedTag\n\tvar imageDetails []model.ImageDetail\n\tharborClient := client.GetHarborClient()\n\n\trepoName := request.ProjectName + \"/\" + request.ImageName\n\n\t// get tags\n\tif request.Tag == \"\" {\n\t\timageTags, _, err = harborClient.RepositoriesRepoNameTagsGet(repoName)\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"Failed to get RepositoriesRepoNameTagsGet: %v\", err)\n\t\t\treturn imageDetails, errors.New(msg)\n\t\t}\n\t} else {\n\t\timageTag, _, err := harborClient.RepositoriesRepoNameTagsTagGet(repoName, request.Tag)\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"Failed to get RepositoriesRepoNameTagsTagGet: %v\", err)\n\t\t\treturn imageDetails, errors.New(msg)\n\t\t}\n\t\timageTags = append(imageTags, *imageTag)\n\t}\n\tlog.Printf(\"imageTags:%#v\", imageTags)\n\n\t// get manifest\n\tfor _, imageTag := range imageTags {\n\t\tvar imageDetail model.ImageDetail\n\t\tmanifest, _, err := harborClient.RepositoriesRepoNameTagsTagManifestGet(repoName, imageTag.Name, \"\")\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"Failed to get RepositoriesRepoNameTagsTagManifestGet: %v\", err)\n\t\t\treturn imageDetails, errors.New(msg)\n\t\t}\n\t\timageDetail.Image = imageTag\n\t\timageDetail.Manifest = *manifest\n\t\timageDetails = append(imageDetails, imageDetail)\n\t}\n\n\tlog.Printf(\"imageDetails:%#v\", imageDetails)\n\treturn imageDetails, nil\n}", "func AMI(channel, region string) (ami string, err error) {\n\tif channel != DefaultChannel {\n\t\treturn \"\", fmt.Errorf(\"channel %q is not yet supported\", channel)\n\t}\n\n\tif region != \"us-east-1\" {\n\t\treturn \"\", fmt.Errorf(\"region %q is not yet supported\", region)\n\t}\n\n\treturn \"ami-0af8953af3ec06b7c\", nil\n}", "func (c *MemcachedManager) Get(id string) (ami.AMI, error) {\n\tc.RLock()\n\tdefer c.RUnlock()\n\n\titem, err := c.client.Get(id)\n\tif err != nil && err == memcache.ErrCacheMiss {\n\t\treturn ami.AMI{}, nil\n\t}\n\tif err != nil {\n\t\treturn ami.AMI{}, err\n\t}\n\n\tvar ami ami.AMI\n\n\tif err = c.unmarshal(item.Value, &ami); err != nil {\n\t\treturn ami, err\n\t}\n\n\treturn ami, nil\n}", "func IamDetails() iamOutput {\n\t//sess, _ := session.NewSession(&aws.Config{})\n\tsess, _ := session.NewSession(&aws.Config{})\n\tfmt.Println(\"IAMMMMMMMMMM inGIT\")\n\tiamsvc := iam.New(sess)\n\tiamOutput1, _ := iamsvc.ListUsers(&iam.ListUsersInput{})\n\tcount := 0\n\tiDetailList := []iamDetail{}\n\tiDetail := iamDetail{}\n\tiOutput := iamOutput{}\n\n\tfor _, value := range iamOutput1.Users {\n\t\tcount++\n\n\t\tmfaOutput, _ := iamsvc.ListMFADevices(&iam.ListMFADevicesInput{UserName: value.UserName})\n\n\t\tmfaConig := \"Enabled\"\n\t\tif len(mfaOutput.MFADevices) == 0 {\n\n\t\t\tmfaConig = \"Disabled\"\n\t\t}\n\n\t\tPasswordLastUsed := \"\"\n\t\tif value.PasswordLastUsed == nil {\n\t\t\tPasswordLastUsed = \"Password Disabled\"\n\t\t} else {\n\t\t\tPasswordLastUsed = strings.Split((value.PasswordLastUsed).Format(time.RFC850), \" \")[1]\n\t\t}\n\t\tInlinePolicyOutput, _ := iamsvc.ListUserPolicies(&iam.ListUserPoliciesInput{UserName: value.UserName})\n\t\tUserPolicies, _ := iamsvc.ListAttachedUserPolicies(&iam.ListAttachedUserPoliciesInput{UserName: value.UserName})\n\t\tUserGroups, _ := iamsvc.ListGroupsForUser(&iam.ListGroupsForUserInput{UserName: value.UserName})\n\n\t\tuserAttchedGroupsOutput := []string{}\n\t\tfor _, b := range UserGroups.Groups {\n\t\t\tuserAttchedGroupsOutput = append(userAttchedGroupsOutput, aws.StringValue(b.GroupName))\n\t\t}\n\t\tif len(userAttchedGroupsOutput) == 0 {\n\t\t\tuserAttchedGroupsOutput = append(userAttchedGroupsOutput, \"None\")\n\t\t}\n\t\tuserAttchedPolicyOutput := []string{}\n\t\tfor _, j := range UserPolicies.AttachedPolicies {\n\t\t\tuserAttchedPolicyOutput = append(userAttchedPolicyOutput, aws.StringValue(j.PolicyName))\n\t\t}\n\t\tif len(userAttchedPolicyOutput) == 0 {\n\t\t\tuserAttchedPolicyOutput = append(userAttchedPolicyOutput, \"None\")\n\t\t}\n\t\tuserInlinePolicyOutput := aws.StringValueSlice(InlinePolicyOutput.PolicyNames)\n\t\tif len(userInlinePolicyOutput) == 0 {\n\t\t\tuserInlinePolicyOutput = append(userInlinePolicyOutput, \"None\")\n\t\t}\n\n\t\tfmt.Printf(\">>>>> %v>>>>>%35v | %10v |%10v |%v| %v |%v | %v \\n\", count, aws.StringValue(value.UserName),\n\t\t\tPasswordLastUsed, strings.Split((value.CreateDate).Format(time.RFC850), \" \")[1],\n\t\t\tmfaConig, userAttchedGroupsOutput, userAttchedPolicyOutput, userInlinePolicyOutput)\n\n\t\tiDetail.Count = count\n\t\tiDetail.Username = aws.StringValue(value.UserName)\n\t\tiDetail.PasswordLastUsed = PasswordLastUsed\n\t\tiDetail.CreateDate = strings.Split((value.CreateDate).Format(time.RFC850), \" \")[1]\n\t\tiDetail.MfaConig = mfaConig\n\t\tiDetail.UserAttchedGroupsOutput = strings.Join(userAttchedGroupsOutput, \",\")\n\t\tiDetail.UserAttchedPolicyOutput = strings.Join(userAttchedPolicyOutput, \",\")\n\t\tiDetail.UserInlinePolicyOutput = strings.Join(userInlinePolicyOutput, \",\")\n\t\tiDetailList = append(iDetailList, iDetail)\n\t}\n\tiOutput.IamDetailList = iDetailList\n\treturn iOutput\n}", "func (client *Client) GetResultLatest(bucketKey string, testID string) (Result, error) {\n\treturn client.GetResult(bucketKey, testID, \"latest\")\n}", "func retrieveComputeInstanceMetadata() (metadata ComputeInstanceMetadata, err error) {\n\tvar m ComputeInstanceMetadata\n\tc := &http.Client{}\n\n\treq, _ := http.NewRequest(\"GET\", azureInstanceMetadataEndpoint+\"/compute\", nil)\n\treq.Header.Add(\"Metadata\", \"True\")\n\tq := req.URL.Query()\n\tq.Add(\"format\", \"json\")\n\tq.Add(\"api-version\", \"2017-12-01\")\n\treq.URL.RawQuery = q.Encode()\n\n\tresp, err := c.Do(req)\n\tif err != nil {\n\t\treturn m, fmt.Errorf(\"sending Azure Instance Metadata Service request failed: %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\trawJSON, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn m, fmt.Errorf(\"reading response body failed: %v\", err)\n\t}\n\tif err := json.Unmarshal(rawJSON, &m); err != nil {\n\t\treturn m, fmt.Errorf(\"unmarshaling JSON response failed: %v\", err)\n\t}\n\n\treturn m, nil\n}", "func (a *Client) GetBlocksLatest(params *GetBlocksLatestParams) (*GetBlocksLatestOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetBlocksLatestParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetBlocksLatest\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/blocks/latest\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetBlocksLatestReader{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.(*GetBlocksLatestOK)\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 GetBlocksLatest: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (o *ApplianceSetupInfoAllOf) GetLatestVersion() string {\n\tif o == nil || o.LatestVersion == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.LatestVersion\n}", "func (c *Client) GetMempoolInfo() (info *MempoolInfo, err error) {\r\n\r\n\tvar resp string\r\n\t// https://api.whatsonchain.com/v1/bsv/<network>/mempool/info\r\n\tif resp, err = c.request(fmt.Sprintf(\"%s%s/mempool/info\", apiEndpoint, c.Network), http.MethodGet, nil); err != nil {\r\n\t\treturn\r\n\t}\r\n\r\n\terr = json.Unmarshal([]byte(resp), &info)\r\n\treturn\r\n}", "func (d *Dao) MonitorInfo(c context.Context, aid int64) (minfo json.RawMessage, err error) {\n\tip := metadata.String(c, metadata.RemoteIP)\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t\tData json.RawMessage `json:\"data\"`\n\t}\n\tif err = d.client.RESTfulGet(c, d.monitorInfoURL, ip, nil, &res, aid); err != nil {\n\t\treturn\n\t}\n\tcode := ecode.Int(res.Code)\n\tif !code.Equal(ecode.OK) {\n\t\terr = errors.Wrap(code, d.monitorInfoURL)\n\t\treturn\n\t}\n\tminfo = res.Data\n\treturn\n}", "func (c Provider) Latest(name string) (r *results.Result, s results.Status) {\n\trs, s := c.Releases(name)\n\tif s == results.OK {\n\t\tsort.Sort(rs)\n\t\tr = rs.Last()\n\t}\n\treturn\n}", "func (applications *Applications) Last() (*Result, error) {\n\tif applications.LastURL != \"\" {\n\t\tbody, err := applications.getCursor(applications.LastURL)\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(\"last cursor not available\")\n}", "func (o *Avi) FetchNetworkProfile() (byName map[string]string, byUUID map[string]string, err error) {\r\n\tbyName = make(map[string]string)\r\n\tbyUUID = make(map[string]string)\r\n\tavi := new(tmavi.Avi)\r\n\tavi.Client = o.Client\r\n\tresp, err := avi.GetAllNetworkProfile()\r\n\tif err != nil {\r\n\t\treturn\r\n\t}\r\n\tfor _, v := range resp {\r\n\t\tbyName[*v.Name] = *v.UUID\r\n\t\tbyUUID[*v.UUID] = *v.Name\r\n\t}\r\n\treturn\r\n}", "func (n *NasaApodClient) FetchAPOD(date string, hd bool) (*Apod, string, error) {\n\turl := nasaApodAPIGet +\n\t\tn.apiKey\n\tif len(date) != 0 {\n\t\turl += \"&date=\" + date\n\t}\n\tif hd {\n\t\turl += \"&hd=true\"\n\t}\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tif strings.Contains(string(bytes), \"OVER_RATE_LIMIT\") {\n\t\treturn nil, \"\", fmt.Errorf(\"http get rate limit reached, wait or use a proper key instead of the default one\")\n\t}\n\tapod := &Apod{}\n\tjson.Unmarshal(bytes, apod)\n\tif apod.ServiceVersion != nasaApodServiceVersion {\n\t\tlog.Printf(\"[WARNING] remote service version %s != %s\\n\", apod.ServiceVersion, nasaApodServiceVersion)\n\t}\n\treturn apod, makeArchiveDate(apod.Date), nil\n}", "func getClusterDetails(clientWrapper *client.Wrapper, args Arguments) (\n\t*models.V4ClusterDetailsResponse,\n\t*models.V5ClusterDetailsResponse,\n\t*models.V5GetNodePoolsResponse,\n\t*client.ClusterStatus,\n\t*models.V4GetCredentialResponse,\n\terror) {\n\n\tvar clusterDetailsV4 *models.V4ClusterDetailsResponse\n\tvar clusterDetailsV5 *models.V5ClusterDetailsResponse\n\tvar clusterStatus *client.ClusterStatus\n\tvar nodePools *models.V5GetNodePoolsResponse\n\n\tvar err error\n\targs.clusterNameOrID, err = clustercache.GetID(args.apiEndpoint, args.clusterNameOrID, clientWrapper)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, nil, microerror.Mask(err)\n\t}\n\n\t// first try v5\n\tif args.verbose {\n\t\tfmt.Println(color.WhiteString(\"Fetching details for cluster via v5 API endpoint.\"))\n\t}\n\tclusterDetailsV5, v5Err := getClusterDetailsV5(args)\n\tif v5Err == nil {\n\t\t// fetch node pools\n\t\t// perform API call\n\t\tauxParams := clientWrapper.DefaultAuxiliaryParams()\n\t\tauxParams.ActivityName = activityName\n\t\tresponse, err := clientWrapper.GetNodePools(args.clusterNameOrID, auxParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, nil, nil, microerror.Mask(err)\n\t\t}\n\t\tnodePools = &response.Payload\n\t} else {\n\t\t// If this is a 404 error, we assume the cluster is not a V5 one.\n\t\t// If it is 400, it's likely \"not supported on this provider\". We swallow this in order to test for v4 next.\n\t\t// If this is a \"Malformed response\" error, we assume the API is not capable of\n\t\t// handling V5 yet. TODO: This can be phased out once the API is up-to-date.\n\t\t// In both these case we continue below, otherwise we return the error.\n\t\tif !errors.IsClusterNotFoundError(v5Err) && !clienterror.IsMalformedResponse(v5Err) && !clienterror.IsBadRequestError(v5Err) {\n\t\t\treturn nil, nil, nil, nil, nil, microerror.Mask(v5Err)\n\t\t}\n\n\t\t// Fall back to v4.\n\t\tif args.verbose {\n\t\t\tfmt.Println(color.WhiteString(\"No usable v5 response. Fetching details for cluster via v4 API endpoint.\"))\n\t\t}\n\n\t\tvar clusterDetailsV4Err error\n\t\tclusterDetailsV4, clusterDetailsV4Err = getClusterDetailsV4(args)\n\t\tif clusterDetailsV4Err != nil {\n\t\t\t// At this point, every error is a sign of something unexpected, so\n\t\t\t// simply return.\n\t\t\treturn nil, nil, nil, nil, nil, microerror.Mask(clusterDetailsV4Err)\n\t\t}\n\n\t\tif args.verbose {\n\t\t\tfmt.Println(color.WhiteString(\"Fetching status for v4 cluster.\"))\n\t\t}\n\t\tauxParams := clientWrapper.DefaultAuxiliaryParams()\n\t\tauxParams.ActivityName = activityName\n\t\tvar clusterStatusErr error\n\t\tclusterStatus, clusterStatusErr = clientWrapper.GetClusterStatus(args.clusterNameOrID, auxParams)\n\t\tif clusterStatusErr != nil {\n\t\t\t// Return an error if it is something else than 404 Not Found,\n\t\t\t// as 404s are expected during cluster creation.\n\t\t\tif !errors.IsClusterNotFoundError(clusterStatusErr) {\n\t\t\t\treturn nil, nil, nil, nil, nil, microerror.Mask(clusterStatusErr)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar credentialDetails *models.V4GetCredentialResponse\n\t{\n\t\tcredentialID := \"\"\n\t\tclusterOwner := \"\"\n\t\tvar created time.Time\n\n\t\tif clusterDetailsV4 != nil {\n\t\t\tcredentialID = clusterDetailsV4.CredentialID\n\t\t\tclusterOwner = clusterDetailsV4.Owner\n\t\t\tcreated = util.ParseDate(clusterDetailsV4.CreateDate)\n\t\t} else if clusterDetailsV5 != nil {\n\t\t\tcredentialID = clusterDetailsV5.CredentialID\n\t\t\tclusterOwner = clusterDetailsV5.Owner\n\t\t\tcreated = util.ParseDate(clusterDetailsV5.CreateDate)\n\t\t}\n\n\t\tif credentialID != \"\" {\n\t\t\tif args.verbose {\n\t\t\t\tfmt.Println(color.WhiteString(\"Fetching credential details for organization %s\", clusterOwner))\n\t\t\t}\n\n\t\t\tvar credentialDetailsErr error\n\t\t\tcredentialDetails, credentialDetailsErr = getOrgCredentials(clusterOwner, credentialID, args)\n\t\t\tif credentialDetailsErr != nil {\n\t\t\t\tif time.Since(created) < clusterCreationExpectedDuration {\n\t\t\t\t\tfmt.Println(\"This is expected for clusters which are most likely still in creation.\")\n\t\t\t\t}\n\t\t\t\t// Print any error occurring here, but don't return, as this is non-critical.\n\t\t\t\tfmt.Printf(color.YellowString(\"Warning: credential details for org %s (credential ID %s) could not be fetched.\\n\", clusterOwner, credentialID))\n\t\t\t\tfmt.Printf(\"Error details: %s\\n\", credentialDetailsErr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn clusterDetailsV4, clusterDetailsV5, nodePools, clusterStatus, credentialDetails, nil\n}", "func (b *Backend) GetAccountAtLatestBlock(\n\tctx context.Context,\n\taddress sdk.Address,\n) (*sdk.Account, error) {\n\tb.logger.\n\t\tWithField(\"address\", address).\n\t\tDebugf(\"👤 GetAccountAtLatestBlock called\")\n\n\taccount, err := b.getAccount(address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn account, nil\n}", "func GetLatest(art1, art2 string) string {\n\tif !IsSameArtifact(art1, art2) {\n\t\treturn \"\"\n\t}\n\n\tarts1 := Split(art1)\n\tarts2 := Split(art2)\n\n\tif arts1[2] > arts2[2] {\n\t\treturn art1\n\t}\n\treturn art2\n}", "func (c *Client) LatestObservationForDefaultStationLastRetrieved() time.Time {\n\t// return zero time if station does not exist in obeservations map\n\treturn c.observations[c.defaultStationID].observationLastRetrieved\n}", "func (rra *RoundRobinArchive) Latest() time.Time { return rra.latest }", "func (f ProcessInstanceIDFetcher) Fetch(logger lager.Logger, appGUID string) (map[int]string, error) {\n\tlogger = logger.Session(\"process-instance-id-fetch\", lager.Data{\"app-guid\": appGUID})\n\tlogger.Info(\"start\")\n\tdefer logger.Info(\"end\")\n\n\tstart := time.Now().Add(-30 * time.Second)\n\tend := time.Now()\n\n\tprocessInstanceIDs := map[int]string{}\n\n\tfor i := 0; i < maxReadTries; i++ {\n\t\tenvelopes, err := f.client.Read(context.Background(), appGUID, start,\n\t\t\tlogcache.WithDescending(),\n\t\t\tlogcache.WithEnvelopeTypes(logcache_v1.EnvelopeType_GAUGE),\n\t\t\tlogcache.WithNameFilter(\"absolute_entitlement\"),\n\t\t\tlogcache.WithEndTime(end),\n\t\t\tlogcache.WithLimit(f.limit),\n\t\t)\n\n\t\tif err != nil {\n\t\t\tlogger.Error(\"log-cache-read-failed\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, envelope := range envelopes {\n\t\t\tinstanceID, err := strconv.Atoi(envelope.InstanceId)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Info(\"ignoring-corrupt-instance-id\", lager.Data{\"envelope\": envelope})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tprocessInstanceID := envelope.Tags[\"process_instance_id\"]\n\t\t\tif len(processInstanceID) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif _, exists := processInstanceIDs[instanceID]; !exists {\n\t\t\t\tprocessInstanceIDs[instanceID] = processInstanceID\n\t\t\t}\n\t\t}\n\n\t\tif len(envelopes) < f.limit {\n\t\t\tbreak\n\t\t}\n\n\t\tlogger.Info(\"more-metrics-to-fetch\", lager.Data{\"iteration\": i, \"max-iterations\": maxReadTries, \"page-size\": f.limit})\n\t\tend = time.Unix(0, envelopes[len(envelopes)-1].Timestamp)\n\t}\n\n\treturn processInstanceIDs, nil\n}", "func getLatestBlocks(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tblockCount := blockdata.GetBlockCount() // get the latest blocks\n\n\tvar blocks []*btcjson.GetBlockVerboseResult\n\n\t// blockheight - 1 in the loop. Get the blockhash from the height\n\tfor i := 0; i < 10; i++ {\n\t\tprevBlock := blockCount - int64(i)\n\t\thash, _ := blockdata.GetBlockHash(prevBlock)\n\n\t\tblock, err := blockdata.GetBlock(hash)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tblocks = append(blocks, block)\n\t}\n\tjson.NewEncoder(w).Encode(blocks)\n}", "func FindLatestAMIModifiedDistroEvent(id string) (EventLogEntry, error) {\n\tevents := []EventLogEntry{}\n\tres := EventLogEntry{}\n\terr := db.Aggregate(EventCollection, latestDistroEventsPipeline(id, 1, true, time.Now()), &events)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\tif len(events) > 0 {\n\t\tres = events[0]\n\t}\n\treturn res, nil\n}", "func (rdb *RatesStorage) GetLastResolvedBlockInfo(reserveAddr ethereum.Address) (lbdCommon.BlockInfo, error) {\n\tconst (\n\t\tselectStmt = `SELECT time,block FROM token_rates WHERE time=\n\t\t(SELECT MAX(time) FROM token_rates) AND reserve_id=(SELECT id FROM reserves WHERE reserves.address=$1) LIMIT 1`\n\t)\n\tvar (\n\t\trateTableResult = lbdCommon.BlockInfo{}\n\t\tlogger = rdb.sugar.With(\"func\", caller.GetCurrentFunctionName())\n\t)\n\n\tlogger.Debugw(\"Querying last resolved block from rates table...\", \"query\", selectStmt)\n\tif err := rdb.db.Get(&rateTableResult, selectStmt, reserveAddr.Hex()); err != nil {\n\t\treturn rateTableResult, err\n\t}\n\trateTableResult.Timestamp = rateTableResult.Timestamp.UTC()\n\n\treturn rateTableResult, nil\n}", "func (sc *snapshotInfoContainer) GetOldest() SnapshotInfo {\n\te := sc.snapshotList.Back()\n\n\tif e == nil {\n\t\treturn nil\n\t} else {\n\t\treturn e.Value.(SnapshotInfo)\n\t}\n}", "func (a API) GetMiningInfo(cmd *None) (e error) {\n\tRPCHandlers[\"getmininginfo\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (f *Fetch) FetchMultiInfo(ctx context.Context, ips []netip.Addr) (\n\tresults []Response, err error) {\n\tctx, cancel := context.WithCancel(ctx)\n\n\ttype asyncResult struct {\n\t\tindex int\n\t\tresult Response\n\t\terr error\n\t}\n\tresultsCh := make(chan asyncResult)\n\n\tfor i, ip := range ips {\n\t\tgo func(index int, ip netip.Addr) {\n\t\t\taResult := asyncResult{\n\t\t\t\tindex: index,\n\t\t\t}\n\t\t\taResult.result, aResult.err = f.FetchInfo(ctx, ip)\n\t\t\tresultsCh <- aResult\n\t\t}(i, ip)\n\t}\n\n\tresults = make([]Response, len(ips))\n\tfor i := 0; i < len(ips); i++ {\n\t\taResult := <-resultsCh\n\t\tif aResult.err != nil {\n\t\t\tif err == nil {\n\t\t\t\t// Cancel on the first error encountered\n\t\t\t\terr = aResult.err\n\t\t\t\tcancel()\n\t\t\t}\n\t\t\tcontinue // ignore errors after the first one\n\t\t}\n\n\t\tresults[aResult.index] = aResult.result\n\t}\n\n\tclose(resultsCh)\n\tcancel()\n\n\treturn results, err\n}", "func (c *redisClient) retrieveInfo() (string, error) {\n\treturn c.client.Info(\"all\").Result()\n}", "func FetchAmazonFile() (*FetchResult, error) {\n\treq := newAmazonFetchRequest()\n\tresults, err := fetchFeedFiles([]fetchRequest{req})\n\tif err != nil || len(results) != 1 {\n\t\treturn nil,\n\t\t\tfmt.Errorf(\"Failed to fetch. err: %s\", err)\n\t}\n\treturn &results[0], nil\n}", "func (f Fetcher) printLastFetchTime() {\n\tt := f.resp.Header[\"Date\"][0]\n\tfmt.Printf(\"Last fetch: %s\\n\", t)\n}", "func (b *Backend) GetLatestBlock(ctx context.Context, isSealed bool) (*flowgo.Block, error) {\n\tblock, err := b.emulator.GetLatestBlock()\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tblockID := block.ID()\n\n\tb.logger.WithFields(logrus.Fields{\n\t\t\"blockHeight\": block.Header.Height,\n\t\t\"blockID\": hex.EncodeToString(blockID[:]),\n\t}).Debug(\"🎁 GetLatestBlock called\")\n\n\treturn block, nil\n}", "func (i *Interpreter) GetLatest() (string, error) {\n\tvar motions []*structs.Motion\n\tvar data []byte\n\tvar err error\n\n\tif motions, err = i.sqlh.GetLastMotion(); err == nil {\n\t\tif data, err = json.Marshal(motions); err == nil {\n\t\t\treturn string(data), nil\n\t\t}\n\t}\n\n\treturn \"\", err\n}", "func GetLatest(rssFeed string) (string, string, error) {\n\tfp := gofeed.NewParser()\n\tfmt.Println(\"Feed created\")\n\n\tfeed, err := fp.ParseURL(rssFeed)\n\tif err != nil {\n\t\tfmt.Println(\"Error found, \", err)\n\t\treturn \"\", \"\", err\n\t}\n\tfmt.Println(\"Feed read\", time.Now())\n\tmessageString := fmt.Sprintf(\"%s\\r\\n%s\", feed.Items[0].Title, feed.Items[0].Link)\n\tfmt.Println(\"Message created, \", messageString)\n\treturn messageString, feed.Items[0].Link, nil\n}", "func getClusterDetailsV5(args Arguments) (*models.V5ClusterDetailsResponse, error) {\n\tclientWrapper, err := client.NewWithConfig(args.apiEndpoint, args.userProvidedToken)\n\tif err != nil {\n\t\treturn nil, microerror.Mask(err)\n\t}\n\n\t// perform API call\n\tauxParams := clientWrapper.DefaultAuxiliaryParams()\n\tauxParams.ActivityName = activityName\n\n\tresponse, err := clientWrapper.GetClusterV5(args.clusterNameOrID, auxParams)\n\tif err != nil {\n\t\tif clienterror.IsAccessForbiddenError(err) {\n\t\t\treturn nil, microerror.Mask(errors.AccessForbiddenError)\n\t\t}\n\t\tif clienterror.IsUnauthorizedError(err) {\n\t\t\treturn nil, microerror.Mask(errors.NotAuthorizedError)\n\t\t}\n\t\tif clienterror.IsNotFoundError(err) {\n\t\t\treturn nil, microerror.Mask(errors.ClusterNotFoundError)\n\t\t}\n\t\tif clienterror.IsInternalServerError(err) {\n\t\t\treturn nil, microerror.Mask(errors.InternalServerError)\n\t\t}\n\n\t\treturn nil, microerror.Mask(err)\n\t}\n\n\treturn response.Payload, nil\n}", "func TestLatestMetaDataProfile(t *testing.T) {\n\texpected_body := `default-hvm`\n\n\tdoBodyTest(t, \"GET\", \"/latest/meta-data/profile\", expected_body)\n\tdoBodyTest(t, \"GET\", \"/latest/meta-data/profile/\", expected_body)\n}", "func Latest(name, dir string, rm client.RepoMap, archs []string, proxyServer string) (string, error) {\n\tver, repo, arch, err := client.FindRepoLatest(goolib.PackageInfo{Name: name, Arch: \"\", Ver: \"\"}, rm, archs)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trs, err := client.FindRepoSpec(goolib.PackageInfo{Name: name, Arch: arch, Ver: ver}, rm[repo])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn FromRepo(rs, repo, dir, proxyServer)\n}", "func (a API) GetCurrentNetWait(cmd *None) (out *string, e error) {\n\tRPCHandlers[\"getcurrentnet\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetCurrentNetRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func (c *repoCacheManager) fetchImages(tags []string) (fetchImagesResult, error) {\n\timages := map[string]image.Info{}\n\n\t// Create a list of images that need updating\n\tvar toUpdate []imageToUpdate\n\n\t// Counters for reporting what happened\n\tvar missing, refresh int\n\tfor _, tag := range tags {\n\t\tif tag == \"\" {\n\t\t\treturn fetchImagesResult{}, fmt.Errorf(\"empty tag in fetched tags\")\n\t\t}\n\n\t\t// See if we have the manifest already cached\n\t\tnewID := c.repoID.ToRef(tag)\n\t\tkey := NewManifestKey(newID.CanonicalRef())\n\t\tbytes, deadline, err := c.cacheClient.GetKey(key)\n\t\t// If err, then we don't have it yet. Update.\n\t\tswitch {\n\t\tcase err != nil: // by and large these are cache misses, but any error shall count as \"not found\"\n\t\t\tif err != ErrNotCached {\n\t\t\t\tc.logger.Log(\"warning\", \"error from cache\", \"err\", err, \"ref\", newID)\n\t\t\t}\n\t\t\tmissing++\n\t\t\ttoUpdate = append(toUpdate, imageToUpdate{ref: newID, previousRefresh: initialRefresh})\n\t\tcase len(bytes) == 0:\n\t\t\tc.logger.Log(\"warning\", \"empty result from cache\", \"ref\", newID)\n\t\t\tmissing++\n\t\t\ttoUpdate = append(toUpdate, imageToUpdate{ref: newID, previousRefresh: initialRefresh})\n\t\tdefault:\n\t\t\tvar entry registry.ImageEntry\n\t\t\tif err := json.Unmarshal(bytes, &entry); err == nil {\n\t\t\t\tif c.trace {\n\t\t\t\t\tc.logger.Log(\"trace\", \"found cached manifest\", \"ref\", newID, \"last_fetched\", entry.LastFetched.Format(time.RFC3339), \"deadline\", deadline.Format(time.RFC3339))\n\t\t\t\t}\n\n\t\t\t\tif entry.ExcludedReason == \"\" {\n\t\t\t\t\timages[tag] = entry.Info\n\t\t\t\t\tif c.now.After(deadline) {\n\t\t\t\t\t\tpreviousRefresh := minRefresh\n\t\t\t\t\t\tlastFetched := entry.Info.LastFetched\n\t\t\t\t\t\tif !lastFetched.IsZero() {\n\t\t\t\t\t\t\tpreviousRefresh = deadline.Sub(lastFetched)\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttoUpdate = append(toUpdate, imageToUpdate{ref: newID, previousRefresh: previousRefresh, previousDigest: entry.Info.Digest})\n\t\t\t\t\t\trefresh++\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif c.trace {\n\t\t\t\t\t\tc.logger.Log(\"trace\", \"excluded in cache\", \"ref\", newID, \"reason\", entry.ExcludedReason)\n\t\t\t\t\t}\n\t\t\t\t\tif c.now.After(deadline) {\n\t\t\t\t\t\ttoUpdate = append(toUpdate, imageToUpdate{ref: newID, previousRefresh: excludedRefresh})\n\t\t\t\t\t\trefresh++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tresult := fetchImagesResult{\n\t\timagesFound: images,\n\t\timagesToUpdate: toUpdate,\n\t\timagesToUpdateRefreshCount: refresh,\n\t\timagesToUpdateMissingCount: missing,\n\t}\n\n\treturn result, nil\n}", "func (c *Client) GetCurrentBlockInfo() (cbi *CurrentBlockInfo, err error) {\n\terr = c.Get(&cbi, \"clientInit\", nil)\n\n\treturn cbi, err\n}", "func (nc *NSBClient) GetAbciInfo() (*AbciInfoResponse, error) {\n\tb, err := nc.handler.Group(\"/abci_info\").GetWithParams(request.Param{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar bb []byte\n\tbb, err = nc.preloadJSONResponse(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar a AbciInfo\n\terr = json.Unmarshal(bb, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn a.Response, nil\n}", "func (c *Collector) Fetch(address, username, password string) error {\n\treqJobs, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"%s/api/json\", address),\n\t\tnil,\n\t)\n\n\tif username != \"\" && password != \"\" {\n\t\treqJobs.SetBasicAuth(username, password)\n\t}\n\n\tjobs, err := simpleClient().Do(reqJobs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to request jobs api. %s\", err)\n\t}\n\tdefer jobs.Body.Close()\n\n\tif err := json.NewDecoder(jobs.Body).Decode(c); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse jobs api. %s\", err)\n\t}\n\n\treqQueue, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"%s/queue/api/json\", address),\n\t\tnil,\n\t)\n\n\tif username != \"\" && password != \"\" {\n\t\treqQueue.SetBasicAuth(username, password)\n\t}\n\n\tqueue, err := simpleClient().Do(reqQueue)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to request queue api. %s\", err)\n\t}\n\tdefer queue.Body.Close()\n\n\tif err := json.NewDecoder(queue.Body).Decode(c); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse queue api. %s\", err)\n\t}\n\n\treturn nil\n}", "func fetch(ctx context.Context, params newsclient.Params) (*news.Response, error) {\n\tauthKey, err := auth.LookupAPIAuthKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client.Get(ctx, authKey, params)\n}", "func GetArtifactWithLatestVersion(art string, ch chan<- string, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tartifactRepo := &Maven{}\n\n\tlatestArt, _ := artifactRepo.GetLatestVersion(art)\n\tif latestArt == \"\" {\n\t\treturn\n\t}\n\n\tlatestVersion := GetVersion(latestArt)\n\n\tch <- art + \":\" + latestVersion\n}", "func (bidb *BlockInfoStorage) GetBlockInfo(atTime time.Time) (common.BlockInfo, error) {\n\tvar (\n\t\tlogger = bidb.sugar.With(\n\t\t\t\"func\", caller.GetCurrentFunctionName(),\n\t\t\t\"time\", atTime.String(),\n\t\t)\n\t\tresult common.BlockInfo\n\t)\n\tconst selectStmt = `SELECT block, time FROM %[1]s WHERE time>$1 AND time<$2 Limit 1`\n\tquery := fmt.Sprintf(selectStmt, bidb.tableNames[blockInfoTable])\n\tlogger.Debugw(\"querying blockInfo...\", \"query\", query)\n\tif err := bidb.db.Get(&result, query, timeutil.Midnight(atTime), timeutil.Midnight(atTime).AddDate(0, 0, 1)); err != nil {\n\t\treturn common.BlockInfo{}, err\n\t}\n\treturn result, nil\n}" ]
[ "0.5529186", "0.5462934", "0.51881176", "0.5097993", "0.50877535", "0.5053881", "0.50063366", "0.4925705", "0.48764256", "0.48067775", "0.4782997", "0.4776161", "0.47612095", "0.46991083", "0.4668599", "0.46620175", "0.46407685", "0.46041173", "0.45941803", "0.4584719", "0.45738596", "0.455366", "0.4547512", "0.45033196", "0.44996792", "0.4499268", "0.449824", "0.4490759", "0.4480419", "0.44640583", "0.4461197", "0.4458774", "0.44453034", "0.4443015", "0.44206387", "0.4407322", "0.43960893", "0.43960655", "0.4389514", "0.43763465", "0.43742415", "0.43731707", "0.4362216", "0.434119", "0.43380874", "0.4335818", "0.4329419", "0.43197885", "0.43165207", "0.43119735", "0.43119735", "0.43119735", "0.4300201", "0.42969286", "0.4295168", "0.4284109", "0.4271653", "0.42510498", "0.42390722", "0.42181218", "0.42127895", "0.42102888", "0.41977236", "0.41956303", "0.41910917", "0.41887933", "0.41728333", "0.4172592", "0.41613674", "0.41584736", "0.4151808", "0.4146717", "0.41463324", "0.41285455", "0.41277155", "0.41056538", "0.4105002", "0.41013318", "0.4100913", "0.40974227", "0.40964368", "0.4073679", "0.40657514", "0.4062342", "0.40604222", "0.40512916", "0.40495738", "0.404398", "0.40343258", "0.4030669", "0.40306488", "0.40215766", "0.40171072", "0.40086424", "0.40007398", "0.39895135", "0.3986019", "0.3977708", "0.39751995", "0.39667428" ]
0.8119029
0
SelectRegion returns the region to use.
func SelectRegion(optRegion string) (region string, err error) { if optRegion == "OS Environment 'AWS_REGION'" { if os.Getenv("AWS_REGION") != "" { return os.Getenv("AWS_REGION"), err } return usEast1, err } return optRegion, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) Region() (string, error) {\n\treturn c.get(\"/region\")\n}", "func GetRegion(licenseKey string) string {\n\tmatches := regionLicenseRegex.FindStringSubmatch(licenseKey)\n\tif len(matches) > 1 {\n\t\treturn matches[1]\n\t}\n\n\treturn \"\"\n}", "func (o GetTrafficPolicyDocumentRuleRegionOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetTrafficPolicyDocumentRuleRegion) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func SetRegion(r string) {\n\tcurrentRegion = r\n}", "func (r InvokeCommandRequest) GetRegionId() string {\n return r.RegionId\n}", "func (t *Territory) Region(ctx context.Context, db DB) (*Region, error) {\n\treturn RegionByRegionID(ctx, db, t.RegionID)\n}", "func (a *Application) Region() *Region {\n\treturn a.makeRegion()\n}", "func (m *Manager) SelectClosestRegion() (closestRegion string, err error) {\n\n\tregionIPs := []regionPingTimes{\n\t\t{\"ca-central\", \"speedtest.toronto1.linode.com\", 0},\n\t\t{\"us-central\", \"speedtest.dallas.linode.com\", 0},\n\t\t{\"us-west\", \"speedtest.fremont.linode.com\", 0},\n\t\t{\"us-east\", \"speedtest.newark.linode.com\", 0},\n\t\t{\"eu-central\", \"speedtest.frankfurt.linode.com\", 0},\n\t\t{\"eu-west\", \"speedtest.london.linode.com\", 0},\n\t\t{\"ap-south\", \"speedtest.singapore.linode.com\", 0},\n\t\t{\"ap-southeast\", \"speedtest.syd1.linode.com\", 0},\n\t\t{\"ap-west\", \"speedtest.mumbai1.linode.com\", 0},\n\t\t{\"ap-northeast\", \"speedtest.tokyo2.linode.com\", 0},\n\t}\n\n\t// default to NYC\n\tclosestRegion = \"us-east\"\n\n\t// get ping time to each region\n\t// to see which is the closest\n\tvar lowestPingTime = math.MaxInt64\n\tfor _, region := range regionIPs {\n\t\tpingTime, err := core.GetPingTime(region.ipAddress)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tregion.result = pingTime\n\n\t\t// is this datacenter closer than others we've seen so far\n\t\tif int(pingTime) < lowestPingTime {\n\t\t\tclosestRegion = region.name\n\t\t\tlowestPingTime = int(pingTime)\n\t\t}\n\t}\n\n\treturn closestRegion, nil\n}", "func (o *DisplayInfo) GetRegion() string {\n\tif o == nil || o.Region == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Region\n}", "func (t *Toon) Region() *Region {\n\treturn regionByID(t.RegionID())\n}", "func GetRegion(configuredRegion string) (string, error) {\n\tif configuredRegion != \"\" {\n\t\treturn configuredRegion, nil\n\t}\n\n\tsess, err := session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t})\n\tif err != nil {\n\t\treturn \"\", errwrap.Wrapf(\"got error when starting session: {{err}}\", err)\n\t}\n\n\tregion := aws.StringValue(sess.Config.Region)\n\tif region != \"\" {\n\t\treturn region, nil\n\t}\n\n\tmetadata := ec2metadata.New(sess, &aws.Config{\n\t\tEndpoint: ec2Endpoint,\n\t\tEC2MetadataDisableTimeoutOverride: aws.Bool(true),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: time.Second,\n\t\t},\n\t})\n\tif !metadata.Available() {\n\t\treturn DefaultRegion, nil\n\t}\n\n\tregion, err = metadata.Region()\n\tif err != nil {\n\t\treturn \"\", errwrap.Wrapf(\"unable to retrieve region from instance metadata: {{err}}\", err)\n\t}\n\n\treturn region, nil\n}", "func (CcsAwsSession *ccsAwsSession) GetRegion() *string {\n\treturn CcsAwsSession.session.Config.Region\n}", "func CurrentRegion() string {\n\treturn currentRegion\n}", "func (o GetGroupResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetGroupResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func (s serverConfigV14) GetRegion() string {\n\tserverConfigMu.RLock()\n\tdefer serverConfigMu.RUnlock()\n\n\treturn s.Region\n}", "func GetRegion(ctx *pulumi.Context) string {\n\tv, err := config.Try(ctx, \"newrelic:region\")\n\tif err == nil {\n\t\treturn v\n\t}\n\tvar value string\n\tif d := internal.GetEnvOrDefault(\"US\", nil, \"NEW_RELIC_REGION\"); d != nil {\n\t\tvalue = d.(string)\n\t}\n\treturn value\n}", "func (r AuthPrivilegeRequest) GetRegionId() string {\n return \"\"\n}", "func (r CreateBackupPlanRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o MonitorV1Output) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *MonitorV1) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (config *Config) GetRegion() string {\n\tregion := config.Region\n\n\tif region == \"\" {\n\t\tregion = Region[\"bj\"]\n\t}\n\n\treturn region\n}", "func (v *VCard) Region() string {\n\treturn v.getFirstAddressField(4)\n}", "func (r InvokeRequest) GetRegionId() string {\n return r.RegionId\n}", "func GetRegion(svc *ec2metadata.EC2Metadata) (string, error) {\n\tdoc, err := svc.GetInstanceIdentityDocument()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn doc.Region, nil\n}", "func (r CreateImageFromSnapshotsRequest) GetRegionId() string {\n return r.RegionId\n}", "func (r DescribeSnapshotPolicyDiskRelationsRequest) GetRegionId() string {\n return r.RegionId\n}", "func (jbobject *RegionsRegions) GetCurrentRegion() *RegionsRegion {\n\tjret, err := javabind.GetEnv().CallStaticMethod(\"com/amazonaws/regions/Regions\", \"getCurrentRegion\", \"com/amazonaws/regions/Region\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tretconv := javabind.NewJavaToGoCallable()\n\tdst := &javabind.Callable{}\n\tretconv.Dest(dst)\n\tif err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {\n\t\tpanic(err)\n\t}\n\tretconv.CleanUp()\n\tunique_x := &RegionsRegion{}\n\tunique_x.Callable = dst\n\treturn unique_x\n}", "func (o GetHostedZoneResultOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetHostedZoneResult) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (c *Client) GetRegion() string {\n\treturn c.config.Region\n}", "func GetRegion(kpp string) int {\n\ti, _ := strconv.Atoi(kpp[:2])\n\treturn i\n}", "func (r CreateClusterRequest) GetRegionId() string {\n return r.RegionId\n}", "func (c *Client) GetRegion() Region {\n\treturn c.region\n}", "func (c *Client) GetRegion() Region {\n\treturn c.region\n}", "func Region() string {\n\tl := locale()\n\n\ttag, err := language.Parse(l)\n\tif err != nil {\n\t\treturn defaultRegion\n\t}\n\n\tregion, _ := tag.Region()\n\n\treturn region.String()\n}", "func (o GetTrafficPolicyDocumentRuleGeoProximityLocationOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetTrafficPolicyDocumentRuleGeoProximityLocation) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func GetRegion(metaEndPoint string, preferEnv bool) string {\n\tvar region string\n\tif preferEnv {\n\t\tregion = getRegionFromEnv()\n\t\tif region == \"\" {\n\t\t\tregion = getRegionFromInstanceDocument(metaEndPoint)\n\t\t}\n\t} else {\n\t\tregion = getRegionFromInstanceDocument(metaEndPoint)\n\t\tif region == \"\" {\n\t\t\tregion = getRegionFromEnv()\n\t\t}\n\t}\n\tif region == \"\" {\n\t\tlog.Println(\"No region information available. Defaulting to us-west-2\")\n\t\tregion = \"us-west-2\"\n\t}\n\treturn region\n}", "func (c *Client) Region() string {\n\treturn c.region.String()\n}", "func (o PublicDelegatedPrefixPublicDelegatedSubPrefixResponseOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PublicDelegatedPrefixPublicDelegatedSubPrefixResponse) string { return v.Region }).(pulumi.StringOutput)\n}", "func (o ServerGroupOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ServerGroup) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (o LookupRegionCommitmentResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupRegionCommitmentResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func GetRegion(ctx *pulumi.Context) string {\n\tv, err := config.Try(ctx, \"aws:region\")\n\tif err == nil {\n\t\treturn v\n\t}\n\tif dv, ok := getEnvOrDefault(\"\", nil, \"AWS_REGION\", \"AWS_DEFAULT_REGION\").(string); ok {\n\t\treturn dv\n\t}\n\treturn v\n}", "func (r DescribeAuditLogRequest) GetRegionId() string {\n return r.RegionId\n}", "func Get_region(ipaddress string) IP2Locationrecord {\n\treturn handleError(defaultDB.query(ipaddress, region))\n}", "func (o *Workloadv1Location) GetRegion() string {\n\tif o == nil || o.Region == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Region\n}", "func (c *MockAzureCloud) Region() string {\n\treturn c.Location\n}", "func (m *metadata) GetRegion() string {\n\treturn m.region\n}", "func (o HealthCheckAlarmIdentifierOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v HealthCheckAlarmIdentifier) string { return v.Region }).(pulumi.StringOutput)\n}", "func (o AiFeatureStoreEntityTypeFeatureOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AiFeatureStoreEntityTypeFeature) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func Region() *Command {\n\tcmd := &Command{\n\t\tCommand: &cobra.Command{\n\t\t\tUse: \"region\",\n\t\t\tShort: \"Display commands to list datacenter regions\",\n\t\t\tLong: \"The subcommands of `doctl compute region` retrieve information about DigitalOcean datacenter regions.\",\n\t\t},\n\t}\n\n\tregionDesc := `List DigitalOcean datacenter regions displaying their name, slug, and availability.\n\nUse the slugs displayed by this command to specify regions in other commands.\n`\n\tCmdBuilder(cmd, RunRegionList, \"list\", \"List datacenter regions\", regionDesc,\n\t\tWriter, aliasOpt(\"ls\"), displayerType(&displayers.Region{}))\n\n\treturn cmd\n}", "func (r OnlineSqlTaskQueryRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o RecordLatencyRoutingPolicyOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RecordLatencyRoutingPolicy) string { return v.Region }).(pulumi.StringOutput)\n}", "func (o HealthCheckAlarmIdentifierPtrOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *HealthCheckAlarmIdentifier) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Region\n\t}).(pulumi.StringPtrOutput)\n}", "func (r *Bucket) Region() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"region\"])\n}", "func Region(v string) predicate.Location {\n\treturn predicate.Location(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldRegion), v))\n\t})\n}", "func (o *VmRestorePoint) GetRegionId() string {\n\tif o == nil || o.RegionId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.RegionId\n}", "func (o GetTrafficPolicyDocumentEndpointOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetTrafficPolicyDocumentEndpoint) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (o StorageNodeStatusGeographyOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageNodeStatusGeography) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (a *AZs) GetRegion(az string) string {\n\tfor _, vaz := range *a {\n\t\tif az == vaz.Name {\n\t\t\treturn vaz.Region\n\t\t}\n\t}\n\treturn \"\"\n}", "func (o DatabaseReplicaOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DatabaseReplica) pulumi.StringPtrOutput { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (r AttachGroupPolicyRequest) GetRegionId() string {\n return \"\"\n}", "func (o LookupRegionNetworkEndpointGroupResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupRegionNetworkEndpointGroupResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func (r SetAuthConfigRequest) GetRegionId() string {\n return \"\"\n}", "func (o VoiceConnectorOutput) AwsRegion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VoiceConnector) pulumi.StringPtrOutput { return v.AwsRegion }).(pulumi.StringPtrOutput)\n}", "func (r StatusReportRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o LookupSpacesBucketResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSpacesBucketResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func (o PublicAdvertisedPrefixPublicDelegatedPrefixResponseOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PublicAdvertisedPrefixPublicDelegatedPrefixResponse) string { return v.Region }).(pulumi.StringOutput)\n}", "func (r SearchLogContextRequest) GetRegionId() string {\n return r.RegionId\n}", "func getRegion(name string) (aws.Region, error) {\n\tvar regions = map[string]aws.Region{\n\t\taws.APNortheast.Name: aws.APNortheast,\n\t\taws.APSoutheast.Name: aws.APSoutheast,\n\t\taws.APSoutheast2.Name: aws.APSoutheast2,\n\t\taws.EUCentral.Name: aws.EUCentral,\n\t\taws.EUWest.Name: aws.EUWest,\n\t\taws.USEast.Name: aws.USEast,\n\t\taws.USWest.Name: aws.USWest,\n\t\taws.USWest2.Name: aws.USWest2,\n\t\taws.USGovWest.Name: aws.USGovWest,\n\t\taws.SAEast.Name: aws.SAEast,\n\t}\n\tregion, ok := regions[name]\n\tif !ok {\n\t\treturn aws.Region{}, fmt.Errorf(\"No region matches %s\", name)\n\t}\n\treturn region, nil\n}", "func (o *LogsArchiveDestinationAzure) GetRegion() string {\n\tif o == nil || o.Region == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Region\n}", "func (d *DB) Get_region(ipaddress string) (IP2Locationrecord, error) {\n\treturn d.query(ipaddress, region)\n}", "func (r ReportTaskRequest) GetRegionId() string {\n return r.RegionId\n}", "func (r DelSubDeviceWithCoreRequest) GetRegionId() string {\n return r.RegionId\n}", "func (bc *BasicLineGraph) GetRegion(regionID uint3264) *RegionInfo {\n\tbc.RLock()\n\tdefer bc.RUnlock()\n\treturn bc.Regions.GetRegion(regionID)\n}", "func (o GetEndpointResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetEndpointResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func (r GetLargeScreenDataRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o ContainerV1Output) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ContainerV1) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (o SslCertificateOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SslCertificate) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (r DescribeCacheInstancesRequest) GetRegionId() string {\n return r.RegionId\n}", "func (c *namespaceCluster) GetRegion(id uint64) *core.RegionInfo {\n\tr := c.Cluster.GetRegion(id)\n\tif r == nil || !c.checkRegion(r) {\n\t\treturn nil\n\t}\n\treturn r\n}", "func (r DescribeBillSummarysRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o LiteSubscriptionOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *LiteSubscription) pulumi.StringPtrOutput { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (o *VirtualMachineToAlternativeRestoreOptions) GetRegionId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.RegionId\n}", "func (o InstanceOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (o *DisplayInfo) SetRegion(v string) {\n\to.Region = &v\n}", "func (r CreateCollectInfoRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o LookupDatabaseMysqlResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDatabaseMysqlResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func (this *BuoyController) Region() {\n\tbuoyBusiness.Region(&this.BaseController, this.GetString(\":region\"))\n}", "func (r DeployRequest) GetRegionId() string {\n return \"\"\n}", "func (o NetworkOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Network) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (r GeneralAlterEventRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o RegionNetworkEndpointGroupOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RegionNetworkEndpointGroup) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (r LastDownsampleRequest) GetRegionId() string {\n return r.RegionId\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 *Info) GetRegion() string {\n\treturn m.ec2Metadata.getRegion()\n}", "func RegionFromSession(session *sessions.Session) string {\n\tv := sessionGet(session, regionKey)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\tstrVal, ok := v.(string)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn strVal\n}", "func (r ListSmsSendOverviewUsingGETRequest) GetRegionId() string {\n return \"\"\n}", "func (r DescribeSlowLogRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o VolumeV2Output) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *VolumeV2) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (s *square) getRegion() error {\n\treg := region{}\n\tswitch {\n\tcase s.pos.rowNumber >= 0 && s.pos.rowNumber <= 2:\n\t\treg.minRowNumber = 0\n\t\treg.maxRowNumber = 2\n\tcase s.pos.rowNumber >= 3 && s.pos.rowNumber <= 5:\n\t\treg.minRowNumber = 3\n\t\treg.maxRowNumber = 5\n\tcase s.pos.rowNumber >= 6 && s.pos.rowNumber <= 8:\n\t\treg.minRowNumber = 6\n\t\treg.maxRowNumber = 8\n\tdefault:\n\t\treturn fmt.Errorf(\"rowNumber %d is invalid\", s.pos.rowNumber)\n\t}\n\n\tswitch {\n\tcase s.pos.colNumber >= 0 && s.pos.colNumber <= 2:\n\t\treg.minColNumber = 0\n\t\treg.maxColNumber = 2\n\tcase s.pos.colNumber >= 3 && s.pos.colNumber <= 5:\n\t\treg.minColNumber = 3\n\t\treg.maxColNumber = 5\n\tcase s.pos.colNumber >= 6 && s.pos.colNumber <= 8:\n\t\treg.minColNumber = 6\n\t\treg.maxColNumber = 8\n\tdefault:\n\t\treturn fmt.Errorf(\"colNumber %d is invalid\", s.pos.colNumber)\n\t}\n\ts.reg = reg\n\treturn nil\n}", "func (f *Frontend) detectRegion(lang language.Tag, r *http.Request) language.Region {\n\treg, err := language.ParseRegion(strings.TrimSpace(r.FormValue(\"r\")))\n\tif err != nil {\n\t\treg, _ = lang.Region()\n\t}\n\n\treturn reg.Canonicalize()\n}" ]
[ "0.6212933", "0.61665523", "0.59823793", "0.5979998", "0.5961696", "0.59247506", "0.59140015", "0.590351", "0.58544534", "0.5823417", "0.58158934", "0.5806475", "0.5804442", "0.5792979", "0.57887846", "0.5777168", "0.57462037", "0.5742536", "0.57243466", "0.57242405", "0.57004416", "0.56942993", "0.5686588", "0.568492", "0.56671727", "0.5663966", "0.5663857", "0.566111", "0.5650635", "0.5638497", "0.5638306", "0.5638306", "0.56335217", "0.5629282", "0.5623882", "0.56105864", "0.5610506", "0.56069326", "0.5587283", "0.55792195", "0.55788803", "0.557641", "0.5553947", "0.55510265", "0.5549924", "0.55436856", "0.5535041", "0.5517252", "0.5513622", "0.55129045", "0.5500582", "0.5495979", "0.54849136", "0.54755694", "0.5463475", "0.5453081", "0.5449328", "0.5448819", "0.5444659", "0.5442628", "0.54399383", "0.5439198", "0.5435711", "0.54333144", "0.5433047", "0.5425034", "0.54233736", "0.54189795", "0.54137456", "0.5408466", "0.540521", "0.5399572", "0.539919", "0.53984106", "0.5384796", "0.5377205", "0.536242", "0.5353339", "0.534977", "0.5341671", "0.5340759", "0.53382087", "0.53382087", "0.53355587", "0.5335254", "0.5334782", "0.53295666", "0.53263134", "0.53241587", "0.5314988", "0.53106433", "0.53090274", "0.5308669", "0.5300518", "0.5288735", "0.5267876", "0.5257234", "0.52533126", "0.5242838", "0.522686" ]
0.72929907
0
New creates a new gRPC server with all RPC services registered. Callers are responsible for setting up the listener and any other server options.
func New(svcs svc.Services, opts ...grpc.ServerOption) *grpc.Server { opts = append(opts, grpc.CustomCodec(sourcegraph.GRPCCodec)) s := grpc.NewServer(opts...) svc.RegisterAll(s, svcs) return s }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(config *GrpcServerConfig) (*GrpcServer, error) {\n\tif nil == config {\n\t\treturn nil, fmt.Errorf(\"Configuration must be provided\")\n\t}\n\tif len(config.Name) == 0 {\n\t\treturn nil, fmt.Errorf(\"Name of server must be provided\")\n\t}\n\tif len(config.Address) == 0 {\n\t\treturn nil, fmt.Errorf(\"Address must be provided\")\n\t}\n\tif len(config.Net) == 0 {\n\t\treturn nil, fmt.Errorf(\"Net must be provided\")\n\t}\n\n\tl, err := net.Listen(config.Net, config.Address)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to setup server: %s\", err.Error())\n\t}\n\n\treturn &GrpcServer{\n\t\tname: config.Name,\n\t\tlistener: l,\n\t\topts: config.Opts,\n\t}, nil\n}", "func New(cfg Config, dis *disbad.Disbad) service.Service {\n\treturn &grpcServer{\n\t\tcfg: cfg,\n\t\tserver: &server{\n\t\t\tcfg: cfg,\n\t\t\tdis: dis,\n\t\t},\n\t}\n}", "func New(config Config) *Server {\n\treturn &Server{\n\t\tgrpcAddr: config.GRPCAddr,\n\t\trestAddr: config.RESTAddr,\n\t}\n}", "func NewServer(opt ...Option) Server {\n\treturn newGrpcServer(opt...)\n}", "func New(c *conf.RPCServer, l *logic.Logic) *grpc.Server {\n\tkeepParams := grpc.KeepaliveParams(keepalive.ServerParameters{\n\t\tMaxConnectionIdle: time.Duration(c.IdleTimeout),\n\t\tMaxConnectionAgeGrace: time.Duration(c.ForceCloseWait),\n\t\tTime: time.Duration(c.KeepAliveInterval),\n\t\tTimeout: time.Duration(c.KeepAliveTimeout),\n\t\tMaxConnectionAge: time.Duration(c.MaxLifeTime),\n\t})\n\tsrv := grpc.NewServer(keepParams)\n\tpb.RegisterLogicServer(srv, &server{l})\n\tlis, err := net.Listen(c.Network, c.Addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo func() {\n\t\tif err := srv.Serve(lis); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\treturn srv\n}", "func NewServer(opts ...server.Option) server.Server {\n\treturn grpc.NewServer(opts...)\n}", "func New(opts ...Option) (*Server, error) {\n\tcfg := options{\n\t\tlog: log.Base(),\n\t}\n\n\tvar srvOpts []grpc.ServerOption\n\n\tfor _, o := range opts {\n\t\to(&cfg)\n\t}\n\n\tif cfg.errored() {\n\t\treturn nil, fmt.Errorf(\"error during server setup: %v\", cfg.errs)\n\t}\n\n\tif !cfg.insecure {\n\t\tif (cfg.tlsCert == \"\" || cfg.tlsKey == \"\") && cfg.certificates == nil {\n\t\t\treturn nil, errors.New(\"either set insecure or define TLS certificates appropriately\")\n\t\t}\n\n\t\tif cfg.certificates == nil {\n\t\t\tcrt, err := tls.X509KeyPair(\n\t\t\t\t[]byte(cfg.tlsCert),\n\t\t\t\t[]byte(cfg.tlsKey),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcfg.certificates = append(cfg.certificates, crt)\n\t\t}\n\n\t\tcreds := credentials.NewTLS(serverTLS(&cfg))\n\t\tsrvOpts = append(srvOpts, grpc.Creds(creds))\n\t}\n\n\tif len(cfg.ssInterceptors) > 0 {\n\t\tc := middleware.ChainStreamServer(cfg.ssInterceptors...)\n\t\tsrvOpts = append(srvOpts, grpc.StreamInterceptor(c))\n\t}\n\n\tif len(cfg.usInterceptors) > 0 {\n\t\tc := middleware.ChainUnaryServer(cfg.usInterceptors...)\n\t\tsrvOpts = append(srvOpts, grpc.UnaryInterceptor(c))\n\t}\n\n\tsrv := Server{\n\t\tstate: Init,\n\t\ttransport: grpc.NewServer(srvOpts...),\n\t\tlog: cfg.log,\n\t\tnotifyChan: make(map[State][]chan<- State),\n\t}\n\n\tsrv.shutdown = srv.transport.GracefulStop\n\n\tif cfg.httpPassthrough || cfg.httpPassthroughInsecure {\n\t\tsrv.httpMux = grpc_runtime.NewServeMux(\n\t\t\tgrpc_runtime.WithMarshalerOption(\n\t\t\t\tgrpc_runtime.MIMEWildcard,\n\t\t\t\t&grpc_runtime.JSONPb{\n\t\t\t\t\tMarshalOptions: protojson.MarshalOptions{\n\t\t\t\t\t\tIndent: \"\",\n\t\t\t\t\t\tUseProtoNames: true,\n\t\t\t\t\t\tEmitUnpopulated: true,\n\t\t\t\t\t\tMultiline: true,\n\t\t\t\t\t},\n\t\t\t\t\tUnmarshalOptions: protojson.UnmarshalOptions{\n\t\t\t\t\t\tDiscardUnknown: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t),\n\t\t)\n\n\t\tmux := http.NewServeMux()\n\t\tmux.Handle(\"/\", srv.httpMux)\n\n\t\tif cfg.certificates != nil {\n\t\t\tsrv.httpConfig = &tls.Config{\n\t\t\t\tCertificates: cfg.certificates,\n\t\t\t\tNextProtos: []string{\"h2\"},\n\t\t\t\tClientCAs: cfg.mustGetCertPool(),\n\t\t\t\tClientAuth: cfg.clientAuth,\n\t\t\t\t//nolint -- the only way to make this proper is to have a SAN in the cert, which may expose\n\t\t\t\t// some of the internals. I could go either way on this one..\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t}\n\t\t}\n\n\t\tsrv.httpTransport = &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%d\", cfg.port),\n\t\t\tHandler: grpcHandlerFunc(srv.Transport(), mux),\n\t\t\tTLSConfig: srv.httpConfig,\n\t\t\tIdleTimeout: time.Second * idletimeout,\n\t\t\tReadHeaderTimeout: time.Second * readheadertimeout,\n\t\t\tMaxHeaderBytes: maxheaderbytes,\n\t\t}\n\n\t\tvar err error\n\n\t\tswitch {\n\t\tcase cfg.httpPassthrough:\n\t\t\tsrv.httpListener, err = srv.getListener(cfg.port, cfg.certificates)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase cfg.httpPassthroughInsecure:\n\t\t\tsrv.httpListener, err = srv.getListener(cfg.port, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tsrv.listener, err = srv.getListener(internalServerPort, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\trpcLis, _ := srv.getListener(cfg.port, nil)\n\t\tsrv.listener = rpcLis\n\t}\n\n\tif cfg.reflect {\n\t\treflection.Register(srv.transport)\n\t}\n\n\treturn &srv, nil\n}", "func NewServer(opts Opts) (net.Listener, *grpc.Server) {\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", opts.Host, opts.Port))\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen on %s:%d: %v\", opts.Host, opts.Port, err)\n\t}\n\tlog.Notice(\"Listening on %s:%d\", opts.Host, opts.Port)\n\n\ts := grpc.NewServer(OptionalTLS(opts.KeyFile, opts.CertFile, opts.TLSMinVersion,\n\t\tgrpc.ChainUnaryInterceptor(append([]grpc.UnaryServerInterceptor{\n\t\t\tLogUnaryRequests,\n\t\t\tserverMetrics.UnaryServerInterceptor(),\n\t\t\tgrpc_recovery.UnaryServerInterceptor(),\n\t\t}, unaryAuthInterceptor(opts)...)...),\n\t\tgrpc.ChainStreamInterceptor(append([]grpc.StreamServerInterceptor{\n\t\t\tLogStreamRequests,\n\t\t\tserverMetrics.StreamServerInterceptor(),\n\t\t\tgrpc_recovery.StreamServerInterceptor(),\n\t\t}, streamAuthInterceptor(opts)...)...),\n\t\tgrpc.MaxRecvMsgSize(419430400), // 400MB\n\t\tgrpc.MaxSendMsgSize(419430400),\n\t)...)\n\n\tserverMetrics.InitializeMetrics(s)\n\treflection.Register(s)\n\tif !opts.NoHealth {\n\t\tgrpc_health_v1.RegisterHealthServer(s, health.NewServer())\n\t}\n\treturn lis, s\n}", "func NewServer(ops ...Option) (*Server, error) {\n\tconf := toGRPCConfig(ops...)\n\tvar srv *grpc.Server\n\tif conf.tlsConfig != nil {\n\t\tsrv = grpc.NewServer(grpc.Creds(credentials.NewTLS(conf.tlsConfig)), grpc.MaxRecvMsgSize(math.MaxInt32), grpc.MaxSendMsgSize(math.MaxInt32))\n\t} else {\n\t\tsrv = grpc.NewServer(grpc.MaxRecvMsgSize(math.MaxInt32), grpc.MaxSendMsgSize(math.MaxInt32))\n\t}\n\n\trpc.RegisterGRpcServer(srv)\n\n\tls, err := net.Listen(\"tcp\", conf.addr)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"grpc: listen failed, addr = %s\", conf.addr)\n\t}\n\n\treturn &Server{\n\t\tserver: srv,\n\t\tlistener: ls,\n\t\trunning: utils.NewAtomicBool(false),\n\t\treadyCh: make(chan struct{}),\n\t\tstopCh: make(chan struct{}),\n\t}, nil\n}", "func newGRPCServer(ctx context.Context, cfg *config.ServerConfig, authCtx interfaces.AuthenticationContext,\n\topts ...grpc.ServerOption) (*grpc.Server, error) {\n\t// Not yet implemented for streaming\n\tvar chainedUnaryInterceptors grpc.UnaryServerInterceptor\n\tif cfg.Security.UseAuth {\n\t\tlogger.Infof(ctx, \"Creating gRPC server with authentication\")\n\t\tchainedUnaryInterceptors = grpc_middleware.ChainUnaryServer(grpcPrometheus.UnaryServerInterceptor,\n\t\t\tauth.GetAuthenticationCustomMetadataInterceptor(authCtx),\n\t\t\tgrpcauth.UnaryServerInterceptor(auth.GetAuthenticationInterceptor(authCtx)),\n\t\t\tauth.AuthenticationLoggingInterceptor,\n\t\t\tblanketAuthorization,\n\t\t)\n\t} else {\n\t\tlogger.Infof(ctx, \"Creating gRPC server without authentication\")\n\t\tchainedUnaryInterceptors = grpc_middleware.ChainUnaryServer(grpcPrometheus.UnaryServerInterceptor)\n\t}\n\n\tserverOpts := []grpc.ServerOption{\n\t\tgrpc.StreamInterceptor(grpcPrometheus.StreamServerInterceptor),\n\t\tgrpc.UnaryInterceptor(chainedUnaryInterceptors),\n\t}\n\tserverOpts = append(serverOpts, opts...)\n\tgrpcServer := grpc.NewServer(serverOpts...)\n\tgrpcPrometheus.Register(grpcServer)\n\tflyteService.RegisterAdminServiceServer(grpcServer, adminservice.NewAdminServer(cfg.KubeConfig, cfg.Master))\n\tif cfg.Security.UseAuth {\n\t\tflyteService.RegisterAuthMetadataServiceServer(grpcServer, authCtx.AuthMetadataService())\n\t\tflyteService.RegisterIdentityServiceServer(grpcServer, authCtx.IdentityService())\n\t}\n\n\thealthServer := health.NewServer()\n\thealthServer.SetServingStatus(\"\", grpc_health_v1.HealthCheckResponse_SERVING)\n\tgrpc_health_v1.RegisterHealthServer(grpcServer, healthServer)\n\n\tif cfg.GrpcServerReflection {\n\t\treflection.Register(grpcServer)\n\t}\n\treturn grpcServer, nil\n}", "func NewServer(opt ...Option) Server {\r\n\treturn newRpcServer(opt...)\r\n}", "func New(c *conf.Config, s *service.Service) (svr *rpc.Server) {\n\tr := &RPC{s: s}\n\tsvr = rpc.NewServer(c.RPCServer)\n\tif err := svr.Register(r); err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func newGRPCServer(t *testing.T, srv transportv1pb.TransportServiceServer) *fakeGRPCServer {\n\t// gRPC testPack.\n\tlis := bufconn.Listen(100)\n\tt.Cleanup(func() { require.NoError(t, lis.Close()) })\n\n\ts := grpc.NewServer()\n\tt.Cleanup(s.Stop)\n\n\t// Register service.\n\tif srv != nil {\n\t\ttransportv1pb.RegisterTransportServiceServer(s, srv)\n\t}\n\n\t// Start.\n\tgo func() {\n\t\tif err := s.Serve(lis); err != nil && !errors.Is(err, grpc.ErrServerStopped) {\n\t\t\tpanic(fmt.Sprintf(\"Serve returned err = %v\", err))\n\t\t}\n\t}()\n\n\treturn &fakeGRPCServer{Listener: lis}\n}", "func New(s *service.Service) (svr *rpc.Server) {\n\tr := &RPC{s: s}\n\tsvr = rpc.NewServer(nil)\n\tif err := svr.Register(r); err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func New(server *grpc.Server) Service {\n\ts := &service{}\n\tpb.RegisterRuntimeServiceServer(server, s)\n\tpb.RegisterImageServiceServer(server, s)\n\treturn s\n}", "func NewGRPC(ctx context.Context, config *Config) *grpc.Server {\n\t// Setup our gRPC connection factory\n\tconnFactory := secureconn.NewFactory(*config.ServiceCerts)\n\n\t// Register our API\n\tgrpcServer := connFactory.NewServer(tracing.GlobalServerInterceptor())\n\tsrv := NewLicenseControlServer(config)\n\tlc.RegisterLicenseControlServer(grpcServer, srv)\n\thealth.RegisterHealthServer(grpcServer, srv.health)\n\n\t// Register reflection service on gRPC server.\n\treflection.Register(grpcServer)\n\treturn grpcServer\n}", "func New() (grpc_fpl.FPLClient, func(), error) {\n\tport := viper.GetString(\"port\")\n\tconn, err := grpc.Dial(fmt.Sprintf(\"localhost:%v\", port), grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error while connecting to gRPC server at port %v: %v\", port, err)\n\t}\n\n\tclient := grpc_fpl.NewFPLClient(conn)\n\n\tcleanup := func() {\n\t\tif conn != nil {\n\t\t\tconn.Close()\n\t\t}\n\t}\n\treturn client, cleanup, nil\n}", "func NewServer() (server *Server, err error) {\n\tserver = &Server{\n\t\tserviceName: OwnService,\n\t\thandlers: make(map[string]*handlerEntry),\n\t\tstreamingHandlers: make(map[string]*handlerEntry),\n\t}\n\tlistenAddr := \":\" + core.InstanceListenPortFlag.Get()\n\tserver.listener, err = net.Listen(\"tcp\", listenAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserver.grpcServer = grpc.NewServer()\n\tcore.RegisterLeverRPCServer(server.grpcServer, server)\n\treturn server, nil\n}", "func NewServer(config *Config, opts []grpc.ServerOption) (*Server, error) {\n\tif config == nil {\n\t\treturn nil, errors.New(\"config not provided\")\n\t}\n\n\ts := grpc.NewServer(opts...)\n\treflection.Register(s)\n\n\tsrv := &Server{\n\t\ts: s,\n\t\tconfig: config,\n\t\tclients: map[string]*Client{},\n\t}\n\tvar err error\n\tif srv.config.Port < 0 {\n\t\tsrv.config.Port = 0\n\t}\n\tsrv.lis, err = net.Listen(\"tcp\", fmt.Sprintf(\":%d\", srv.config.Port))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open listener port %d: %v\", srv.config.Port, err)\n\t}\n\tgnmipb.RegisterGNMIServer(srv.s, srv)\n\tlog.V(1).Infof(\"Created Server on %s\", srv.Address())\n\treturn srv, nil\n}", "func NewGrpcServer(scaleHandler *scaling.ScaleHandler, address, certDir string, certsReady chan struct{}) GrpcServer {\n\treturn GrpcServer{\n\t\taddress: address,\n\t\tscalerHandler: scaleHandler,\n\t\tcertDir: certDir,\n\t\tcertsReady: certsReady,\n\t}\n}", "func NewGRPC(ctx context.Context, config *config.DataFeedConfig, connFactory *secureconn.Factory) *grpc.Server {\n\tgrpcServer := connFactory.NewServer(tracing.GlobalServerInterceptor())\n\tsrv := &Server{\n\t\tcfg: config,\n\t\thealth: health.NewService(),\n\t}\n\thealth.RegisterHealthServer(grpcServer, srv.health)\n\n\t// Register reflection service on gRPC server.\n\treflection.Register(grpcServer)\n\treturn grpcServer\n}", "func NewGRPC(port string, options ...grpc.ServerOption) *GRPC {\n\tsrv := grpc.NewServer(options...)\n\treturn &GRPC{\n\t\tServer: srv,\n\t\tport: port,\n\t}\n}", "func New(options ...OptionsFunc) (*Server, error) {\n\ts := &Server{\n\t\tauxAddr: \":9090\",\n\t\tstopChan: make(chan struct{}, 1),\n\t}\n\n\tfor _, f := range options {\n\t\tif err := f(s); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"options func failed\")\n\t\t}\n\t}\n\n\treturn s, nil\n}", "func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) {\n\tc, err := parseConfig(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuserManager, plug, err := getDriver(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsvc := &service{\n\t\tusermgr: userManager,\n\t\tplugin: plug,\n\t}\n\n\treturn svc, nil\n}", "func NewServer(driver Driver, addr chan string) *GrpcServer {\n\treturn &GrpcServer{\n\t\tdriver: driver,\n\t\taddress: addr,\n\t}\n}", "func NewGrpcServer(addr string, protos []string, opts ...grpc.ServerOption) (*GrpcServer, error) {\n\tdescFromProto, err := grpcurl.DescriptorSourceFromProtoFiles([]string{}, protos...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot parse proto file: %v\", err)\n\t}\n\tgs := &GrpcServer{\n\t\taddr: addr,\n\t\tdesc: descFromProto,\n\t\tserver: grpc.NewServer(opts...),\n\t\thandlerM: map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error{},\n\t}\n\n\tgs.server = grpc.NewServer()\n\tservices, err := grpcurl.ListServices(gs.desc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list services\")\n\t}\n\tfor _, svcName := range services {\n\t\tdsc, err := gs.desc.FindSymbol(svcName)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to find service: %s, error: %v\", svcName, err)\n\t\t}\n\t\tsd := dsc.(*desc.ServiceDescriptor)\n\n\t\tunaryMethods := []grpc.MethodDesc{}\n\t\tstreamMethods := []grpc.StreamDesc{}\n\t\tfor _, mtd := range sd.GetMethods() {\n\t\t\tlogger.Debugf(\"protocols/grpc\", \"try to add method: %v of service: %s\", mtd, svcName)\n\n\t\t\tif mtd.IsClientStreaming() || mtd.IsServerStreaming() {\n\t\t\t\tstreamMethods = append(streamMethods, grpc.StreamDesc{\n\t\t\t\t\tStreamName: mtd.GetName(),\n\t\t\t\t\tHandler: gs.getStreamHandler(mtd),\n\t\t\t\t\tServerStreams: mtd.IsServerStreaming(),\n\t\t\t\t\tClientStreams: mtd.IsClientStreaming(),\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tunaryMethods = append(unaryMethods, grpc.MethodDesc{\n\t\t\t\t\tMethodName: mtd.GetName(),\n\t\t\t\t\tHandler: gs.getUnaryHandler(mtd),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tsvcDesc := grpc.ServiceDesc{\n\t\t\tServiceName: svcName,\n\t\t\tHandlerType: (*interface{})(nil),\n\t\t\tMethods: unaryMethods,\n\t\t\tStreams: streamMethods,\n\t\t\tMetadata: sd.GetFile().GetName(),\n\t\t}\n\t\tgs.server.RegisterService(&svcDesc, &mockServer{})\n\t}\n\n\treturn gs, nil\n}", "func NewGrpcServer(ctx context.Context, host string, port int) *GrpcServer {\n\treturn &GrpcServer{\n\t\tCtx: ctx,\n\t\thost: host,\n\t\tport: port,\n\t\tServer: grpc.NewServer(grpc.WriteBufferSize(2147483647), grpc.ReadBufferSize(2147483647)),\n\t\tState: Init,\n\t\tlistener: nil,\n\t\tservices: make([]ServiceInterface, 0),\n\t};\n}", "func New(initCtx context.Context, c *configpb.ServerConf, l *logger.Logger) (*Server, error) {\n\tconn, err := Listen(&net.UDPAddr{Port: int(c.GetPort())}, l)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\t<-initCtx.Done()\n\t\tconn.Close()\n\t}()\n\n\ts := &Server{\n\t\tc: c,\n\t\tconn: conn,\n\t\tl: l,\n\t}\n\n\treturn s, s.initConnection()\n}", "func NewGRPCServer(logger log.Logger, protoAddr string, app types.Application) service.Service {\n\tproto, addr := tmnet.ProtocolAndAddress(protoAddr)\n\ts := &GRPCServer{\n\t\tlogger: logger,\n\t\tproto: proto,\n\t\taddr: addr,\n\t\tapp: app,\n\t}\n\ts.BaseService = *service.NewBaseService(logger, \"ABCIServer\", s)\n\treturn s\n}", "func New(opts ...Option) Service {\n\to := newOptions(opts...)\n\ts := &server{\n\t\tid: o.ID,\n\t\troutes: make([]Route, 0),\n\t}\n\treturn s\n}", "func NewServer(options ...ServerOption) *Server {\n s := &Server{\n codecs: make(map[string]Codec),\n services: new(serviceMap),\n }\n for _, option := range options {\n option(s)\n }\n return s\n}", "func NewGrpcServer(c *Config) internal.Server {\n\ts := grpc.NewServer(c.serverOptions()...)\n\treflection.Register(s)\n\tfor _, svr := range c.Servers {\n\t\tsvr.RegisterWithServer(s)\n\t}\n\treturn &GrpcServer{\n\t\tserver: s,\n\t\tConfig: c,\n\t}\n}", "func New(ctx context.Context, conf Config) *Server {\n\tsvc := &rpc.Service{}\n\n\ttwirpServer := garo.NewAgentConfigurationServiceServer(svc, nil)\n\tapi := configureAPI(twirpServer, conf.Logger)\n\n\tsrv := http.Server{\n\t\tAddr: conf.Addr,\n\t\tHandler: api,\n\t}\n\n\treturn &Server{&srv, ctx, conf}\n}", "func New(srv *cmutation.Server) *Server {\n\treturn &Server{srv}\n}", "func NewServer(conf *Config, be *backend.Backend) (*Server, error) {\n\tauthInterceptor := interceptors.NewAuthInterceptor(be.Config.AuthWebhookURL)\n\tdefaultInterceptor := interceptors.NewDefaultInterceptor()\n\n\topts := []grpc.ServerOption{\n\t\tgrpc.UnaryInterceptor(grpcmiddleware.ChainUnaryServer(\n\t\t\tauthInterceptor.Unary(),\n\t\t\tdefaultInterceptor.Unary(),\n\t\t\tgrpcprometheus.UnaryServerInterceptor,\n\t\t)),\n\t\tgrpc.StreamInterceptor(grpcmiddleware.ChainStreamServer(\n\t\t\tauthInterceptor.Stream(),\n\t\t\tdefaultInterceptor.Stream(),\n\t\t\tgrpcprometheus.StreamServerInterceptor,\n\t\t)),\n\t}\n\n\tif conf.CertFile != \"\" && conf.KeyFile != \"\" {\n\t\tcreds, err := credentials.NewServerTLSFromFile(conf.CertFile, conf.KeyFile)\n\t\tif err != nil {\n\t\t\tlog.Logger.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\t\topts = append(opts, grpc.Creds(creds))\n\t}\n\n\topts = append(opts, grpc.MaxConcurrentStreams(math.MaxUint32))\n\n\tyorkieServiceCtx, yorkieServiceCancel := context.WithCancel(context.Background())\n\n\tgrpcServer := grpc.NewServer(opts...)\n\thealthpb.RegisterHealthServer(grpcServer, health.NewServer())\n\tapi.RegisterYorkieServer(grpcServer, newYorkieServer(yorkieServiceCtx, be))\n\tapi.RegisterClusterServer(grpcServer, newClusterServer(be))\n\tgrpcprometheus.Register(grpcServer)\n\n\treturn &Server{\n\t\tconf: conf,\n\t\tgrpcServer: grpcServer,\n\t\tyorkieServiceCancel: yorkieServiceCancel,\n\t}, nil\n}", "func NewServer() *Server {\n\n\tsrvr := grpc.NewServer(\n\t\tgrpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(unaryInterceptors...)),\n\t)\n\n\ts := &Server{Server: srvr}\n\treturn s\n}", "func NewGRPCServer(c *conf.Config, rs registry.Registry, srv center.ICenter) *grpc.Server {\n\t// 启动grpc服务\n\tsv := grpc.NewServer(&c.GrpcServer, app.WithHost(c.App.Host), app.WithID(c.App.ServerID),\n\t\tapp.WithName(c.App.Name), app.WithRegistry(rs))\n\tsv.Init()\n\tpb.RegisterCenterServer(sv.Server, &server{srv})\n\tsv.AddHook(grpc.NewTracingHook())\n\t//启动服务\n\tsv.Start()\n\treturn sv\n}", "func New(e *calc.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tAddH: NewAddHandler(e.Add, uh),\n\t}\n}", "func NewServer(binding string, nodeMgr NodeManagerInterface) GRPCServer {\n\ts := grpc.NewServer()\n\tmyServer := &server{\n\t\tbinding: binding,\n\t\ts: s,\n\t\tnodeMgr: nodeMgr,\n\t}\n\tpb.RegisterCloudProviderVsphereServer(s, myServer)\n\treflection.Register(s)\n\treturn myServer\n}", "func New(ctx context.Context, cc *grpc.ClientConn, logger log.Logger) server.AddService {\n\treturn client{ctx, pb.NewAddClient(cc), logger}\n}", "func New(svc *service.Service) *Server {\n\tvar rc struct {\n\t\tServer *warden.ServerConfig\n\t}\n\tif err := paladin.Get(\"application.toml\").UnmarshalTOML(&rc); err != nil {\n\t\tif err != paladin.ErrNotExist {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tws := warden.NewServer(rc.Server)\n\tapi.RegisterDebugServiceServer(ws.Server(), svc)\n\tws, err := ws.Start()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tappid := env.AppID\n\tzone := env.Zone\n\thostname := fmt.Sprintf(\"grpc-%s-%s-%d-%d\", appid, env.Hostname, time.Now().Unix(), os.Getpid())\n\taddrs := utility.GetArrary(\"GRPC_ADDR\", \"grpc://192.168.110.31:9107\", \"grpc.addr\", \"etcd grpc addr\", \",\")\n\n\tbuilder, err := etcd.New(nil)\n\tif err == nil {\n\t\t//注册服务发现\n\t\tbuilder.Build(appid)\n\t\t_, err := builder.Register(context.Background(), &naming.Instance{\n\t\t\tAppID: appid,\n\t\t\tHostname: hostname,\n\t\t\tZone: zone,\n\t\t\tAddrs: addrs,\n\t\t})\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tlog.Error(fmt.Sprintf(\"DebugService init grpc etcd server(appid:%s,hostname:%s).\", appid, hostname))\n\n\treturn &Server{\n\t\tws: ws,\n\t\tbuilder: builder,\n\t}\n}", "func New(ctx context.Context, opts ...Option) *Server {\n\tctx, span := trace.StartSpan(ctx, \"server_init\")\n\tdefer span.End()\n\n\tlog := common.Logger(ctx)\n\tengine := gin.New()\n\ts := &Server{\n\t\tRouter: engine,\n\t\tAdminRouter: engine,\n\t\tsvcConfigs: map[string]*http.Server{\n\t\t\tWebServer: &http.Server{\n\t\t\t\tMaxHeaderBytes: getEnvInt(EnvMaxHeaderSize, http.DefaultMaxHeaderBytes),\n\t\t\t\tReadHeaderTimeout: getEnvDuration(EnvReadHeaderTimeout, 0),\n\t\t\t\tReadTimeout: getEnvDuration(EnvReadTimeout, 0),\n\t\t\t\tWriteTimeout: getEnvDuration(EnvWriteTimeout, 0),\n\t\t\t\tIdleTimeout: getEnvDuration(EnvHTTPIdleTimeout, 0),\n\t\t\t},\n\t\t\tAdminServer: &http.Server{},\n\t\t\tGRPCServer: &http.Server{},\n\t\t},\n\t\t// MUST initialize these before opts\n\t\tappListeners: new(appListeners),\n\t\tfnListeners: new(fnListeners),\n\t\ttriggerListeners: new(triggerListeners),\n\n\t\t// Almost everything else is configured through opts (see NewFromEnv for ex.) or below\n\t}\n\n\tfor _, opt := range opts {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\terr := opt(ctx, s)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Fatal(\"Error during server opt initialization.\")\n\t\t}\n\t}\n\n\tif s.svcConfigs[WebServer].Addr == \"\" {\n\t\ts.svcConfigs[WebServer].Addr = fmt.Sprintf(\":%d\", DefaultPort)\n\t}\n\tif s.svcConfigs[AdminServer].Addr == \"\" {\n\t\ts.svcConfigs[AdminServer].Addr = fmt.Sprintf(\":%d\", DefaultPort)\n\t}\n\tif s.svcConfigs[GRPCServer].Addr == \"\" {\n\t\ts.svcConfigs[GRPCServer].Addr = fmt.Sprintf(\":%d\", DefaultGRPCPort)\n\t}\n\n\trequireConfigSet := func(id string, val interface{}) {\n\t\tif val == nil {\n\t\t\tlog.Fatalf(\"Invalid configuration for server type %s, %s must be configured during startup\", s.nodeType, id)\n\t\t}\n\t}\n\trequireConfigNotSet := func(id string, val interface{}) {\n\t\tif val != nil {\n\t\t\tlog.Fatalf(\"Invalid configuration for server type %s, %s must not be configured during startup\", s.nodeType, id)\n\t\t}\n\t}\n\n\t// Check that WithAgent options have been processed correctly.\n\t// Yuck the yuck - server should really be split into several interfaces (LB, Runner, API) and each should be instantiated separately\n\tswitch s.nodeType {\n\tcase ServerTypeAPI:\n\t\trequireConfigNotSet(\"agent\", s.agent)\n\t\trequireConfigSet(\"datastore\", s.datastore)\n\t\trequireConfigSet(\"triggerAnnotator\", s.triggerAnnotator)\n\tcase ServerTypeFull:\n\t\trequireConfigSet(\"agent\", s.agent)\n\t\trequireConfigSet(\"lbReadAccess\", s.lbReadAccess)\n\t\trequireConfigSet(\"datastore\", s.datastore)\n\t\trequireConfigSet(\"triggerAnnotator\", s.triggerAnnotator)\n\n\tcase ServerTypeLB:\n\t\trequireConfigSet(\"lbReadAccess\", s.lbReadAccess)\n\t\trequireConfigSet(\"agent\", s.agent)\n\n\tcase ServerTypePureRunner:\n\t\trequireConfigSet(\"agent\", s.agent)\n\n\tdefault:\n\n\t\tlog.Fatal(\"unknown server type %d\", s.nodeType)\n\n\t}\n\n\ts.Router.Use(loggerWrap, traceWrap) // TODO should be opts\n\toptionalCorsWrap(s.Router) // TODO should be an opt\n\tapiMetricsWrap(s)\n\t// panicWrap is last, specifically so that logging, tracing, cors, metrics, etc wrappers run\n\ts.Router.Use(panicWrap)\n\ts.AdminRouter.Use(panicWrap)\n\ts.bindHandlers(ctx)\n\n\treturn s\n}", "func New(auth Authorizer, errorWriter ErrorWriter, clean CleanCredentials) *Server {\n\treturn &Server{\n\t\tpeers: map[string]peer{},\n\t\tauthorizer: auth,\n\t\tcleanCredentials: clean,\n\t\terrorWriter: errorWriter,\n\t\tsessions: newSessionManager(),\n\t}\n}", "func newRPCServer(agent *agent, caFile, certFile, keyFile string, rpcAddrs []string) (*server, error) {\n\tcreds, err := credentials.NewServerTLSFromFile(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err, \"failed to read certificate/key from %v/%v\", certFile, keyFile)\n\t}\n\n\tcaCert, err := ioutil.ReadFile(caFile)\n\tif err != nil {\n\t\treturn nil, trace.ConvertSystemError(err)\n\t}\n\tcaCertPool := x509.NewCertPool()\n\tcaCertPool.AppendCertsFromPEM(caCert)\n\n\tbackend := grpc.NewServer(grpc.Creds(creds))\n\tserver := &server{agent: agent, Server: backend}\n\tpb.RegisterAgentServer(backend, server)\n\n\thealthzHandler := newHealthHandler(server)\n\n\t// handler is a multiplexer for both gRPC and HTTPS queries.\n\t// The HTTPS endpoint returns the cluster status as JSON\n\t// TODO: why does server need to handle both gRPC and HTTPS queries?\n\thandler := grpcHandlerFunc(server, healthzHandler)\n\n\tfor _, addr := range rpcAddrs {\n\t\tsrv := newHTTPServer(addr, newTLSConfig(caCertPool), handler)\n\t\tserver.httpServers = append(server.httpServers, srv)\n\n\t\t// TODO: separate Start function to start listening.\n\t\tgo func(srv *http.Server) {\n\t\t\terr := srv.ListenAndServeTLS(certFile, keyFile)\n\t\t\tif err == http.ErrServerClosed {\n\t\t\t\tlog.WithError(err).Debug(\"Server has been shutdown/closed.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Errorf(\"Failed to serve on %v.\", srv.Addr)\n\t\t\t\treturn\n\t\t\t}\n\t\t}(srv)\n\t}\n\treturn server, nil\n}", "func NewGRPCServer(s *service.Service) *grpc.Server {\n\tg := s.ConnFactory.NewServer(\n\t\tgrpc.UnaryInterceptor(\n\t\t\tgrpc_middleware.ChainUnaryServer(\n\t\t\t\ttracing.ServerInterceptor(tracing.GlobalTracer()),\n\t\t\t\tInputValidationInterceptor(),\n\t\t\t),\n\t\t),\n\t)\n\thealth.RegisterHealthServer(g, health.NewService())\n\treflection.Register(g)\n\treturn g\n}", "func New(cfg *types.RPC) *RPC {\n\tInitCfg(cfg)\n\tif cfg.EnableTrace {\n\t\tgrpc.EnableTracing = true\n\t}\n\treturn &RPC{cfg: cfg}\n}", "func New(e *goastarter.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tAddH: NewAddHandler(e.Add, uh),\n\t}\n}", "func New(\n\taddr string,\n\thandler Handler,\n\tlog *log.Logger,\n\tworkersCount uint8,\n) (srv *Server) {\n\tsrv = &Server{\n\t\taddr: addr,\n\t\thandler: handler,\n\t\tlog: log,\n\t\tClients: newClients(),\n\t\tchStop: make(chan bool, 1),\n\t\tchRequest: make(chan *tRequest, workersCount),\n\t}\n\n\treturn\n}", "func NewGRPCServer(endpoints endpoints.Endpoints) pb.EventServiceServer {\n\treturn &gRPCServer{\n\t\tcreate: gkit.NewServer(\n\t\t\tendpoints.Create,\n\t\t\tdecodeCreateEventRequest,\n\t\t\tencodeCreateEventResponse,\n\t\t),\n\t\tretrieve: gkit.NewServer(\n\t\t\tendpoints.Retrieve,\n\t\t\tdecodeRetrieveEventRequest,\n\t\t\tencodeRetrieveEventResponse,\n\t\t),\n\t}\n}", "func NewServer(cfg ServerConfig, logger *log.Logger, unaryInterceptors []grpc.UnaryServerInterceptor, streamInterceptors []grpc.StreamServerInterceptor) *grpc.Server {\n\topts := []grpcrecovery.Option{\n\t\tgrpcrecovery.WithRecoveryHandlerContext(func(ctx context.Context, rec interface{}) (err error) {\n\t\t\tlogger.Critical(ctx, \"[gRPC|Server] Recovered in %v\", rec)\n\n\t\t\treturn status.Errorf(codes.Internal, \"Recovered in %v\", rec)\n\t\t}),\n\t}\n\n\tserver := grpc.NewServer(\n\t\tgrpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{\n\t\t\tMinTime: cfg.ServerMinTime, // If a client pings more than once every 5 minutes, terminate the connection\n\t\t\tPermitWithoutStream: true, // Allow pings even when there are no active streams\n\t\t}),\n\t\tgrpc.KeepaliveParams(keepalive.ServerParameters{\n\t\t\tTime: cfg.ServerTime, // Ping the client if it is idle for 2 hours to ensure the connection is still active\n\t\t\tTimeout: cfg.ServerTimeout, // Wait 20 second for the ping ack before assuming the connection is dead\n\t\t}),\n\t\tgrpcmiddleware.WithUnaryServerChain(\n\t\t\tappend([]grpc.UnaryServerInterceptor{\n\t\t\t\tgrpcrecovery.UnaryServerInterceptor(opts...),\n\t\t\t\tmiddleware.TransformUnaryIncomingError(),\n\t\t\t\tmiddleware.SetMetadataFromUnaryRequest(),\n\t\t\t\tfirewall.SetIdentityFromUnaryRequest(),\n\t\t\t\tmiddleware.LogUnaryRequest(logger),\n\t\t\t}, unaryInterceptors...)...,\n\t\t),\n\t\tgrpcmiddleware.WithStreamServerChain(\n\t\t\tappend([]grpc.StreamServerInterceptor{\n\t\t\t\tgrpcrecovery.StreamServerInterceptor(opts...),\n\t\t\t\tmiddleware.TransformStreamIncomingError(),\n\t\t\t\tmiddleware.SetMetadataFromStreamRequest(),\n\t\t\t\tfirewall.SetIdentityFromStreamRequest(),\n\t\t\t\tmiddleware.LogStreamRequest(logger),\n\t\t\t}, streamInterceptors...)...,\n\t\t),\n\t)\n\n\treturn server\n}", "func NewGRPCServer(addr string, pluginHost PluginHost) (*GRPCServer, error) {\n\tl, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"create listener: %w\", err)\n\t}\n\n\tif pluginHost == nil {\n\t\treturn nil, errors.New(\"plugin host is nil\")\n\t}\n\n\tserver := &GRPCServer{\n\t\tlistener: l,\n\t\tpluginHost: pluginHost,\n\t}\n\n\treturn server, nil\n}", "func NewServer(addr string) (*Server, error) {\n\ts := &Server{\n\t\trequests: make(chan *protocol.NetRequest, 8),\n\t\tresponses: make(chan *protocol.NetResponse, 8),\n\t\tAddr: addr,\n\t\trunning: true,\n\t\tgames: make(map[uint64]poker.GameLike, 0),\n\t}\n\n\tlis, err := net.Listen(\"tcp\", serverAddr())\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen: %v\\n\", err)\n\t}\n\tgrpcServer := grpc.NewServer()\n\tpb.RegisterGameServerServer(grpcServer, s)\n\n\tlog.Printf(\"server listening at %v\\n\", lis.Addr())\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to serve: `%v`\\n\", err)\n\t}\n\n\treturn s, nil\n}", "func New(addr string) *Server {\n\tsrv := new(Server)\n\tsrv.Context = new(Context)\n\tsrv.Context.Channels = make(map[string]*channel.Channel)\n\tsrv.Address = addr\n\treturn srv\n}", "func New() pb.LinesServiceServer {\n\treturn &service{}\n}", "func New(addr string, port int) *Server {\n\tctx, cancel := context.WithCancel(context.Background())\n\treturn &Server{\n\t\taddr: addr,\n\t\tport: port,\n\t\tctx: ctx,\n\t\tctxCancel: cancel,\n\t}\n}", "func NewGrpcServer(\n\taddress string,\n\tcerts *GrpcSecurity,\n\tsecure bool,\n\tprobe ReadyProbe,\n) *GrpcServer {\n\tserver := &GrpcServer{\n\t\taddress: address,\n\t\tsecure: secure,\n\t\tGrpcSecurity: certs,\n\t\tprobe: probe,\n\t}\n\treturn server\n}", "func New(cfg *types.RPC) *RPC {\r\n\tInitCfg(cfg)\r\n\tif cfg.EnableTrace {\r\n\t\tgrpc.EnableTracing = true\r\n\t}\r\n\treturn &RPC{cfg: cfg}\r\n}", "func NewServer(ctx interface{}) (*Server, error) {\n\tif ctx == nil {\n\t\treturn nil, fmt.Errorf(\"rpc: ctx is nil\")\n\t}\n\tctxType := reflect.TypeOf(ctx)\n\tif ctxType.Kind() != reflect.Ptr {\n\t\treturn nil, fmt.Errorf(\"rpc: ctx is not pointer\")\n\t}\n\n\treturn &Server{\n\t\tcodecs: make(map[string]Codec),\n\t\tservices: new(serviceMap),\n\t\tctxType: ctxType.Elem(),\n\t}, nil\n}", "func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) {\n\tc, err := parseConfig(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgatewaySelector, err := pool.GatewaySelector(c.GatewayAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tservice := &service{\n\t\tconf: c,\n\t\tgatewaySelector: gatewaySelector,\n\t}\n\n\treturn service, nil\n}", "func NewServer(opts ...Option) Service {\n\treturn newService(opts...)\n}", "func NewGrpcServer(option *ServerOption) *grpc.Server {\n\topts := []grpc.ServerOption{\n\t\tgrpc.MaxRecvMsgSize(option.MaxRecvMsgSize),\n\t\tgrpc.MaxSendMsgSize(option.MaxSendMsgSize),\n\t\tgrpc.InitialWindowSize(option.InitialWindowSize),\n\t\tgrpc.InitialConnWindowSize(option.InitialConnWindowSize),\n\t\tgrpc.MaxConcurrentStreams(option.MaxConcurrentStreams),\n\t\tgrpc.KeepaliveParams(keepalive.ServerParameters{Time: option.KeepaliveTime, Timeout: option.KeepaliveTimeout}),\n\t\tgrpc.KeepaliveEnforcementPolicy(serverEnforcement),\n\t}\n\tif option.StatsHandler != nil {\n\t\topts = append(opts, grpc.StatsHandler(option.StatsHandler))\n\t}\n\n\tvar unaryInterceptor grpc.UnaryServerInterceptor\n\tvar streamInterceptor grpc.StreamServerInterceptor\n\tif option.Interceptor != nil {\n\t\tunaryInterceptor = func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {\n\t\t\tif err := option.Interceptor(info.FullMethod); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn handler(ctx, req)\n\t\t}\n\n\t\tstreamInterceptor = func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {\n\t\t\tif err := option.Interceptor(info.FullMethod); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn handler(srv, stream)\n\t\t}\n\t}\n\tif unaryInterceptor != nil {\n\t\topts = append(opts, grpc.UnaryInterceptor(unaryInterceptor))\n\t}\n\tif streamInterceptor != nil {\n\t\topts = append(opts, grpc.StreamInterceptor(streamInterceptor))\n\t}\n\n\tserver := grpc.NewServer(opts...)\n\theartbeat.RegisterHeartbeatServer(server, &heartbeat.HeartbeatService{ClusterID: option.ClusterID})\n\treturn server\n}", "func New() (*Server, error) {\n\treturn &Server{}, nil\n}", "func New(listener net.Listener, httpServer *http.Server) goroutine.BackgroundRoutine {\n\treturn &server{\n\t\tserver: httpServer,\n\t\tmakeListener: func() (net.Listener, error) { return listener, nil },\n\t}\n}", "func NewGRPCServer(\n\tendpoints endpoints.Endpoints,\n\toptions []kitgrpc.ServerOption,\n\tlogger log.Logger,\n) pb.JoblistingServiceServer {\n\terrorLogger := kitgrpc.ServerErrorLogger(logger)\n\toptions = append(options, errorLogger)\n\n\treturn &grpcServer{\n\t\tcreateJobPost: kitgrpc.NewServer(\n\t\t\tendpoints.CreateJobPost,\n\t\t\tdecodeCreateJobPostRequest,\n\t\t\tencodeCreateJobPostResponse,\n\t\t\toptions...,\n\t\t),\n\t\tbulkCreateJobPost: kitgrpc.NewServer(\n\t\t\tendpoints.BulkCreateJobPost,\n\t\t\tdecodeBulkCreateJobPostRequest,\n\t\t\tencodeBulkCreateJobPostResponse,\n\t\t\toptions...,\n\t\t),\n\t\tgetAllJobPosts: kitgrpc.NewServer(\n\t\t\tendpoints.GetAllJobPosts,\n\t\t\tdecodeGetAllJobPostsRequest,\n\t\t\tencodeGetAllJobPostsResponse,\n\t\t\toptions...,\n\t\t),\n\t\tgetJobPostByID: kitgrpc.NewServer(\n\t\t\tendpoints.GetJobPostByID,\n\t\t\tdecodeGetJobPostByIDRequest,\n\t\t\tencodeGetJobPostByIDResponse,\n\t\t\toptions...,\n\t\t),\n\t\tupdateJobPost: kitgrpc.NewServer(\n\t\t\tendpoints.UpdateJobPost,\n\t\t\tdecodeUpdateJobPostRequest,\n\t\t\tencodeUpdateJobPostResponse,\n\t\t\toptions...,\n\t\t),\n\t\tdeleteJobPost: kitgrpc.NewServer(\n\t\t\tendpoints.DeleteJobPost,\n\t\t\tdecodeDeleteJobPostRequest,\n\t\t\tencodeDeleteJobPostResponse,\n\t\t\toptions...,\n\t\t),\n\n\t\tcreateCompany: kitgrpc.NewServer(\n\t\t\tendpoints.CreateCompany,\n\t\t\tdecodeCreateCompanyRequest,\n\t\t\tencodeCreateCompanyResponse,\n\t\t\toptions...,\n\t\t),\n\t\tlocalCreateCompany: kitgrpc.NewServer(\n\t\t\tendpoints.LocalCreateCompany,\n\t\t\tdecodeCreateCompanyRequest,\n\t\t\tencodeCreateCompanyResponse,\n\t\t\toptions...,\n\t\t),\n\t\tgetAllCompanies: kitgrpc.NewServer(\n\t\t\tendpoints.GetAllCompanies,\n\t\t\tdecodeGetAllCompaniesRequest,\n\t\t\tencodeGetAllCompaniesResponse,\n\t\t\toptions...,\n\t\t),\n\t\tupdateCompany: kitgrpc.NewServer(\n\t\t\tendpoints.UpdateCompany,\n\t\t\tdecodeUpdateCompanyRequest,\n\t\t\tencodeUpdateCompanyResponse,\n\t\t\toptions...,\n\t\t),\n\t\tlocalUpdateCompany: kitgrpc.NewServer(\n\t\t\tendpoints.LocalUpdateCompany,\n\t\t\tdecodeUpdateCompanyRequest,\n\t\t\tencodeUpdateCompanyResponse,\n\t\t\toptions...,\n\t\t),\n\t\tdeleteCompany: kitgrpc.NewServer(\n\t\t\tendpoints.DeleteCompany,\n\t\t\tdecodeDeleteCompanyRequest,\n\t\t\tencodeDeleteCompanyResponse,\n\t\t\toptions...,\n\t\t),\n\n\t\tcreateIndustry: kitgrpc.NewServer(\n\t\t\tendpoints.CreateIndustry,\n\t\t\tdecodeCreateIndustryRequest,\n\t\t\tencodeCreateIndustryResponse,\n\t\t\toptions...,\n\t\t),\n\t\tgetAllIndustries: kitgrpc.NewServer(\n\t\t\tendpoints.GetAllIndustries,\n\t\t\tdecodeGetAllIndustriesRequest,\n\t\t\tencodeGetAllIndustriesResponse,\n\t\t\toptions...,\n\t\t),\n\t\tdeleteIndustry: kitgrpc.NewServer(\n\t\t\tendpoints.DeleteIndustry,\n\t\t\tdecodeDeleteIndustryRequest,\n\t\t\tencodeDeleteIndustryResponse,\n\t\t\toptions...,\n\t\t),\n\n\t\tcreateJobFunction: kitgrpc.NewServer(\n\t\t\tendpoints.CreateJobFunction,\n\t\t\tdecodeCreateJobFunctionRequest,\n\t\t\tencodeCreateJobFunctionResponse,\n\t\t\toptions...,\n\t\t),\n\t\tgetAllJobFunctions: kitgrpc.NewServer(\n\t\t\tendpoints.GetAllJobFunctions,\n\t\t\tdecodeGetAllJobFunctionsRequest,\n\t\t\tencodeGetAllJobFunctionsResponse,\n\t\t\toptions...,\n\t\t),\n\t\tdeleteJobFunction: kitgrpc.NewServer(\n\t\t\tendpoints.DeleteJobFunction,\n\t\t\tdecodeDeleteJobFunctionRequest,\n\t\t\tencodeDeleteJobFunctionResponse,\n\t\t\toptions...,\n\t\t),\n\n\t\tcreateKeyPerson: kitgrpc.NewServer(\n\t\t\tendpoints.CreateKeyPerson,\n\t\t\tdecodeCreateKeyPersonRequest,\n\t\t\tencodeCreateKeyPersonResponse,\n\t\t\toptions...,\n\t\t),\n\t\tbulkCreateKeyPerson: kitgrpc.NewServer(\n\t\t\tendpoints.BulkCreateKeyPerson,\n\t\t\tdecodeBulkCreateKeyPersonRequest,\n\t\t\tencodeBulkCreateKeyPersonResponse,\n\t\t\toptions...,\n\t\t),\n\t\tgetAllKeyPersons: kitgrpc.NewServer(\n\t\t\tendpoints.GetAllKeyPersons,\n\t\t\tdecodeGetAllKeyPersonsRequest,\n\t\t\tencodeGetAllKeyPersonsResponse,\n\t\t\toptions...,\n\t\t),\n\t\tgetKeyPersonByID: kitgrpc.NewServer(\n\t\t\tendpoints.GetKeyPersonByID,\n\t\t\tdecodeGetKeyPersonByIDRequest,\n\t\t\tencodeGetKeyPersonByIDResponse,\n\t\t\toptions...,\n\t\t),\n\t\tupdateKeyPerson: kitgrpc.NewServer(\n\t\t\tendpoints.UpdateKeyPerson,\n\t\t\tdecodeUpdateKeyPersonRequest,\n\t\t\tencodeUpdateKeyPersonResponse,\n\t\t\toptions...,\n\t\t),\n\t\tdeleteKeyPerson: kitgrpc.NewServer(\n\t\t\tendpoints.DeleteKeyPerson,\n\t\t\tdecodeDeleteKeyPersonRequest,\n\t\t\tencodeDeleteKeyPersonResponse,\n\t\t\toptions...,\n\t\t),\n\n\t\tcreateJobPlatform: kitgrpc.NewServer(\n\t\t\tendpoints.CreateJobPlatform,\n\t\t\tdecodeCreateJobPlatformRequest,\n\t\t\tencodeCreateJobPlatformResponse,\n\t\t\toptions...,\n\t\t),\n\t\tgetAllJobPlatforms: kitgrpc.NewServer(\n\t\t\tendpoints.GetAllJobPlatforms,\n\t\t\tdecodeGetAllJobPlatformsRequest,\n\t\t\tencodeGetAllJobPlatformsResponse,\n\t\t\toptions...,\n\t\t),\n\t\tdeleteJobPlatform: kitgrpc.NewServer(\n\t\t\tendpoints.DeleteJobPlatform,\n\t\t\tdecodeDeleteJobPlatformRequest,\n\t\t\tencodeDeleteJobPlatformResponse,\n\t\t\toptions...,\n\t\t),\n\n\t\tlogger: logger,\n\t}\n}", "func NewGRPCServer(c *conf.DownloaderServerConfig, downloaderService *service.DownloaderService, logger log.Logger) *grpc.Server {\n\tvar opts = []grpc.ServerOption{\n\t\tgrpc.Middleware(\n\t\t\trecovery.Recovery(),\n\t\t),\n\t}\n\tif c.Grpc.Network != \"\" {\n\t\topts = append(opts, grpc.Network(c.Grpc.Network))\n\t}\n\tif c.Grpc.Addr != \"\" {\n\t\topts = append(opts, grpc.Address(c.Grpc.Addr))\n\t}\n\tif c.Grpc.Timeout > 0 {\n\t\topts = append(opts, grpc.Timeout(time.Duration(c.Grpc.Timeout)*time.Second))\n\t}\n\tsrv := grpc.NewServer(opts...)\n\tv1.RegisterDownloaderServer(srv, downloaderService)\n\treturn srv\n}", "func newRPCServer(parallelTotal int, reporter reporters.Reporter) (*RPCServer, error) {\n\tlistener, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RPCServer{\n\t\tlistener: listener,\n\t\thandler: newServerHandler(parallelTotal, reporter),\n\t}, nil\n}", "func NewServer(svc things.Service) mainflux.ThingsServiceServer {\n\treturn &grpcServer{\n\t\tcanAccess: kitgrpc.NewServer(\n\t\t\tcanAccessEndpoint(svc),\n\t\t\tdecodeCanAccessRequest,\n\t\t\tencodeIdentityResponse,\n\t\t),\n\t\tidentify: kitgrpc.NewServer(\n\t\t\tidentifyEndpoint(svc),\n\t\t\tdecodeIdentifyRequest,\n\t\t\tencodeIdentityResponse,\n\t\t),\n\t}\n}", "func New() (s *Service, err error) {\n\tvar (\n\t\trpcClient warden.ClientConfig\n\t\tct paladin.TOML\n\t)\n\tif err = paladin.Get(\"grpc.toml\").Unmarshal(&ct); err != nil {\n\t\treturn\n\t}\n\tif err = ct.Get(\"Client\").UnmarshalTOML(&rpcClient); err != nil {\n\t\treturn\n\t}\n\terr = paladin.Watch(\"application.toml\", s.ac)\n\treturn\n}", "func NewServer(logger config.Logger, store core.Storer, nodeManager core.Noder) *Server {\n\treturn &Server{\n\t\tlogger: logger,\n\t\tstore: store,\n\t\tnodeManager: nodeManager,\n\t\tgrpcServer: grpc.NewServer(),\n\t}\n}", "func New(port string) *Server {\n\treturn &Server{\n\t\tport: port,\n\t\tmanager: endly.New(),\n\t}\n}", "func newServer(listenAddrs []string) (*server, error) {\n\tlogin := cfg.Username + \":\" + cfg.Password\n\tauth := \"Basic \" + base64.StdEncoding.EncodeToString([]byte(login))\n\ts := server{\n\t\tauthsha: sha256.Sum256([]byte(auth)),\n\t}\n\n\t// Check for existence of cert file and key file\n\tif !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {\n\t\t// if both files do not exist, we generate them.\n\t\terr := genCertPair(cfg.RPCCert, cfg.RPCKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tkeypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig := tls.Config{\n\t\tCertificates: []tls.Certificate{keypair},\n\t}\n\n\tipv4ListenAddrs, ipv6ListenAddrs, err := parseListeners(listenAddrs)\n\tlisteners := make([]net.Listener, 0,\n\t\tlen(ipv6ListenAddrs)+len(ipv4ListenAddrs))\n\tfor _, addr := range ipv4ListenAddrs {\n\t\tlistener, err := tls.Listen(\"tcp4\", addr, &tlsConfig)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"RPCS: Can't listen on %s: %v\", addr,\n\t\t\t\terr)\n\t\t\tcontinue\n\t\t}\n\t\tlisteners = append(listeners, listener)\n\t}\n\n\tfor _, addr := range ipv6ListenAddrs {\n\t\tlistener, err := tls.Listen(\"tcp6\", addr, &tlsConfig)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"RPCS: Can't listen on %s: %v\", addr,\n\t\t\t\terr)\n\t\t\tcontinue\n\t\t}\n\t\tlisteners = append(listeners, listener)\n\t}\n\tif len(listeners) == 0 {\n\t\treturn nil, errors.New(\"no valid listen address\")\n\t}\n\n\ts.listeners = listeners\n\n\treturn &s, nil\n}", "func NewServer() *Server {}", "func NewGRPCServer(endpoints greeterendpoint.Endpoints, logger log.Logger) pb.GreeterServer {\n\toptions := []grpctransport.ServerOption{\n\t\tgrpctransport.ServerErrorLogger(logger),\n\t}\n\n\treturn &grpcServer{\n\t\tgreeter: grpctransport.NewServer(\n\t\t\tendpoints.GreetingEndpoint,\n\t\t\tdecodeGRPCGreetingRequest,\n\t\t\tencodeGRPCGreetingResponse,\n\t\t\toptions...,\n\t\t),\n\t}\n}", "func New(cfg *viper.Viper) *Server {\n\tsrv := &Server{cfg: cfg}\n\n\t// Create App Context\n\tsrv.runCtx, srv.runCancel = context.WithCancel(context.Background())\n\n\t// Initiate a new logger\n\tsrv.log = logrus.New()\n\tif srv.cfg.GetBool(\"debug\") {\n\t\tsrv.log.Level = logrus.DebugLevel\n\t\tsrv.log.Debug(\"Enabling Debug Logging\")\n\t}\n\tif srv.cfg.GetBool(\"trace\") {\n\t\tsrv.log.Level = logrus.TraceLevel\n\t\tsrv.log.Debug(\"Enabling Trace Logging\")\n\t}\n\tif srv.cfg.GetBool(\"disable_logging\") {\n\t\tsrv.log.Level = logrus.FatalLevel\n\t}\n\n\treturn srv\n\n}", "func NewServer(c *Config) (*Server, error) {\n\t// validate config\n\tif err := validation.Validate.Struct(c); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid config: %v\", err)\n\t}\n\n\t// create root context\n\tctx, cancel := context.WithCancel(context.Background())\n\n\t// register handlers\n\tmux := runtime.NewServeMux()\n\topts := []grpc.DialOption{grpc.WithInsecure()}\n\terr := proto.RegisterTodosHandlerFromEndpoint(ctx, mux, c.Endpoint, opts)\n\tif err != nil {\n\t\tdefer cancel()\n\t\treturn nil, fmt.Errorf(\"unable to register gateway handler: %v\", err)\n\t}\n\n\ts := Server{\n\t\tcancel: cancel,\n\t\tlog: c.Log,\n\t\tmux: mux,\n\t\tport: c.Port,\n\t}\n\treturn &s, nil\n}", "func NewServer(gsrv *grpc.Server, readHandler ReadHandler, writeHandler WriteHandler) (*Server, error) {\n\tif readHandler == nil && writeHandler == nil {\n\t\treturn nil, fmt.Errorf(\"readHandler and writeHandler cannot both be nil\")\n\t}\n\n\tserver := &Server{\n\t\tstatus: make(map[string]*pb.QueryWriteStatusResponse),\n\t\treadHandler: readHandler,\n\t\twriteHandler: writeHandler,\n\t\trpc: &grpcService{},\n\t}\n\tserver.rpc.parent = server\n\n\t// Register a server.\n\tpb.RegisterByteStreamServer(gsrv, server.rpc)\n\n\treturn server, nil\n}", "func New(\n\tserverID string,\n\ttracer *zipkin.Tracer,\n\tfS fetching.Service,\n\taS adding.Service,\n\tmS modifying.Service,\n\trS removing.Service,\n) Server {\n\ta := &server{\n\t\tserverID: serverID,\n\t\ttracer: tracer,\n\t\tfetching: fS,\n\t\tadding: aS,\n\t\tmodifying: mS,\n\t\tremoving: rS}\n\trouter(a)\n\n\treturn a\n}", "func New(\n\tserverID string,\n\ttracer *zipkin.Tracer,\n\tfS fetching.Service,\n\taS adding.Service,\n\tmS modifying.Service,\n\trS removing.Service,\n) Server {\n\ta := &server{\n\t\tserverID: serverID,\n\t\ttracer: tracer,\n\t\tfetching: fS,\n\t\tadding: aS,\n\t\tmodifying: mS,\n\t\tremoving: rS}\n\trouter(a)\n\n\treturn a\n}", "func New(cfg *config.Config) (*Server, error) {\n\tstorageMgr, err := storage.NewManager(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create storage manager\")\n\t}\n\n\tsourceClient, err := source.NewSourceClient()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create source client\")\n\t}\n\t// progress manager\n\tprogressMgr, err := progress.NewManager(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create progress manager\")\n\t}\n\n\t// cdn manager\n\tcdnMgr, err := cdn.NewManager(cfg, storageMgr, progressMgr, sourceClient)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create cdn manager\")\n\t}\n\n\t// task manager\n\ttaskMgr, err := task.NewManager(cfg, cdnMgr, progressMgr, sourceClient)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create task manager\")\n\t}\n\tstorageMgr.SetTaskMgr(taskMgr)\n\tstorageMgr.InitializeCleaners()\n\tprogressMgr.SetTaskMgr(taskMgr)\n\t// gc manager\n\tgcMgr, err := gc.NewManager(cfg, taskMgr, cdnMgr)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create gc manager\")\n\t}\n\n\treturn &Server{\n\t\tConfig: cfg,\n\t\tTaskMgr: taskMgr,\n\t\tGCMgr: gcMgr,\n\t}, nil\n}", "func New(fetcherSvc *services.Fetcher, log *logrus.Entry) *Server {\n\treturn &Server{\n\t\tFetcherSvc: fetcherSvc,\n\t\tLog: log,\n\t}\n}", "func New(config *configuration.Config, vs *library.Library, auth *auth.Manager) *Server {\n\treturn &Server{\n\t\tBase: subapp.NewBase(AppName),\n\t\tconfig: config,\n\t\tlibrary: vs,\n\t\tauthManager: auth,\n\t\trender: render.New(),\n\t}\n}", "func New(opt *Options) (server *Server, err error) {\n\tserver = &Server{\n\t\toptions: opt,\n\t\tServer: http.Server{\n\t\t\tAddr: fmt.Sprintf(\"0.0.0.0:%v\", opt.Config.Port),\n\t\t\tErrorLog: slog.New(log.New().Writer(), \"server\", 0),\n\t\t},\n\t}\n\n\tserver.Handler, err = server.createHandler()\n\treturn\n}", "func New(options Options) Server {\n\treturn &server{\n\t\tbindAddress: options.BindAddress,\n\t\tmux: http.NewServeMux(),\n\t}\n}", "func New(config Config) *Server {\n\treturn &Server{\n\t\tconfig: config,\n\t\tregistrars: make([]Registration, 0, 1),\n\t}\n}", "func NewServer(s server.Server, tls *tls.Config) *grpc.Server {\n\tvar opts []grpc.ServerOption\n\tif tls != nil {\n\t\t// Add TLS Credentials as a ServerOption for server connections.\n\t\topts = append(opts, grpc.Creds(credentials.NewTLS(tls)))\n\t}\n\n\tgrpcServer := grpc.NewServer(opts...)\n\trpcpb.RegisterGroupsServer(grpcServer, newGroupServer(s))\n\trpcpb.RegisterProfilesServer(grpcServer, newProfileServer(s))\n\trpcpb.RegisterSelectServer(grpcServer, newSelectServer(s))\n\trpcpb.RegisterIgnitionServer(grpcServer, newIgnitionServer(s))\n\trpcpb.RegisterGenericServer(grpcServer, newGenericServer(s))\n\treturn grpcServer\n}", "func NewServer(cli typedCore.CoreV1Interface, cfg ServerConfig) (*Server, error) {\n\tjwtSigningKey, err := ensureJWT(cli, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig, err := prepareTLSConfig(cli, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauth := &authorization{jwtSigningKey: jwtSigningKey}\n\n\ts := &Server{\n\t\thttpServer: &http.Server{\n\t\t\tAddr: cfg.HTTPAddress,\n\t\t\tReadTimeout: time.Second * 30,\n\t\t\tReadHeaderTimeout: time.Second * 15,\n\t\t\tWriteTimeout: time.Second * 30,\n\t\t\tTLSConfig: tlsConfig,\n\t\t},\n\t\tgrpcServer: grpc.NewServer(\n\t\t\tgrpc.UnaryInterceptor(auth.ensureGRPCAuth),\n\t\t\tgrpc.Creds(credentials.NewTLS(tlsConfig)),\n\t\t),\n\t\tgrpcAddress: cfg.GRPCAddress,\n\t}\n\thandler, err := buildHTTPHandler(s, cfg, auth)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.httpServer.Handler = handler\n\n\tpb.RegisterOperatorServer(s.grpcServer, s)\n\treturn s, nil\n}", "func NewRPC(port string, kval *kval.Store) *RPCServer {\n\treturn &RPCServer{\n\t\tport: port,\n\t\tstore: kval,\n\t}\n}", "func NewGRPCServer(l hclog.Logger, idb *data.ItemDB) *GRPCServer {\n\treturn &GRPCServer{l, idb}\n}", "func newRPCServerService() (*rpcServerService, error) {\n return &rpcServerService{serviceMap: util.NewSyncMap()}, nil\n}", "func NewServer() *Server {\n\treturn &Server{\n\t\tcodecs: make(map[string]Codec),\n\t\tservices: new(serviceMap),\n\t}\n}", "func NewGRPCServer(handlers Handler, tracer tracing.Tracer, gp *pool.GoroutinePool) mixerpb.MixerServer {\n\treturn &grpcServer{\n\t\thandlers: handlers,\n\t\tattrMgr: attribute.NewManager(),\n\t\ttracer: tracer,\n\t\tgp: gp,\n\t\tsendMsg: func(stream grpc.Stream, m proto.Message) error {\n\t\t\treturn stream.SendMsg(m)\n\t\t},\n\t}\n}", "func NewServer(l net.Listener, reg registry.Cache, ctl *config.Controller, opts ...ServerOption) *Server {\n\to := defaultServerOptions()\n\tfor _, opt := range opts {\n\t\topt(o)\n\t}\n\n\teds := newEndpointDiscoveryServer(reg)\n\tcds := newConfigDiscoveryServer(ctl)\n\tdds := newDependencyDiscoveryServer(ctl)\n\ts := &Server{\n\t\tl: l,\n\t\toptions: o,\n\t\teds: eds,\n\t\tcds: cds,\n\t\tdds: dds,\n\t}\n\n\tg := grpc.NewServer(s.grpcOptions()...)\n\tapi.RegisterDiscoveryServiceServer(g, s)\n\ts.g = g\n\treturn s\n}", "func NewGRPCServer(ctx context.Context, endpoint ServiceEndpoints) pb.MicroServiceServer {\n\treturn &grpcServer{\n\t\tService: grpctransport.NewServer(\n\t\t\tendpoint.ServiceEndpoint,\n\t\t\tDecodeGRPCServiceRequest,\n\t\t\tEncodeGRPCServiceResponse,\n\t\t),\n\t}\n}", "func NewGrpcServer() *Grpcserver {\r\n\treturn &Grpcserver{grpc: &Grpc{}}\r\n}", "func NewServer(conf config.Config, conns service.Connections) gitalypb.ServerServiceServer {\n\ts := &Server{\n\t\tconf: conf,\n\t\tconns: conns,\n\t}\n\n\treturn s\n}", "func New(config ServiceConfig) *Service {\n\n\ts := &Service{\n\t\tPeerAdded: make(chan string),\n\t\tPeerRemoved: make(chan string),\n\t\tstopChan: make(chan interface{}),\n\t\tpeers: make(peerMap),\n\t\tconfig: config,\n\t}\n\n\t// Spawn a new goroutine for managing peers.\n\tgo s.run()\n\n\treturn s\n}", "func New() *Server {\n\ts := &Server{\n\t\thandlers: map[string][]HandlerFunc{},\n\t\tclosing: make(chan struct{}),\n\t\tclosed: make(chan struct{}),\n\t}\n\ts.pool.New = func() interface{} {\n\t\treturn s.allocateContext()\n\t}\n\treturn s\n}", "func NewServer(config *structs.Config) (*Server, error) {\n\n\ts := &Server{\n\t\tconfig: config,\n\t\trpcServer: rpc.NewServer(),\n\t\tshutdownChan: make(chan struct{}),\n\t}\n\n\t// Setup our LeaderCandidate object for leader elections and session renewal.\n\tleaderKey := s.config.ConsulKeyRoot + \"/\" + \"leader\"\n\ts.candidate = newLeaderCandidate(s.config.ConsulClient, leaderKey,\n\t\tleaderLockTimeout)\n\tgo s.leaderTicker()\n\n\tjobScalingPolicy := newJobScalingPolicy()\n\n\tif !s.config.ClusterScalingDisable || !s.config.JobScalingDisable {\n\t\t// Setup our JobScalingPolicy Watcher and start running this.\n\t\tgo s.config.NomadClient.JobWatcher(jobScalingPolicy)\n\t}\n\n\tif !s.config.ClusterScalingDisable {\n\t\t// Setup the node registry and initiate worker pool and node discovery.\n\t\tnodeRegistry := structs.NewNodeRegistry()\n\t\tgo s.config.NomadClient.NodeWatcher(nodeRegistry, s.config)\n\n\t\t// Launch our cluster scaling main ticker function\n\t\tgo s.clusterScalingTicker(nodeRegistry, jobScalingPolicy)\n\t}\n\n\t// Launch our job scaling main ticker function\n\tif !s.config.JobScalingDisable {\n\t\tgo s.jobScalingTicker(jobScalingPolicy)\n\t}\n\n\tif err := s.setupRPC(); err != nil {\n\t\ts.Shutdown()\n\t\treturn nil, fmt.Errorf(\"failed to start RPC layer: %v\", err)\n\t}\n\n\t// Start the RPC listeners\n\tgo s.listen()\n\tlogging.Info(\"core/server: the RPC server has started and is listening at %v\", s.config.RPCAddr)\n\n\treturn s, nil\n}", "func New(cfg *Config) *Server {\n\tdefaultConfig(cfg)\n\tlog.Printf(\"%+v\\n\", cfg)\n\treturn &Server{\n\t\tcfg: cfg,\n\t\thandlers: make([]connectionHandler, cfg.Count),\n\t\tevents: make(chan eventWithData, cfg.Count),\n\t}\n}", "func New(cfg *config.Config, store *jot.JotStore, manager *auth.PasswordManager) *Server {\n\treturn &Server{\n\t\tmanager: manager,\n\t\tstore: store,\n\t\tcfg: cfg,\n\t}\n}" ]
[ "0.7930491", "0.7909664", "0.7693801", "0.7675437", "0.76696235", "0.7554032", "0.75522393", "0.73965055", "0.73447937", "0.7235632", "0.72117573", "0.7203954", "0.7199533", "0.7189548", "0.71885747", "0.7149648", "0.7148844", "0.71254337", "0.71176326", "0.7110725", "0.71102035", "0.70977306", "0.7076868", "0.7068747", "0.7039487", "0.7021807", "0.7016214", "0.70141035", "0.6971043", "0.6970111", "0.69665366", "0.69491124", "0.6936977", "0.6929256", "0.6927578", "0.6885038", "0.68834907", "0.6882195", "0.6879135", "0.6878005", "0.6875968", "0.6871841", "0.6866771", "0.6865209", "0.6859605", "0.68594885", "0.68525815", "0.6851145", "0.68458915", "0.68433857", "0.6841226", "0.6834455", "0.6833665", "0.682595", "0.6825132", "0.6815051", "0.68079555", "0.67725694", "0.67674917", "0.6765694", "0.6763409", "0.67548835", "0.6730351", "0.67295504", "0.6728767", "0.67280084", "0.6725644", "0.6724314", "0.6722733", "0.67175", "0.6715784", "0.6693491", "0.6690194", "0.66858387", "0.668418", "0.66811794", "0.6679612", "0.6679612", "0.6678515", "0.66731703", "0.66698736", "0.6668336", "0.666583", "0.66612124", "0.66605467", "0.6657384", "0.6656255", "0.6643009", "0.6641619", "0.66381097", "0.6634781", "0.6628363", "0.66233844", "0.6622661", "0.6620408", "0.661185", "0.6607249", "0.6592399", "0.6585124", "0.6581785" ]
0.78891164
2
WithAddr returns Option that sets addr
func WithAddr(addr string) Option { return func(c *gatewayClient) { if len(addr) != 0 { c.addr = addr } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WithAddr(addr string) Option {\n\treturn func(c *config) {\n\t\tc.Addr = addr\n\t}\n}", "func WithAddress(addr string) Option {\n\treturn addrOption{address: addr}\n}", "func Addr(s string) Option {\n\treturn func(o *Options) {\n\t\to.Addr = s\n\t}\n}", "func WithAddr(addr string) BotOption {\n\treturn func(b *Bot) {\n\t\tb.addr = addr\n\t}\n}", "func WithAddress(address string) Option {\n\treturn addressOption(address)\n}", "func WithAddress(with string) wrapping.Option {\n\treturn func() interface{} {\n\t\treturn OptionFunc(func(o *options) error {\n\t\t\to.withAddress = with\n\t\t\treturn nil\n\t\t})\n\t}\n}", "func WithAddr(addr string) Option {\n\treturn func(r *Redis) {\n\t\tr.server.addr = addr\n\t}\n}", "func WithAddr(addr string) Opt {\n\treturn func(fwdr *TCPForwarder) {\n\t\tfwdr.Addr = addr\n\t}\n}", "func WithAddr(addr string) Option {\n\treturn func(c *config) {\n\t\tc.ListenAddr = addr\n\t\tc.LinkAddr = addr\n\t}\n}", "func WithAddress(address string) Option {\n\treturn func(o *Options) {\n\t\to.Address = address\n\t}\n}", "func WithAddress(address string) Option {\n\treturn func(b *builder) {\n\t\tb.address = address\n\t}\n}", "func withAddress(address string) Option {\n\treturn func(options *Options) (err error) {\n\t\tif options.Address, err = url.Parse(address); nil != err {\n\t\t\t// compatible host:port\n\t\t\tswitch {\n\t\t\tcase strings.Contains(err.Error(), \"cannot contain colon\"):\n\t\t\t\toptions.Address, err = url.Parse(fmt.Sprintf(\"//%s\", address))\n\t\t\tcase strings.Contains(err.Error(), \"missing protocol scheme\"):\n\t\t\t\toptions.Address, err = url.Parse(fmt.Sprintf(\"//%s\", address))\n\t\t\t}\n\t\t}\n\t\t// default path: /\n\t\tif options.Address != nil && \"\" == options.Address.Path {\n\t\t\toptions.Address.Path = \"/\"\n\t\t}\n\t\treturn err\n\t}\n}", "func Address(a string) Option {\n\treturn func(o *Options) {\n\t\to.Address = a\n\t}\n}", "func ConnAddr(addr string) ConnOption {\n\treturn func(c *Conn) error {\n\t\tc.addr = addr\n\t\treturn nil\n\t}\n}", "func withAddress(node *Address) addressOption {\n\treturn func(m *AddressMutation) {\n\t\tm.oldValue = func(context.Context) (*Address, error) {\n\t\t\treturn node, nil\n\t\t}\n\t\tm.id = &node.ID\n\t}\n}", "func WithAddress(a ...string) CallOption {\n\treturn func(o *CallOptions) {\n\t\to.Address = a\n\t}\n}", "func WithAddr(addr string) IngressOption {\n\treturn func(c *IngressClient) {\n\t\tc.addr = addr\n\t}\n}", "func WithAddr(addr string) RedisClientOption {\n\treturn func(rs *RedisStorage) {\n\t\trs.addr = addr\n\t}\n}", "func (p *Pinger) SetAddr(addr string) error {\n\toldAddr := p.addr\n\tp.addr = addr\n\terr := p.Resolve()\n\tif err != nil {\n\t\tp.addr = oldAddr\n\t\treturn err\n\t}\n\treturn nil\n}", "func WithAddr(addr string) JSONSourceOption {\n\treturn func(j *JSONSource) {\n\t\tj.addr = addr\n\t}\n}", "func Address(addr string) Option {\n\treturn func(o *Options) {\n\t\to.ServerOptions = append(o.ServerOptions, server.Address(addr))\n\t}\n}", "func Address(addr string) Option {\n\treturn func(o *Options) {\n\t\to.Server.Init(server.Address(addr))\n\t}\n}", "func WithRemoteAddr(addr string) RemoteOption {\n\treturn rpcAddr(addr)\n}", "func (r *RTNL) SetAddr(iface int, a net.IPNet) error {\n\tif err := r.init(); err != nil {\n\t\treturn err\n\t}\n\tones, _ := a.Mask.Size()\n\tmsg := rtnetlink.AddressMessage{\n\t\tFamily: uint8(getFamily(a.IP)),\n\t\tPrefixLength: uint8(ones),\n\t\t// TODO detect the right scope to set, or get it as input argument\n\t\tScope: unix.RT_SCOPE_UNIVERSE,\n\t\tIndex: uint32(iface),\n\t\tAttributes: rtnetlink.AddressAttributes{\n\t\t\tAddress: a.IP,\n\t\t\tLocal: a.IP,\n\t\t},\n\t}\n\tif a.IP.To4() != nil {\n\t\t// Broadcast is only required for IPv4\n\t\tip := make(net.IP, net.IPv4len)\n\t\tbinary.BigEndian.PutUint32(\n\t\t\tip,\n\t\t\tbinary.BigEndian.Uint32(a.IP.To4())|\n\t\t\t\t^binary.BigEndian.Uint32(net.IP(a.Mask).To4()))\n\t\tmsg.Attributes.Broadcast = ip\n\t}\n\tif err := r.conn.Address.New(&msg); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *service) SetAddr(val string) {\n\n\ts.mu.Lock()\n\ts.addr = val\n\ts.mu.Unlock()\n}", "func WithAddress(address string) PersonOption {\n\treturn func(p *Person) {\n\t\tp.Address = address\n\t}\n}", "func (_ResolverContract *ResolverContractTransactor) SetAddr(opts *bind.TransactOpts, node [32]byte, addr common.Address) (*types.Transaction, error) {\n\treturn _ResolverContract.contract.Transact(opts, \"setAddr\", node, addr)\n}", "func WithHost(p string) Option {\n\treturn func(o *options) {\n\t\to.host = p\n\t}\n}", "func Address(addr string) ServerOption {\n\treturn func(s *Server) {\n\t\ts.address = addr\n\t}\n}", "func (_Contract *ContractTransactor) SetAddr(opts *bind.TransactOpts, node [32]byte, coinType *big.Int, a []byte) (*types.Transaction, error) {\n\treturn _Contract.contract.Transact(opts, \"setAddr\", node, coinType, a)\n}", "func (w *Wallet) SetAddr(a string) {\n\tw.mutex.Lock()\n\tw.Addr = a\n\tw.mutex.Unlock()\n}", "func WithHost(host string) Option {\n\treturn func(c *gate.Configuration) {\n\t\tc.Host = host\n\t}\n}", "func WithConfig(cfg Config) Option {\n\treturn optionFunc(func(c *config) {\n\t\tc.addr = cfg.Host + \":\" + strconv.FormatUint(uint64(cfg.Port), 10)\n\t})\n}", "func (_ResolverContract *ResolverContractSession) SetAddr(node [32]byte, addr common.Address) (*types.Transaction, error) {\n\treturn _ResolverContract.Contract.SetAddr(&_ResolverContract.TransactOpts, node, addr)\n}", "func SetAddress(ip string) Option {\n\treturn func(n *Node) error {\n\t\tn.address = ip\n\t\treturn nil\n\t}\n}", "func WithServerAddress(address string) Option {\n\treturn func(g *gateway) {\n\t\tg.serverAddress = address\n\t}\n}", "func (_ResolverContract *ResolverContractTransactorSession) SetAddr(node [32]byte, addr common.Address) (*types.Transaction, error) {\n\treturn _ResolverContract.Contract.SetAddr(&_ResolverContract.TransactOpts, node, addr)\n}", "func (p *Plugin) SetAddr(addr net.Addr) {\n\tp.mu.Lock()\n\tp.addr = addr\n\tp.mu.Unlock()\n}", "func (_ResolverContract *ResolverContractCaller) Addr(opts *bind.CallOpts, node [32]byte) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _ResolverContract.contract.Call(opts, out, \"addr\", node)\n\treturn *ret0, err\n}", "func (_Contract *ContractSession) SetAddr(node [32]byte, coinType *big.Int, a []byte) (*types.Transaction, error) {\n\treturn _Contract.Contract.SetAddr(&_Contract.TransactOpts, node, coinType, a)\n}", "func WithAddress(address string) EngineOpt {\n\treturn func(e *engine) error {\n\t\t// set the fully qualified connection string in the database engine\n\t\te.config.Address = address\n\n\t\treturn nil\n\t}\n}", "func (_Contract *ContractTransactorSession) SetAddr(node [32]byte, coinType *big.Int, a []byte) (*types.Transaction, error) {\n\treturn _Contract.Contract.SetAddr(&_Contract.TransactOpts, node, coinType, a)\n}", "func SetAddress(addr string) ServerOptionFunc {\n\treturn func(s *Server) error {\n\t\ts.address = addr\n\t\treturn nil\n\t}\n}", "func WithMakeDefault(makeDefault bool) NewAddressOption {\n\treturn func(r *rpc.NewAddrRequest) {\n\t\tr.MakeDefault = makeDefault\n\t}\n}", "func WithAddressDialer(dialer func(context.Context, string) (net.Conn, error)) Option {\n\treturn optionFunc(func(opts *options) {\n\t\topts.dialer = dialer\n\t})\n}", "func (s *Server) WithAddr(addr string) *Server {\n\ts.srv.Addr = addr\n\treturn s\n}", "func (s *Server) WithAddr(addr string) *Server {\n\ts.srv.Addr = addr\n\treturn s\n}", "func (_ResolverContract *ResolverContractSession) Addr(node [32]byte) (common.Address, error) {\n\treturn _ResolverContract.Contract.Addr(&_ResolverContract.CallOpts, node)\n}", "func (_m *MockHTTPServerInterface) SetAddr(_a0 string) {\n\t_m.Called(_a0)\n}", "func (_ResolverContract *ResolverContractCallerSession) Addr(node [32]byte) (common.Address, error) {\n\treturn _ResolverContract.Contract.Addr(&_ResolverContract.CallOpts, node)\n}", "func withAddressID(id int64) addressOption {\n\treturn func(m *AddressMutation) {\n\t\tvar (\n\t\t\terr error\n\t\t\tonce sync.Once\n\t\t\tvalue *Address\n\t\t)\n\t\tm.oldValue = func(ctx context.Context) (*Address, error) {\n\t\t\tonce.Do(func() {\n\t\t\t\tif m.done {\n\t\t\t\t\terr = fmt.Errorf(\"querying old values post mutation is not allowed\")\n\t\t\t\t} else {\n\t\t\t\t\tvalue, err = m.Client().Address.Get(ctx, id)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn value, err\n\t\t}\n\t\tm.id = &id\n\t}\n}", "func (w *Wireguard) SetAddr(cidr string) error {\n\taddr, err := netlink.ParseAddr(cidr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := netlink.AddrAdd(w, addr); err != nil && !os.IsExist(err) {\n\t\treturn err\n\t}\n\treturn nil\n}", "func WithLinkAddr(addr string) Option {\n\treturn func(c *config) {\n\t\tc.LinkAddr = addr\n\t}\n}", "func Proxy(addr string) Option {\n\treturn func(o *Options) {\n\t\to.Proxy = addr\n\t}\n}", "func WithListenAddr(addrs ...multiaddr.Multiaddr) Option {\n\treturn func(c *Config) (err error) {\n\t\tc.addrs = addrs\n\t\treturn\n\t}\n}", "func (s *server) Address(a string) Server {\n\ts.address = a\n\treturn s\n}", "func (in *ActionIpAddressIndexInput) SetAddr(value string) *ActionIpAddressIndexInput {\n\tin.Addr = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"Addr\"] = nil\n\treturn in\n}", "func (h *Host) SetAdress(a string) {\n}", "func (b *Builder) SetAddr(encodedAddr string) *Builder {\n\tb.encodedAddr = encodedAddr\n\treturn b\n}", "func (o *Member) SetAddr(v string) {\n\to.Addr = &v\n}", "func newNetAddress(addr net.Addr, services wire.ServiceFlag) (*wire.NetAddress, error) {\n\t// addr will be a net.TCPAddr when not using a proxy.\n\tif tcpAddr, ok := addr.(*net.TCPAddr); ok {\n\t\tip := tcpAddr.IP\n\t\tport := uint16(tcpAddr.Port)\n\t\tna := wire.NewNetAddressIPPort(ip, port, services)\n\t\treturn na, nil\n\t}\n\n\t// addr will be a socks.ProxiedAddr when using a proxy.\n\tif proxiedAddr, ok := addr.(*socks.ProxiedAddr); ok {\n\t\tip := net.ParseIP(proxiedAddr.Host)\n\t\tif ip == nil {\n\t\t\tip = net.ParseIP(\"0.0.0.0\")\n\t\t}\n\t\tport := uint16(proxiedAddr.Port)\n\t\tna := wire.NewNetAddressIPPort(ip, port, services)\n\t\treturn na, nil\n\t}\n\n\t// For the most part, addr should be one of the two above cases, but\n\t// to be safe, fall back to trying to parse the information from the\n\t// address string as a last resort.\n\thost, portStr, err := net.SplitHostPort(addr.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tip := net.ParseIP(host)\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tna := wire.NewNetAddressIPPort(ip, uint16(port), services)\n\treturn na, nil\n}", "func WithHost(host string) ConfigOption {\n\treturn func(c *Config) {\n\t\tc.host = host\n\t}\n}", "func WithHost(host string) InstanceOpt {\n\treturn func(i *Instance) error {\n\t\ti.host = host\n\t\treturn nil\n\t}\n}", "func WithStatusAddr(addr string) func(o *DebugOpts) {\n\treturn func(o *DebugOpts) {\n\t\to.Addr = addr\n\t}\n}", "func (_Contract *ContractSession) Addr(node [32]byte) (common.Address, error) {\n\treturn _Contract.Contract.Addr(&_Contract.CallOpts, node)\n}", "func (cl *DoHClient) SetRemoteAddr(addr string) (err error) {\n\tcl.addr, err = url.Parse(addr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcl.query = cl.addr.Query()\n\n\treturn\n}", "func AddDelAddr (command *parser.Command) (err error) {\n\tvar (\n\t\tnsName string\n\t\ttargetNS ns.NetNS\n\t)\n\n\tif command.TargetType == parser.NSNONE {\n\t\ttargetNS, err = ns.GetCurrentNS()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%v\", err)\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tnsName, err = getNamepace(command)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%v\", err)\n\t\t\treturn err\n\t\t}\n\t\ttargetNS, err = ns.GetNS(nsName)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%v\", err)\n\t\t\treturn err\n\t\t}\n\t\tdefer targetNS.Close()\n\t}\n\n\tif command.OptionVia != \"\" {\n\t\treturn fmt.Errorf(\"address command does not support via keyword\")\n\t}\n\t//Add check (no via, dev is valid)\n\tip, mask, err := net.ParseCIDR(\n\t\tfmt.Sprintf(\"%s/%s\", command.Network, command.NetworkLength))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = targetNS.Do(func(_ ns.NetNS) error {\n\t\toptionDevIf, err2 := netlink.LinkByName(command.OptionDev)\n\t\tif err2 != nil {\n\t\t\treturn err2\n\t\t}\n\t\taddr := &netlink.Addr{IPNet: &net.IPNet{IP: ip, Mask: mask.Mask}, Label: \"\"}\n\n\t\tswitch command.Operation {\n\t\tcase parser.ADDRADD:\n\t\t\tif err3 := netlink.AddrAdd(optionDevIf, addr); err3 != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to add IP addr %v to %q: %v\",\n addr, command.OptionDev, err3)\n\t\t\t}\n\t\tcase parser.ADDRDEL:\n\t\t\tif err3 := netlink.AddrDel(optionDevIf, addr); err3 != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete IP addr %v to %q: %v\",\n addr, command.OptionDev, err3)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\treturn nil\n}", "func WithHost(host string) ConfigOption {\n\treturn func(cfg *Config) {\n\t\tcfg.Host = host\n\t}\n}", "func (o *Options) WithListenAddress(value string) *Options {\n\to.addr = value\n\treturn o\n}", "func SetAddress(net Addresser) {\n\taddress = net\n}", "func (_Votes *VotesCaller) ImplAddress(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _Votes.contract.Call(opts, out, \"implAddress\")\n\treturn *ret0, err\n}", "func Addr(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tr = r.WithContext(context.WithValue(r.Context(), RemoteAddrKey, r.RemoteAddr))\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (app *App) Address(addr string) *App {\n\tapp.Addr = addr\n\treturn app\n}", "func NewAddr(host string) *Addr {\n\t// Older versions of the transport only supported insecure connections (i.e.\n\t// WS instead of WSS). Assume that is the case here.\n\treturn NewAddrWithScheme(host, false)\n}", "func NewAddr(host string) *Addr {\n\t// Older versions of the transport only supported insecure connections (i.e.\n\t// WS instead of WSS). Assume that is the case here.\n\treturn NewAddrWithScheme(host, false)\n}", "func (_Contract *ContractCallerSession) Addr(node [32]byte) (common.Address, error) {\n\treturn _Contract.Contract.Addr(&_Contract.CallOpts, node)\n}", "func (_Contract *ContractCaller) Addr(opts *bind.CallOpts, node [32]byte) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"addr\", node)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func OptListenAddress(address string) Opt {\n\treturn func(app *App) {\n\t\tapp.listenAddress = address\n\t}\n}", "func Host(h string) PinningOption {\n\treturn func(o *Pinning) {\n\t\to.Host = h\n\t}\n}", "func WithRPCAddrs(addrs []string) Option {\n\treturn newFuncOption(func(o *options) {\n\t\to.rpcAddrs = addrs\n\t})\n}", "func (b *base) SetAddr(addr *rnet.Addr) Sender {\n\tb.Header.SetAddr(addr)\n\treturn b\n}", "func (f *Factory) WithAddress(address string) *Factory {\n\tf.address = address\n\treturn f\n}", "func (s *Server) SetAddr(address string) {\n\ts.config.Address = address\n}", "func SetIToAddr(addr uint16) { // ANNN\n\tVI = addr\n\tPC += 2\n}", "func (mt *mockTokenBuilder) SetIPAddress(ip string) {\n\t//TODO some mocking\n}", "func WithHost(host string) Option {\n\treturn func(c *Client) error {\n\t\tc.transport.URL = transport.DefaultURL\n\t\tu, err := url.Parse(host)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif u.Scheme != \"\" {\n\t\t\tc.transport.URL.Scheme = u.Scheme\n\t\t}\n\t\tc.transport.URL.Host = u.Host\n\t\tif !strings.Contains(c.transport.URL.Host, \":\") {\n\t\t\tc.transport.URL.Host += \":\" + string(transport.DefaultPort)\n\t\t}\n\t\treturn nil\n\t}\n}", "func (k msgServer) SetGovAddress(goCtx context.Context, msg *types.MsgSetGovAddress) (*types.MsgSetGovAddressResponse, error) {\n\n\treturn &types.MsgSetGovAddressResponse{}, nil\n}", "func (m *mOutboundMockGetIPAddress) Set(f func() (r packets.NodeAddress)) *OutboundMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.GetIPAddressFunc = f\n\treturn m.mock\n}", "func (p *TCPPeer) addr() util.Endpoint {\n\treturn p.endpoint\n}", "func Host(host string) Option {\n\treturn func(o *Options) {\n\t\to.host = host\n\t}\n}", "func (f *FFS) NewAddr(ctx context.Context, name string, options ...NewAddressOption) (string, error) {\n\tr := &rpc.NewAddrRequest{Name: name}\n\tfor _, opt := range options {\n\t\topt(r)\n\t}\n\tresp, err := f.client.NewAddr(ctx, r)\n\treturn resp.Addr, err\n}", "func Addr(v interface{}) interface{} {\n\tvv := reflect.ValueOf(v)\n\n\t// Create a slice with v in it so that we have an addressable value.\n\tsliceType := reflect.SliceOf(vv.Type())\n\tslice := reflect.MakeSlice(sliceType, 1, 1)\n\tif v != nil {\n\t\tslice.Index(0).Set(vv)\n\t}\n\treturn slice.Index(0).Addr().Interface()\n}", "func initAddr(addr string) (string, error) {\n\thost, port, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif host == \"\" {\n\t\thost = \"127.0.0.1\"\n\t}\n\treturn net.JoinHostPort(host, port), nil\n}", "func WithHost(host string) ClientOption {\n\treturn func(cfg *clientConfig) {\n\t\tcfg.host = host\n\t}\n}", "func WithPort(port int) Option {\n\treturn func(o *P) {\n\t\to.Port = port\n\t}\n}", "func OwnerAddr(wk *key.Key) NodeOpt {\n\treturn func(opts *nodeOpts) error {\n\t\topts.ownerKey = wk\n\t\treturn nil\n\t}\n}", "func SetAddr(addr string) {\n\tcfg.Listen = addr\n}", "func WithUseRemoteAddress(useRemoteAddress bool) option {\n\treturn func(c *KubernetesConfigurator) {\n\t\tc.useRemoteAddress = useRemoteAddress\n\t}\n}", "func (k Keeper) SetWithdrawAddr(ctx sdk.Context, delegatorId chainTypes.AccountID, withdrawId chainTypes.AccountID) error {\n\tif k.blacklistedAddrs[withdrawId.String()] {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"%s is blacklisted from receiving external funds\", withdrawId)\n\t}\n\n\tif !k.GetWithdrawAddrEnabled(ctx) {\n\t\treturn types.ErrSetWithdrawAddrDisabled\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeSetWithdrawAddress,\n\t\t\tsdk.NewAttribute(types.AttributeKeyWithdrawAddress, withdrawId.String()),\n\t\t),\n\t)\n\n\tk.SetDelegatorWithdrawAddr(ctx, delegatorId, withdrawId)\n\treturn nil\n}", "func WithAddrs(addrs ...string) Option {\n\treturn func(c *queue) {\n\t\tc.hostPool = hostpool.NewEpsilonGreedy(addrs, 0, new(hostpool.LinearEpsilonValueCalculator))\n\t}\n}" ]
[ "0.76389706", "0.7539186", "0.73077774", "0.70884806", "0.70842564", "0.7081532", "0.7016024", "0.700227", "0.6962173", "0.67795646", "0.67089266", "0.6640528", "0.654892", "0.6468325", "0.6336481", "0.62987196", "0.62357277", "0.6130344", "0.6128888", "0.6106797", "0.60978425", "0.60646844", "0.60418105", "0.6040935", "0.60284936", "0.60208714", "0.6013145", "0.59790856", "0.5975782", "0.5974016", "0.5953431", "0.58885324", "0.5873064", "0.58268166", "0.5799945", "0.5786709", "0.5778814", "0.57711464", "0.5706542", "0.56907904", "0.5678196", "0.5666506", "0.5648946", "0.5609677", "0.55709773", "0.5566603", "0.5566603", "0.5557438", "0.55454373", "0.55236447", "0.55190575", "0.54921865", "0.5492004", "0.54722315", "0.5456668", "0.5447699", "0.5430854", "0.54176295", "0.5415745", "0.53509164", "0.5336627", "0.53218156", "0.5317608", "0.5306467", "0.53042173", "0.5297714", "0.5297216", "0.5296707", "0.5289708", "0.5286664", "0.5249095", "0.52401364", "0.5234689", "0.52315676", "0.52315676", "0.5210804", "0.52011573", "0.5190889", "0.51881814", "0.5183167", "0.5177045", "0.51755595", "0.5152167", "0.5129989", "0.5100375", "0.50954527", "0.50881386", "0.5086348", "0.5084498", "0.50804764", "0.5075401", "0.5054606", "0.5049427", "0.50490105", "0.5044903", "0.50376296", "0.5022336", "0.5007618", "0.500368", "0.49961793" ]
0.7487863
2
add flag to command
func addEnvironmentFlag(cmd *cobra.Command) { cmd.Flags().StringArrayVarP(&environment, "env", "e", []string{}, "environment variables to pass to container") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v *VersionCommand) addFlags() {\n\t// TODO: add flags here\n}", "func (p *PublisherMunger) AddFlags(cmd *cobra.Command, config *github.Config) {}", "func (c *Command) addFlag(flag *Flag) {\n\n\tif _, exists := c.innerFlagsLong[flag.Long]; exists {\n\t\tpanic(fmt.Errorf(\"Flag '%s' already exists \", flag.Long))\n\t}\n\tif _, exists := c.innerFlagsShort[flag.Short]; exists {\n\t\tpanic(fmt.Errorf(\"Flag '%s' already exists \", flag.Short))\n\t}\n\tc.innerFlagsLong[flag.Long] = flag\n\tc.orderedFlags = append(c.orderedFlags, flag)\n\tif flag.Short != \"\" {\n\t\tc.innerFlagsShort[flag.Short] = flag\n\t}\n\n}", "func (*SigMentionHandler) AddFlags(cmd *cobra.Command, config *github.Config) {}", "func (PingCIMunger) AddFlags(cmd *cobra.Command, config *github_util.Config) {}", "func (p *PullCommand) addFlags() {\n\t// TODO: add flags here\n}", "func (n *NetworkInspectCommand) addFlags() {\n\t//TODO add flags\n\tn.cmd.Flags().StringVarP(&n.format, \"format\", \"f\", \"\", \"Format the output using the given go template\")\n}", "func (f *ForjFlag) set_cmd(cmd clier.CmdClauser, paramIntType, name, help string, options *ForjOpts) {\n\tvar flag_name string\n\tif f.instance_name == \"\" {\n\t\tflag_name = name\n\t} else {\n\t\tflag_name = f.instance_name + \"-\" + name\n\t}\n\n\tf.flag = cmd.Flag(flag_name, help)\n\tf.name = name\n\tf.help = help\n\tf.value_type = paramIntType\n\tif options != nil {\n\t\tif f.options != nil {\n\t\t\tf.options.MergeWith(options)\n\t\t} else {\n\t\t\tf.options = options\n\t\t}\n\n\t}\n\tf.set_options(options)\n\n\tswitch paramIntType {\n\tcase String:\n\t\tf.flagv = f.flag.String()\n\tcase Bool:\n\t\tf.flagv = f.flag.Bool()\n\t}\n\tgotrace.Trace(\"kingping.Arg '%s' added to '%s'\", name, cmd.FullCommand())\n}", "func (i *SinkFlags) Add(cmd *cobra.Command) {\n\ti.AddWithFlagName(cmd, \"sink\", \"s\")\n}", "func (n *NetworkRemoveCommand) addFlags() {\n\t//TODO add flags\n}", "func (i *ImageInspectCommand) addFlags() {\n\ti.cmd.Flags().StringVarP(&i.format, \"format\", \"f\", \"\", \"Format the output using the given go template\")\n}", "func (n *NetworkListCommand) addFlags() {\n\t//TODO add flags\n}", "func (o *unsafeCommonOptions) addFlags(cmd *cobra.Command) {\n\tcmd.PersistentFlags().BoolVar(&o.noConfirm, \"no-confirm\", false, \"Don't ask user whether to confirm executing meta command\")\n}", "func addHelpCommandFlag(usage string, fs *pflag.FlagSet) {\n\tfs.BoolP(flagHelp, flagHelpShorthand, false,\n\t\tfmt.Sprintf(\"Help for the %s command.\", color.GreenString(strings.Split(usage, \" \")[0])))\n}", "func setupAddCommand(cmd *cobra.Command) {\n\tcmd.Flags().String(\"record\", \"\", \"Record Name\")\n\n\tif err := cmd.MarkFlagRequired(\"record\"); err != nil {\n\t\tlog.Fatalf(\"Lethal damage: %s\\n\\n\", err)\n\t}\n\n\tcmd.Flags().String(\"zone\", \"\", \"Zone Name\")\n\n\tif err := cmd.MarkFlagRequired(\"zone\"); err != nil {\n\t\tlog.Fatalf(\"Lethal damage: %s\\n\\n\", err)\n\t}\n\n\tcmd.Flags().String(\"dns-provider\", \"\", \"DNS Provider\")\n\n\tif err := cmd.MarkFlagRequired(\"dns-provider\"); err != nil {\n\t\tlog.Fatalf(\"Lethal damage: %s\\n\\n\", err)\n\t}\n\n\tcmd.Flags().String(\"ip-provider\", \"google\", \"IP Provider\")\n\tcmd.Flags().Int(\"interval\", 1, \"Interval in Minutes\")\n\tcmd.Flags().Bool(\"daemon\", false, \"Daemon\")\n}", "func (n *NetworkCreateCommand) addFlags() {\n\tflagSet := n.cmd.Flags()\n\n\tflagSet.StringVarP(&n.name, \"name\", \"n\", \"\", \"the name of network\")\n\tflagSet.StringVarP(&n.driver, \"driver\", \"d\", \"bridge\", \"the driver of network\")\n\tflagSet.StringVar(&n.gateway, \"gateway\", \"\", \"the gateway of network\")\n\tflagSet.StringVar(&n.ipRange, \"ip-range\", \"\", \"the range of network's ip\")\n\tflagSet.StringVar(&n.subnet, \"subnet\", \"\", \"the subnet of network\")\n\tflagSet.StringVar(&n.ipamDriver, \"ipam-driver\", \"default\", \"the ipam driver of network\")\n\tflagSet.BoolVar(&n.enableIPv6, \"enable-ipv6\", false, \"enable ipv6 network\")\n\tflagSet.StringSliceVarP(&n.options, \"option\", \"o\", nil, \"create network with options\")\n\tflagSet.StringSliceVarP(&n.labels, \"label\", \"l\", nil, \"create network with labels\")\n}", "func AddFlags(cmd *cobra.Command) {\n\tcmd.Flags().BoolVarP(&quiet, \"quiet\", \"q\", false, \"Suppress output to stderr.\")\n}", "func (n *NetworkConnectCommand) addFlags() {\n\tflagSet := n.cmd.Flags()\n\n\tflagSet.StringVar(&n.ipAddress, \"ip\", \"\", \"IP Address\")\n\tflagSet.StringVar(&n.ipv6Address, \"ip6\", \"\", \"IPv6 Address\")\n\tflagSet.StringSliceVar(&n.links, \"link\", []string{}, \"Add link to another container\")\n\tflagSet.StringSliceVar(&n.aliases, \"alias\", []string{}, \"Add network-scoped alias for the container\")\n\tflagSet.StringSliceVar(&n.linklocalips, \"link-local-ip\", []string{}, \"Add a link-local address for the container\")\n}", "func (c *Commands) FlagDemo(m *discordgo.MessageCreate, f *arguments.Flag) error {\n\tvar fs = arguments.NewFlagSet()\n\n\topt := fs.Bool(\"opt\", false, \"\")\n\tstr := fs.String(\"str\", \"\", \"\")\n\n\tif err := f.With(fs); err != nil {\n\t\treturn errors.Wrap(err, \"Invalid flags\")\n\t}\n\n\targs := fs.Args()\n\n\treturn c.Context.Send(m.ChannelID, fmt.Sprintf(\n\t\t`opt: %v, str: \"%s\", args: %v`,\n\t\t*opt, *str, args),\n\t)\n}", "func AddFlags(cmd *cobra.Command) {\n\tcmd.Flags().String(\"log-level\", \"info\", \"The log-level for the operator. Possible values: trace, debug, info, warning, error, fatal, panic\")\n\tcmd.Flags().String(\"jaeger-version\", version.DefaultJaeger(), \"Deprecated: the Jaeger version is now managed entirely by the operator. This option is currently no-op.\")\n\tcmd.Flags().String(\"jaeger-agent-image\", \"jaegertracing/jaeger-agent\", \"The Docker image for the Jaeger Agent\")\n\tcmd.Flags().String(\"jaeger-query-image\", \"jaegertracing/jaeger-query\", \"The Docker image for the Jaeger Query\")\n\tcmd.Flags().String(\"jaeger-collector-image\", \"jaegertracing/jaeger-collector\", \"The Docker image for the Jaeger Collector\")\n\tcmd.Flags().String(\"jaeger-ingester-image\", \"jaegertracing/jaeger-ingester\", \"The Docker image for the Jaeger Ingester\")\n\tcmd.Flags().String(\"jaeger-all-in-one-image\", \"jaegertracing/all-in-one\", \"The Docker image for the Jaeger all-in-one\")\n\tcmd.Flags().String(\"jaeger-cassandra-schema-image\", \"jaegertracing/jaeger-cassandra-schema\", \"The Docker image for the Jaeger Cassandra Schema\")\n\tcmd.Flags().String(\"jaeger-spark-dependencies-image\", \"ghcr.io/jaegertracing/spark-dependencies/spark-dependencies\", \"The Docker image for the Spark Dependencies Job\")\n\tcmd.Flags().String(\"jaeger-es-index-cleaner-image\", \"jaegertracing/jaeger-es-index-cleaner\", \"The Docker image for the Jaeger Elasticsearch Index Cleaner\")\n\tcmd.Flags().String(\"jaeger-es-rollover-image\", \"jaegertracing/jaeger-es-rollover\", \"The Docker image for the Jaeger Elasticsearch Rollover\")\n\tcmd.Flags().String(\"openshift-oauth-proxy-image\", \"quay.io/openshift/origin-oauth-proxy:4.12\", \"The Docker image location definition for the OpenShift OAuth Proxy\")\n\tcmd.Flags().String(\"openshift-oauth-proxy-imagestream-ns\", \"\", \"The namespace for the OpenShift OAuth Proxy imagestream\")\n\tcmd.Flags().String(\"openshift-oauth-proxy-imagestream-name\", \"\", \"The name for the OpenShift OAuth Proxy imagestream\")\n\tcmd.Flags().String(\"platform\", v1.FlagPlatformAutoDetect, \"The target platform the operator will run. Possible values: 'kubernetes', 'openshift', 'auto-detect'\")\n\tcmd.Flags().String(\"es-provision\", v1.FlagProvisionElasticsearchAuto, \"Whether to auto-provision an Elasticsearch cluster for suitable Jaeger instances. Possible values: 'yes', 'no', 'auto'. When set to 'auto' and the API name 'logging.openshift.io' is available, auto-provisioning is enabled.\")\n\tcmd.Flags().String(\"kafka-provision\", \"auto\", \"Whether to auto-provision a Kafka cluster for suitable Jaeger instances. Possible values: 'yes', 'no', 'auto'. When set to 'auto' and the API name 'kafka.strimzi.io' is available, auto-provisioning is enabled.\")\n\tcmd.Flags().Bool(\"kafka-provisioning-minimal\", false, \"(unsupported) Whether to provision Kafka clusters with minimal requirements, suitable for demos and tests.\")\n\tcmd.Flags().String(\"secure-listen-address\", \"\", \"\")\n\tcmd.Flags().String(\"health-probe-bind-address\", \":8081\", \"The address the probe endpoint binds to.\")\n\tcmd.Flags().Int(\"webhook-bind-port\", 9443, \"The address webhooks expose.\")\n\tcmd.Flags().String(\"tls-min-version\", \"VersionTLS12\", \"Minimum TLS version supported. Value must match version names from https://golang.org/pkg/crypto/tls/#pkg-constants.\")\n\tcmd.Flags().StringSlice(\"tls-cipher-suites\", nil, \"Comma-separated list of cipher suites for the server. Values are from tls package constants (https://golang.org/pkg/crypto/tls/#pkg-constants). If omitted, the default Go cipher suites will be used\")\n\tcmd.Flags().Bool(\"leader-elect\", false, \"Enable leader election for controller manager. \"+\n\t\t\"Enabling this will ensure there is only one active controller manager.\")\n\n\tdocURL := fmt.Sprintf(\"https://www.jaegertracing.io/docs/%s\", version.DefaultJaegerMajorMinor())\n\tcmd.Flags().String(\"documentation-url\", docURL, \"The URL for the 'Documentation' menu item\")\n}", "func (PickMustHaveMilestone) AddFlags(cmd *cobra.Command, config *github.Config) {}", "func (g *Generator) AddFlags(command *cobra.Command) {\n\tflags := command.Flags()\n\tflags.SortFlags = false\n\n\tflags.StringP(base.Output, \"o\", \"\", \"output dir path\")\n\tif err := command.MarkFlagRequired(base.Output); err != nil {\n\t\tpanic(err)\n\t}\n\n\tflags.StringP(mfdFlag, \"m\", \"\", \"mfd file path\")\n\tif err := command.MarkFlagRequired(mfdFlag); err != nil {\n\t\tpanic(err)\n\t}\n\n\tflags.StringSliceP(nsFlag, \"n\", []string{}, \"namespaces to generate. separate by comma\\n\")\n\tflags.StringSliceP(entitiesFlag, \"e\", []string{}, \"entities to generate, must be in vt.xml file. separate by comma\")\n\n\tflags.String(routesTemplateFlag, \"\", \"path to routes custom template\")\n\tflags.String(listTemplateFlag, \"\", \"path to list custom template\")\n\tflags.String(filterTemplateFlag, \"\", \"path to filter custom template\")\n\tflags.String(formTemplateFlag, \"\", \"path to form custom template\\n\")\n}", "func AddCommand(c *cobra.Command) {\n\tc.AddCommand(cmd)\n\n\tfs := cmd.Flags()\n\tfs.SortFlags = false\n\n\topts.Request = request.New(\"\")\n\trequest.AddFlags(opts.Request, fs)\n\n\tfs.StringVarP(&opts.Value, \"value\", \"v\", \"test\", \"Use `string` for the placeholder\")\n\tfs.BoolVar(&opts.ShowRequest, \"show-request\", false, \"Also print HTTP request\")\n}", "func (cc *BackupCommand) addFlags() {\n\tflagSet := cc.cmd.Flags()\n\thome, _ := homedir.Dir()\n\tbackPath := filepath.Join(home, \".mysshbackup\")\n\tflagSet.StringVarP(&cc.backupPath, \"path\", \"p\", backPath, \"backup path\")\n\n}", "func (nd *NetworkDisconnectCommand) addFlags() {\n\t// add flags\n\tnd.cmd.Flags().BoolVarP(&nd.force, \"force\", \"f\", false, \"Force the container to disconnect from a network\")\n}", "func Flag(discord *discordgo.Session, message *discordgo.MessageCreate) {\r\n\tif message.ChannelID == channelid {\r\n\t\tif message.Content == (commandPrefix + \"flag\") {\r\n\t\t\t_, err := discord.ChannelMessageSend(message.ChannelID, \"Support Turned back On\")\r\n\t\t\tif err != nil {\r\n\t\t\t\ttools.Log.WithField(\"Error\", err).Warn(\"Unusual Error\")\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t\tflag = 0\r\n\t\t}\r\n\t}\r\n}", "func (cli *Application) AddCommand(c Command) {\n\tcli.Log.Debugf(\"CLI:AddCommand - %q\", c.Name())\n\t// Can only check command name here since nothing stops you to add possible\n\t// shadow flags after this command was added.\n\tif _, exists := cli.commands[c.Name()]; exists {\n\t\tcli.errs.Add(errors.Newf(FmtErrCommandNameInUse, c.Name()))\n\t\treturn\n\t}\n\tcli.commands[c.Name()] = c\n}", "func AddCommand(parentCmd, cmd *cobra.Command, envPrefix string) (*viper.Viper, *Flagger) {\n\tparentCmd.AddCommand(cmd)\n\tcfg := InitConfig(envPrefix)\n\treturn cfg, NewFlagger(cmd, cfg)\n}", "func (c *Command) AddFlag(flag *Flag) error {\n\tcc := c.GetCobraCmd()\n\tflagSetter := cc.Flags\n\tif flag.Persist {\n\t\tflagSetter = cc.PersistentFlags\n\t}\n\n\tswitch flag.Type {\n\tcase TypeString:\n\t\tflagSetter().StringVarP(flag.StringVar, flag.Name, flag.Shorthand, flag.StringValue, T(flag.Description))\n\tcase TypeInt:\n\t\tflagSetter().IntVarP(flag.IntVar, flag.Name, flag.Shorthand, flag.IntValue, T(flag.Description))\n\tcase TypeBool:\n\t\tflagSetter().BoolVarP(flag.BoolVar, flag.Name, flag.Shorthand, flag.BoolValue, T(flag.Description))\n\tdefault:\n\t\treturn failures.FailInput.New(\"Unknown type:\" + string(flag.Type))\n\t}\n\n\treturn nil\n}", "func (o *Options) AddFlags(cmd *cobra.Command) {\n\to.cmd = cmd\n\n\tcompletionCommand.SetHelpFunc(func(cmd *cobra.Command, args []string) {\n\t\tif shellPath, ok := os.LookupEnv(\"SHELL\"); ok {\n\t\t\tshell := shellPath[strings.LastIndex(shellPath, \"/\")+1:]\n\t\t\tfmt.Println(FetchLoadInstructions(shell))\n\t\t} else {\n\t\t\tfmt.Println(\"SHELL environment variable not set, falling back to bash\")\n\t\t\tfmt.Println(FetchLoadInstructions(\"bash\"))\n\t\t}\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 0)\n\t})\n\n\tversionCommand := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Print version information.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Printf(\"%s\\n\", version.Print(\"kube-state-metrics\"))\n\t\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 0)\n\t\t},\n\t}\n\n\tcmd.AddCommand(completionCommand, versionCommand)\n\n\to.cmd.Flags().Usage = func() {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\to.cmd.Flags().PrintDefaults()\n\t}\n\n\tklogFlags := flag.NewFlagSet(\"klog\", flag.ExitOnError)\n\tklog.InitFlags(klogFlags)\n\to.cmd.Flags().AddGoFlagSet(klogFlags)\n\t_ = o.cmd.Flags().Lookup(\"logtostderr\").Value.Set(\"true\")\n\to.cmd.Flags().Lookup(\"logtostderr\").DefValue = \"true\"\n\to.cmd.Flags().Lookup(\"logtostderr\").NoOptDefVal = \"true\"\n\n\tautoshardingNotice := \"When set, it is expected that --pod and --pod-namespace are both set. Most likely this should be passed via the downward API. This is used for auto-detecting sharding. If set, this has preference over statically configured sharding. This is experimental, it may be removed without notice.\"\n\n\to.cmd.Flags().BoolVar(&o.CustomResourcesOnly, \"custom-resource-state-only\", false, \"Only provide Custom Resource State metrics (experimental)\")\n\to.cmd.Flags().BoolVar(&o.EnableGZIPEncoding, \"enable-gzip-encoding\", false, \"Gzip responses when requested by clients via 'Accept-Encoding: gzip' header.\")\n\to.cmd.Flags().BoolVarP(&o.Help, \"help\", \"h\", false, \"Print Help text\")\n\to.cmd.Flags().BoolVarP(&o.UseAPIServerCache, \"use-apiserver-cache\", \"\", false, \"Sets resourceVersion=0 for ListWatch requests, using cached resources from the apiserver instead of an etcd quorum read.\")\n\to.cmd.Flags().Int32Var(&o.Shard, \"shard\", int32(0), \"The instances shard nominal (zero indexed) within the total number of shards. (default 0)\")\n\to.cmd.Flags().IntVar(&o.Port, \"port\", 8080, `Port to expose metrics on.`)\n\to.cmd.Flags().IntVar(&o.TelemetryPort, \"telemetry-port\", 8081, `Port to expose kube-state-metrics self metrics on.`)\n\to.cmd.Flags().IntVar(&o.TotalShards, \"total-shards\", 1, \"The total number of shards. Sharding is disabled when total shards is set to 1.\")\n\to.cmd.Flags().StringVar(&o.Apiserver, \"apiserver\", \"\", `The URL of the apiserver to use as a master`)\n\to.cmd.Flags().StringVar(&o.CustomResourceConfig, \"custom-resource-state-config\", \"\", \"Inline Custom Resource State Metrics config YAML (experimental)\")\n\to.cmd.Flags().StringVar(&o.CustomResourceConfigFile, \"custom-resource-state-config-file\", \"\", \"Path to a Custom Resource State Metrics config file (experimental)\")\n\to.cmd.Flags().StringVar(&o.Host, \"host\", \"::\", `Host to expose metrics on.`)\n\to.cmd.Flags().StringVar(&o.Kubeconfig, \"kubeconfig\", \"\", \"Absolute path to the kubeconfig file\")\n\to.cmd.Flags().StringVar(&o.Namespace, \"pod-namespace\", \"\", \"Name of the namespace of the pod specified by --pod. \"+autoshardingNotice)\n\to.cmd.Flags().StringVar(&o.Pod, \"pod\", \"\", \"Name of the pod that contains the kube-state-metrics container. \"+autoshardingNotice)\n\to.cmd.Flags().StringVar(&o.TLSConfig, \"tls-config\", \"\", \"Path to the TLS configuration file\")\n\to.cmd.Flags().StringVar(&o.TelemetryHost, \"telemetry-host\", \"::\", `Host to expose kube-state-metrics self metrics on.`)\n\to.cmd.Flags().StringVar(&o.Config, \"config\", \"\", \"Path to the kube-state-metrics options config file\")\n\to.cmd.Flags().StringVar((*string)(&o.Node), \"node\", \"\", \"Name of the node that contains the kube-state-metrics pod. Most likely it should be passed via the downward API. This is used for daemonset sharding. Only available for resources (pod metrics) that support spec.nodeName fieldSelector. This is experimental.\")\n\to.cmd.Flags().Var(&o.AnnotationsAllowList, \"metric-annotations-allowlist\", \"Comma-separated list of Kubernetes annotations keys that will be used in the resource' labels metric. By default the metric contains only name and namespace labels. To include additional annotations provide a list of resource names in their plural form and Kubernetes annotation keys you would like to allow for them (Example: '=namespaces=[kubernetes.io/team,...],pods=[kubernetes.io/team],...)'. A single '*' can be provided per resource instead to allow any annotations, but that has severe performance implications (Example: '=pods=[*]').\")\n\to.cmd.Flags().Var(&o.LabelsAllowList, \"metric-labels-allowlist\", \"Comma-separated list of additional Kubernetes label keys that will be used in the resource' labels metric. By default the metric contains only name and namespace labels. To include additional labels provide a list of resource names in their plural form and Kubernetes label keys you would like to allow for them (Example: '=namespaces=[k8s-label-1,k8s-label-n,...],pods=[app],...)'. A single '*' can be provided per resource instead to allow any labels, but that has severe performance implications (Example: '=pods=[*]'). Additionally, an asterisk (*) can be provided as a key, which will resolve to all resources, i.e., assuming '--resources=deployments,pods', '=*=[*]' will resolve to '=deployments=[*],pods=[*]'.\")\n\to.cmd.Flags().Var(&o.MetricAllowlist, \"metric-allowlist\", \"Comma-separated list of metrics to be exposed. This list comprises of exact metric names and/or regex patterns. The allowlist and denylist are mutually exclusive.\")\n\to.cmd.Flags().Var(&o.MetricDenylist, \"metric-denylist\", \"Comma-separated list of metrics not to be enabled. This list comprises of exact metric names and/or regex patterns. The allowlist and denylist are mutually exclusive.\")\n\to.cmd.Flags().Var(&o.MetricOptInList, \"metric-opt-in-list\", \"Comma-separated list of metrics which are opt-in and not enabled by default. This is in addition to the metric allow- and denylists\")\n\to.cmd.Flags().Var(&o.Namespaces, \"namespaces\", fmt.Sprintf(\"Comma-separated list of namespaces to be enabled. Defaults to %q\", &DefaultNamespaces))\n\to.cmd.Flags().Var(&o.NamespacesDenylist, \"namespaces-denylist\", \"Comma-separated list of namespaces not to be enabled. If namespaces and namespaces-denylist are both set, only namespaces that are excluded in namespaces-denylist will be used.\")\n\to.cmd.Flags().Var(&o.Resources, \"resources\", fmt.Sprintf(\"Comma-separated list of Resources to be enabled. Defaults to %q\", &DefaultResources))\n}", "func (b *taskBuilder) cmd(c ...string) {\n\tb.Spec.Command = c\n}", "func initFlag(cmd *cobra.Command) {\n\t//\tcobra.OnInitialize(initConfig)\n\t// add Pesistent flags\n\tcmd.PersistentFlags().StringP(\"server\", \"s\", \"localhost:6789\", \"katib manager API endpoint\")\n\n\t//bind viper\n\tviper.BindPFlag(\"server\", cmd.PersistentFlags().Lookup(\"server\"))\n}", "func AddModeFlag(mode *ops.Mode, cmd *cobra.Command) {\n\t*mode = ops.Conformance // default\n\tcmd.PersistentFlags().Var(\n\t\tmode, \"mode\",\n\t\tfmt.Sprintf(\"What mode to run sonobuoy in. [%s]\", strings.Join(ops.GetModes(), \", \")),\n\t)\n}", "func (s *BasePCREListener) EnterOption_flag(ctx *Option_flagContext) {}", "func AddStringFlag(cmd *cobra.Command, name string, aliases []string, value string, env, usage string) {\n\tif env != \"\" {\n\t\tusage = fmt.Sprintf(\"%s [$%s]\", usage, env)\n\t}\n\tif envV, ok := os.LookupEnv(env); ok {\n\t\tvalue = envV\n\t}\n\taliasesUsage := fmt.Sprintf(\"Alias of --%s\", name)\n\tp := new(string)\n\tflags := cmd.Flags()\n\tflags.StringVar(p, name, value, usage)\n\tfor _, a := range aliases {\n\t\tif len(a) == 1 {\n\t\t\t// pflag doesn't support short-only flags, so we have to register long one as well here\n\t\t\tflags.StringVarP(p, a, a, value, aliasesUsage)\n\t\t} else {\n\t\t\tflags.StringVar(p, a, value, aliasesUsage)\n\t\t}\n\t}\n}", "func (this *Command) NewFlag(name, alias, usage string, multiple bool) *Command {\n\treturn this.AddOption(NewFlag(name, alias, usage, multiple))\n}", "func (co *ConfigOption) setFlag(cmd *cobra.Command) error {\n\tswitch co.OptType {\n\tcase types.String:\n\t\t// Set an empty string if no default was provided, since some value is always required for pflags\n\t\tif co.FlagDefault == nil {\n\t\t\tco.FlagDefault = \"\"\n\t\t}\n\t\tcmd.PersistentFlags().String(co.Name, co.FlagDefault.(string), co.UsageText())\n\tcase types.Int:\n\t\tcmd.PersistentFlags().Int(co.Name, co.FlagDefault.(int), co.UsageText())\n\tcase types.Bool:\n\t\tcmd.PersistentFlags().Bool(co.Name, co.FlagDefault.(bool), co.UsageText())\n\tcase types.Uint:\n\t\tcmd.PersistentFlags().Uint(co.Name, co.FlagDefault.(uint), co.UsageText())\n\tcase types.Uint32:\n\t\tcmd.PersistentFlags().Uint32(co.Name, co.FlagDefault.(uint32), co.UsageText())\n\tcase types.Float64:\n\t\tcmd.PersistentFlags().Float64(co.Name, co.FlagDefault.(float64), co.UsageText())\n\tdefault:\n\t\treturn errors.New(\"Unexpected OptType\")\n\t}\n\n\tco.flag = cmd.PersistentFlags().Lookup(co.Name)\n\n\treturn nil\n}", "func (c *cmdCreate) AddFlags(fs *flag.FlagSet) {\n\tfs.StringVar(&(c.fileName), \"f\", \"\", \"gateway app file\")\n\tfs.StringVar(&(c.pingport), \"pingport\", \"\", \"ping port\")\n}", "func AddCommand(c *cobra.Command) {\n\tc.AddCommand(cmd)\n\n\tfs := cmd.Flags()\n\tfs.SortFlags = false\n\n\tfs.StringSliceVarP(&opts.Range, \"range\", \"r\", nil, \"set range `from-to`\")\n\tfs.StringVar(&opts.RangeFormat, \"range-format\", \"%d\", \"set `format` for range\")\n\n\tfs.StringVarP(&opts.Filename, \"file\", \"f\", \"\", \"read values from `filename`\")\n\tfs.StringVar(&opts.Logfile, \"logfile\", \"\", \"write copy of printed messages to `filename`.log\")\n\tfs.StringVar(&opts.Logdir, \"logdir\", os.Getenv(\"MONSOON_LOG_DIR\"), \"automatically log all output to files in `dir`\")\n\n\tfs.IntVarP(&opts.Threads, \"threads\", \"t\", 5, \"make as many as `n` parallel requests\")\n\tfs.IntVar(&opts.BufferSize, \"buffer-size\", 100000, \"set number of buffered items to `n`\")\n\tfs.IntVar(&opts.Skip, \"skip\", 0, \"skip the first `n` requests\")\n\tfs.IntVar(&opts.Limit, \"limit\", 0, \"only run `n` requests, then exit\")\n\tfs.Float64Var(&opts.RequestsPerSecond, \"requests-per-second\", 0, \"do at most `n` requests per second (e.g. 0.5)\")\n\n\t// add all options to define a request\n\topts.Request = request.New(\"\")\n\trequest.AddFlags(opts.Request, fs)\n\n\tfs.IntVar(&opts.FollowRedirect, \"follow-redirect\", 0, \"follow `n` redirects\")\n\n\tfs.StringSliceVar(&opts.HideStatusCodes, \"hide-status\", nil, \"hide responses with this status `code,[code-code],[-code],[...]`\")\n\tfs.StringSliceVar(&opts.ShowStatusCodes, \"show-status\", nil, \"show only responses with this status `code,[code-code],[code-],[...]`\")\n\tfs.StringSliceVar(&opts.HideHeaderSize, \"hide-header-size\", nil, \"hide responses with this header size (`size,from-to,from-,-to`)\")\n\tfs.StringSliceVar(&opts.HideBodySize, \"hide-body-size\", nil, \"hide responses with this body size (`size,from-to,from-,-to`)\")\n\tfs.StringArrayVar(&opts.HidePattern, \"hide-pattern\", nil, \"hide responses containing `regex` in response header or body (can be specified multiple times)\")\n\tfs.StringArrayVar(&opts.ShowPattern, \"show-pattern\", nil, \"show only responses containing `regex` in response header or body (can be specified multiple times)\")\n\n\tfs.StringArrayVar(&opts.Extract, \"extract\", nil, \"extract `regex` from response body (can be specified multiple times)\")\n\tfs.StringArrayVar(&opts.ExtractPipe, \"extract-pipe\", nil, \"pipe response body to `cmd` to extract data (can be specified multiple times)\")\n\tfs.IntVar(&opts.MaxBodySize, \"max-body-size\", 5, \"read at most `n` MiB from a returned response body (used for extracting data from the body)\")\n}", "func cmdAdd(mainArgs []string) error {\n\tadd := flag.NewFlagSet(\"add\", flag.ExitOnError)\n\tname := add.Bool(\"n\", false, commentAddName)\n\tday := add.String(\"d\", \"t\", commentAddDay)\n\tadd.Parse(mainArgs[1:])\n\targs := add.Args()\n\tif len(args) < 1 {\n\t\treturn errors.New(notEnoughSubCmdArgsError)\n\t}\n\tnewTask := Task{}\n\tvar c *Favorite\n\tvar err error\n\tif *name {\n\t\tc, err = getFavoriteByName(args[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif c != nil {\n\t\tnewTask.Name = c.Name\n\t\tnewTask.Content = c.Content\n\t\tnewTask.IsFin = false\n\t} else {\n\t\tnewTask.Name = \"\"\n\t\tnewTask.Content = strings.Join(args, \" \")\n\t\tnewTask.IsFin = false\n\t}\n\treturn addTask(&newTask, *day)\n}", "func (c *cmdVersion) AddFlags(fs *flag.FlagSet) {\n\t// no flags\n}", "func addRenderFlags(settings *render.Settings, cmd *cobra.Command) {\n\tflags := cmd.Flags()\n\n\tflags.StringVarP(\n\t\t&settings.Label,\n\t\t\"label\",\n\t\t\"l\",\n\t\t\"\",\n\t\t\"filter documents by Labels\")\n\n\tflags.StringVarP(\n\t\t&settings.Annotation,\n\t\t\"annotation\",\n\t\t\"a\",\n\t\t\"\",\n\t\t\"filter documents by Annotations\")\n\n\tflags.StringVarP(\n\t\t&settings.APIVersion,\n\t\t\"apiversion\",\n\t\t\"g\",\n\t\t\"\",\n\t\t\"filter documents by API version\")\n\n\tflags.StringVarP(\n\t\t&settings.Kind,\n\t\t\"kind\",\n\t\t\"k\",\n\t\t\"\",\n\t\t\"filter documents by Kinds\")\n}", "func newCommand(name, argsSpec, description string, init func(*flag.FlagSet), f func(*flag.FlagSet) error) command {\n\tfs := flag.NewFlagSet(name, flag.ExitOnError)\n\tinit(fs)\n\tif fs.Usage == nil {\n\t\tfs.Usage = func() {\n\t\t\tfmt.Fprintln(os.Stderr, \"#\", description)\n\t\t\tfmt.Fprintln(os.Stderr, name, argsSpec)\n\t\t\tfs.PrintDefaults()\n\t\t}\n\t}\n\treturn command{fs, f}\n}", "func (cli *Application) flag(name string) flags.Interface {\n\tif id, exists := cli.flagAliases[name]; exists {\n\t\treturn cli.flags[id]\n\t}\n\treturn flags.NewBoolFlag(name)\n}", "func (f *VerboseFlags) AddFlags(cmd *cobra.Command) {\n\tmessage := \"Output more information in JSON format. (default false)\"\n\tif strings.HasPrefix(cmd.Use, \"open-stream\") {\n\t\tmessage = \"Output more information. (default false)\"\n\t}\n\tcmd.Flags().BoolVarP(&f.IsVerbose, \"verbose\", \"v\", false, message)\n}", "func AddCommand(c *cobra.Command, globalOptions *options.Options) {\n\tc.AddCommand(cmd)\n\tgopts = globalOptions\n}", "func addHelpFlag(name string, fs *pflag.FlagSet) {\n\tfs.BoolP(flagHelp, flagHelpShorthand, false, fmt.Sprintf(\"Help for %s.\", name))\n}", "func AddPodFlag(cmd *cobra.Command) *string {\n\tv := \"\"\n\tcmd.Flags().StringVar(&v, \"pod\", \"\", \"Query a particular ingress-nginx pod\")\n\treturn &v\n}", "func AddDeploymentFlag(cmd *cobra.Command) *string {\n\tv := \"\"\n\tcmd.Flags().StringVar(&v, \"deployment\", DefaultIngressDeploymentName, \"The name of the ingress-nginx deployment\")\n\treturn &v\n}", "func addFlags(cmd *cobra.Command) {\n\tname = cmd.Flags().StringSliceP(\"name\", \"n\", []string{}, \"filter servers by Name tag, multiple comma separated values are allowed\")\n\tenv = cmd.Flags().StringSliceP(\"env\", \"e\", []string{}, \"filter servers by Env tag, multiple comma separated values are allowed\")\n\tregion = cmd.Flags().StringSliceP(\"region\", \"r\", []string{\"us-east-1\"}, \"look for servers in selected AWS region(s), any of: us-east-1,us-west-2,eu-west-1,ap-northeast-1,ap-southeast-2,all\")\n\tignoreCase = cmd.Flags().BoolP(\"ignore-case\", \"i\", false, \"ignore case in tag filters\")\n\n\t// Remove confusing `[]` symbols from region's default value.\n\tcmd.Flags().VisitAll(func(flag *pflag.Flag) {\n\t\tif flag.Name == \"region\" {\n\t\t\tflag.DefValue = strings.Map(func(r rune) rune {\n\t\t\t\tif r == '[' || r == ']' {\n\t\t\t\t\treturn '\"'\n\t\t\t\t}\n\t\t\t\treturn r\n\t\t\t}, flag.DefValue)\n\t\t}\n\t})\n}", "func AddFlags(v *viper.Viper, command *cobra.Command, inits ...func(*flag.FlagSet)) (*viper.Viper, *cobra.Command) {\n\tflagSet := new(flag.FlagSet)\n\tfor i := range inits {\n\t\tinits[i](flagSet)\n\t}\n\tcommand.Flags().AddGoFlagSet(flagSet)\n\n\tconfigureViper(v)\n\tv.BindPFlags(command.Flags())\n\treturn v, command\n}", "func (g *App) AddExtraCommand(ptrSt interface{}, names, help string, inits ...extraCmdInit) {\n\tif g.root == nil {\n\t\tpanic(\"need Bind or use NewWith\")\n\t}\n\n\tv := reflect.ValueOf(ptrSt)\n\tif v.Kind() != reflect.Ptr && v.Elem().Kind() != reflect.Struct {\n\t\tpanic(\"not a pointer to a struct\")\n\t}\n\tif len(names) == 0 {\n\t\tpanic(\"name the extra command\")\n\t}\n\n\tnameslice := strings.Split(names, \",\")\n\tfor i := 0; i < len(nameslice); i++ {\n\t\tnameslice[i] = strings.TrimSpace(nameslice[i])\n\t\tg.parser.HintCommand(nameslice[i])\n\t\tg.parser.HintCommand(nameslice[i], []string{\"help\"})\n\t}\n\tcmd := command{\n\t\tNames: nameslice,\n\t\tHelp: help,\n\t\tSelfV: v,\n\t\tParent: g.root,\n\t\tAutoNoBoolOptions: g.AutoNoBoolOptions,\n\t}\n\tlname := cmd.LongestName()\n\tfor ni := 0; ni < len(cmd.Names); ni++ {\n\t\tg.parser.HintAlias(cmd.Names[ni], lname)\n\t}\n\n\tfor _, init := range inits {\n\t\tinit(&cmd)\n\t}\n\n\terr := g.scanMeta(v.Type(), &cmd)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tg.root.Extras = append(g.root.Extras, &cmd)\n}", "func Decorate(c Command) *cobra.Command {\n\tvar flags []string\n\tif len(c.Flags) > 0 {\n\t\tflags = append(flags, c.Flags...)\n\t}\n\tcc := &cobra.Command{\n\t\tUse: c.Name,\n\t\tShort: fmt.Sprintf(\"[PLUGIN] %s\", c.Description),\n\t\tAliases: c.Aliases,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tplugCmd := c.Name\n\t\t\tif c.UseCommand != \"\" {\n\t\t\t\tplugCmd = c.UseCommand\n\t\t\t}\n\n\t\t\tax := []string{plugCmd}\n\t\t\tif plugCmd == \"-\" {\n\t\t\t\tax = []string{}\n\t\t\t}\n\n\t\t\tax = append(ax, args...)\n\t\t\tax = append(ax, flags...)\n\n\t\t\tbin, err := LookPath(c.Binary)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tex := exec.Command(bin, ax...)\n\t\t\tif runtime.GOOS != \"windows\" {\n\t\t\t\tex.Env = append(envy.Environ(), \"BUFFALO_PLUGIN=1\")\n\t\t\t}\n\t\t\tex.Stdin = os.Stdin\n\t\t\tex.Stdout = os.Stdout\n\t\t\tex.Stderr = os.Stderr\n\t\t\treturn log(strings.Join(ex.Args, \" \"), ex.Run)\n\t\t},\n\t}\n\tcc.DisableFlagParsing = true\n\treturn cc\n}", "func addTransactionFlags(cmd *cobra.Command, explanation string) {\n\tcmd.Flags().String(\"passphrase\", \"\", fmt.Sprintf(\"passphrase for %s\", explanation))\n\tcmd.Flags().String(\"privatekey\", \"\", fmt.Sprintf(\"private key for %s\", explanation))\n\tcmd.Flags().String(\"gasprice\", \"\", \"Gas price for the transaction\")\n\tcmd.Flags().Int64(\"gaslimit\", 0, \"Gas limit for the transaction; 0 is auto-select\")\n\tcmd.Flags().Int64(\"nonce\", -1, \"Nonce for the transaction; -1 is auto-select\")\n}", "func addIncludeRequestFlag(cmd *cobra.Command) {\n\tcmd.Flags().BoolVar(&includeRequest, \"include-request\", false, \"include the query request in the output\")\n}", "func versionFlag(cmd *cobra.Command) {\n\tversion, err := cmd.Flags().GetBool(\"version\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tif version {\n\t\tfmt.Printf(\"\\nversion: %s\\n\\nbuild: %s\\n\\n\",\n\t\t\tbuildVersion, buildDate)\n\t\tos.Exit(0)\n\t}\n}", "func (commandConfig *CommandConfig) AddFlag(name string, shortName string, isBool bool, defaultValue string) (*Flag, bool) {\n\n\t// clean argument values\n\t_name := removeWhitespaces(name)\n\t_shortName := removeWhitespaces(shortName)\n\t_defaultValue := trimWhitespaces(defaultValue)\n\n\t// inverted flag is a boolean flag with `no-` prefix\n\t_isInvert := false\n\n\t// short flag name should be only one character long\n\tif _shortName != \"\" {\n\t\t_shortName = _shortName[:1]\n\t}\n\n\t// set up `Flag` field values\n\tif isBool {\n\n\t\t// check for an inverted flag\n\t\tif strings.HasPrefix(name, \"no-\") {\n\t\t\t_isInvert = true // is an inverted flag\n\t\t\t_name = strings.TrimLeft(name, \"no-\") // trim `no-` prefix\n\t\t\t_defaultValue = \"true\" // default value of an inverted flag is `true`\n\t\t\t_shortName = \"\" // no short flag name for an inverted flag\n\t\t} else {\n\t\t\t_defaultValue = \"false\" // default value of a boolean flag is `true`\n\t\t}\n\t}\n\n\t// return if flag is already registered\n\tif _flag, ok := commandConfig.Flags[_name]; ok {\n\t\treturn _flag, true\n\t}\n\n\t// create a `Flag` object\n\tflag := &Flag{\n\t\tName: _name,\n\t\tShortName: _shortName,\n\t\tIsBoolean: isBool,\n\t\tIsInverted: _isInvert,\n\t\tDefaultValue: _defaultValue,\n\t}\n\n\t// register flag with the command-config\n\tcommandConfig.Flags[_name] = flag\n\n\t// register short flag name (for mapping)\n\tif len(_shortName) > 0 {\n\t\tcommandConfig.flagsShort[_shortName] = _name\n\t}\n\n\treturn flag, false\n}", "func OptFlag(flag uint) Option {\n\treturn Option{func(conf *mpConf) {\n\t\tconf.flags |= C.uint(flag)\n\t}}\n}", "func addFlagWithEnvDefault(c *cobra.Command, flag string, defVal string, help string) {\n\tc.PersistentFlags().String(\n\t\tflag,\n\t\tdefaultValue(flag, defVal),\n\t\tfmt.Sprintf(\"%s (${%s})\", help, GetEnvName(flag)))\n}", "func SupportFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&URL, \"url\", \"u\", \"\", \"Recipe URL\")\n\tcmd.Flags().StringVarP(&FilePath, \"filepath\", \"f\", \"\", \"Recipe file path\")\n}", "func AddFlags(rootCmd *cobra.Command) {\n\tflag.CommandLine.VisitAll(func(gf *flag.Flag) {\n\t\trootCmd.PersistentFlags().AddGoFlag(gf)\n\t})\n}", "func (o *PullRequestOptions) AddFlags(cmd *cobra.Command) {\n\to.Options.AddFlags(cmd)\n\n\tcmd.Flags().IntVarP(&o.Number, \"pr\", \"\", 0, \"the Pull Request number. If not specified we detect it via $PULL_NUMBER or $BRANCH_NAME environment variables\")\n\n}", "func Add() *cli.Command {\n\treturn &cli.Command{\n\t\tName: \"add\",\n\t\tAliases: []string{\"a\"},\n\t\tArgsUsage: \"\",\n\t\tUsage: \"add SHOW_NAME FOLDER\",\n\t\tDescription: \"Add new show to follow\",\n\t\tFlags: []cli.Flag{\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"title\",\n\t\t\t\tAliases: []string{\"n\"},\n\t\t\t\tUsage: \"Show identification name\",\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"resolution\",\n\t\t\t\tAliases: []string{\"r\"},\n\t\t\t\tUsage: \"Resolution of the torrent\",\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"codec\",\n\t\t\t\tAliases: []string{\"c\"},\n\t\t\t\tUsage: \"Codec to be downloaded\",\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"quality\",\n\t\t\t\tAliases: []string{\"q\"},\n\t\t\t\tUsage: \"Quality of the torrent\",\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"external-id\",\n\t\t\t\tAliases: []string{\"ex\"},\n\t\t\t\tUsage: \"assign external ID\",\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"key\",\n\t\t\t\tAliases: []string{\"k\"},\n\t\t\t\tUsage: \"Show directory name\",\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"folder\",\n\t\t\t\tAliases: []string{\"f\"},\n\t\t\t\tUsage: \"Where is going to save the show\",\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t\t&cli.StringSliceFlag{\n\t\t\t\tName: \"services\",\n\t\t\t\tAliases: []string{\"s\"},\n\t\t\t\tUsage: \"Coma separated type of services (showrss, eztv, rarbg)\",\n\t\t\t\tDefaultText: \"[eztv, rarbg]\",\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"type\",\n\t\t\t\tAliases: []string{\"t\"},\n\t\t\t\tUsage: \"Type of show sync (latest, since, all)\",\n\t\t\t\tDefaultText: \"latest\",\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t\t&cli.IntFlag{\n\t\t\t\tName: \"season\",\n\t\t\t\tUsage: \"since seasson\",\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t},\n\t\tAction: func(c *cli.Context) error {\n\t\t\tkey := c.String(\"key\")\n\t\t\ttitle := c.String(\"title\")\n\t\t\tfolder := c.String(\"folder\")\n\t\t\tservices := c.StringSlice(\"services\")\n\t\t\tfollowType := c.String(\"type\")\n\t\t\texternalID := c.String(\"external-id\")\n\t\t\tcodec := c.String(\"codec\")\n\t\t\tquality := c.String(\"quality\")\n\t\t\tresolution := c.String(\"resolution\")\n\t\t\tseason := c.Int(\"season\")\n\n\t\t\tif key == \"\" {\n\t\t\t\tkey = slug.Make(title)\n\t\t\t}\n\n\t\t\tif len(services) == 0 {\n\t\t\t\tservices = []string{eztv.ServiceType, rarbg.ServiceType}\n\t\t\t}\n\n\t\t\tif followType == \"\" {\n\t\t\t\tfollowType = \"latest\"\n\t\t\t}\n\n\t\t\tif folder == \"\" {\n\t\t\t\tfolder = storage.AppConfiguration.ShowsDir + key\n\t\t\t}\n\n\t\t\tfolderPath, err := filepath.Abs(folder)\n\t\t\tif err != nil {\n\t\t\t\treturn cli.Exit(err.Error(), 0)\n\t\t\t}\n\n\t\t\tif externalID == \"\" {\n\t\t\t\ttitle, key, externalID, err = common.SearchAndSelectOnImdb(title, \"\")\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn cli.Exit(err.Error(), 0)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tshow := &models.Show{\n\t\t\t\tID: key,\n\t\t\t\tTitle: title,\n\t\t\t\tDirectory: folderPath + \"/\",\n\t\t\t\tExternalID: externalID,\n\t\t\t\tConfiguration: &models.ShowConf{\n\t\t\t\t\tServices: services,\n\t\t\t\t\tFollowType: followType,\n\t\t\t\t\tCodec: codec,\n\t\t\t\t\tQuality: quality,\n\t\t\t\t\tResolution: resolution,\n\t\t\t\t\tSince: season,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tfmt.Printf(\"Adding show %s \\n\\r\", show.PrintString())\n\n\t\t\t_, err = common.Add(show)\n\t\t\tif err != nil {\n\t\t\t\treturn cli.Exit(err.Error(), 0)\n\t\t\t}\n\n\t\t\tshowData, _ := json.MarshalIndent(show, \"\", \" \")\n\n\t\t\tfmt.Printf(\"%s \\n\", showData)\n\t\t\tfmt.Printf(\"saved on: %s/%s/%s.json \\n\\r\", storage.DbDir, storage.Db.Collections.Shows, key)\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func (s *BasePCREListener) EnterOption_flags(ctx *Option_flagsContext) {}", "func (i *SinkFlags) AddWithFlagName(cmd *cobra.Command, fname, short string) {\n\tflag := \"--\" + fname\n\tif short == \"\" {\n\t\tcmd.Flags().StringVar(&i.Sink, fname, \"\", \"\")\n\t} else {\n\t\tcmd.Flags().StringVarP(&i.Sink, fname, short, \"\", \"\")\n\t}\n\tcmd.Flag(fname).Usage = \"Addressable sink for events. \" +\n\t\t\"You can specify a broker, channel, Knative service or URI. \" +\n\t\t\"Examples: '\" + flag + \" broker:nest' for a broker 'nest', \" +\n\t\t\"'\" + flag + \" channel:pipe' for a channel 'pipe', \" +\n\t\t\"'\" + flag + \" ksvc:mysvc:mynamespace' for a Knative service 'mysvc' in another namespace 'mynamespace', \" +\n\t\t\"'\" + flag + \" https://event.receiver.uri' for an HTTP URI, \" +\n\t\t\"'\" + flag + \" ksvc:receiver' or simply '\" + flag + \" receiver' for a Knative service 'receiver' in the current namespace. \" +\n\t\t\"'\" + flag + \" special.eventing.dev/v1alpha1/channels:pipe' for GroupVersionResource of v1alpha1 'pipe'. \" +\n\t\t\"If a prefix is not provided, it is considered as a Knative service in the current namespace.\"\n\t// Use default mapping if empty\n\tif i.SinkMappings == nil {\n\t\ti.SinkMappings = defaultSinkMappings\n\t}\n\tfor _, p := range config.GlobalConfig.SinkMappings() {\n\t\t//user configuration might override the default configuration\n\t\ti.SinkMappings[p.Prefix] = schema.GroupVersionResource{\n\t\t\tResource: p.Resource,\n\t\t\tGroup: p.Group,\n\t\t\tVersion: p.Version,\n\t\t}\n\t}\n}", "func init() {\n\trootCmd.AddCommand(markCmd)\n\n\tmarkCmd.Flags().BoolP(\"done\", \"d\", true, \"true to mark todo as done, false to mark as undone\")\n}", "func AddCommand(ctx context.Context,\n\tcb CommandBuilder,\n\tcommandBuffer VkCommandBuffer,\n\tr *api.GlobalState,\n\ts *api.GlobalState,\n\trebuildInfo interface{}) (func(), api.Cmd, error) {\n\tswitch t := rebuildInfo.(type) {\n\tcase *VkCmdBeginRenderPassArgs:\n\t\treturn rebuildVkCmdBeginRenderPass(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdEndRenderPassArgs:\n\t\treturn rebuildVkCmdEndRenderPass(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdNextSubpassArgs:\n\t\treturn rebuildVkCmdNextSubpass(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdBindPipelineArgs:\n\t\treturn rebuildVkCmdBindPipeline(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdBindDescriptorSetsArgs:\n\t\treturn rebuildVkCmdBindDescriptorSets(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdBindVertexBuffersArgs:\n\t\treturn rebuildVkCmdBindVertexBuffers(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdBindIndexBufferArgs:\n\t\treturn rebuildVkCmdBindIndexBuffer(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdPipelineBarrierArgs:\n\t\treturn rebuildVkCmdPipelineBarrier(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdWaitEventsArgs:\n\t\treturn rebuildVkCmdWaitEvents(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdBeginQueryArgs:\n\t\treturn rebuildVkCmdBeginQuery(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdBlitImageArgs:\n\t\treturn rebuildVkCmdBlitImage(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdClearAttachmentsArgs:\n\t\treturn rebuildVkCmdClearAttachments(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdClearColorImageArgs:\n\t\treturn rebuildVkCmdClearColorImage(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdClearDepthStencilImageArgs:\n\t\treturn rebuildVkCmdClearDepthStencilImage(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdCopyBufferArgs:\n\t\treturn rebuildVkCmdCopyBuffer(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdCopyBufferToImageArgs:\n\t\treturn rebuildVkCmdCopyBufferToImage(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdCopyImageArgs:\n\t\treturn rebuildVkCmdCopyImage(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdCopyImageToBufferArgs:\n\t\treturn rebuildVkCmdCopyImageToBuffer(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdCopyQueryPoolResultsArgs:\n\t\treturn rebuildVkCmdCopyQueryPoolResults(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdDispatchArgs:\n\t\treturn rebuildVkCmdDispatch(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdDispatchIndirectArgs:\n\t\treturn rebuildVkCmdDispatchIndirect(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdDrawArgs:\n\t\treturn rebuildVkCmdDraw(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdDrawIndexedArgs:\n\t\treturn rebuildVkCmdDrawIndexed(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdDrawIndexedIndirectArgs:\n\t\treturn rebuildVkCmdDrawIndexedIndirect(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdDrawIndirectArgs:\n\t\treturn rebuildVkCmdDrawIndirect(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdEndQueryArgs:\n\t\treturn rebuildVkCmdEndQuery(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdExecuteCommandsArgs:\n\t\treturn rebuildVkCmdExecuteCommands(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdFillBufferArgs:\n\t\treturn rebuildVkCmdFillBuffer(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdPushConstantsArgs:\n\t\treturn rebuildVkCmdPushConstants(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdResetQueryPoolArgs:\n\t\treturn rebuildVkCmdResetQueryPool(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdResolveImageArgs:\n\t\treturn rebuildVkCmdResolveImage(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdSetBlendConstantsArgs:\n\t\treturn rebuildVkCmdSetBlendConstants(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdSetDepthBiasArgs:\n\t\treturn rebuildVkCmdSetDepthBias(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdSetDepthBoundsArgs:\n\t\treturn rebuildVkCmdSetDepthBounds(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdSetEventArgs:\n\t\treturn rebuildVkCmdSetEvent(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdResetEventArgs:\n\t\treturn rebuildVkCmdResetEvent(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdSetLineWidthArgs:\n\t\treturn rebuildVkCmdSetLineWidth(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdSetScissorArgs:\n\t\treturn rebuildVkCmdSetScissor(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdSetStencilCompareMaskArgs:\n\t\treturn rebuildVkCmdSetStencilCompareMask(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdSetStencilReferenceArgs:\n\t\treturn rebuildVkCmdSetStencilReference(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdSetStencilWriteMaskArgs:\n\t\treturn rebuildVkCmdSetStencilWriteMask(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdSetViewportArgs:\n\t\treturn rebuildVkCmdSetViewport(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdUpdateBufferArgs:\n\t\treturn rebuildVkCmdUpdateBuffer(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdWriteTimestampArgs:\n\t\treturn rebuildVkCmdWriteTimestamp(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdDebugMarkerBeginEXTArgs:\n\t\treturn rebuildVkCmdDebugMarkerBeginEXT(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdDebugMarkerEndEXTArgs:\n\t\treturn rebuildVkCmdDebugMarkerEndEXT(ctx, cb, commandBuffer, r, s, t)\n\tcase *VkCmdDebugMarkerInsertEXTArgs:\n\t\treturn rebuildVkCmdDebugMarkerInsertEXT(ctx, cb, commandBuffer, r, s, t)\n\tdefault:\n\t\tx := fmt.Sprintf(\"Should not reach here: %T\", t)\n\t\tpanic(x)\n\t}\n}", "func (cli *Application) AddFlag(f flags.Interface) {\n\tcli.Log.Debugf(\"CLI:AddFlag - %q\", f.Name())\n\t// Verify flag\n\tcli.errs.Add(f.Verify())\n\n\t// add flag if there was no errors\n\tif cli.errs.Nil() {\n\t\tnextFlagID := len(cli.flags) + 1\n\t\t// assign the flag and set error if there is flag alias shadowing.\n\t\tcli.flags[nextFlagID] = f\n\t\t// Check that flag or it's aliases do not shadow other global flag\n\t\tfor _, alias := range f.GetAliases() {\n\t\t\tif flagID, exists := cli.flagAliases[alias]; exists {\n\t\t\t\tcli.errs.Appendf(FmtErrFlagShadowing, f.Name(), alias, cli.flags[flagID].Name())\n\t\t\t} else {\n\t\t\t\tcli.flagAliases[alias] = nextFlagID\n\t\t\t}\n\t\t}\n\t}\n}", "func AddCommand(c *cli.Context, i storage.Impl) (n storage.Note, err error) {\n\tnName, err := NoteName(c)\n\tif err != nil {\n\t\treturn n, err\n\t}\n\n\tif exists := i.NoteExists(nName); exists == true {\n\t\treturn n, fmt.Errorf(\"Note already exists\")\n\t}\n\n\tn.Name = nName\n\tn.Temporary = c.Bool(\"t\")\n\n\t// Only open editor if -p (read from clipboard) isnt set\n\tif c.IsSet(\"p\") {\n\t\tnText, err := clipboard.ReadAll()\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t\tn.Text = nText\n\t} else {\n\t\tif err := writer.WriteNote(&n); err != nil {\n\t\t\treturn n, err\n\t\t}\n\t}\n\n\tif err := i.SaveNote(&n); err != nil {\n\t\treturn n, err\n\t}\n\n\treturn n, nil\n}", "func AddIntFlag(cmd *cobra.Command, name string, aliases []string, value int, env, usage string) {\n\tif env != \"\" {\n\t\tusage = fmt.Sprintf(\"%s [$%s]\", usage, env)\n\t}\n\tif envV, ok := os.LookupEnv(env); ok {\n\t\tv, err := strconv.ParseInt(envV, 10, 64)\n\t\tif err != nil {\n\t\t\tlogrus.WithError(err).Warnf(\"Invalid int value for `%s`\", env)\n\t\t}\n\t\tvalue = int(v)\n\t}\n\taliasesUsage := fmt.Sprintf(\"Alias of --%s\", name)\n\tp := new(int)\n\tflags := cmd.Flags()\n\tflags.IntVar(p, name, value, usage)\n\tfor _, a := range aliases {\n\t\tif len(a) == 1 {\n\t\t\t// pflag doesn't support short-only flags, so we have to register long one as well here\n\t\t\tflags.IntVarP(p, a, a, value, aliasesUsage)\n\t\t} else {\n\t\t\tflags.IntVar(p, a, value, aliasesUsage)\n\t\t}\n\t}\n}", "func (f CommandFlag) FlagString() string {\r\n\tswitch f.NumArgs {\r\n\tcase 0:\r\n\t\treturn fmt.Sprintf(\"-%s, --%s\", f.ShortFlag, f.LongFlag)\r\n\tcase 1:\r\n\t\treturn fmt.Sprintf(\"-%s, --%s [value]\", f.ShortFlag, f.LongFlag)\r\n\tcase 2:\r\n\t\treturn fmt.Sprintf(\"-%s, --%s [key] [value]\", f.ShortFlag, f.LongFlag)\r\n\tdefault:\r\n\t\tpanic(\"Missing case\")\r\n\t}\r\n}", "func AddFormatFlag(c *kingpin.CmdClause, format *string, style *string) {\n\tc.Flag(\"format\", \"Sets the output format.\").\n\t\tDefault(TableFormat).\n\t\tNoEnvar().\n\t\tShort('f').\n\t\tEnumVar(format, PlainTextFormat, TableFormat, TreeFormat, JSONFormat)\n\n\tc.Flag(\"style\", fmt.Sprintf(\"The highlighting style of the Json output. Applicable to --format=%s only. Disabled (none) by default.\", JSONFormat)).\n\t\tDefault(\"none\").\n\t\tEnumVar(style, internal.HighlightStyles...)\n}", "func (cmd *GetCurrentUserCommand) RegisterFlags(cc *cobra.Command, c *client.Client) {\n}", "func (c *Command) addArgument(arg interface{}) {\n\tc.Arguments = append(c.Arguments, arg)\n}", "func addProxmoxLoginCommandFlags(flagSet *flag.FlagSet, payload *ProxmoxLoginRequest) {\n\tflagSet.StringVar(\n\t\t&payload.Username, api.FlagUsername, api.DefaultUsername,\n\t\t\"The username that is authorized to carry out subsequent operations.\",\n\t)\n\tflagSet.StringVar(\n\t\t&payload.Password, api.FlagPassword, \"\",\n\t\t\"The password for the user. Required.\",\n\t)\n\tflagSet.StringVar(\n\t\t&payload.Realm, api.FlagRealm, api.DefaultRealm,\n\t\t\"The realm in Proxmox to log into.\",\n\t)\n\tflagSet.StringVar(\n\t\t&payload.ApiServer, api.FlagApiServer, \"\",\n\t\t\"The address for the Proxmox API server. API paths will be appended to this address. Required.\",\n\t)\n\tflagSet.BoolVar(\n\t\t&payload.Force, api.FlagForce, api.DefaultForce,\n\t\t\"If set, command will ignore existing ticket cache and force a re-login.\",\n\t)\n}", "func Flag(flag int) Option {\n\treturn func(o *options) {\n\t\to.flag = flag\n\t}\n}", "func (cmd *TransmissionTokenUserCommand) RegisterFlags(cc *cobra.Command, c *client.Client) {\n}", "func overrideFlagUsageText(f *flag.FlagSet) {\n\n\tf.Usage = func() {\n\t\tfmt.Println(\"\\nCross-Origin Resource Sharing Interrogator (CORSI) v\" + version + \" by Superhac\")\n\t\tfmt.Println(\"Usage: cori [OPTION]... [url]\")\n\t\tflag.PrintDefaults()\n\t}\n}", "func Add(path, branch string) func(*types.Cmd) {\n\treturn func(g *types.Cmd) {\n\t\tg.AddOptions(\"add\")\n\t\tg.AddOptions(path)\n\t\tif len(branch) > 0 {\n\t\t\tg.AddOptions(branch)\n\t\t}\n\t}\n}", "func (*bzlLibraryLang) RegisterFlags(fs *flag.FlagSet, cmd string, c *config.Config) {}", "func CommandFlagSet(cmd string, cmdFlags []string, st reflect.Type, v reflect.Value) *flag.FlagSet {\n\tcfs := flag.NewFlagSet(cmd, flag.ExitOnError)\n\trecurse := true\n\n\t// iterate over the nested fields of the user provided struct,\n\t// and create the required flagset flags.\n\t//\n\tIterFields(recurse, st, v, func(field reflect.Value, sf reflect.StructField, currentCmd ...string) {\n\t\t// we're overloading the use of variadic functions to allow some iterations\n\t\t// over our struct to pass a cmd, and others that aren't a command to not.\n\t\t//\n\t\t// this means when we explicitly access the first index, there isn't ever\n\t\t// any expectation for there to be more than one command passed through.\n\t\t//\n\t\tif currentCmd[0] == cmd {\n\t\t\tswitch field.Kind() {\n\t\t\tcase reflect.Bool:\n\t\t\t\tvar v bool\n\t\t\t\tcfs.BoolVar(&v, strings.ToLower(sf.Name), false, sf.Tag.Get(\"usage\"))\n\t\t\t\tcfs.BoolVar(&v, sf.Tag.Get(\"short\"), false, sf.Tag.Get(\"usage\")+\" (shorthand)\")\n\t\t\tcase reflect.Int:\n\t\t\t\tvar v int\n\t\t\t\tcfs.IntVar(&v, strings.ToLower(sf.Name), 0, sf.Tag.Get(\"usage\"))\n\t\t\t\tcfs.IntVar(&v, sf.Tag.Get(\"short\"), 0, sf.Tag.Get(\"usage\")+\" (shorthand)\")\n\t\t\tcase reflect.String:\n\t\t\t\tvar v string\n\t\t\t\tcfs.StringVar(&v, strings.ToLower(sf.Name), \"\", sf.Tag.Get(\"usage\"))\n\t\t\t\tcfs.StringVar(&v, sf.Tag.Get(\"short\"), \"\", sf.Tag.Get(\"usage\")+\" (shorthand)\")\n\t\t\t}\n\t\t}\n\t})\n\n\treturn cfs\n}", "func appendToFlag(arg, val string) string {\n\tif !strings.ContainsRune(arg, '=') {\n\t\targ = arg + \"=\"\n\t}\n\tif arg[len(arg)-1] != '=' && arg[len(arg)-1] != ' ' {\n\t\targ += \" \"\n\t}\n\targ += val\n\treturn arg\n}", "func (i *Install) AttachCmd(cmd *cobra.Command) {\n\ti.OperationGlobal = &OperationGlobal{}\n\ti.OperationGlobal.AttachCmd(cmd)\n\tcmd.Flags().IntVar(&i.EgClientPort, \"mesh-control-plane-client-port\", DefaultMeshClientPort, \"Mesh control plane client port for remote accessing\")\n\tcmd.Flags().IntVar(&i.EgAdminPort, \"mesh-control-plane-admin-port\", DefaultMeshAdminPort, \"Port of mesh control plane admin for management\")\n\tcmd.Flags().IntVar(&i.EgPeerPort, \"mesh-control-plane-peer-port\", DefaultMeshPeerPort, \"Port of mesh control plane for consensus each other\")\n\tcmd.Flags().IntVar(&i.MeshControlPlaneCheckHealthzMaxTime,\n\t\t\"mesh-control-plane-check-healthz-max-time\",\n\t\tDefaultMeshControlPlaneCheckHealthzMaxTime,\n\t\t\"Max timeout in second for checking control panel component whether ready or not\")\n\n\tcmd.Flags().IntVar(&i.EgServicePeerPort, \"mesh-control-plane-service-peer-port\", DefaultMeshPeerPort, \"Port of Easegress cluster peer\")\n\tcmd.Flags().IntVar(&i.EgServiceAdminPort, \"mesh-control-plane-service-admin-port\", DefaultMeshAdminPort, \"Port of Easegress admin address\")\n\n\tcmd.Flags().StringVar(&i.MeshControlPlaneStorageClassName, \"mesh-storage-class-name\", DefaultMeshControlPlaneStorageClassName, \"Mesh storage class name\")\n\tcmd.Flags().StringVar(&i.MeshControlPlanePersistVolumeCapacity, \"mesh-control-plane-pv-capacity\", DefaultMeshControlPlanePersistVolumeCapacity,\n\t\tMeshControlPlanePVNotExistedHelpStr)\n\n\tcmd.Flags().Int32Var(&i.MeshIngressServicePort, \"mesh-ingress-service-port\", DefaultMeshIngressServicePort, \"Port of mesh ingress controller\")\n\n\tcmd.Flags().StringVar(&i.EaseMeshRegistryType, \"registry-type\", DefaultMeshRegistryType, MeshRegistryTypeHelpStr)\n\tcmd.Flags().IntVar(&i.HeartbeatInterval, \"heartbeat-interval\", DefaultHeartbeatInterval, \"Heartbeat interval for mesh service\")\n\n\tcmd.Flags().StringVar(&i.ImageRegistryURL, \"image-registry-url\", DefaultImageRegistryURL, \"Image registry URL\")\n\tcmd.Flags().StringVar(&i.EasegressImage, \"easegress-image\", DefaultEasegressImage, \"Easegress image name\")\n\tcmd.Flags().StringVar(&i.EaseMeshOperatorImage, \"easemesh-operator-image\", DefaultEaseMeshOperatorImage, \"Mesh operator image name\")\n\n\tcmd.Flags().IntVar(&i.EasegressControlPlaneReplicas, \"easemesh-control-plane-replicas\", DefaultMeshControlPlaneReplicas, \"Mesh control plane replicas\")\n\tcmd.Flags().IntVar(&i.MeshIngressReplicas, \"easemesh-ingress-replicas\", DefaultMeshIngressReplicas, \"Mesh ingress controller replicas\")\n\tcmd.Flags().IntVar(&i.EaseMeshOperatorReplicas, \"easemesh-operator-replicas\", DefaultMeshOperatorReplicas, \"Mesh operator controller replicas\")\n\tcmd.Flags().StringVarP(&i.SpecFile, \"file\", \"f\", \"\", \"A yaml file specifying the install params\")\n\tcmd.Flags().BoolVar(&i.CleanWhenFailed, \"clean-when-failed\", true, \"Clean resources when installation failed\")\n}", "func AddConfFlag(c *cobra.Command) {\n\tc.PersistentFlags().StringP(\"conf\", \"c\", \"\", \"configuration file to use\")\n}", "func AddTokenVarFlags(cmd *cobra.Command) {\n\tcmd.PersistentFlags().StringP(\"token\", \"t\", \"\", \"Github Repo token\")\n}", "func AddApplicationFlag(cmd *cobra.Command) {\n\tcmd.Flags().String(genericclioptions.ApplicationFlagName, \"\", \"Application, defaults to active application\")\n\tcompletion.RegisterCommandFlagHandler(cmd, \"app\", completion.AppCompletionHandler)\n}", "func AddRakkessFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringSliceVar(&opts.Verbs, constants.FlagVerbs, []string{\"list\", \"create\", \"update\", \"delete\"}, fmt.Sprintf(\"show access for verbs out of (%s)\", strings.Join(constants.ValidVerbs, \", \")))\n\tcmd.Flags().StringVarP(&opts.OutputFormat, constants.FlagOutput, \"o\", \"icon-table\", fmt.Sprintf(\"output format out of (%s)\", strings.Join(constants.ValidOutputFormats, \", \")))\n\tcmd.Flags().StringSliceVar(&diffWith, constants.FlagDiffWith, nil, \"Show diff for modified call. For example --diff-with=namespace=kube-system.\")\n\n\topts.ConfigFlags.AddFlags(cmd.Flags())\n}", "func (t *Term) AddCommand(name string, funct func([]string)) {\n\tt.cmds[name] = funct\n}", "func SetFlags(flag int) { std.SetFlags(flag) }", "func (cmd *TechListHyTechCommand) RegisterFlags(cc *cobra.Command, c *client.Client) {\n}", "func Flag(flag string) (string, bool) {\n\tonce.Do(cmdLineOpener)\n\tcanonicalFlag := strings.Replace(flag, \"-\", \"_\", -1)\n\tvalue, present := procCmdLine.AsMap[canonicalFlag]\n\treturn value, present\n}", "func (cmd *UserListHyUserCommand) RegisterFlags(cc *cobra.Command, c *client.Client) {\n}", "func Register(rootCommand *cobra.Command, opFlagName string) {\n\topURLFlagName = opFlagName\n\trootCommand.AddCommand(listCmd)\n}", "func (cmd *HealthHealthCommand) RegisterFlags(cc *cobra.Command, c *client.Client) {\n}", "func (s *StressFlag) AddExtraUsage(eu string) {}", "func (list *CommandList) AppendOption(opt string) {\n\tfor i, cmd := range list.commands {\n\t\tlist.commands[i] = append(cmd, opt)\n\t}\n}", "func AddSkipPreflightFlag(flag *bool, cmd *cobra.Command) {\n\tcmd.PersistentFlags().BoolVar(\n\t\tflag, \"skip-preflight\", false,\n\t\t\"If true, skip all checks before kicking off the sonobuoy run.\",\n\t)\n}", "func skykeyaddcmd(skykeyString string) {\n\terr := skykeyAdd(httpClient, skykeyString)\n\tif err != nil && strings.Contains(err.Error(), skykey.ErrSkykeyWithNameAlreadyExists.Error()) {\n\t\tdie(\"Skykey name already used. Try using the --rename-as parameter with a different name.\")\n\t}\n\tif err != nil {\n\t\tdie(errors.AddContext(err, \"Failed to add skykey\"))\n\t}\n\n\tfmt.Printf(\"Successfully added new skykey: %v\\n\", skykeyString)\n}", "func addDelete(topLevel *cobra.Command) {\n\ttopLevel.AddCommand(&cobra.Command{\n\t\tUse: \"delete\",\n\t\tShort: `See \"kubectl help delete\" for detailed usage.`,\n\t\tRunE: passthru(\"kubectl\"),\n\t\t// We ignore unknown flags to avoid importing everything Go exposes\n\t\t// from our commands.\n\t\tFParseErrWhitelist: cobra.FParseErrWhitelist{\n\t\t\tUnknownFlags: true,\n\t\t},\n\t})\n}", "func SetFlags(flag int) {\n Std.SetFlags(flag)\n}" ]
[ "0.7305491", "0.71374214", "0.70801497", "0.6962519", "0.6829208", "0.6820963", "0.6622024", "0.66144663", "0.65771437", "0.6571255", "0.6538782", "0.6514415", "0.649275", "0.6487715", "0.6423864", "0.6382977", "0.6378511", "0.6375695", "0.6354164", "0.6279711", "0.6216544", "0.6206103", "0.6188545", "0.6185154", "0.6157917", "0.6126276", "0.6034761", "0.5996919", "0.59891236", "0.5985719", "0.5928569", "0.59239376", "0.5916266", "0.59013855", "0.5881377", "0.5872121", "0.5853865", "0.5847975", "0.58300704", "0.58217466", "0.5819943", "0.5797668", "0.5779665", "0.57740396", "0.57688963", "0.57602584", "0.5754462", "0.5743651", "0.5731535", "0.5726882", "0.57251763", "0.57234627", "0.57214963", "0.5719666", "0.5707345", "0.57043594", "0.5701926", "0.5698077", "0.5692596", "0.5690169", "0.5684346", "0.5667135", "0.56328654", "0.5613473", "0.5610659", "0.56047237", "0.5587356", "0.55797553", "0.55725753", "0.55633724", "0.55369943", "0.55361146", "0.55329543", "0.5526428", "0.5524341", "0.5522868", "0.55206347", "0.55094945", "0.5499367", "0.5495099", "0.54839265", "0.5474906", "0.546403", "0.5460133", "0.54587007", "0.54532856", "0.54532254", "0.5449111", "0.5446488", "0.5445695", "0.5444409", "0.54415727", "0.54414415", "0.54346716", "0.5425554", "0.54250944", "0.5424923", "0.5420941", "0.54192525", "0.54136753" ]
0.57369286
48
sanitycheck passed env variables
func checkEnvironmentFlag(cmd *cobra.Command) (err error) { for i, env := range environment { e := strings.Split(env, "=") // error on empty flag or env name if len(e) == 0 || e[0] == "" { return fmt.Errorf("invalid env flag: '%s'", env) } // if only name given, get from os.Env if len(e) == 1 { environment[i] = fmt.Sprintf("%s=%s", e[0], os.Getenv(e[0])) } } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CheckEnvVars() {\n\tenvvars := []string{\"AWS_ACCESS_KEY_ID\", \"AWS_SECRET_ACCESS_KEY\", \"AWS_STORAGE_BUCKET_NAME\", \"AWS_CONFIG_FILE\", \"FETCH_ID\", \"FETCH_OFFSET\", \"FETCH_LIMIT\"}\n\tfor _, envvar := range envvars {\n\t\tif os.Getenv(envvar) == \"\" {\n\t\t\tpanic(fmt.Errorf(\"environment variable `%s` is missing or empty,\", envvar))\n\t\t}\n\t}\n}", "func Check() {\n\tvar missing []string\n\tfor _, key := range viper.GetStringSlice(\"env_var_names\") {\n\t\tif _, ok := os.LookupEnv(key); !ok {\n\t\t\tmissing = append(missing, key)\n\t\t}\n\t}\n\tif len(missing) > 0 {\n\t\tlog.Fatalf(\"CheckEnv(): missing the following environmental variables: \\n\\t%s\", strings.Join(missing, \"\\n\\t\"))\n\t}\n}", "func checkEnvVar(envVars *map[string]string) error {\n\tvar missingVars []string\n\tfor name, v := range *envVars {\n\t\tif v == \"\" {\n\t\t\tmissingVars = append(missingVars, name)\n\t\t}\n\t}\n\tif len(missingVars) > 0 {\n\t\treturn fmt.Errorf(\"Missing environment variables %v\", missingVars)\n\t}\n\treturn nil\n}", "func checkUpEnvironment() {\n\tPlatform = os.Getenv(\"K8S_PLATFORM\")\n\tK8sVersion = os.Getenv(\"K8S_VERSION\")\n\n\tExpect(os.Getenv(\"MCLI_ORG_ID\")).ShouldNot(BeEmpty(), \"Please, setup MCLI_ORG_ID environment variable\")\n\tExpect(os.Getenv(\"MCLI_PUBLIC_API_KEY\")).ShouldNot(BeEmpty(), \"Please, setup MCLI_PUBLIC_API_KEY environment variable\")\n\tExpect(os.Getenv(\"MCLI_PRIVATE_API_KEY\")).ShouldNot(BeEmpty(), \"Please, setup MCLI_PRIVATE_API_KEY environment variable\")\n\tExpect(os.Getenv(\"MCLI_OPS_MANAGER_URL\")).ShouldNot(BeEmpty(), \"Please, setup MCLI_OPS_MANAGER_URL environment variable\")\n\tmongocli.GetVersionOutput()\n}", "func checkEnvVars(id string, secret string) bool {\n\tvar envVarsExist bool = true\n\tif id == \"\" || secret == \"\" {\n\t\tenvVarsExist = false\n\t}\n\treturn envVarsExist\n}", "func CheckEnvVars(t *testing.T, envVars ...string) {\n\tvar missing []string\n\n\tfor _, envVar := range envVars {\n\t\tif os.Getenv(envVar) == \"\" {\n\t\t\tmissing = append(missing, envVar)\n\t\t}\n\t}\n\n\tif len(missing) > 0 {\n\t\trequire.FailNow(t, fmt.Sprintf(\"missing required AWS environment variables: %s\", missing))\n\t}\n}", "func CheckEnvVars() error {\n\n\tenvVars := []string{\n\t\t\"HUSKYCI_CLIENT_API_ADDR\",\n\t\t\"HUSKYCI_CLIENT_REPO_URL\",\n\t\t\"HUSKYCI_CLIENT_REPO_BRANCH\",\n\t\t// \"HUSKYCI_CLIENT_TOKEN\", (optional for now)\n\t\t// \"HUSKYCI_CLIENT_API_USE_HTTPS\", (optional)\n\t\t// \"HUSKYCI_CLIENT_NPM_DEP_URL\", (optional)\n\t}\n\n\tvar envIsSet bool\n\tvar allEnvIsSet bool\n\tvar errorString string\n\n\tenv := make(map[string]string)\n\tallEnvIsSet = true\n\tfor i := 0; i < len(envVars); i++ {\n\t\tenv[envVars[i]], envIsSet = os.LookupEnv(envVars[i])\n\t\tif !envIsSet {\n\t\t\terrorString = errorString + envVars[i] + \" \"\n\t\t\tallEnvIsSet = false\n\t\t}\n\t}\n\tif !allEnvIsSet {\n\t\treturn errors.New(errorString)\n\t}\n\treturn nil\n}", "func mustGetenv(k string) string {\n\tv := os.Getenv(k)\n\tif v == \"\" {\n\t\tlog.Fatalf(\"Warning: %s environment variable not set.\\n\", k)\n\t}\n\treturn v\n}", "func mustGetenv(k string) string {\n\tv := os.Getenv(k)\n\tif v == \"\" {\n\t\tlog.Fatalf(\"Warning: %s environment variable not set.\\n\", k)\n\t}\n\treturn v\n}", "func checkEnv(envVar string) string {\n\tv := os.Getenv(envVar)\n\tif v == \"\" {\n\t\tlog.Panicf(\"%s environment variable not set.\", envVar)\n\t}\n\treturn v\n}", "func verifyEnvironment() error {\n\n\tif os.Getenv(\"GCP_CREDENTIALS_PATH\") == \"\" {\n\t\t// set default\n\t\tos.Setenv(\"GCP_CREDENTIALS_PATH\", \"./.secrets/strucim-gateway-keys.json\")\n\t}\n\n\t_, err := os.Stat(os.Getenv(\"GCP_CREDENTIALS_PATH\"))\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tlog.Println(\"Google credentials file not found\")\n\t\t}\n\t\treturn err\n\t}\n\n\tif os.Getenv(\"GATEWAY_ENDPOINT\") == \"\" {\n\t\tos.Setenv(\"GATEWAY_ENDPOINT\", \":8080\")\n\t}\n\n\tif os.Getenv(\"IDENTIFY_BUCKET\") == \"\" {\n\t\tos.Setenv(\"IDENTIFY_BUCKET\", \"pointcloud-identification\")\n\t}\n\n\tif os.Getenv(\"IDENTIFY_POINTCLOUD_TOPIC\") == \"\" {\n\t\tos.Setenv(\"IDENTIFY_POINTCLOUD_TOPIC\", \"identify-request\")\n\t}\n\n\tif os.Getenv(\"IDENTIFY_POINTCLOUD_STATUS_TOPIC\") == \"\" {\n\t\tos.Setenv(\"IDENTIFY_POINTCLOUD_STATUS_TOPIC\", \"identify-status\")\n\t}\n\n\treturn nil\n}", "func checkArguments() {\n\tif len(dockerRegistryUrl) == 0 {\n\t\tlog.Fatalln(\"Environment Variable 'DOCKER_REGISTRY_URL' not set\")\n\t}\n\n\tif len(replaceRegistryUrl) == 0 {\n\t\tlog.Fatalln(\"Environment Variable 'REPLACE_REGISTRY_URL' not set\")\n\t}\n\n\t_, err := strconv.ParseBool(replaceRegistryUrl)\n\tif err != nil {\n\t\tlog.Fatalln(\"Invalid Value in Environment Variable 'REPLACE_REGISTRY_URL'\")\n\t}\n}", "func validateAndGetEnvVars() (*environmentVariables, error) {\n\tenvVars := &environmentVariables{}\n\tuploadAPIURL := os.Getenv(\"UPLOAD_API_URL\")\n\tif len(uploadAPIURL) == 0 {\n\t\treturn nil, errors.Errorf(\"UPLOAD_API_URL environment variable is not set\")\n\t}\n\tenvVars.UploadAPIURL = uploadAPIURL\n\n\tpostAPIURL := os.Getenv(\"POST_API_URL\")\n\tif len(postAPIURL) == 0 {\n\t\treturn nil, errors.Errorf(\"POST_API_URL environment variable is not set\")\n\t}\n\tenvVars.PostAPIURL = postAPIURL\n\n\tmattermostDeployments := os.Getenv(\"MATTERMOST_DEPLOYMENTS\")\n\tif len(mattermostDeployments) == 0 {\n\t\tenvVars.MattermostDeployments = []string{}\n\t} else {\n\t\tenvVars.MattermostDeployments = strings.Split(mattermostDeployments, \",\")\n\t}\n\n\tmattermostNamespace := os.Getenv(\"MATTERMOST_NAMESPACE\")\n\tif len(mattermostNamespace) == 0 {\n\t\treturn nil, errors.Errorf(\"CHANNEL_ID environment variable is not set.\")\n\t}\n\tenvVars.MattermostNamespace = mattermostNamespace\n\n\tprofilingTime := os.Getenv(\"PROFILING_TIME\")\n\tif len(profilingTime) == 0 {\n\t\treturn nil, errors.Errorf(\"PROFILING_TIME environment variable is not set.\")\n\t}\n\tenvVars.ProfilingTime = profilingTime\n\n\tchannelID := os.Getenv(\"CHANNEL_ID\")\n\tif len(channelID) == 0 {\n\t\treturn nil, errors.Errorf(\"CHANNEL_ID environment variable is not set.\")\n\t}\n\tenvVars.ChannelID = channelID\n\n\ttoken := os.Getenv(\"TOKEN\")\n\tif len(token) == 0 {\n\t\treturn nil, errors.Errorf(\"TOKEN environment variable is not set.\")\n\t}\n\tenvVars.Token = token\n\n\tdeveloperMode := os.Getenv(\"DEVELOPER_MODE\")\n\tif len(developerMode) == 0 {\n\t\tenvVars.DevMode = \"false\"\n\t} else {\n\t\tenvVars.DevMode = developerMode\n\t}\n\n\treturn envVars, nil\n}", "func EnsureENVSet() (ok bool, missing string) {\n\n\t// Ports for queues and DB\n\tReportQueuePort := os.Getenv(\"REPORT_QUEUE_PORT\")\n\tNotifierQueuePort := os.Getenv(\"NOTIFIER_QUEUE_PORT\")\n\tESPort := os.Getenv(\"ES_PORT\")\n\n\t// AWS\n\tS3Region := os.Getenv(\"S3_REGION\")\n\tS3Bucket := os.Getenv(\"S3_BUCKET\")\n\tAWSAccessKeyID := os.Getenv(\"AWS_ACCESS_KEY_ID\")\n\tAWSSecretAccessKey := os.Getenv(\"AWS_SECRET_ACCESS_KEY\")\n\n\tif ReportQueuePort == \"\" {\n\t\treturn false, \"Report Queue Port\"\n\t}\n\n\tif NotifierQueuePort == \"\" {\n\t\treturn false, \"Notifier Queue Port\"\n\t}\n\n\tif ESPort == \"\" {\n\t\treturn false, \"Elasticsearch Port\"\n\t}\n\n\tif S3Region == \"\" {\n\t\treturn false, \"S3 Region\"\n\t}\n\n\tif S3Bucket == \"\" {\n\t\treturn false, \"S3 Bucket\"\n\t}\n\n\tif AWSAccessKeyID == \"\" {\n\t\treturn false, \"AWS Access Key ID\"\n\t}\n\n\tif AWSSecretAccessKey == \"\" {\n\t\treturn false, \"AWS Secret Access Key\"\n\t}\n\n\treturn true, \"\"\n}", "func validateEnv() (err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t_, err = utils.MultiErrorList(err)\n\t\t\terr = fmt.Errorf(\"invalid environment: %w\", err)\n\t\t}\n\t}()\n\tfor _, kv := range strings.Split(emptyStringsEnv, \"\\n\") {\n\t\tif strings.TrimSpace(kv) == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\ti := strings.Index(kv, \"=\")\n\t\tif i == -1 {\n\t\t\treturn errors.Errorf(\"malformed .env file line: %s\", kv)\n\t\t}\n\t\tk := kv[:i]\n\t\t_, ok := os.LookupEnv(k)\n\t\tif ok {\n\t\t\terr = multierr.Append(err, fmt.Errorf(\"environment variable %s must not be set: %v\", k, v2.ErrUnsupported))\n\t\t}\n\t}\n\treturn\n}", "func mustGetenv(name string) string {\n\tvalue := os.Getenv(name)\n\tif value == \"\" {\n\t\tpanic(name + \" not defined in environment\")\n\t}\n\treturn value\n}", "func checkRequiredKubeEnvVars(t *testing.T) {\n\tt.Helper()\n\tmustGetEnv(t, awsRegionEnv)\n\tmustGetEnv(t, kubeSvcRoleARNEnv)\n\tmustGetEnv(t, kubeDiscoverySvcRoleARNEnv)\n\tmustGetEnv(t, eksClusterNameEnv)\n}", "func validateVariable(value string, envName string) {\n\tif len(value) == 0 {\n\t\tlog.Printf(\"The environment variable %s has not been set\", envName)\n\t} else {\n\t\tlog.Printf(\"The environment variable %s is %s\", envName, value)\n\t}\n}", "func TestEnvironment(t *testing.T) {\n\tvariables := []string{\n\t\t\"MONGO_URI\",\n\t\t\"SECRET_KEY\",\n\t\t\"MAGIC_LINK\",\n\t\t\"ROOT_LINK\",\n\t\t\"GITHUB_API\",\n\t\t\"GITHUB_OAUTH\",\n\t\t\"GITHUB_ORG\",\n\t\t\"DEBRICKED_API\",\n\t\t\"DEBRICKED_USER\",\n\t\t\"DEBRICKED_PASS\",\n\t}\n\tfor e := range variables {\n\t\tif _, present := os.LookupEnv(variables[e]); !present {\n\t\t\tt.Errorf(\"Expected environment variable %s to be set\", variables[e])\n\t\t}\n\t}\n}", "func validateEnvironmentVariables(command *exec.Cmd) {\n\n\tif command.Path == appconfig.PowerShellPluginCommandName {\n\t\tenv := command.Env\n\t\tenv = append(env, fmtEnvVariable(\"HOME\", \"/\"))\n\t\ti := 0\n\t\tfor _, a := range env {\n\t\t\tif strings.Contains(a, \"TERM\") {\n\t\t\t\tif i == len(env)-1 {\n\t\t\t\t\tenv = env[:i]\n\t\t\t\t} else {\n\t\t\t\t\tenv = append(env[:i], env[i+1:]...)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t\tcommand.Env = env\n\t}\n}", "func ensureAtLeastOne(keys []string) bool {\n\tfor _, varName := range keys {\n\t\tif _, found := os.LookupEnv(varName); found {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func EnsureENVSet() (ok bool) {\n\tNotifierPort := os.Getenv(\"NOTIFIER_QUEUE_PORT\")\n\tSendGridAPIKey := os.Getenv(\"SENDGRID_API_KEY\")\n\n\tif NotifierPort == \"\" || SendGridAPIKey == \"\" {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func EnsureEnvVars(vars ...BuildVar) error {\n\tmissingVars := make([]BuildVar, 0)\n\tfor _, v := range vars {\n\t\tif os.Getenv(string(v)) == \"\" {\n\t\t\tmissingVars = append(missingVars, v)\n\t\t}\n\t}\n\tif len(missingVars) > 0 {\n\t\treturn errors.Errorf(\"the following environment variables are missing: %v\", missingVars)\n\t}\n\treturn nil\n}", "func CheckAWSEnvVars(t *testing.T) {\n\tCheckEnvVars(t,\n\t\t\"AWS_ACCESS_KEY\",\n\t\t\"AWS_SECRET_ACCESS_KEY\",\n\t\t\"AWS_ROLE\",\n\t\t\"AWS_REGION\",\n\t)\n}", "func assertEnv(ctx context.Context, client client.Client, spec corev1.PodSpec, component, container, key, expectedValue string) error {\n\tvalue, err := getEnv(ctx, client, spec, component, container, key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif value != nil && strings.ToLower(*value) != expectedValue {\n\t\treturn ErrIncompatibleCluster{\n\t\t\terr: fmt.Sprintf(\"%s=%s is not supported\", key, *value),\n\t\t\tcomponent: component,\n\t\t\tfix: fmt.Sprintf(\"remove the %s env var or set it to '%s'\", key, expectedValue),\n\t\t}\n\t}\n\n\treturn nil\n}", "func mustGetEnv(t *testing.T, key string) string {\n\tt.Helper()\n\tval := os.Getenv(key)\n\trequire.NotEmpty(t, val, \"%s environment variable must be set and not empty\", key)\n\treturn val\n}", "func checkRequired() {\n\tdefer func() {\n\t\tif perr := recover(); perr != nil {\n\t\t\tvar ok bool\n\t\t\tperr, ok = perr.(error)\n\t\t\tif !ok {\n\t\t\t\tfmt.Errorf(\"Panicking: %v\", perr)\n\t\t\t}\n\t\t}\n\t}()\n\tfor _, req := range required {\n\t\tif os.Getenv(req) == \"\" {\n\t\t\tmissingRequiredValue(req)\n\t\t}\n\t}\n}", "func mustEnv(key string, value *string, defaultVal string) {\r\n\tif *value = os.Getenv(key); *value == \"\" {\r\n\t\t*value = defaultVal\r\n\t\tfmt.Printf(\"%s env variable not set, using default value.\\n\", key)\r\n\t}\r\n}", "func getenvRequired(key string) string {\n\tvalue := os.Getenv(key)\n\tif value == \"\" {\n\t\tPtEnvError(fmt.Sprintf(\"no %s environment variable\", key))\n\t}\n\treturn value\n}", "func mustGetEnv(name string) string {\n\tenv, ok := os.LookupEnv(name)\n\tif !ok {\n\t\tlog.WithField(\"env\", name).Fatalf(\"missing required environment variable for configuration\")\n\t}\n\tlog.WithField(name, env).Info(\"using env variable\")\n\treturn env\n}", "func CheckEnv(lookupFunc func(key string) (string, bool)) (err error) {\n\tif lookupFunc == nil {\n\t\tlookupFunc = os.LookupEnv\n\t}\n\n\tenvVars := [4]string{\n\t\tEnvHueBridgeAddress,\n\t\tEnvHueBridgeUsername,\n\t\tEnvHueRemoteToken,\n\t\tEnvRedisURL,\n\t}\n\n\tfor _, v := range envVars {\n\t\tif _, ok := lookupFunc(v); !ok {\n\t\t\treturn models.NewMissingEnvError(v)\n\t\t}\n\t}\n\n\treturn nil\n}", "func VerifyEnvironment() {\n\tfor _, envVarNames := range envVariables {\n\t\tif _, ok := os.LookupEnv(envVar); !ok {\n\t\t\tlog.Fatalf(\"Missing environment variable: %s\\n\", envVar)\n\t\t}\n\t}\n}", "func assertEnvIsSet(ctx context.Context, client client.Client, spec corev1.PodSpec, component, container, key, expectedValue string) error {\n\tvalue, err := getEnv(ctx, client, spec, component, container, key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif value == nil || strings.ToLower(*value) != expectedValue {\n\t\treturn ErrIncompatibleCluster{\n\t\t\terr: fmt.Sprintf(\"%s=%s is not supported\", key, *value),\n\t\t\tcomponent: component,\n\t\t\tfix: fmt.Sprintf(\"remove the %s env var or set it to '%s'\", key, expectedValue),\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestValidGetEnvValueForField3(t *testing.T) {\n\tosGetenv = mockInvalidOsGetenv\n\n\tif _, err := getEnvValueForField(\"$ENV_VAR\"); err == nil {\n\t\tt.Errorf(\"Invalid Hostname Returned No Error\")\n\t}\n}", "func CheckEnvironment(env string) {\n\t// Compare and validate environments\n\tif !IsValid(env) {\n\t\tpanic(\"JUS_ENVIRONMENT not setted!\\n\" +\n\t\t\t\"To correct this, run this command in your terminal: export JUS_ENVIRONMENT=developer\\n\" +\n\t\t\t\"Available environments: developer, sandbox, production, test\")\n\t}\n}", "func env() error {\n\t// regexp for TF_VAR_ terraform vars\n\ttfVar := regexp.MustCompile(`^TF_VAR_.*$`)\n\n\t// match terraform vars in environment\n\tfor _, e := range os.Environ() {\n\t\t// split on value\n\t\tpair := strings.SplitN(e, \"=\", 2)\n\n\t\t// match on TF_VAR_*\n\t\tif tfVar.MatchString(pair[0]) {\n\t\t\t// pull out the name\n\t\t\tname := strings.Split(pair[0], \"TF_VAR_\")\n\n\t\t\t// lower case the terraform variable\n\t\t\t// to accommodate cicd injection capitalization\n\t\t\terr := os.Setenv(fmt.Sprintf(\"TF_VAR_%s\",\n\t\t\t\tstrings.ToLower(name[1])), pair[1])\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}", "func RequireEnv(s string) string {\n\tv := os.Getenv(s)\n\tif v == \"\" {\n\t\tlog.Fatalf(\"missing required environment variable %q\", s)\n\t}\n\treturn v\n}", "func MustGetEnvs(variables ...string) []string {\n\tvar values []string\n\tfor _, v := range variables {\n\t\tval := os.Getenv(v)\n\t\tif v == \"\" {\n\t\t\tlog.Panicf(\"%v environment variable not set.\", val)\n\t\t}\n\t\tvalues = append(values, val)\n\t}\n\treturn values\n}", "func safeEnvs() []string {\n\tenvs := os.Environ()\n\tenvs = append(envs, \"BORG_PASSPHRASE=\", \"BORG_REPO=\")\n\treturn envs\n}", "func validateEnv(vars []corev1.EnvVar, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i, ev := range vars {\n\t\tidxPath := fldPath.Index(i)\n\t\tif len(ev.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"name\"), \"\"))\n\t\t} else {\n\t\t\tfor _, msg := range validation.IsEnvVarName(ev.Name) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"name\"), ev.Name, msg))\n\t\t\t}\n\t\t}\n\t\tallErrs = append(allErrs, validateEnvVarValueFrom(ev, idxPath.Child(\"valueFrom\"))...)\n\t}\n\treturn allErrs\n}", "func requireEnv(envVar string) string {\n\tval, _ := getEnv(envVar, true)\n\treturn val\n}", "func (rg *reportGenerator) getRequiredEnv() {\n\tenv := map[string]string{}\n\n\tenv[projectUsernameKey] = os.Getenv(projectUsernameKey)\n\tenv[projectRepoNameKey] = os.Getenv(projectRepoNameKey)\n\tenv[jobNameKey] = os.Getenv(jobNameKey)\n\tenv[githubAPITokenKey] = os.Getenv(githubAPITokenKey)\n\n\tfor k, v := range env {\n\t\tif v == \"\" {\n\t\t\trg.logger.Fatal(\n\t\t\t\t\"Required environment variable not set\",\n\t\t\t\tzap.String(\"env_var\", k),\n\t\t\t)\n\t\t}\n\t}\n\n\trg.envVariables = env\n}", "func (c *Comic) checkRequiredVars(commandName string) error {\n\tfor _, varName := range c.getRequiredVarNames(commandName) {\n\t\tif !c.vip.IsSet(varName) {\n\t\t\treturn fmt.Errorf(\"config not present: %s\", varName)\n\t\t}\n\t}\n\n\treturn nil\n}", "func CheckAWSEnvVarsForECS(t *testing.T) {\n\tCheckEnvVars(t,\n\t\t\"AWS_ACCESS_KEY\",\n\t\t\"AWS_SECRET_ACCESS_KEY\",\n\t\t\"AWS_ROLE\",\n\t\t\"AWS_REGION\",\n\t\t\"AWS_ECS_CLUSTER\",\n\t\t\"AWS_ECS_TASK_DEFINITION_PREFIX\",\n\t\t\"AWS_ECS_TASK_ROLE\",\n\t\t\"AWS_ECS_EXECUTION_ROLE\",\n\t)\n}", "func CheckDotEnv() {\n\terr := godotenv.Load()\n\tif err != nil && os.Getenv(env) == local {\n\t\tlog.Println(\"Error loading .env file\")\n\t}\n}", "func getRequiredEnv(name string) string {\n\tval := os.Getenv(name)\n\tif val == \"\" {\n\t\tlog.Fatalf(\"Missing required environment variable %s\\n\", name)\n\t}\n\treturn val\n}", "func reqEnv(name string) string {\n\tval := os.Getenv(name)\n\tif len(val) == 0 {\n\t\tlog.Fatalf(\"no %s environment variable set\", name)\n\t}\n\treturn val\n}", "func CheckAWSEnvVarsForECSAndSecretsManager(t *testing.T) {\n\tCheckEnvVars(t,\n\t\t\"AWS_ACCESS_KEY\",\n\t\t\"AWS_SECRET_ACCESS_KEY\",\n\t\t\"AWS_ROLE\",\n\t\t\"AWS_REGION\",\n\t\t\"AWS_ECS_CLUSTER\",\n\t\t\"AWS_SECRET_PREFIX\",\n\t\t\"AWS_ECS_TASK_DEFINITION_PREFIX\",\n\t\t\"AWS_ECS_TASK_ROLE\",\n\t\t\"AWS_ECS_EXECUTION_ROLE\",\n\t)\n}", "func Check(env string) error {\n\tswitch env {\n\tcase Testing, Development, Staging, Production:\n\t\treturn nil\n\tdefault:\n\t\treturn errors.Errorf(\"invalid: %s\", env)\n\t}\n\n}", "func TestEnvVars(t *testing.T) {\n\t// Arrange\n\tos.Setenv(snapEnv, \"/snap/testsnap/x1\")\n\tos.Setenv(snapCommonEnv, \"/snap/testsnap/common\")\n\tos.Setenv(snapDataEnv, \"/var/snap/testsnap/x1\")\n\tos.Setenv(snapInstNameEnv, \"testsnap\")\n\tos.Setenv(snapRevEnv, \"2112\")\n\n\t// Test\n\terr := getEnvVars()\n\n\t// Assert values\n\tassert.Nil(t, err)\n\tassert.Equal(t, Snap, \"/snap/testsnap/x1\")\n\tassert.Equal(t, SnapCommon, \"/snap/testsnap/common\")\n\tassert.Equal(t, SnapData, \"/var/snap/testsnap/x1\")\n\tassert.Equal(t, SnapInst, \"testsnap\")\n\tassert.Equal(t, SnapRev, \"2112\")\n\tassert.Equal(t, SnapConf, \"/snap/testsnap/x1/config\")\n\tassert.Equal(t, SnapDataConf, \"/var/snap/testsnap/x1/config\")\n}", "func checkEnvForDebug() bool {\n\treturn os.Getenv(legacyDebugVar) != \"\"\n}", "func (r *CheckedDaemonSet) assertEnv(ctx context.Context, client client.Client, container, key, expectedValue string) error {\n\tif err := assertEnv(ctx, client, r.Spec.Template.Spec, ComponentCalicoNode, container, key, expectedValue); err != nil {\n\t\treturn err\n\t}\n\tr.ignoreEnv(container, key)\n\treturn nil\n}", "func CheckAWSEnvVarsForSecretsManager(t *testing.T) {\n\tCheckEnvVars(t,\n\t\t\"AWS_ACCESS_KEY\",\n\t\t\"AWS_SECRET_ACCESS_KEY\",\n\t\t\"AWS_SECRET_PREFIX\",\n\t\t\"AWS_ROLE\",\n\t\t\"AWS_REGION\",\n\t)\n}", "func MustGetEnv(key string) string {\n\tvalue := os.Getenv(key)\n\tif value == \"\" {\n\t\tLogFail(fmt.Sprintf(\"%s not set!\", key))\n\t}\n\treturn value\n}", "func TestValidGetEnvValueForField(t *testing.T) {\n\tosHostname = mockValidOsHostname\n\tosGetenv = mockValidOsGetenv\n\n\tfor _, dataToCheck := range []string{\"$HOSTNAME\", \"$ENV_VAR\", \"test_value\"} {\n\t\tcheckedData, err := getEnvValueForField(dataToCheck)\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error Encountered Getting Env Value For Field: %s\", err.Error())\n\t\t}\n\n\t\tif checkedData != \"test_value\" {\n\t\t\tt.Errorf(\"Value Does Not Match 'test_value': %s\", checkedData)\n\t\t}\n\t}\n\n}", "func ValidateEnv(val string) (string, error) {\n\tarr := strings.Split(val, \"=\")\n\tif arr[0] == \"\" {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"invalid environment variable: %s\", val))\n\t}\n\tif len(arr) > 1 {\n\t\treturn val, nil\n\t}\n\tif !doesEnvExist(val) {\n\t\treturn val, nil\n\t}\n\treturn fmt.Sprintf(\"%s=%s\", val, os.Getenv(val)), nil\n}", "func sanityCheck() error {\n\t_, err := os.Stat(\"/opt/delivery\")\n\tif os.IsNotExist(err) {\n\t\treturn nil\n\t}\n\n\t_, err = os.Stat(\"/opt/delivery/.created-by-a2-self-test\")\n\tif os.IsNotExist(err) {\n\t\treturn errors.New(\"self test upgrade mode cannot be run on a system with Chef Automate v1\")\n\t}\n\n\treturn err\n}", "func getEnvRequired(envVar string) string {\n\tval := strings.TrimSpace(os.Getenv(envVar))\n\n\tif val == \"\" {\n\t\tlog.Fatalf(\"required environmental variable %q not set, exiting.\", envVar)\n\t}\n\n\tlog.Debugf(\"%s set to: %s\", envVar, val)\n\n\treturn val\n}", "func getRequiredEnv(key string) string {\n\tvalue, exists := os.LookupEnv(key)\n\tif !exists {\n\t\tlogrus.Fatalf(\"Environment variable not set: %s\", key)\n\t}\n\treturn value\n}", "func RequiredEnvs(envvars ...string) (string, error) {\n\tfor _, envvar := range envvars {\n\t\tif _, defined := os.LookupEnv(envvar); !defined {\n\t\t\treturn \"\", fmt.Errorf(\"required environmental variable missing: ${%s}\", envvar)\n\t\t}\n\t}\n\treturn \"\", nil\n}", "func checkInputVars() {\n\n\tvar err error\n\n\t_, err = url.ParseRequestURI(swiftAuthUrl)\n\tif err != nil {\n\t\tlog.Fatalf(\"Wrong or empty URL for Swift Endpoint: %s \\n\", err.Error())\n\t}\n\n\tif swiftUserName == \"\" {\n\t\tlogFatalfwithUsage(\"Empty username for Swift login!\\n\")\n\t}\n\n\tif swiftPassword == \"\" {\n\t\tlogFatalfwithUsage(\"Empty password for Swift login!\\n\")\n\t}\n\n}", "func TestAccPreCheck(t *testing.T, additionalEnvVars *[]string) {\n\trequiredEnvVars := []string{\n\t\t\"AZDO_ORG_SERVICE_URL\",\n\t\t\"AZDO_PERSONAL_ACCESS_TOKEN\",\n\t}\n\tif additionalEnvVars != nil {\n\t\trequiredEnvVars = append(requiredEnvVars, *additionalEnvVars...)\n\t}\n\n\tfor _, variable := range requiredEnvVars {\n\t\tif os.Getenv(variable) == \"\" {\n\t\t\tt.Fatalf(\"`%s` must be set for acceptance tests!\", variable)\n\t\t}\n\t}\n}", "func testGetenv(s string) string {\n\tswitch s {\n\tcase \"*\":\n\t\treturn \"all the args\"\n\tcase \"#\":\n\t\treturn \"NARGS\"\n\tcase \"$\":\n\t\treturn \"PID\"\n\tcase \"1\":\n\t\treturn \"ARGUMENT1\"\n\tcase \"HOME\":\n\t\treturn \"/usr/gopher\"\n\tcase \"H\":\n\t\treturn \"(Value of H)\"\n\tcase \"home_1\":\n\t\treturn \"/usr/foo\"\n\tcase \"_\":\n\t\treturn \"underscore\"\n\t}\n\treturn \"\"\n}", "func EnsureIntegrationEnvironment(t *testing.T) {\n\tif os.Getenv(\"AKV2K8S_CLIENT_ID\") == \"\" {\n\t\tt.Skip(\"Skipping integration test - no credentials\")\n\t}\n\n\tos.Setenv(\"AZURE_CLIENT_ID\", os.Getenv(\"AKV2K8S_CLIENT_ID\"))\n\tos.Setenv(\"AZURE_CLIENT_SECRET\", os.Getenv(\"AKV2K8S_CLIENT_SECRET\"))\n\tos.Setenv(\"AZURE_TENANT_ID\", os.Getenv(\"AKV2K8S_CLIENT_TENANT_ID\"))\n\tos.Setenv(\"AZURE_SUBSCRIPTION_ID\", os.Getenv(\"AKV2K8S_AZURE_SUBSCRIPTION_ID\"))\n}", "func TestExists(t *testing.T) {\r\n\tt.Log(\"Given the need to read environment variables.\")\r\n\t{\r\n\t\tuStr := \"postgres://root:[email protected]:8080/postgres?sslmode=disable\"\r\n\r\n\t\tos.Setenv(\"MYAPP_PROC_ID\", \"322\")\r\n\t\tos.Setenv(\"MYAPP_SOCKET\", \"./tmp/sockets.po\")\r\n\t\tos.Setenv(\"MYAPP_PORT\", \"4034\")\r\n\t\tos.Setenv(\"MYAPP_FLAG\", \"true\")\r\n\t\tos.Setenv(\"MYAPP_DSN\", uStr)\r\n\r\n\t\tcfg.Init(\"MYAPP\")\r\n\r\n\t\tt.Log(\"\\tWhen given a namspace key to search for that exists.\")\r\n\t\t{\r\n\t\t\tproc, err := cfg.Int(\"PROC_ID\")\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tt.Errorf(\"\\t\\t%s Should not return error when valid key %q\", failed, \"PROC_ID\")\r\n\t\t\t} else {\r\n\t\t\t\tt.Logf(\"\\t\\t%s Should not return error when valid key %q\", succeed, \"PROC_ID\")\r\n\r\n\t\t\t\tif proc != 322 {\r\n\t\t\t\t\tt.Errorf(\"\\t\\t%s Should have key %q with value %d\", failed, \"PROC_ID\", 322)\r\n\t\t\t\t} else {\r\n\t\t\t\t\tt.Logf(\"\\t\\t%s Should have key %q with value %d\", succeed, \"PROC_ID\", 322)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tsocket, err := cfg.String(\"SOCKET\")\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tt.Errorf(\"\\t\\t%s Should not return error when valid key %q\", failed, \"SOCKET\")\r\n\t\t\t} else {\r\n\t\t\t\tt.Logf(\"\\t\\t%s Should not return error when valid key %q\", succeed, \"SOCKET\")\r\n\r\n\t\t\t\tif socket != \"./tmp/sockets.po\" {\r\n\t\t\t\t\tt.Errorf(\"\\t\\t%s Should have key %q with value %q\", failed, \"SOCKET\", \"./tmp/sockets.po\")\r\n\t\t\t\t} else {\r\n\t\t\t\t\tt.Logf(\"\\t\\t%s Should have key %q with value %q\", succeed, \"SOCKET\", \"./tmp/sockets.po\")\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tport, err := cfg.Int(\"PORT\")\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tt.Errorf(\"\\t\\t%s Should not return error when valid key %q\", failed, \"PORT\")\r\n\t\t\t} else {\r\n\t\t\t\tt.Logf(\"\\t\\t%s Should not return error when valid key %q\", succeed, \"PORT\")\r\n\r\n\t\t\t\tif port != 4034 {\r\n\t\t\t\t\tt.Errorf(\"\\t\\t%s Should have key %q with value %d\", failed, \"PORT\", 4034)\r\n\t\t\t\t} else {\r\n\t\t\t\t\tt.Logf(\"\\t\\t%s Should have key %q with value %d\", succeed, \"PORT\", 4034)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tflag, err := cfg.Bool(\"FLAG\")\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tt.Errorf(\"\\t\\t%s Should not return error when valid key %q\", failed, \"FLAG\")\r\n\t\t\t} else {\r\n\t\t\t\tt.Logf(\"\\t\\t%s Should not return error when valid key %q\", succeed, \"FLAG\")\r\n\r\n\t\t\t\tif flag == false {\r\n\t\t\t\t\tt.Errorf(\"\\t\\t%s Should have key %q with value %v\", failed, \"FLAG\", true)\r\n\t\t\t\t} else {\r\n\t\t\t\t\tt.Logf(\"\\t\\t%s Should have key %q with value %v\", succeed, \"FLAG\", true)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tu, err := cfg.URL(\"DSN\")\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tt.Errorf(\"\\t\\t%s Should not return error when valid key %q\", failed, \"DSN\")\r\n\t\t\t} else {\r\n\t\t\t\tt.Logf(\"\\t\\t%s Should not return error when valid key %q\", succeed, \"DSN\")\r\n\r\n\t\t\t\tif u.String() != uStr {\r\n\t\t\t\t\tt.Errorf(\"\\t\\t%s Should have key %q with value %v\", failed, \"DSN\", true)\r\n\t\t\t\t} else {\r\n\t\t\t\t\tt.Logf(\"\\t\\t%s Should have key %q with value %v\", succeed, \"DSN\", true)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func checkOptional() {\n\tdefer func() {\n\t\tif perr := recover(); perr != nil {\n\t\t\tvar ok bool\n\t\t\tperr, ok = perr.(error)\n\t\t\tif !ok {\n\t\t\t\tfmt.Errorf(\"Panicking: %v\", perr)\n\t\t\t}\n\t\t}\n\t}()\n\tfor _, req := range optional {\n\t\tif os.Getenv(req) == \"\" {\n\t\t\tmissingOptionalValue(req)\n\t\t}\n\t}\n}", "func checkEnv() bool {\n\n\tfmt.Println(\"Checking for tsc, node, (npm or yarn) installations.\")\n\n\tvar missing []string\n\t_, errTsc := searchCommand(\"tsc\")\n\tif errTsc != nil {\n\t\tmissing = append(missing, \"tsc: TypeScript compiler. Please install tsc.\")\n\t}\n\t_, errNode := searchCommand(\"node\")\n\tif errNode != nil {\n\t\tmissing = append(missing, \"node: JavaScript runtime environment. Please install node.\")\n\t}\n\t_, errNpm := searchCommand(\"npm\")\n\t_, errYarn := searchCommand(\"yarn\")\n\tif errNpm != nil && errYarn != nil {\n\t\tmissing = append(missing, \"npm or yarn: JavaScript package managers. Please install one or the other.\")\n\t}\n\tif len(missing) > 0 {\n\t\tfmt.Println(\"Missing possible installations\")\n\t\tfor _, msg := range missing {\n\t\t\tfmt.Println(msg)\n\t\t}\n\t\treturn true\n\t} else {\n\t\tfmt.Println(\"Looks good!\")\n\t\treturn false\n\t}\n}", "func validateConfig() {\n\tif viper.Get(\"project\") == \"\" {\n\t\tlog.Fatal(\"Error: --project is required\")\n\t}\n\tif viper.Get(\"region\") == \"\" {\n\t\tlog.Fatal(\"Error: --region is required, e.g. us-west1\")\n\t}\n}", "func MustGetEnv(name string) string {\n\tvalue, found := os.LookupEnv(name)\n\tif !found {\n\t\tlog.Fatalf(\"environment variable %s is missing\", name)\n\t}\n\treturn value\n}", "func EnvVarTest(resourceName string, sourceType string, envString string) {\n\n\tif sourceType == \"git\" {\n\t\t// checking the values of the env vars pairs in bc\n\t\tenvVars := runCmd(\"oc get bc \" + resourceName + \" -o go-template='{{range .spec.strategy.sourceStrategy.env}}{{.name}}{{.value}}{{end}}'\")\n\t\tExpect(envVars).To(Equal(envString))\n\t}\n\n\t// checking the values of the env vars pairs in dc\n\tenvVars := runCmd(\"oc get dc \" + resourceName + \" -o go-template='{{range .spec.template.spec.containers}}{{range .env}}{{.name}}{{.value}}{{end}}{{end}}'\")\n\tExpect(envVars).To(Equal(envString))\n}", "func MustGetenv(varname string, defaultValue string) string {\n\tlog.Debugf(\"Reading environment variable %v\", varname)\n\n\tvalue := os.Getenv(varname)\n\tif value == \"\" {\n\t\tif defaultValue == \"\" {\n\t\t\tlog.Fatalf(\"Missing env variable %v\", varname)\n\t\t}\n\t\tvalue = defaultValue\n\t}\n\n\treturn value\n}", "func (ev Vars) MustVars(keys ...string) {\n\tfor _, key := range keys {\n\t\tif !ev.HasVar(key) {\n\t\t\tpanic(fmt.Sprintf(\"the following environment variables are required: `%s`\", strings.Join(keys, \",\")))\n\t\t}\n\t}\n}", "func MustGetenv(varname string) string {\n\tvalue := os.Getenv(varname)\n\tif value == \"\" {\n\t\tpanic(fmt.Errorf(\"Missing env variable %v\", varname))\n\t}\n\n\treturn value\n}", "func validateEmptyPipEnv(t *testing.T) {\n\t//pipFreezeCmd := &PipFreezeCmd{Executable: \"pip\", Command: \"freeze\"}\n\tpipFreezeCmd := &PipCmd{Command: \"freeze\", Options: []string{\"--local\"}}\n\tout, err := gofrogcmd.RunCmdOutput(pipFreezeCmd)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif out != \"\" {\n\t\tt.Fatalf(\"Provided pip virtual-environment contains installed packages: %s\\n. Please provide a clean environment.\", out)\n\t}\n}", "func (r *CheckedDaemonSet) assertEnvIsSet(ctx context.Context, client client.Client, container, key, expectedValue string) error {\n\tif err := assertEnvIsSet(ctx, client, r.Spec.Template.Spec, ComponentCalicoNode, container, key, expectedValue); err != nil {\n\t\treturn err\n\t}\n\tr.ignoreEnv(container, key)\n\treturn nil\n}", "func TestValidGetEnvValueForField2(t *testing.T) {\n\tosHostname = mockInvalidOsHostname\n\n\tif _, err := getEnvValueForField(\"$HOSTNAME\"); err == nil {\n\t\tt.Errorf(\"Invalid Hostname Returned No Error\")\n\t}\n}", "func ParseEnvironment() error {\n\n\t// Use AZURE_BASE_GROUP_NAME and `config.GenerateGroupName()`\n\tbaseGroupName = os.Getenv(\"AZURE_BASE_GROUP_NAME\")\n\n\tif baseGroupName == \"\" {\n\t\treturn errors.New(\"need AZURE_BASE_GROUP_NAME\")\n\t}\n\tlocationDefault = os.Getenv(\"AZURE_LOCATION_DEFAULT\")\n\tif locationDefault == \"\" {\n\t\treturn errors.New(\"need AZURE_LOCATION_DEFAULT\")\n\t}\n\n\tclientID = os.Getenv(\"AZURE_CLIENT_ID\")\n\tif clientID == \"\" {\n\t\treturn errors.New(\"need AZURE_CLIENT_ID\")\n\t}\n\t// clientSecret\n\tclientSecret = os.Getenv(\"AZURE_CLIENT_SECRET\")\n\tif clientSecret == \"\" {\n\t\treturn errors.New(\"need AZURE_CLIENT_SECRET\")\n\t}\n\t// tenantID (AAD)\n\ttenantID = os.Getenv(\"AZURE_TENANT_ID\")\n\tif tenantID == \"\" {\n\t\treturn errors.New(\"need AZURE_TENANT_ID\")\n\t}\n\t// subscriptionID (ARM)\n\tsubscriptionID = os.Getenv(\"AZURE_SUBSCRIPTION_ID\")\n\treturn nil\n}", "func MustGet(name string) string {\n\tenvVar, ok := os.LookupEnv(name)\n\tif !ok {\n\t\tlog.Fatalf(\"environment variable (%s) has not been set\", name)\n\t}\n\tif envVar == \"\" {\n\t\tlog.Fatalf(\"environment variable (%s) is empty\", name)\n\t}\n\treturn envVar\n}", "func MustGetEnv(variable string) string {\n\tv := os.Getenv(variable)\n\tif v == \"\" {\n\t\tlog.Panicf(\"%v environment variable not set.\", variable)\n\t}\n\treturn v\n}", "func initVariables() error {\n\tswitch h, err := os.Hostname(); {\n\tcase err == nil:\n\t\tENVS.Hostname = h\n\tcase os.IsNotExist(err):\n\t\tENVS.Hostname = \"(none)\"\n\tdefault:\n\t\treturn err\n\t}\n\n\tswitch ifs, err := getNetIfaces(); {\n\tcase err == nil:\n\t\tENVS.Network = ifs\n\tdefault:\n\t\treturn err\n\t}\n\n\tswitch out, err := exec.Command(\"./myenvs\").Output(); {\n\tcase err == nil:\n\t\tif err := json.Unmarshal(out, &ENVS.X); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase !os.IsNotExist(err):\n\t\treturn fmt.Errorf(\"%s: %s\", err, out)\n\t}\n\n\treturn nil\n}", "func CleanEnv() {\n\t// apparently os.Unsetenv doesn't exist in the version of go I'm using\n\t_ = os.Setenv(\"BM_CONFIG_DIR\", \"\")\n\t_ = os.Setenv(\"BM_USER\", \"\")\n\t_ = os.Setenv(\"BM_ACCOUNT\", \"\")\n\t_ = os.Setenv(\"BM_ENDPOINT\", \"\")\n\t_ = os.Setenv(\"BM_AUTH_ENDPOINT\", \"\")\n\t_ = os.Setenv(\"BM_DEBUG_LEVEL\", \"\")\n}", "func TestNotExists(t *testing.T) {\r\n\tt.Log(\"Given the need to panic when environment variables are missing.\")\r\n\t{\r\n\t\tos.Setenv(\"MYAPP_PROC_ID\", \"322\")\r\n\t\tos.Setenv(\"MYAPP_SOCKET\", \"./tmp/sockets.po\")\r\n\t\tos.Setenv(\"MYAPP_PORT\", \"4034\")\r\n\t\tos.Setenv(\"MYAPP_FLAG\", \"true\")\r\n\r\n\t\tcfg.Init(\"MYAPP\")\r\n\r\n\t\tt.Log(\"\\tWhen given a namspace key to search for that does NOT exist.\")\r\n\t\t{\r\n\t\t\tshouldPanic(t, \"STAMP\", func() {\r\n\t\t\t\tcfg.MustTime(\"STAMP\")\r\n\t\t\t})\r\n\r\n\t\t\tshouldPanic(t, \"PID\", func() {\r\n\t\t\t\tcfg.MustInt(\"PID\")\r\n\t\t\t})\r\n\r\n\t\t\tshouldPanic(t, \"DEST\", func() {\r\n\t\t\t\tcfg.MustString(\"DEST\")\r\n\t\t\t})\r\n\r\n\t\t\tshouldPanic(t, \"ACTIVE\", func() {\r\n\t\t\t\tcfg.MustBool(\"ACTIVE\")\r\n\t\t\t})\r\n\r\n\t\t\tshouldPanic(t, \"SOCKET_DSN\", func() {\r\n\t\t\t\tcfg.MustURL(\"SOCKET_DSN\")\r\n\t\t\t})\r\n\t\t}\r\n\t}\r\n}", "func sourceSanityCheck(source string, sa Source) {\n\tif len(sa.PrivateKey) > 0 {\n\t\tif _, err := os.Stat(sa.PrivateKey); err != nil {\n\t\t\tFatalf(\"resolvePuppetEnvironment(): could not find SSH private key \" + sa.PrivateKey + \" for source \" + source + \" in config file \" + configFile + \" Error: \" + err.Error())\n\t\t}\n\t}\n\tif len(sa.Basedir) <= 0 {\n\t\tFatalf(\"resolvePuppetEnvironment(): config setting basedir is not set for source \" + source + \" in config file \" + configFile)\n\t}\n\tif len(sa.Remote) <= 0 {\n\t\tFatalf(\"resolvePuppetEnvironment(): config setting remote is not set for source \" + source + \" in config file \" + configFile)\n\t}\n}", "func env(key string, fallback string) string {\n\tif v := os.Getenv(key); v != \"\" {\n\t\treturn v\n\t}\n\treturn fallback\n}", "func checkPrerequisites() {\n\n\t// First load the required config file\n\tcfg.LoadConfigFile()\n\n\ttoken = cfg.GetUserToken()\n\tif token == \"\" {\n\t\tcmd.UsageAndExit(\"GitHub token cannot be empty.\", 1)\n\t}\n\n}", "func (e CliEnv) Validate() error {\n\tif e.AWSProfile == \"\" {\n\t\treturn ErrMissingAWSProfile\n\t}\n\n\tif e.AWSRegion == \"\" {\n\t\treturn ErrMissingAWSRegion\n\t}\n\n\tif e.StackName == \"\" {\n\t\treturn ErrMissingStackName\n\t}\n\n\treturn nil\n}", "func MustGet(k string) string {\n\tv := os.Getenv(k)\n\tif v == \"\" {\n\t\tlog.Panicln(\"ENV missing, key: \" + k)\n\t}\n\n\tv = *stringUtil.RemoveEmptyQuote(&v)\n\n\treturn v\n}", "func MustGetEnv(env string) string {\n\tenvValue := os.Getenv(env)\n\tif envValue == \"\" {\n\t\tlogrus.WithField(\"env\", env).Fatal(\"MustGetEnv did not find env\")\n\t}\n\treturn envValue\n}", "func (util *Utils) CheckEnvironment(path string) string {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn \"\"\n\t}\n\treturn path\n}", "func tmplENV(keys ...string) (value string) {\n\tswitch len(keys) {\n\tcase 1:\n\t\tvalue = os.Getenv(keys[0])\n\tcase 2:\n\t\tvalue = os.Getenv(keys[0])\n\t\tif value == \"\" {\n\t\t\tvalue = keys[1]\n\t\t}\n\t}\n\treturn\n}", "func TestEnvEmpty(t *testing.T) {\n\tenverr := pkg.LoadEnv()\n\n\tif _, err := os.Stat(\"../.env\"); os.IsNotExist(err) {\n\t\tif enverr != nil {\n\t\t\tt.Error(\"Env does not exist\")\n\t\t}\n\t}\n}", "func MustGetEnv(variable string) string {\n\tvalue := os.Getenv(variable)\n\tif len(value) == 0 {\n\t\tpanic(fmt.Errorf(\"%s env not found\", variable))\n\t}\n\treturn value\n}", "func TestGetEnvAsInt32(t *testing.T) {\n for i := 0; i < len(testInt32s); i++ {\n // set environment variables\n if testInt32s[i].ShouldSet {\n os.Setenv(\n testInt32s[i].Key,\n testInt32s[i].Value,\n )\n }\n\n // get environment variables\n if v := GetEnvAsInt32(\n testInt32s[i].Key,\n testInt32s[i].Default,\n ); v != testInt32s[i].Expected {\n t.Errorf(\n \"ENV %s is %d; expected %d\",\n testInt32s[i].Key,\n v,\n testInt32s[i].Expected,\n )\n }\n }\n}", "func CheckRequired() (token string, port string, err error) {\n\tvar found bool\n\n\t// Check for BOT_TOKEN, we need this to connect to Discord\n\ttoken, found = os.LookupEnv(\"BOT_TOKEN\")\n\tif !found || token == \"\" {\n\t\terr = errors.New(\"BOT_TOKEN not defined in environment variables\")\n\t\treturn\n\t}\n\n\t// Check for PORT, we need this to for our HTTP server in our container\n\tport, found = os.LookupEnv(\"PORT\")\n\tif !found || port == \"\" {\n\t\tport = \"8080\"\n\t}\n\n\t// Check for strings from slice, these are not needed now, but are needed in the callbacks\n\tfor _, envVar := range []string{\"BOT_NAME\", \"BOT_KEYWORD\", \"ROLE_PREFIX\"} {\n\t\tvalue, found := os.LookupEnv(envVar)\n\t\tif !found || value == \"\" {\n\t\t\terr = errors.New(\"%s not defined in environment variables\" + envVar)\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}", "func getEnv(envVar string, require bool) (val string, ok bool) {\n\tif val, ok = os.LookupEnv(envVar); !ok {\n\t\tif require {\n\t\t\tpanic(fmt.Sprintf(\"env: missing required environment variable: %s\", envVar))\n\t\t}\n\t}\n\n\treturn\n}", "func loadEnvironmentVariables() {\n\tpgDb = os.Getenv(\"PGDB\")\n\tif len(pgDb) == 0 {\n\t\tpanic(\"No pgDB environment variable\")\n\t}\n\n\tpgUser = os.Getenv(\"PGUSER\")\n\tif len(pgUser) == 0 {\n\t\tpanic(\"No pgUSER environment variable\")\n\t}\n\n\tpgPassword = os.Getenv(\"PGPASSWORD\")\n\tif len(pgPassword) == 0 {\n\t\tpanic(\"No pgPASSWORD environment variable\")\n\t}\n\n\tpgHost = os.Getenv(\"PGHOST\")\n\tif len(pgHost) == 0 {\n\t\tpanic(\"No pgHOST environment variable\")\n\t}\n\n\tuploadFolderPath = os.Getenv(\"UPLOAD_FOLDER_PATH\")\n\tif len(uploadFolderPath) == 0 {\n\t\tpanic(\"No UPLOAD_FOLDER_PATH environment variable\")\n\t}\n}", "func ValidateHostEnvironment(mTLSEnabled bool, mode modes.DaprMode, namespace string) error {\n\tswitch mode {\n\tcase modes.KubernetesMode:\n\t\tif mTLSEnabled && namespace == \"\" {\n\t\t\treturn errors.New(\"actors must have a namespace configured when running in Kubernetes mode\")\n\t\t}\n\t}\n\treturn nil\n}", "func MustGetStringFlagsFromEnv(flagPrefix string, vars ...*EnvValueHolder) {\n\tfor _, k := range vars {\n\t\tvalue, err := GetStringFlagFromEnv(flagPrefix + k.N)\n\t\tif err != nil && !k.hasDefault() {\n\t\t\tlog.Logger().Panic().Err(err).Msg(\"failed to load string flag from env\")\n\t\t}\n\n\t\tk.assign(value)\n\t}\n}", "func setupEnv() config.Config {\n\trequiredEnvVars := []string {\n\t\tconfig.EnvURL,\n\t\tconfig.EnvPort,\n\t}\n\n\tfor _, key := range requiredEnvVars {\n\t\t_, exists := os.LookupEnv(key)\n\t\tif !exists {\n\t\t\tfmt.Printf(\"Environment mismatch. Missing required: %s\\n\", key)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tclientURL := os.Getenv(config.EnvURL)\n\tport := os.Getenv(config.EnvPort)\n\n\treturn config.Config{MemDBSchema: config.DBSchema, SSEServerUrl: clientURL, PORT: port}\n}", "func TestRecipesHaveEnv(t *testing.T) {\n\tinput := \"testdata/test12.mk\"\n\tgot, _, err := startMk(\"-f\", input)\n\n\tif err != nil {\n\t\tt.Errorf(\"%s exec failed: %v\", input, err)\n\t}\n\n\t// Make sure that the output has the right variables in it.\n\t// got should be the contents of the environment.\n\tenvs := make([]string, 0)\n\tfor _, b := range bytes.Split(got, []byte(\"\\n\")) {\n\t\tenvs = append(envs, string(b))\n\t}\nouter:\n\tfor _, ekv := range []string{\n\t\t\"bar=thebigness\",\n\t\t\"TEST_MAIN=mk\",\n\t\t\"shell=sh\",\n\t} {\n\t\tfor _, v := range envs {\n\t\t\tif v == ekv {\n\t\t\t\tcontinue outer\n\t\t\t}\n\t\t}\n\t\tt.Errorf(\"%s: output missing %s\", input, ekv)\n\t}\n}" ]
[ "0.78410727", "0.7515614", "0.7483698", "0.73864317", "0.7376858", "0.7362639", "0.7346198", "0.73146194", "0.73146194", "0.7275108", "0.7230925", "0.72183424", "0.71962416", "0.7170809", "0.71596515", "0.71004254", "0.7020969", "0.70109403", "0.7000705", "0.7000282", "0.69855297", "0.69831985", "0.6941713", "0.6938118", "0.6928353", "0.68777084", "0.6875583", "0.68261075", "0.68171847", "0.67293", "0.67161906", "0.67048115", "0.66826427", "0.6676641", "0.6666596", "0.6605843", "0.65973985", "0.659498", "0.65818244", "0.64991987", "0.6484263", "0.64810807", "0.6475365", "0.64673644", "0.6460096", "0.64097965", "0.63873297", "0.6368838", "0.6353724", "0.63396984", "0.63368267", "0.6335152", "0.6334239", "0.6322851", "0.63160217", "0.63081473", "0.6307514", "0.6299457", "0.6295783", "0.62800336", "0.6277219", "0.6267101", "0.6259076", "0.6258525", "0.6256439", "0.6246298", "0.6245078", "0.6221438", "0.6208844", "0.6208205", "0.618005", "0.6177816", "0.61755973", "0.6173743", "0.6171884", "0.61595386", "0.6134736", "0.61296946", "0.6109056", "0.6108758", "0.61027265", "0.6102372", "0.60994077", "0.60916585", "0.6084528", "0.60819465", "0.60762584", "0.60757226", "0.6074294", "0.6071803", "0.6059452", "0.60588765", "0.6058236", "0.60557216", "0.6055027", "0.6054046", "0.604531", "0.6039821", "0.6034043", "0.6009009" ]
0.69267994
25
Init preforms any db snapshot initalization functions that need to be run with general tok init functions
func Init() (err error) { mkSnapshotDir() return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *DbRecorder) Init(db squirrel.DBProxyBeginner, flavor string) {\n\tb := squirrel.StatementBuilder.RunWith(db)\n\tif flavor == \"postgres\" {\n\t\tb = b.PlaceholderFormat(squirrel.Dollar)\n\t}\n\n\td.builder = &b\n\td.db = db\n\td.flavor = flavor\n}", "func init() {\n\tloadTheEnv()\n\tcreateDBInstance()\n\tloadRepDB()\n\tstartKafka()\n}", "func init() {\n\tlog.DebugMode = cuxs.IsDebug()\n\tlog.Log = log.New()\n\n\tif e := cuxs.DbSetup(); e != nil {\n\t\tpanic(e)\n\t}\n}", "func (db database) Init() error {\n\tscript := `CREATE TABLE IF NOT EXISTS txs (\n\t\thash VARCHAR NOT NULL PRIMARY KEY,\n\t\tstatus SMALLINT,\n\t\tcreated_time BIGINT,\n\t\tselector VARCHAR(255),\n\t\ttxid VARCHAR,\n\t\ttxindex BIGINT,\n\t\tamount VARCHAR(100),\n\t\tpayload VARCHAR,\n\t\tphash VARCHAR,\n\t\tto_address VARCHAR,\n\t\tnonce VARCHAR,\n\t\tnhash VARCHAR,\n\t\tgpubkey VARCHAR,\n\t\tghash VARCHAR,\n\t\tversion VARCHAR\n\t);\nCREATE TABLE IF NOT EXISTS gateways (\n\t\tgateway_address VARCHAR NOT NULL PRIMARY KEY,\n\t\tstatus SMALLINT,\n\t\tcreated_time BIGINT,\n\t\tselector VARCHAR(255),\n\t\tpayload VARCHAR,\n\t\tphash VARCHAR,\n\t\tto_address VARCHAR,\n\t\tnonce VARCHAR,\n\t\tnhash VARCHAR,\n\t\tgpubkey VARCHAR,\n\t\tghash VARCHAR,\n\t\tversion VARCHAR\n);\n`\n\t_, err := db.db.Exec(script)\n\treturn err\n}", "func (db *Database) Init() {\n\tdata, dbErr := tiedot.OpenDB(db.Location)\n\tif dbErr != nil {\n\t\tlog.Error(dbConnectionError{\n\t\t\tmsg: \"Failed to connect to the tiedot database\",\n\t\t\terr: dbErr,\n\t\t})\n\t}\n\n\t// Set up the collections - throw away the error for now.\n\tfor _, c := range db.Collections {\n\t\tdata.Create(c.Name)\n\t\tdata.Use(c.Name).Index(c.Index)\n\t}\n\n\tdb.Data = data\n}", "func InitDB(init bool) {\n\tif init {\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS kv (\n\t\t\tk TEXT PRIMARY KEY,\n\t\t\tv TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS datasets (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tname TEXT,\n\t\t\t-- 'data' or 'computed'\n\t\t\ttype TEXT,\n\t\t\tdata_type TEXT,\n\t\t\tmetadata TEXT DEFAULT '',\n\t\t\t-- only set if computed\n\t\t\thash TEXT,\n\t\t\tdone INTEGER DEFAULT 1\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS annotate_datasets (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tdataset_id INTEGER REFERENCES datasets(id),\n\t\t\tinputs TEXT,\n\t\t\ttool TEXT,\n\t\t\tparams TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS pytorch_archs (\n\t\t\tid TEXT PRIMARY KEY,\n\t\t\tparams TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS pytorch_components (\n\t\t\tid TEXT PRIMARY KEY,\n\t\t\tparams TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS exec_nodes (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tname TEXT,\n\t\t\top TEXT,\n\t\t\tparams TEXT,\n\t\t\tparents TEXT,\n\t\t\tworkspace TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS exec_ds_refs (\n\t\t\tnode_id INTEGER,\n\t\t\tdataset_id INTEGER,\n\t\t\tUNIQUE(node_id, dataset_id)\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS workspaces (\n\t\t\tname TEXT PRIMARY KEY\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS ws_datasets (\n\t\t\tdataset_id INTEGER,\n\t\t\tworkspace TEXT,\n\t\t\tUNIQUE(dataset_id, workspace)\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS jobs (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tname TEXT,\n\t\t\t-- e.g. 'execnode'\n\t\t\ttype TEXT,\n\t\t\t-- how to process the job output and render the job\n\t\t\top TEXT,\n\t\t\tmetadata TEXT,\n\t\t\tstart_time TIMESTAMP,\n\t\t\tstate TEXT DEFAULT '',\n\t\t\tdone INTEGER DEFAULT 0,\n\t\t\terror TEXT DEFAULT ''\n\t\t)`)\n\n\t\t// add missing pytorch components\n\t\tcomponentPath := \"python/skyhook/pytorch/components/\"\n\t\tfiles, err := ioutil.ReadDir(componentPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor _, fi := range files {\n\t\t\tif !strings.HasSuffix(fi.Name(), \".json\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tid := strings.Split(fi.Name(), \".json\")[0]\n\t\t\tbytes, err := ioutil.ReadFile(filepath.Join(componentPath, fi.Name()))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdb.Exec(\"INSERT OR REPLACE INTO pytorch_components (id, params) VALUES (?, ?)\", id, string(bytes))\n\t\t}\n\n\t\t// add missing pytorch archs\n\t\tarchPath := \"exec_ops/pytorch/archs/\"\n\t\tfiles, err = ioutil.ReadDir(archPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor _, fi := range files {\n\t\t\tif !strings.HasSuffix(fi.Name(), \".json\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tid := strings.Split(fi.Name(), \".json\")[0]\n\t\t\tbytes, err := ioutil.ReadFile(filepath.Join(archPath, fi.Name()))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdb.Exec(\"INSERT OR REPLACE INTO pytorch_archs (id, params) VALUES (?, ?)\", id, string(bytes))\n\t\t}\n\n\t\t// add default workspace if it doesn't exist\n\t\tvar count int\n\t\tdb.QueryRow(\"SELECT COUNT(*) FROM workspaces WHERE name = ?\", \"default\").Scan(&count)\n\t\tif count == 0 {\n\t\t\tdb.Exec(\"INSERT INTO workspaces (name) VALUES (?)\", \"default\")\n\t\t}\n\t}\n\n\t// now run some database cleanup steps\n\n\t// mark jobs that are still running as error\n\tdb.Exec(\"UPDATE jobs SET error = 'terminated', done = 1 WHERE done = 0\")\n\n\t// delete temporary datasetsTODO\n}", "func (_m *Database) Init() {\n\t_m.Called()\n}", "func (s *InMemoryHandler) Init() error {\n\ts.logger = log.WithFields(log.Fields{\"app\": \"inmemory-db\"})\n\ts.functions = make(map[string]model.FunctionConfig)\n\treturn nil\n}", "func (d *TileDB) Init() error {\n\t// TODO(mhutchinson): Consider storing the entries too:\n\t// CREATE TABLE IF NOT EXISTS entries (revision INTEGER, keyhash BLOB, key STRING, value STRING, PRIMARY KEY (revision, keyhash))\n\n\tif _, err := d.db.Exec(\"CREATE TABLE IF NOT EXISTS revisions (revision INTEGER PRIMARY KEY, datetime TIMESTAMP, logroot BLOB, count INTEGER)\"); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.db.Exec(\"CREATE TABLE IF NOT EXISTS tiles (revision INTEGER, path BLOB, tile BLOB, PRIMARY KEY (revision, path))\"); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.db.Exec(\"CREATE TABLE IF NOT EXISTS logs (module TEXT, revision INTEGER, leaves BLOB, PRIMARY KEY (module, revision))\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (sessionRepo *mockSessionRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func Init() {\n\tcreateDB(\"backendtest\")\n\tuseDB(\"backendtest\")\n\tCreateUserTable()\n\tCreateEventTable()\n\tCreateAddFriendTable()\n}", "func (transactionRepo *mockTransactionRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func init() {\n\tlog.Info(\"Initializing database\")\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%s user=%s \"+\n\t\t\"password=%s dbname=%s sslmode=disable\",\n\t\tconfig.Config().GetString(\"database.host\"),\n\t\tconfig.Config().GetString(\"database.port\"),\n\t\tconfig.Config().GetString(\"database.user\"),\n\t\tconfig.Config().GetString(\"database.password\"),\n\t\tconfig.Config().GetString(\"database.name\"))\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tlog.Info(\"Successfully connected to database!\")\n}", "func (programRepo *mockProgramRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (meta *Meta) init() {\n\tmeta.client = utils.CreateMongoDB(dbConfig.Str(\"address\"), log)\n\tmeta.database = meta.client.Database(dbConfig.Str(\"db\"))\n\tmeta.collection = meta.database.Collection(metaCollection)\n}", "func Init() {\n\tinitOnce := func() {\n\t\tp := parser.New()\n\t\ttbls := make([]*model.TableInfo, 0)\n\t\tdbID := autoid.PerformanceSchemaDBID\n\t\tfor _, sql := range perfSchemaTables {\n\t\t\tstmt, err := p.ParseOneStmt(sql, \"\", \"\")\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tmeta, err := ddl.BuildTableInfoFromAST(stmt.(*ast.CreateTableStmt))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\ttbls = append(tbls, meta)\n\t\t\tvar ok bool\n\t\t\tmeta.ID, ok = tableIDMap[meta.Name.O]\n\t\t\tif !ok {\n\t\t\t\tpanic(fmt.Sprintf(\"get performance_schema table id failed, unknown system table `%v`\", meta.Name.O))\n\t\t\t}\n\t\t\tfor i, c := range meta.Columns {\n\t\t\t\tc.ID = int64(i) + 1\n\t\t\t}\n\t\t}\n\t\tdbInfo := &model.DBInfo{\n\t\t\tID: dbID,\n\t\t\tName: util.PerformanceSchemaName,\n\t\t\tCharset: mysql.DefaultCharset,\n\t\t\tCollate: mysql.DefaultCollationName,\n\t\t\tTables: tbls,\n\t\t}\n\t\tinfoschema.RegisterVirtualTable(dbInfo, tableFromMeta)\n\t}\n\tif expression.EvalAstExpr != nil {\n\t\tonce.Do(initOnce)\n\t}\n}", "func (r *DarwinTimetable) initDB() error {\n\n\tbuckets := []string{\n\t\t\"Meta\",\n\t\t\"DarwinAssoc\",\n\t\t\"DarwinJourney\"}\n\n\treturn r.db.Update(func(tx *bolt.Tx) error {\n\n\t\tfor _, n := range buckets {\n\t\t\tvar nb []byte = []byte(n)\n\t\t\tif bucket := tx.Bucket(nb); bucket == nil {\n\t\t\t\tif _, err := tx.CreateBucket(nb); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func init() {\n\tinitTokens()\n\tvar err error\n\tLexer, err = initLexer()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (db *Database) init(g []Group, e []Entry, opts *Options) {\n\t// Clear inputted key material.\n\tif db.cparams.ComputedKey == nil {\n\t\tpanic(\"key should have been precomputed\")\n\t}\n\tdb.cparams.Key.Password, db.cparams.Key.KeyFileHash = nil, nil\n\n\tdb.staticIV = opts.staticIV()\n\tdb.groups = make(map[uint32]*Group, len(g))\n\tdb.entries = make([]*Entry, 0, len(e))\n\tdb.rand = opts.getRand()\n\tdb.root = &Group{Name: \"Root\", db: db}\n\tfor i := range g {\n\t\tgg := &g[i]\n\t\tdb.groups[gg.ID] = gg\n\t}\n\tfor i := range e {\n\t\tee := &e[i]\n\t\tif ee.isMetaStream() {\n\t\t\tdb.meta = append(db.meta, ee)\n\t\t} else {\n\t\t\tdb.entries = append(db.entries, ee)\n\t\t}\n\t}\n}", "func (idx *Autoincrement) Init() error {\n\ttokenManager, err := jwt.New(map[string]interface{}{\n\t\t\"secret\": idx.cs3conf.JWTSecret,\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tidx.tokenManager = tokenManager\n\n\tclient, err := pool.GetStorageProviderServiceClient(idx.cs3conf.ProviderAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tidx.storageProvider = client\n\n\tctx, err := idx.getAuthenticatedContext(context.Background())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := idx.makeDirIfNotExists(ctx, idx.indexBaseDir); err != nil {\n\t\treturn err\n\t}\n\n\tif err := idx.makeDirIfNotExists(ctx, idx.indexRootDir); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func init(){\n\n\tcustomers = loadAllCustomers()\n\tBuildRank()\n\tBuildTable()\n\n}", "func init() {\n\tinitTld()\n}", "func (s *Service) Initialize(ctx context.Context) error {\n\treturn s.kv.Update(ctx, func(tx Tx) error {\n\t\tif err := s.initializeAuths(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeDocuments(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeBuckets(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeDashboards(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeKVLog(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeLabels(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeOnboarding(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeOrgs(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeTasks(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializePasswords(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeScraperTargets(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeSecrets(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeSessions(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeSources(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeTelegraf(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeURMs(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeVariables(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeChecks(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeNotificationRule(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := s.initializeNotificationEndpoint(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn s.initializeUsers(ctx, tx)\n\t})\n}", "func DbInit() {\n\tsqlStatement := `\n\t\tCREATE TABLE benutzer (\n\t\t\tfdNummer VARCHAR(256) PRIMARY KEY, \n\t\t\tVorname VARCHAR(256) NOT NULL, \n\t\t\tNachname VARCHAR(256) NULL,\n\t\t\tAge TINYINT NULL,\n\t\t\tStudiengang VARCHAR(256) NULL,\n\t\t\tSemester TINYINT NULL\n\t\t\t);\n\n\t\tCREATE TABLE nachrichten (\n\t\t\tNachrichtID INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\tfdNummer VARCHAR(256) NOT NULL,\n\t\t\tGroupID INTEGER NOT NULL,\n\t\t\tmessage VARCHAR(256) NOT NULL,\n\t\t\tgesendeteUhrzeit DEFAULT CURRENT_TIMESTAMP\n\t\t\t);\n\n\t\tCREATE TABLE chatgroup (\n\t\t\tGroupID INTEGER PRIMARY KEY,\n\t\t\tGroupName VARCHAR(256) NOT NULL\n\t\t\t);\n\t`\n\n\tCreate(sqlStatement)\n}", "func (db *DB) Init(ctx context.Context) error {\n\tinslog := inslogger.FromContext(ctx)\n\tinslog.Debug(\"start storage bootstrap\")\n\tgetGenesisRef := func() (*core.RecordRef, error) {\n\t\tbuff, err := db.get(ctx, prefixkey(scopeIDSystem, []byte{sysGenesis}))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar genesisRef core.RecordRef\n\t\tcopy(genesisRef[:], buff)\n\t\treturn &genesisRef, nil\n\t}\n\n\tcreateGenesisRecord := func() (*core.RecordRef, error) {\n\t\terr := db.AddPulse(\n\t\t\tctx,\n\t\t\tcore.Pulse{\n\t\t\t\tPulseNumber: core.GenesisPulse.PulseNumber,\n\t\t\t\tEntropy: core.GenesisPulse.Entropy,\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = db.SetDrop(ctx, &jetdrop.JetDrop{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlastPulse, err := db.GetLatestPulseNumber(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgenesisID, err := db.SetRecord(ctx, lastPulse, &record.GenesisRecord{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = db.SetObjectIndex(\n\t\t\tctx,\n\t\t\tgenesisID,\n\t\t\t&index.ObjectLifeline{LatestState: genesisID, LatestStateApproved: genesisID},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tgenesisRef := core.NewRecordRef(*genesisID, *genesisID)\n\t\treturn genesisRef, db.set(ctx, prefixkey(scopeIDSystem, []byte{sysGenesis}), genesisRef[:])\n\t}\n\n\tvar err error\n\tdb.genesisRef, err = getGenesisRef()\n\tif err == ErrNotFound {\n\t\tdb.genesisRef, err = createGenesisRecord()\n\t}\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"bootstrap failed\")\n\t}\n\n\treturn nil\n}", "func init() {\n\t_ = godotenv.Load()\n\n\thostname := os.Getenv(\"HOST\")\n\tdbname := os.Getenv(\"DBNAME\")\n\tusername := os.Getenv(\"DBUSER\")\n\tpassword := os.Getenv(\"PASSWORD\")\n\n\tdbString := \"host=\" + hostname + \" user=\" + username + \" dbname=\" + dbname + \" sslmode=disable password=\" + password\n\n\tvar err error\n\tdb, err = gorm.Open(\"postgres\", dbString)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tpanic(\"Unable to connect to DB\")\n\t}\n\n\tdb.AutoMigrate(&QuestionModel{})\n\tdb.AutoMigrate(&AnswerModel{})\n\tdb.AutoMigrate(&UserModel{})\n\tdb.AutoMigrate(&Cohort{})\n}", "func (p *DatabaseHandler) init(s *Server) error {\n\tdb, err := sql.Open(\"sqlite3\", s.srcDir+\"/database.db\")\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn StringError{\"ERROR: Some of databases weren't opened!\"}\n\t}\n\tp.db = db\n\n\tp.createTable()\n\treturn nil\n}", "func init() {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv(\"BRAIN_DB\")))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdb = client.Database(dbName)\n}", "func (classRepo *mockClassRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (achieveRepo *mockAchieveRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func init() {\n\tdbconn, err := database.NewPostgreDB(dbType, connStr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsesconn, err := database.NewRedisCache(addr, pass)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tconfig.dbconn = dbconn\n\tconfig.sessionconn = sesconn\n}", "func (d *Database) Init() error {\n\tif _, err := d.db.Exec(\"CREATE TABLE IF NOT EXISTS leaves (id INTEGER PRIMARY KEY, data BLOB)\"); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.db.Exec(\"CREATE TABLE IF NOT EXISTS tiles (height INTEGER, level INTEGER, offset INTEGER, hashes BLOB, PRIMARY KEY (height, level, offset))\"); err != nil {\n\t\treturn err\n\t}\n\t_, err := d.db.Exec(\"CREATE TABLE IF NOT EXISTS leafMetadata (id INTEGER PRIMARY KEY, module TEXT, version TEXT, fileshash TEXT, modhash TEXT)\")\n\treturn err\n}", "func (s *sqlimpl) Init(options common.ConfigValues) error {\n\n\t// super\n\ts.DAO.Init(options)\n\n\t// Preparing the resources\n\n\ts.ResourcesSQL = resources.NewDAO(s.Handler, \"idm_usr_meta.uuid\").(*resources.ResourcesSQL)\n\tif err := s.ResourcesSQL.Init(options); err != nil {\n\t\treturn err\n\t}\n\n\t// Doing the database migrations\n\tmigrations := &sql.PackrMigrationSource{\n\t\tBox: packr.NewBox(\"../../idm/meta/migrations\"),\n\t\tDir: s.Driver(),\n\t\tTablePrefix: s.Prefix(),\n\t}\n\n\t_, err := sql.ExecMigration(s.DB(), s.Driver(), migrations, migrate.Up, \"idm_usr_meta_\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Preparing the db statements\n\tif options.Bool(\"prepare\", true) {\n\t\tfor key, query := range queries {\n\t\t\tif err := s.Prepare(key, query); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Initing namespace\n\tnsDAO := namespace.NewDAO(s.Handler)\n\tif err := nsDAO.Init(options); err != nil {\n\t\treturn err\n\t}\n\n\ts.nsDAO = nsDAO.(namespace.DAO)\n\n\treturn nil\n}", "func (st *Store) initDB() error {\n\n\tvar err error\n\n\tver, err := st.schemaVersion()\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch ver {\n\tcase 0:\n\t\t// starting from scratch\n\t\tschema := `\nCREATE TABLE url (\n\tid INTEGER PRIMARY KEY,\n\turl TEXT NOT NULL,\n\thash TEXT NOT NULL,\n\tpage_id INTEGER NOT NULL,\n\tcreated TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,\n\tFOREIGN KEY(page_id) REFERENCES page(id)\n);\n\nCREATE TABLE page (\n\tid INTEGER PRIMARY KEY,\n\tcanonical_url TEXT NOT NULL,\n\ttitle TEXT NOT NULL,\n\tcreated TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL\n);\n\nCREATE TABLE warning (\n\tid INTEGER PRIMARY KEY,\n\tpage_id INTEGER NOT NULL,\n\tkind TEXT NOT NULL,\n\tquant INT NOT NULL,\n\tcreated TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,\n\tFOREIGN KEY(page_id) REFERENCES page(id)\n);\n\n\nCREATE TABLE version (\n\tver INTEGER NOT NULL );\n\nINSERT INTO version (ver) VALUES (1);\n`\n\t\t//\t\t`CREATE INDEX article_tag_artid ON article_tag(article_id)`,\n\t\t//\t\t`CREATE INDEX article_url_artid ON article_url(article_id)`,\n\n\t\t_, err = st.db.Exec(schema)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbreak\n\tcase 1: // all good. this is what we're expecting\n\t\tbreak\n\tdefault:\n\t\treturn fmt.Errorf(\"Bad db schema version (expected 1, got %d)\", ver)\n\t}\n\n\treturn nil\n}", "func initNew(sess *xorm.Session) error {\n\tif err := syncAll(sess); err != nil {\n\t\treturn err\n\t}\n\n\t// dummy run migrations\n\tfor _, task := range migrationTasks {\n\t\tif _, err := sess.Insert(&migrations{task.name}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (this *DBHandler) Init() {\n\tvar derr error\n\tthis.db, derr = sql.Open(\"sqlite3\", DB_FILE_NAME)\n\tif derr != nil {\n\t\tfmt.Println(derr)\n\t}\n\tthis.createNewTable(TABLE_WPA)\n\tthis.createNewTable(TABLE_WORDLISTS)\n\tthis.createNewTable(TABLE_RUNS)\n}", "func (tr *TestRecorder) init() {}", "func (auth Authenticate) Init(db *db.MySQL, config *types.Config) *Authenticate {\n\tauth.DB = db\n\tauth.Cache = cache.Cache{}.Init(config)\n\treturn &auth\n}", "func (ctx *Ctx) Init() {\n\t// Outputs\n\tctx.JSONOut = os.Getenv(\"GHA2DB_JSON\") != \"\"\n\tctx.DBOut = os.Getenv(\"GHA2DB_NODB\") == \"\"\n\t// Debug\n\tif os.Getenv(\"GHA2DB_DEBUG\") == \"\" {\n\t\tctx.Debug = 0\n\t} else {\n\t\tdebugLevel, err := strconv.Atoi(os.Getenv(\"GHA2DB_DEBUG\"))\n\t\tFatalOnError(err)\n\t\tif debugLevel > 0 {\n\t\t\tctx.Debug = debugLevel\n\t\t}\n\t}\n\t// CmdDebug\n\tif os.Getenv(\"GHA2DB_CMDDEBUG\") == \"\" {\n\t\tctx.CmdDebug = 0\n\t} else {\n\t\tdebugLevel, err := strconv.Atoi(os.Getenv(\"GHA2DB_CMDDEBUG\"))\n\t\tFatalOnError(err)\n\t\tctx.CmdDebug = debugLevel\n\t}\n\tctx.QOut = os.Getenv(\"GHA2DB_QOUT\") != \"\"\n\tctx.CtxOut = os.Getenv(\"GHA2DB_CTXOUT\") != \"\"\n\t// Threading\n\tctx.ST = os.Getenv(\"GHA2DB_ST\") != \"\"\n\t// NCPUs\n\tif os.Getenv(\"GHA2DB_NCPUS\") == \"\" {\n\t\tctx.NCPUs = 0\n\t} else {\n\t\tnCPUs, err := strconv.Atoi(os.Getenv(\"GHA2DB_NCPUS\"))\n\t\tFatalOnError(err)\n\t\tif nCPUs > 0 {\n\t\t\tctx.NCPUs = nCPUs\n\t\t}\n\t}\n\t// Postgres DB\n\tctx.PgHost = os.Getenv(\"PG_HOST\")\n\tctx.PgPort = os.Getenv(\"PG_PORT\")\n\tctx.PgDB = os.Getenv(\"PG_DB\")\n\tctx.PgUser = os.Getenv(\"PG_USER\")\n\tctx.PgPass = os.Getenv(\"PG_PASS\")\n\tctx.PgSSL = os.Getenv(\"PG_SSL\")\n\tif ctx.PgHost == \"\" {\n\t\tctx.PgHost = \"localhost\"\n\t}\n\tif ctx.PgPort == \"\" {\n\t\tctx.PgPort = \"5432\"\n\t}\n\tif ctx.PgDB == \"\" {\n\t\tctx.PgDB = \"gha\"\n\t}\n\tif ctx.PgUser == \"\" {\n\t\tctx.PgUser = \"gha_admin\"\n\t}\n\tif ctx.PgPass == \"\" {\n\t\tctx.PgPass = \"password\"\n\t}\n\tif ctx.PgSSL == \"\" {\n\t\tctx.PgSSL = \"disable\"\n\t}\n\t// Influx DB\n\tctx.IDBHost = os.Getenv(\"IDB_HOST\")\n\tctx.IDBPort = os.Getenv(\"IDB_PORT\")\n\tctx.IDBDB = os.Getenv(\"IDB_DB\")\n\tctx.IDBUser = os.Getenv(\"IDB_USER\")\n\tctx.IDBPass = os.Getenv(\"IDB_PASS\")\n\tif ctx.IDBHost == \"\" {\n\t\tctx.IDBHost = \"http://localhost\"\n\t}\n\tif ctx.IDBPort == \"\" {\n\t\tctx.IDBPort = \"8086\"\n\t}\n\tif ctx.IDBDB == \"\" {\n\t\tctx.IDBDB = \"gha\"\n\t}\n\tif ctx.IDBUser == \"\" {\n\t\tctx.IDBUser = \"gha_admin\"\n\t}\n\tif ctx.IDBPass == \"\" {\n\t\tctx.IDBPass = \"password\"\n\t}\n\t// Environment controlling index creation, table & tools\n\tctx.Index = os.Getenv(\"GHA2DB_INDEX\") != \"\"\n\tctx.Table = os.Getenv(\"GHA2DB_SKIPTABLE\") == \"\"\n\tctx.Tools = os.Getenv(\"GHA2DB_SKIPTOOLS\") == \"\"\n\tctx.Mgetc = os.Getenv(\"GHA2DB_MGETC\")\n\tif len(ctx.Mgetc) > 1 {\n\t\tctx.Mgetc = ctx.Mgetc[:1]\n\t}\n\t// Default start date\n\tif os.Getenv(\"GHA2DB_STARTDT\") != \"\" {\n\t\tctx.DefaultStartDate = TimeParseAny(os.Getenv(\"GHA2DB_STARTDT\"))\n\t} else {\n\t\tctx.DefaultStartDate = time.Date(2014, 6, 1, 0, 0, 0, 0, time.UTC)\n\t}\n\t// Last InfluxDB series\n\tctx.LastSeries = os.Getenv(\"GHA2DB_LASTSERIES\")\n\tif ctx.LastSeries == \"\" {\n\t\tctx.LastSeries = \"all_prs_merged_d\"\n\t}\n\t// IfluxDB variables\n\tctx.SkipIDB = os.Getenv(\"GHA2DB_SKIPIDB\") != \"\"\n\tctx.ResetIDB = os.Getenv(\"GHA2DB_RESETIDB\") != \"\"\n\n\t// Explain\n\tctx.Explain = os.Getenv(\"GHA2DB_EXPLAIN\") != \"\"\n\n\t// Old (pre 2015) GHA JSONs format\n\tctx.OldFormat = os.Getenv(\"GHA2DB_OLDFMT\") != \"\"\n\n\t// Exact repository full names to match\n\tctx.Exact = os.Getenv(\"GHA2DB_EXACT\") != \"\"\n\n\t// Log to Postgres DB, table `gha_logs`\n\tctx.LogToDB = os.Getenv(\"GHA2DB_SKIPLOG\") == \"\"\n\n\t// Local mode\n\tctx.Local = os.Getenv(\"GHA2DB_LOCAL\") != \"\"\n\n\t// Context out if requested\n\tif ctx.CtxOut {\n\t\tctx.Print()\n\t}\n}", "func init() {\n\tvar err error\n\t//db, err = sql.Open(\"postgres\", \"postgres://wookie:[email protected]/wookie?sslmode=disable\")\n\tdb, err = sql.Open(\"postgres\", \"user=wookie dbname=wookie sslmode=disable\")\n\tif err != nil {\n\t\tERROR.Println(\"init db\", err.Error())\n\t\treturn\n\t}\n\n\t//////////////////////////////////////\n\t// drop tables\n\t// DANGER this will empty the db\n\t//\n\t//////////////////////////////////////\n\t_, err = db.Exec(`DROP TABLE classes, users, quiz, attendance CASCADE`)\n\tfmt.Println(err)\n\n\t/////////////////////////////////////////////\n\t//////creating\n\t/////////////////////////////////////////////\n\n\t_, err = db.Exec(`CREATE TABLE users (\n uid serial PRIMARY KEY,\n email text UNIQUE,\n password bytea,\n salt bytea\n )`)\n\tfmt.Println(err)\n\n\t_, err = db.Exec(`CREATE TABLE attendance (\n cid integer PRIMARY KEY,\n students json,\n date_created date\n )`)\n\tfmt.Println(err)\n\n\t_, err = db.Exec(`CREATE TABLE classes (\n cid serial PRIMARY KEY,\n name text,\n students json,\n uid integer REFERENCES users (uid),\n semester text\n )`)\n\tfmt.Println(err)\n\n\t_, err = db.Exec(`CREATE TABLE quiz (\n qid serial PRIMARY KEY,\n info json,\n type integer,\n cid integer REFERENCES classes (cid)\n )`)\n\tfmt.Println(err)\n}", "func (a *Authorizer) Init(dbPath string) (err error) {\n\n\t// Init the db\n\tif a.db == nil {\n\t\ta.db, err = storm.Open(dbPath)\n\t\tif err != nil {\n\t\t\tzap.L().Error(\"Failed to init database\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\t}\n\treturn a.load()\n}", "func init() {\n\tRepoCreateDatabaseConnection(DatabaseConnection{Name: \"Write presentation\"})\n\tRepoCreateDatabaseConnection(DatabaseConnection{Name: \"Host meetup\"})\n}", "func init() {\n\n\t//\n\t// -- define logging mechanics --\n\t//\n\n\tlog = logrus.New()\n\tlog.Level = logrus.DebugLevel\n\tif metaDebugMode := _getDotEnvVariable(\"DISABLE_DEBUG\"); metaDebugMode == \"1\" {\n\t\tlog.Level = logrus.ErrorLevel\n\t}\n\n\tlog.Formatter = &logrus.JSONFormatter{\n\t\tFieldMap: logrus.FieldMap{\n\t\t\tlogrus.FieldKeyTime: \"timestamp\",\n\t\t\tlogrus.FieldKeyLevel: \"severity\",\n\t\t\tlogrus.FieldKeyMsg: \"message\",\n\t\t},\n\t\tTimestampFormat: time.RFC3339Nano,\n\t}; log.Out = os.Stdout\n\n\t//\n\t// -- define config bound mechanics (using .env) --\n\t//\n\n\tif metaTracerDisabled := _getDotEnvVariable(\"DISABLE_TRACING\"); metaTracerDisabled == \"0\" {\n\t\tlog.Infof(\"%s: tracing enabled.\",metaServiceName)\n\t\tgo rftlp.InitTracing(metaServiceName, _getDotEnvVariable(\"JAEGER_SERVICE_ADDR\"), log)\n\t}\n\n\tif metaProfilerDisabled := _getDotEnvVariable(\"DISABLE_PROFILER\"); metaProfilerDisabled == \"0\" {\n\t\tlog.Infof(\"%s: profiling enabled.\",metaServiceName)\n\t\tgo rftlp.InitProfiling(metaServiceName, metaServiceVersion, log)\n\t}\n\n\tif metaMongoDbUsr = _getDotEnvVariable(\"DB_MONGO_USR\"); metaMongoDbUsr == \"\" {\n\t\tlog.Fatalf(\"%s: mongoDB-Service-User not set <exit>\",metaServiceName)\n\t}\n\n\tif metaMongoDbPwd = _getDotEnvVariable(\"DB_MONGO_PWD\"); metaMongoDbPwd == \"\" {\n\t\tlog.Fatalf(\"%s: mongoDB-Password not set <exit>\",metaServiceName)\n\t}\n\n\tif metaMongoDbPDB = _getDotEnvVariable(\"DB_MONGO_PDB\"); metaMongoDbPDB == \"\" {\n\t\tlog.Fatalf(\"%s: mongoDB primary service db not found <exit>\",metaServiceName)\n\t}\n\n\tif metaMongoDbLnk = _getDotEnvVariable(\"DB_MONGO_LNK\"); metaMongoDbLnk == \"\" {\n\t\tlog.Fatalf(\"%s: mongoDB connection link not found <exit>\",metaServiceName)\n\t}\n\n\tif metaServicePort = _getDotEnvVariable(\"PORT\"); metaServicePort == \"\" {\n\t\tlog.Fatalf(\"%s: service port definition missing <exit>\",metaServiceName)\n\t}\n}", "func (semesterRepo *mockSemesterRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func init() {\n\trefreshPolicies()\n}", "func Init(cfg Configuration, db Database) {\n\tconfig = cfg\n\tdatabase = db\n\truns.Load(database)\n}", "func init() {\n\n\t//load in environment variables from .env\n\t//will print error message when running from docker image\n\t//because env file is passed into docker run command\n\tenvErr := godotenv.Load(\"/home/ubuntu/go/src/github.com/200106-uta-go/BAM-P2/.env\")\n\tif envErr != nil {\n\t\tif !strings.Contains(envErr.Error(), \"no such file or directory\") {\n\t\t\tlog.Println(\"Error loading .env: \", envErr)\n\t\t}\n\t}\n\n\tvar server = os.Getenv(\"DB_SERVER\")\n\tvar dbPort = os.Getenv(\"DB_PORT\")\n\tvar dbUser = os.Getenv(\"DB_USER\")\n\tvar dbPass = os.Getenv(\"DB_PASS\")\n\tvar db = os.Getenv(\"DB_NAME\")\n\n\t// Build connection string\n\tconnString := fmt.Sprintf(\"server=%s;user id=%s;password=%s;port=%s;database=%s;\", server, dbUser, dbPass, dbPort, db)\n\n\t// Create connection pool\n\tvar err error\n\tdatabase, err = sql.Open(\"sqlserver\", connString)\n\tif err != nil {\n\t\tlog.Fatal(\"Error creating connection pool: \", err.Error())\n\t}\n\tctx := context.Background()\n\terr = database.PingContext(ctx)\n\thttputil.GenericErrHandler(\"error\", err)\n\n\t//create user table if it doesn't exist\n\tstatement, err := database.Prepare(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='user_table' and xtype='U') \n\t\tCREATE TABLE user_table (id INT NOT NULL IDENTITY(1,1) PRIMARY KEY, username VARCHAR(255), password VARCHAR(255))`)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t_, err = statement.Exec()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func init() {\n\tdbinfo := fmt.Sprintf(\"user=%s password=%s dbname=%s sslmode=disable\",\n\t\tos.Getenv(\"POSTGRES_USER\"), os.Getenv(\"POSTGRES_PASSWORD\"), DATABASE_NAME)\n\tdb, err := sql.Open(\"postgres\", dbinfo)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tDB = db\n}", "func init() {\n\tdb.RegisterInit(meterReader)\n}", "func init() {\n\tRegisterTSDSDBEngine(\"namespace\", new(Namespace))\n}", "func init() {\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second)\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(CONNECTIONSTRING))\n\n\tif err != nil {\n\t\tlog.Fatal(\"[init]: %s\\n\", err)\n\t}\n\t// Collection types can be used to access the database\n\tdb = client.Database(DBNAME)\n\n}", "func init() {\n\tvar (\n\t\terr error\n\t)\n\tif RDB, err = GetRDB(); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tlogrus.Infoln(\"redis init success !\")\n}", "func InitRootContext() error {\n\t/*\n\t * We will initialize the database instance\n\t * We will initialize root context\n\t */\n\t//initializing the database instance\n\tcfg := GetConfig()\n\td, err := cfg.Db.ConnectWithRetry()\n\tif err != nil {\n\t\tlog.Error(\"error while connecting to the database\")\n\t\treturn err\n\t}\n\n\t//initializing the root context\n\trootContext.Db = d\n\treturn nil\n}", "func (b *BadgerStore) init(dir string) error {\n\n\topts := badger.DefaultOptions(dir)\n\tif dir == \"\" {\n\t\topts = opts.WithInMemory(true)\n\t}\n\topts.Logger = &common.NoopLogger{}\n\tdb, err := badger.Open(opts)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to open database\")\n\t}\n\n\t// Set the database\n\tb.db = db\n\n\t// Initialize the default transaction that auto commits\n\t// on success ops or discards on failure.\n\t// It also enables the renewal of the underlying transaction\n\t// after executing a read/write operation\n\tb.Tx = NewTx(db, true, true)\n\n\treturn nil\n}", "func (a *acceptor) init() error {\n\tinstanceID, err := a.state.load()\n\tif err != nil {\n\t\tlNLErr(\"Load State fail, error: %v\", err)\n\t\treturn err\n\t}\n\n\tif instanceID == 0 {\n\t\tlPLGImp(a.conf.groupIdx, \"Empty database\")\n\t}\n\n\ta.setInstanceID(instanceID)\n\n\tlPLGImp(a.conf.groupIdx, \"OK\")\n\n\treturn nil\n}", "func Init() {\n\tc := config.GetConfig()\n\n\tdb, err = gorm.Open(\"postgres\", \"host=\"+c.GetString(\"db.host\")+\" user=\"+c.GetString(\"db.user\")+\" dbname=\"+c.GetString(\"db.dbname\")+\" sslmode=disable password=\"+c.GetString(\"db.password\"))\n\tif err != nil {\n\t\tpanic(\"failed to connect database : \" + err.Error())\n\t}\n\n\tdb.Exec(\"CREATE EXTENSION IF NOT EXISTS \\\"uuid-ossp\\\";\")\n\n\tdb.AutoMigrate(&models.SendTemplate{}, &models.SmsTemplate{}, &models.User{})\n\n\tdb.Model(&models.SmsTemplate{}).AddForeignKey(\"user_id\", \"users(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&models.SendTemplate{}).AddForeignKey(\"sms_template_id\", \"sms_templates(id)\", \"RESTRICT\", \"RESTRICT\")\n}", "func (s *sqlimpl) Init(options common.ConfigValues) error {\n\n\t// super\n\ts.DAO.Init(options)\n\n\t// Doing the database migrations\n\tmigrations := &sql.PackrMigrationSource{\n\t\tBox: packr.NewBox(\"../../data/meta/migrations\"),\n\t\tDir: s.Driver(),\n\t\tTablePrefix: s.Prefix(),\n\t}\n\n\t_, err := sql.ExecMigration(s.DB(), s.Driver(), migrations, migrate.Up, \"data_meta_\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Preparing the db statements\n\tif options.Bool(\"prepare\", true) {\n\t\tfor key, query := range queries {\n\t\t\tif err := s.Prepare(key, query); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (e *EventSourcedEntity) init() error {\n\te.SnapshotEvery = snapshotEveryDefault\n\treturn nil\n}", "func init() {\n\tcfg = pkg.InitializeConfig()\n\t_, err := pkg.InitializeDb()\n\tif err != nil {\n\t\tpanic(\"failed to initialize db connection : \" + err.Error())\n\t}\n}", "func init() {\n\tgather.Register(sqsRegName, &sqsCreator{})\n}", "func init() {\n\tvar logger = log.Get()\n\tlogger.Info(\"Processing Golang plugin init function!!\" )\n\t//Here you write the code for db connection\n}", "func init(){\n \n err := CreateSchema()\n if err != nil {\n fmt.Printf(\"token-mgr_test:init:%s\\n\", err)\n os.Exit(1)\n }\n MockTokenTuple = TokenTuple{1234, MockUserEmail, \"12345678901234567890\"}\n err = MockTokenTuple.UpdateToken()\n if err != nil {\n fmt.Printf(\"token-mgr_test:init:%s\\n\", err)\n os.Exit(2)\n }\n}", "func init() {\n\tdrmaa2os.RegisterJobTracker(drmaa2os.SingularitySession, NewAllocator())\n}", "func Init(dbpath string) {\n\tdatabase.db, err = sql.Open(\"sqlite3\", dbpath+\"?loc=auto&parseTime=true\")\n\t// database.db, err = sql.Open(\"mysql\", \"Username:Password@tcp(Host:Port)/standardnotes?parseTime=true\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif database.db == nil {\n\t\tlog.Fatal(\"db nil\")\n\t}\n\tdatabase.createTables()\n}", "func init() {\n\tconfig.Read()\n\n\tdao.Server = config.Server\n\tdao.Database = config.Database\n\tdao.Connect()\n}", "func init() {\n\tconfig.Read()\n\n\tdao.Server = config.Server\n\tdao.Database = config.Database\n\tdao.Connect()\n}", "func init() {\n\t// init func\n}", "func (s *OnlineDDLStorage) Init(tctx *tcontext.Context) error {\n\tonlineDB := s.cfg.To\n\tonlineDB.RawDBCfg = config.DefaultRawDBConfig().SetReadTimeout(maxCheckPointTimeout)\n\tdb, dbConns, err := createConns(tctx, s.cfg, onlineDB, 1)\n\tif err != nil {\n\t\treturn terror.WithScope(err, terror.ScopeDownstream)\n\t}\n\ts.db = db\n\ts.dbConn = dbConns[0]\n\n\terr = s.prepare(tctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.Load(tctx)\n}", "func (accountRepo *mockAccountRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (m *metricRedisDbAvgTTL) init() {\n\tm.data.SetName(\"redis.db.avg_ttl\")\n\tm.data.SetDescription(\"Average keyspace keys TTL\")\n\tm.data.SetUnit(\"ms\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n}", "func (d *DB) Init() {\n\td.NumCell = 1024 // set num cell first!\n\td.root = d.NewNode()\n\t//log.Printf(\"+d.root: %v\\n\", d.root)\n}", "func Init() {\n\tdb, err = gorm.Open(getDBConfig())\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\n\t// スキーマのマイグレーション\n\tdb.AutoMigrate(&model.Project{})\n\tdb.AutoMigrate(model.Tag{}).AddForeignKey(\"project_id\", \"projects(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.AutoMigrate(model.Member{}).AddForeignKey(\"project_id\", \"projects(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.AutoMigrate(model.ShuffleLogHead{}).AddForeignKey(\"project_id\", \"projects(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.AutoMigrate(model.ShuffleLogDetail{}).AddForeignKey(\"shuffle_log_head_id\", \"shuffle_log_heads(id)\", \"RESTRICT\", \"RESTRICT\")\n}", "func (d *Database) Init() {\n\t//initialize Directory\n\td.Directory.Param = d.Param\n\td.Directory.Init()\n}", "func (c *Collector) Init() error { return nil }", "func init() {\n\t// capture\n\tbql.MustRegisterGlobalSourceCreator(\"opencv_capture_from_uri\",\n\t\t&opencv.FromURICreator{})\n\tbql.MustRegisterGlobalSourceCreator(\"opencv_capture_from_device\",\n\t\t&opencv.FromDeviceCreator{})\n\n\t// cascade classifier\n\tudf.MustRegisterGlobalUDSCreator(\"opencv_cascade_classifier\",\n\t\tudf.UDSCreatorFunc(opencv.NewCascadeClassifier))\n\tudf.MustRegisterGlobalUDF(\"opencv_detect_multi_scale\",\n\t\tudf.MustConvertGeneric(opencv.DetectMultiScale))\n\tudf.MustRegisterGlobalUDF(\"opencv_draw_rects\",\n\t\tudf.MustConvertGeneric(opencv.DrawRectsToImage))\n\n\t// mount image\n\tudf.MustRegisterGlobalUDSCreator(\"opencv_shared_image\",\n\t\tudf.UDSCreatorFunc(opencv.NewSharedImage))\n\tudf.MustRegisterGlobalUDF(\"opencv_mount_image\",\n\t\tudf.MustConvertGeneric(opencv.MountAlphaImage))\n}", "func (announceRepo *mockAnnounceRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (db *UserDatabase) Init() error {\n\tvar err error\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, stmt := range schemaV1 {\n\t\tlog.Println(stmt)\n\t\ttx.MustExec(stmt)\n\t}\n\tdefaultPassword := getDefaultPassword()\n\t_, err = tx.CreateUser(claudia.ApplicationAdminUsername, defaultPassword)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsessionAuthKey := securecookie.GenerateRandomKey(32)\n\tsessionCryptKey := securecookie.GenerateRandomKey(32)\n\tcrt, key := util.GenerateSelfSignedCert()\n\ttx.MustExec(\"INSERT INTO configuration (schema_version, session_auth_key, session_crypt_key, private_key, public_certificate) VALUES ($1, $2, $3, $4, $5)\",\n\t\tSchemaVersion, sessionAuthKey, sessionCryptKey, key, crt)\n\ttx.Commit()\n\ttx, err = db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tconf, err := tx.GetConfiguration()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\tlog.Printf(\"Successfully initialized database (schema: %d)\", conf.SchemaVersion)\n\treturn nil\n}", "func (db *DB) Init(ctx *Context) (err error) {\n\tconst createTable = `CREATE TABLE IF NOT EXISTS ` + tableName + ` (\n\t\tid SERIAL PRIMARY KEY,\n\t\theader VARCHAR(255),\n\t\tdata TEXT\n\t)`\n\t_, err = db.DB.ExecContext(ctx.Ctx, createTable)\n\treturn\n}", "func init() {\n\tMigrations = append(Migrations, addUserMigration0001)\n}", "func Init(debug bool) {\n\t// Connect to the database\n\tInitDB(debug)\n}", "func (o *OracleDatabase) Init(ctx context.Context, metadata state.Metadata) error {\n\treturn o.dbaccess.Init(ctx, metadata)\n}", "func (userRepo *mockUserRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (userAfhRepo *mockUserAfhRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func initSchema(ctx context.Context, db *sqlx.DB, log *log.Logger, isUnittest bool) func(*sqlx.DB) error {\n\tf := func(db *sqlx.DB) error {\n\t\treturn nil\n\t}\n\n\treturn f\n}", "func init() {\n\tuserHooks := schema.User{}.Hooks()\n\tuser.Hooks[0] = userHooks[0]\n\tuser.Hooks[1] = userHooks[1]\n}", "func DBInit() {\n\t// Mode = \"PRODUCTION\"\n\t// if Mode == \"PRODUCTION\" {\n\t// \tDatabaseURL = \"test.sqlite3\"\n\t// \tDatabaseName = \"sqlite3\"\n\t// } else if Mode == \"DEPLOY\" {\n\tDatabaseURL = os.Getenv(\"DATABASE_URL\")\n\tDatabaseName = \"postgres\"\n\t// }\n\n\tdb, err := gorm.Open(DatabaseName, DatabaseURL)\n\tif err != nil {\n\t\tpanic(\"We can't open database!(dbInit)\")\n\t}\n\t//残りのモデルはまだ入れてない。\n\tdb.AutoMigrate(&model.Post{})\n\tdb.AutoMigrate(&model.User{})\n\tdb.AutoMigrate(&model.Room{})\n\tdefer db.Close()\n}", "func init() {\n\tcollectors.Register(\"zookeeper_db\", func() (collectors.Collector, error) {\n\t\treturn &ZookeeperCollector{\n\t\t\tresourceManager: platform.GetResourceManager(),\n\t\t}, nil\n\t})\n}", "func Init(cfg Configuration) error {\n\tsqlDriver := \"postgres\"\n\tif os.Getenv(\"LIMES_DEBUG_SQL\") == \"1\" {\n\t\tutil.LogInfo(\"Enabling SQL tracing... \\x1B[1;31mTHIS VOIDS YOUR WARRANTY!\\x1B[0m If database queries fail in unexpected ways, check first if the tracing causes the issue.\")\n\t\tsqlDriver += \"-debug\"\n\t}\n\n\tdb, err := sql.Open(sqlDriver, cfg.Location)\n\tif err != nil {\n\t\treturn err\n\t}\n\tDB = &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}\n\tInitGorp()\n\n\t//wait for database to reach our expected migration level (this is useful\n\t//because, depending on the rollout strategy, `limes-migrate` might still be\n\t//running when we are starting, so wait for it to complete)\n\tmigrationLevel, err := getCurrentMigrationLevel(cfg)\n\tutil.LogDebug(\"waiting for database to migrate to schema version %d\", migrationLevel)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := DB.Prepare(fmt.Sprintf(\"SELECT 1 FROM schema_migrations WHERE version = %d\", migrationLevel))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\twaitInterval := 1\n\tfor {\n\t\trows, err := stmt.Query()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif rows.Next() {\n\t\t\t//got a row - success\n\t\t\tbreak\n\t\t}\n\t\t//did not get a row - expected migration not there -> sleep with exponential backoff\n\t\twaitInterval *= 2\n\t\tutil.LogInfo(\"database is not migrated to schema version %d yet - will retry in %d seconds\", migrationLevel, waitInterval)\n\t\ttime.Sleep(time.Duration(waitInterval) * time.Second)\n\t}\n\n\tutil.LogDebug(\"database is migrated - commencing normal startup...\")\n\treturn nil\n}", "func (locationRepo *mockLocationRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (askForHelpRepo *mockAskForHelpRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (mdb *MemoryDB) Init() (err error) {\n\tmdb.table = make(map[string]*TableRow)\n\treturn nil\n}", "func init() {\n\t// Open a connection to GORM\n\tdb, err := gorm.Open(\"sqlite3\", \"shop.db\")\n\tif err != nil {\n\t\tpanic(\"Failed to connect database\")\n\t}\n\n\tDB = db\n\n\tDB.AutoMigrate(models.Supply{})\n}", "func (or *orchestrator) init() {\n\tor.sigStop = make(chan struct{})\n\tor.blkCache = ring.New(orBlockCacheCapacity)\n\n\t// connect services' input channels to their source\n\tor.mgr.trd.inTransaction = or.mgr.bld.outTransaction\n\tor.mgr.acd.inAccount = or.mgr.trd.outAccount\n\tor.mgr.lgd.inLog = or.mgr.trd.outLog\n\tor.mgr.bld.inBlock = or.mgr.bls.outBlock\n\tor.mgr.bls.inDispatched = or.mgr.bld.outDispatched\n\tor.mgr.bud.inTransaction = or.mgr.trd.outTransaction\n\tor.inScanStateSwitch = or.mgr.bls.outStateSwitch\n\n\t// read initial block scanner state\n\t// no need to worry about race condition, init() is called sequentially and this is the last one\n\tor.pushHeads = or.mgr.bls.onIdle\n}", "func init(){\n fmt.Printf(\"init Mongo START\\n\")\n session, err := mgo.Dial(\"localhost\")\n if err != nil {\n panic(err)\n }\n /* defer session.Close() */\n // Optional. Switch the session to a monotonic behavior.\n base_config = &Config{\n session: session,\n }\n fmt.Printf(\"init Mongo DONE\\n\")\n}", "func (oplog *OpLog) init(maxBytes int) {\n\toplogExists := false\n\tobjectsExists := false\n\tnames, _ := oplog.s.DB(\"\").CollectionNames()\n\tfor _, name := range names {\n\t\tswitch name {\n\t\tcase \"oplog_ops\":\n\t\t\toplogExists = true\n\t\tcase \"oplog_states\":\n\t\t\tobjectsExists = true\n\t\t}\n\t}\n\tif !oplogExists {\n\t\tlog.Info(\"OPLOG creating capped collection\")\n\t\terr := oplog.s.DB(\"\").C(\"oplog_ops\").Create(&mgo.CollectionInfo{\n\t\t\tCapped: true,\n\t\t\tMaxBytes: maxBytes,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tif !objectsExists {\n\t\tlog.Info(\"OPLOG creating objects index\")\n\t\tc := oplog.s.DB(\"\").C(\"oplog_states\")\n\t\t// Replication query\n\t\tif err := c.EnsureIndexKey(\"event\", \"ts\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// Replication query with a filter on types\n\t\tif err := c.EnsureIndexKey(\"event\", \"data.t\", \"ts\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// Fallback query\n\t\tif err := c.EnsureIndexKey(\"ts\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// Fallback query with a filter on types\n\t\tif err := c.EnsureIndexKey(\"data.t\", \"ts\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}", "func InitDb() {\n\tdbConnection.MustExec(schema)\n}", "func init() {\n\t//todo...\n}", "func InitSchema() {\n\tup()\n}", "func (env *TestEnv) Init(t *testing.T, testLedgerID string) {\n\tenv.t = t\n\tenv.DBEnv.Init(t)\n\tenv.DB = env.DBEnv.GetDBHandle(testLedgerID)\n\tenv.TStoreEnv = transientstore.NewTestStoreEnv(t)\n\tenv.Txmgr = NewLockbasedTxMgr(env.DB)\n\tenv.TStore = env.TStoreEnv.TestStore\n}", "func (userClassesRepo *mockUserClassRepo) Initialize(ctx context.Context, db *sql.DB) {}" ]
[ "0.6228379", "0.6132799", "0.6124769", "0.611345", "0.6099221", "0.60398847", "0.60326946", "0.6002052", "0.59966946", "0.5975844", "0.59691447", "0.59588313", "0.5943331", "0.59345126", "0.593097", "0.59258366", "0.59011894", "0.59010583", "0.5896269", "0.5892798", "0.58857423", "0.5865996", "0.58640206", "0.5858638", "0.58442533", "0.5841416", "0.5838865", "0.58229595", "0.58114624", "0.5789317", "0.5773263", "0.5767483", "0.5762142", "0.5753206", "0.57485163", "0.5747907", "0.57447505", "0.5732802", "0.57211244", "0.5717781", "0.5710167", "0.57025456", "0.57022834", "0.56899166", "0.56846124", "0.5677988", "0.56690246", "0.56688833", "0.5667853", "0.5666085", "0.56560105", "0.56556654", "0.5631595", "0.5618055", "0.56172884", "0.56170094", "0.561179", "0.5605135", "0.5593652", "0.55906487", "0.55868715", "0.55798715", "0.55729", "0.5563557", "0.5554813", "0.5554813", "0.5554308", "0.5553286", "0.55387986", "0.55348545", "0.5532944", "0.5527854", "0.5527203", "0.55258715", "0.552289", "0.55168986", "0.5516858", "0.5515994", "0.5512371", "0.55105704", "0.5507142", "0.5503614", "0.5500486", "0.55003023", "0.54993916", "0.5498658", "0.54942274", "0.54878426", "0.5486685", "0.5479478", "0.5478808", "0.54777884", "0.5473996", "0.5471606", "0.546245", "0.5458644", "0.54575026", "0.5456698", "0.5452377", "0.54482216" ]
0.5728609
38
UpdateName update current user name
func (this *Client) UpdateName() bool { fmt.Println("Please input user name") fmt.Scanln(&this.Name) sendMsg := fmt.Sprintf("rename|%v\n", this.Name) _, err := this.conn.Write([]byte(sendMsg)) if err != nil { fmt.Println("conn.Write error: ", err) return false } return true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c Controller) UpdateName(w http.ResponseWriter, r *http.Request) {\n\tuserID := chi.URLParam(r, \"userID\")\n\trequest := &UpdateNameRequest{}\n\tif err := render.Bind(r, request); err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := c.userService.UpdateName(r.Context(), userID, request.Name)\n\tif err != nil {\n\t\thttp.Error(w, \"could not update user\", http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (u *User) changeName(name string) {\n u.name = name\n}", "func (srv *Service) UpdateUserName(id string, name string) (*string, error) {\n\t//check if the email already exists\n\t_, err := srv.mongoRepository.GetUserByID(id)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//call driven adapter responsible for updating a user's name inside the database\n\t_, err = srv.mongoRepository.UpdateUserName(id, name)\n\n\tif err != nil {\n\t\t//return the error sent by the repository\n\t\treturn nil, err\n\t}\n\n\tmessage := \"Name updated sucessfully\"\n\n\treturn &message, nil\n}", "func (r *NucypherAccountRepository) UpdateName(name string, updatedBy string, accountID int, now time.Time) error {\n\n\t_, err := r.store.db.NamedExec(`UPDATE nucypher_accounts \n\tSET name=:name, updated_by=:updated_by, updated_at=:updated_at\n\tWHERE (created_by=:updated_by AND account_id=:account_id)`,\n\t\tmap[string]interface{}{\n\t\t\t\"name\": name,\n\t\t\t\"updated_by\": updatedBy,\n\t\t\t\"account_id\": accountID,\n\t\t\t\"updated_at\": now,\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}", "func (b *Bot) SetName(newName string) {\n\tv := url.Values{\"role\": {b.BotId}, \"type\": {\"profile\"}, \"dataType\": {\"name\"}, \"name\": {newName}}\n\trequest, _ := http.NewRequest(\"POST\", fmt.Sprintf(\"https://admin-official.line.me/%v/account/profile/name\", b.BotId), strings.NewReader(v.Encode()))\n\trequest.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded; charset=UTF-8\")\n\trequest.Header.Set(\"X-CSRF-Token\", b.xrt)\n\tresponse, _ := b.client.Do(request)\n\tdefer response.Body.Close()\n}", "func (p *Person) updateName(newFirstName string) {\n\tp.firstName = newFirstName\n}", "func (p *person) updateName(newFirstName string) {\n\tp.firstName = newFirstName\n}", "func (this *Queries_UServ) UpdateUserName(ctx context.Context, db persist.Runnable) *Query_UServ_UpdateUserName {\n\treturn &Query_UServ_UpdateUserName{\n\t\topts: this.opts,\n\t\tctx: ctx,\n\t\tdb: db,\n\t}\n}", "func (*UserSvr) UpdateByName(req *UpdateByNameReq, rsp *UpdateByNameRsp) int {\n\titem := &req.UserItem\n\tif item.Username == \"\" || item.Nickname == \"\" || item.Profile == \"\" {\n\t\treturn common.ErrArg\n\t}\n\tdb := common.GetDb()\n\tresult, err := db.Exec(\"UPDATE users set nickname=? , profile = ? where username=?\",\n\t\treq.UserItem.Nickname, req.UserItem.Profile, req.UserItem.Username)\n\tif err != nil {\n\t\tlog.Printf(\"Update failed,err:%v\", err)\n\t\treturn common.ErrDB\n\t}\n\trowsaffected, err := result.RowsAffected()\n\tif err != nil || rowsaffected != 1 {\n\t\tlog.Printf(\"failed, RowsAffected:%d err:%v\", rowsaffected, err)\n\t\treturn common.ErrArg\n\t}\n\t// here should use redis, but found that this redis lib dose not use conection pool,\n\t// not useful to bench test\n\treturn 0\n}", "func (a *Account) UpdateName(tx *storage.Connection, newName string) error {\n\tif newName == \"\" {\n\t\treturn errors.New(\"Error: invalid name\")\n\t}\n\ta.Name = newName\n\treturn tx.UpdateOnly(a, \"name\", \"updated_at\")\n}", "func (pounterToPerson *person) updateName(newlasttname string) {\n\t(*pounterToPerson).lastname = newlasttname // Update the lastname using the actual location\n}", "func UserNameChange(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"Content-Type\", \"text/javascript\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\tif r.Method != \"POST\" {\n\t\tfmt.Fprintln(w, \"bad request\")\n\t\treturn\n\t}\n\n\tr.ParseForm()\n\tVC := r.Form[\"vc\"][0]\n\tID := r.Form[\"id\"][0]\n\tUserName := r.Form[\"username\"][0]\n\n\tvar temp = new(structs.User)\n\tcollection := session.DB(\"bkbfbtpiza46rc3\").C(\"users\")\n\n\tFindErr := collection.Find(bson.M{\"name\": UserName}).One(&temp)\n\n\tif FindErr == nil {\n\t\tfmt.Fprintln(w, \"reserved\")\n\t\treturn\n\t}\n\n\tif FindErr == mgo.ErrNotFound {\n\n\t\tFindErr = collection.FindId(bson.ObjectIdHex(ID)).One(&temp)\n\n\t\tif temp.Vc == VC {\n\n\t\t\tUpdateErr := collection.UpdateId(temp.ID, bson.M{\"$set\": bson.M{\"name\": UserName}})\n\n\t\t\tif UpdateErr != nil {\n\t\t\t\tfmt.Fprintln(w, \"0\")\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tfmt.Fprintln(w, \"1\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t} else {\n\t\t\tfmt.Fprintln(w, \"-1\")\n\t\t\treturn\n\t\t}\n\n\t}\n\n}", "func (mapper *Mapper) Update(newName string) {\n\tlog.Printf(\"%s has changed their name to %s\\n\", mapper.Username, newName)\n\tmapper.Username = newName\n\tDB.Save(&mapper)\n}", "func (c *Client) ModifyUserName(name, token string, autoSign bool) (*ModifyUserNameResponse, error) {\n\tvar createSign string\n\tif autoSign {\n\t\tcreateSign = \"1\"\n\t}\n\tp := modifyUserNameParams{\n\t\tUserName: name,\n\t\tCreateSignature: createSign,\n\t}\n\tparamMap, err := toMap(p, map[string]string{\n\t\t\"token\": token,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret, err := httpRequest(c, p.URI(), paramMap, nil, func() interface{} {\n\t\treturn &ModifyUserNameResponse{}\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trsp := ret.(*ModifyUserNameResponse)\n\n\tif err = checkErr(rsp.Code, rsp.SubCode, rsp.Message); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rsp, nil\n}", "func (u *GithubGistUpsertOne) UpdateName() *GithubGistUpsertOne {\n\treturn u.Update(func(s *GithubGistUpsert) {\n\t\ts.UpdateName()\n\t})\n}", "func (a *LocalKeyAgent) UpdateUsername(username string) {\n\ta.username = username\n}", "func (cc *Client) SetName(name string) (*User, error) {\n\tif !ValidateName(name) {\n\t\treturn nil, ErrNameInvalid\n\t}\n\tu := &User{}\n\tu.Name = name\n\terr := cc.AuthedRequest(\"POST\", cc.config.BioHost, cc.config.BioPort, \"/v1/bio\", u, u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn u, nil\n}", "func (u *GameServerUpsertOne) UpdateName() *GameServerUpsertOne {\n\treturn u.Update(func(s *GameServerUpsert) {\n\t\ts.UpdateName()\n\t})\n}", "func (u *User) ChangeName(fullName FullName) Events {\n\tu.Person.FullName = fullName\n\n\treturn Events{EventWithPayload(&PersonNameChanged{\n\t\tTenantID: u.TenantID,\n\t\tUsername: u.Username,\n\t\tFullName: fullName,\n\t})}\n}", "func updateName(name string, id int) {\n\tsqlStatement := `\nUPDATE people\nSET Name = $2\nWHERE id = $1;`\n\t_, err := Db.Exec(sqlStatement, id, name)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"People Name Updated\", id)\n\n}", "func (u *GithubGistUpsert) UpdateName() *GithubGistUpsert {\n\tu.SetExcluded(githubgist.FieldName)\n\treturn u\n}", "func (d *Directory) UpdateName(p, name, newName string) error {\n\tiNode, err := d.checkINodeExists(p, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tiNode.lock()\n\tdefer iNode.unlock()\n\tswitch iNode.(type) {\n\tcase *File:\n\t\tiNode.(*File).Name = newName\n\tcase *Directory:\n\t\tiNode.(*Directory).Name = newName\n\t}\n\treturn nil\n}", "func (u *GameServerUpsert) UpdateName() *GameServerUpsert {\n\tu.SetExcluded(gameserver.FieldName)\n\treturn u\n}", "func (pointerToPerson *person) updateName(newFName string) {\n\t(*pointerToPerson).firstName = newFName\n}", "func (pointerToPerson *person) updateName(newFirstName string) {\n\t(*pointerToPerson).firstName = newFirstName\n}", "func (a *Client) UpdateUsername(params *UpdateUsernameParams, authInfo runtime.ClientAuthInfoWriter) (*UpdateUsernameOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewUpdateUsernameParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"updateUsername\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/usernames/{userName}\",\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: &UpdateUsernameReader{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.(*UpdateUsernameOK), nil\n\n}", "func (s Server) ChangeLastname(ctx context.Context, data *userRPC.Lastname) (*userRPC.Empty, error) {\n\terr := s.service.ChangeLastName(ctx, data.GetLastname())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &userRPC.Empty{}, nil\n}", "func (m *Mobile) SetName(username string) error {\n\tif !m.node.Online() {\n\t\treturn core.ErrOffline\n\t}\n\n\treturn m.node.SetName(username)\n}", "func (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne {\n\tuuo.mutation.SetName(s)\n\treturn uuo\n}", "func (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne {\n\tuuo.mutation.SetName(s)\n\treturn uuo\n}", "func (ptrToPerson *person) updateName(newFirstName string) {\n\t(*ptrToPerson).firstName = newFirstName\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 (u *user) Name() string {\n\treturn u.data.Name\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 (db *database) UpdatePersonName(\n\tctx context.Context,\n\tpersonID int,\n\tfirstName, lastName string,\n) error {\n\n\tresult, err := db.ExecContext(ctx, `\n\t\tUPDATE person SET\n\t\t\tfirst_name = $1,\n\t\t\tlast_name = $2\n\t\tWHERE person_id = $3\n\t`, firstName, lastName, personID)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to update person name\")\n\t}\n\n\tn, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to check result of person name update\")\n\t} else if n != 1 {\n\t\treturn errors.Wrapf(\n\t\t\tapp.ErrNotFound,\n\t\t\t\"no such person by id of %d\", personID,\n\t\t)\n\t}\n\n\treturn nil\n}", "func (u Username) Name() string {\n\treturn strings.Title(\n\t\tfmt.Sprintf(\"%s %s\", u.Firstname(), u.Lastname()),\n\t)\n}", "func (ah *AuthHandler) UpdateUsername(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tuser := &data.User{}\n\terr := data.FromJSON(user, r.Body)\n\tif err != nil {\n\t\tah.logger.Error(\"unable to decode user json\", \"error\", err.Error())\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t// data.ToJSON(&GenericError{Error: err.Error()}, w)\n\t\tdata.ToJSON(&GenericResponse{Status: false, Message: err.Error()}, w)\n\t\treturn\n\t}\n\n\tuser.ID = r.Context().Value(UserIDKey{}).(string)\n\tah.logger.Debug(\"udpating username for user : \", user)\n\n\terr = ah.repo.UpdateUsername(context.Background(), user)\n\tif err != nil {\n\t\tah.logger.Error(\"unable to update username\", \"error\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t// data.ToJSON(&GenericError{Error: err.Error()}, w)\n\t\tdata.ToJSON(&GenericResponse{Status: false, Message: \"Unable to update username. Please try again later\"}, w)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\t// data.ToJSON(&UsernameUpdate{Username: user.Username}, w)\n\tdata.ToJSON(&GenericResponse{\n\t\tStatus: true,\n\t\tMessage: \"Successfully updated username\",\n\t\tData: &UsernameUpdate{Username: user.Username},\n\t}, w)\n}", "func SetName(name string) { note.Name = name }", "func (m *AgedAccountsPayable) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\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 (uu *UserUpdate) SetName(s string) *UserUpdate {\n\tuu.mutation.SetName(s)\n\treturn uu\n}", "func (uu *UserUpdate) SetName(s string) *UserUpdate {\n\tuu.mutation.SetName(s)\n\treturn uu\n}", "func TestUpdateName(t *testing.T) {\n\tc := &Command{Use: \"name xyz\"}\n\toriginalName := c.Name()\n\n\tc.Use = \"changedName abc\"\n\tif originalName == c.Name() || c.Name() != \"changedName\" {\n\t\tt.Error(\"c.Name() should be updated on changed c.Use\")\n\t}\n}", "func TestUpdateName(t *testing.T) {\n\tc := &Command{Use: \"name xyz\"}\n\toriginalName := c.Name()\n\n\tc.Use = \"changedName abc\"\n\tif originalName == c.Name() || c.Name() != \"changedName\" {\n\t\tt.Error(\"c.Name() should be updated on changed c.Use\")\n\t}\n}", "func (u User) Name() string {\n\treturn u.name\n}", "func (pointerToPerson *person) updateName(newFirstName string) {\n\t// *pointer (gives the value this memory address is pointing at)\n\t// *pointerToPerosn (operator) means we want to manipulate the value the pointer is referencing\n\t(*pointerToPerson).firstName = newFirstName\n}", "func (s Service) ChangeLastName(ctx context.Context, lastname string) error {\n\tspan := s.tracer.MakeSpan(ctx, \"ChangeLastName\")\n\tdefer span.Finish()\n\n\ttoken := s.retriveToken(ctx)\n\tif token == \"\" {\n\t\treturn errors.New(\"token_is_empty\")\n\t}\n\n\ts.passContext(&ctx)\n\n\tuserID, err := s.authRPC.GetUserID(ctx, token)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\treturn err\n\t}\n\n\t//check for lastname not to be empty or over 32 or contain !alphabets\n\terr = fromTwoToHundredTwentyEight(lastname)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = dashAndSpace(lastname)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdateReg, err := s.repository.Users.GetDateOfRegistration(ctx, userID)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\t//internal error\n\t\treturn err\n\t}\n\n\tif time.Since(dateReg) > 5*(24*time.Hour) {\n\t\treturn errors.New(\"time_for_this_action_is_passed\")\n\t}\n\n\terr = s.repository.Users.ChangeLastName(ctx, userID, lastname)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\treturn nil\n}", "func UpdateName(template *servingv1alpha1.RevisionTemplateSpec, name string) error {\n\tif template.Spec.DeprecatedContainer != nil {\n\t\treturn ApiTooOldError\n\t}\n\ttemplate.Name = name\n\treturn nil\n}", "func (upi *UserPrivateInfo) Update(name string, email string, password string) {\n\tupi.Name = name\n\tupi.Email = email\n\tupi.Password = password\n}", "func (pointerToPerson *person) updateName(newFirstName string) {\n\t// '*' before a type e.g *person is a type description, in our case a pointer that only points to a person type\n\t// '*' operator before a pointer(memory address) requires the actual value the memory address is pointing at\n\t(*pointerToPerson).firstname = newFirstName\n}", "func (*UsersController) Rename(ctx *gin.Context) {\n\tvar renameJSON tat.RenameUserJSON\n\tctx.Bind(&renameJSON)\n\n\tvar userToRename = tat.User{}\n\tfound, err := userDB.FindByUsername(&userToRename, renameJSON.Username)\n\tif !found {\n\t\tctx.JSON(http.StatusBadRequest, gin.H{\"error\": fmt.Errorf(\"user with username %s does not exist\", renameJSON.Username)})\n\t\treturn\n\t} else if err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, gin.H{\"error\": fmt.Errorf(\"Error while fetching user with username %s\", renameJSON.Username)})\n\t\treturn\n\t}\n\n\tif err := userDB.Rename(&userToRename, renameJSON.NewUsername); err != nil {\n\t\tctx.JSON(http.StatusBadRequest, gin.H{\"error\": fmt.Errorf(\"Rename %s user to %s failed\", renameJSON.Username, renameJSON.NewUsername)})\n\t\treturn\n\t}\n\n\tif err := messageDB.ChangeUsernameOnMessages(userToRename.Username, renameJSON.NewUsername); err != nil {\n\t\tctx.JSON(http.StatusBadRequest, gin.H{\"error\": fmt.Errorf(\"Rename %s user to %s failed\", renameJSON.Username, renameJSON.NewUsername)})\n\t\treturn\n\t}\n\tctx.JSON(http.StatusCreated, gin.H{\"info\": \"user is renamed\"})\n}", "func (c *myClient) updateUserPasswordByName(u string, p string) (err error) {\n\tuserRef, err := c.findObjectByNameReturnReference(\"user\", u)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif userRef == nil {\n\t\tlogger.Fatalf(\"%s not found. Exiting\", u)\n\t}\n\tlogger.Infof(\"Changing %s's password\\n\", u)\n\tlogger.Infof(\"Using \" + c.username)\n\tpostBody := fmt.Sprintf(`\n\t\t\t{\n\t\t\t\t\"type\": \"CredentialUpdateParameters\",\n\t\t\t\t\"newCredential\": {\n\t\t\t\t\t\"type\": \"PasswordCredential\",\n\t\t\t\t\t\"password\": \"%s\"\n\t\t\t\t}\n\t\t\t}\n\t\t`, p)\n\tc.LoadAndValidate()\n\t_, _, err = c.httpPost(fmt.Sprintf(\"user/%s/updateCredential\", userRef), postBody)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c.username == u {\n\t\tc.password = p\n\t\tc.LoadAndValidate()\n\t}\n\treturn err\n}", "func (m *LabelActionBase) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (self Users) Update() {\n\tsqlStatement := `UPDATE users SET username = $2 WHERE id = $1`\n\t_, err := self.DB.Exec(sqlStatement, self.Id, self.UserName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (k *Kitten) SetName(name string) {\n k.Name = name\n}", "func (o IotHubDeviceUpdateAccountOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *IotHubDeviceUpdateAccount) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o UserOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *User) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o UserOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *User) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (p Person) ChangeName(newName string) {\n\tp.Name = newName\n}", "func (u *User) Name() string {\n\treturn u.name\n}", "func (u *User) Name() string {\n\treturn u.name\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 (d UserData) SetName(value string) m.UserData {\n\td.ModelData.Set(models.NewFieldName(\"Name\", \"name\"), value)\n\treturn d\n}", "func (u *OrganizationUpsert) UpdateName() *OrganizationUpsert {\n\tu.SetExcluded(organization.FieldName)\n\treturn u\n}", "func (ks *KerbServer) UserName() string {\n\treturn C.GoString(ks.state.username)\n}", "func (u *PetUpsertOne) UpdateName() *PetUpsertOne {\n\treturn u.Update(func(s *PetUpsert) {\n\t\ts.UpdateName()\n\t})\n}", "func (pointerToPerson *person) updateName(newFirstName string) {\n\t(*pointerToPerson).firstName = newFirstName // *p get the value from memory address p\n}", "func (b *ClientAdaptor) SetName(n string) { b.name = n }", "func (self *BaseActor) SetName(newName string) {\n\tself.name = newName\n}", "func (u *OrganizationUpsertOne) UpdateName() *OrganizationUpsertOne {\n\treturn u.Update(func(s *OrganizationUpsert) {\n\t\ts.UpdateName()\n\t})\n}", "func (b *TestDriver) SetName(n string) { b.name = n }", "func ModifyCityName(p *ProfileInfo, newCity string) {\n\tfmt.Printf(\"City changed from %v to %v \\n\", p.City, newCity)\n\tp.City = newCity\n\n}", "func (s UserSet) SetName(value string) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Name\", \"name\"), value)\n}", "func (user *User) GetName() string {\n\treturn user.Username\n}", "func (u *Updater) Name() string {\n\treturn u.name\n}", "func (m *ChatMessageAttachment) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func UpdateUser(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"Updating a user\"))\n}", "func (a *Account) CreateNameUpdate(name, value string) (*Transaction, error) {\n\tsb := txscript.NewScriptBuilder()\n\n\t// Build the name script\n\tsb.AddOp(txscript.OP_3).\n\t\tAddData([]byte(name)).AddData([]byte(value)).\n\t\tAddOp(txscript.OP_2DROP).AddOp(txscript.OP_DROP)\n\n\tlastTx, err := a.getLastNameTx(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a.finishNameTransaction(name, sb, lastTx)\n}", "func (service *RssService) SetNewName(data models.FeedUpdateData, userID int64) models.Feeds {\n\tfeed := models.Feeds{}\n\tservice.db.Where(&models.Feeds{Id: data.FeedId, UserId: userID}).First(&feed)\n\n\tif feed.Id == 0 {\n\t\treturn feed\n\t}\n\n\tif data.IsReadAll {\n\t\tservice.db.Model(&models.Articles{}).\n\t\t\tWhere(&models.Articles{FeedId: feed.Id}).\n\t\t\tNot(&models.Articles{IsRead: true}).\n\t\t\tUpdateColumn(\"is_read = ?\", true)\n\t}\n\tif data.Name != \"\" {\n\t\tfeed.Name = data.Name\n\t\tservice.db.Save(&feed)\n\t}\n\n\treturn feed\n}", "func (u *PetUpsert) UpdateName() *PetUpsert {\n\tu.SetExcluded(pet.FieldName)\n\treturn u\n}", "func UpdateUserCodeByName(c *gin.Context) {\n\tname := c.PostForm(\"name\")\n\n\tif name == \"\" {\n\t\tc.JSON(200, gin.H{\"code\": \"-1\", \"msg\": \"name cannot be empty!\"})\n\t}\n\n\tif db.UserCheckIsExist(name) {\n\t\trand := libs.RandString(10)\n\t\tdb.UserUpdateCodeGetByName(name, rand)\n\t\tc.JSON(200, gin.H{\"code\": \"0\", \"co\": rand})\n\t} else {\n\t\tc.JSON(200, gin.H{\"code\": \"-2\", \"msg\": \"name does not exist!\"})\n\t}\n\n}", "func (m *User) SetPreferredName(value *string)() {\n m.preferredName = value\n}", "func (m *MockIUserService) UpdateUserByName(oldName, newName string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateUserByName\", oldName, newName)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (h *MPU6050Driver) SetName(n string) { h.name = n }", "func (p person) updateFirstName(newName string) {\n\tp.firstName = newName\n}", "func (ul *usernameList) modifyUsername(id int, name string) error {\n\tul.Lock()\n\tdefer ul.Unlock()\n\n\t_, exists := ul.usernameToID[name]\n\tif exists {\n\t\treturn errors.New(\"username already exists\")\n\t}\n\n\toldName, ok := ul.idToUsername[id]\n\tif !ok {\n\t\treturn errors.New(\"connection does not have a username already\")\n\t}\n\n\tif oldName == name {\n\t\treturn nil\n\t}\n\n\tul.idToUsername[id] = name\n\tul.usernameToID[name] = id\n\tdelete(ul.usernameToID, oldName)\n\n\treturn nil\n}", "func (su *SystemUser) Name() string {\n\treturn su.HeaderString(\"name\")\n}", "func (p *person) update(newName string) {\n\tfmt.Printf(\"%+v\\n\", *p)\n\tp.name = newName\n}", "func (suo *SettingUpdateOne) SetName(s string) *SettingUpdateOne {\n\tsuo.mutation.SetName(s)\n\treturn suo\n}", "func (nuo *NodeUpdateOne) SetName(s string) *NodeUpdateOne {\n\tnuo.mutation.SetName(s)\n\treturn nuo\n}", "func (m *PolicyRule) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (internet Internet) UserName(v reflect.Value) (interface{}, error) {\n\treturn internet.username()\n}", "func (u User) GetName() string {\n\treturn u.Name\n}", "func (d *Driver) SetName(n string) { d.name = n }", "func NewName(v string) predicate.User {\n\treturn predicate.User(sql.FieldEQ(FieldNewName, v))\n}", "func (this *Queries_UServ) UpdateNameToFoo(ctx context.Context, db persist.Runnable) *Query_UServ_UpdateNameToFoo {\n\treturn &Query_UServ_UpdateNameToFoo{\n\t\topts: this.opts,\n\t\tctx: ctx,\n\t\tdb: db,\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 (db *Database) SetUsername(user *models.User) error {\n\tuser.Name = strings.ToLower(user.Name)\n\tdbUser, err := db.GetUserByName(user.Name)\n\tif err != nil && !errors.Is(err, models.ErrNotFound) {\n\t\treturn err\n\t}\n\n\tif dbUser != nil {\n\t\tif dbUser.Name == user.Name {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn errors.New(\"name already in use\")\n\t}\n\n\t_, err = db.Collection(userCol).Doc(user.ID).Update(db.ctx, []firestore.Update{\n\t\t{Path: \"name\", Value: user.Name},\n\t})\n\n\treturn err\n}", "func UpdateUser(c *gin.Context) {}", "func (nu *NodeUpdate) SetName(s string) *NodeUpdate {\n\tnu.mutation.SetName(s)\n\treturn nu\n}" ]
[ "0.81112033", "0.7604066", "0.74778044", "0.7455612", "0.7332312", "0.71893257", "0.7169424", "0.71337676", "0.71016157", "0.68882", "0.6878002", "0.68680453", "0.6857677", "0.6740467", "0.6733093", "0.6727908", "0.6665813", "0.66257167", "0.6617168", "0.66098046", "0.6590194", "0.6576891", "0.65734565", "0.6508", "0.64952356", "0.64669913", "0.6461289", "0.64530855", "0.6447126", "0.6447126", "0.64174813", "0.6416716", "0.6409033", "0.6400678", "0.6399409", "0.6377876", "0.6361497", "0.63355654", "0.62749434", "0.62166774", "0.6212446", "0.6212446", "0.61930645", "0.61930645", "0.6174413", "0.61720204", "0.616049", "0.61602116", "0.61557466", "0.6153922", "0.61499876", "0.6127617", "0.6120748", "0.6116644", "0.611491", "0.61042064", "0.6103429", "0.6103429", "0.6103215", "0.6102886", "0.6102886", "0.6102093", "0.60813606", "0.6072609", "0.6053251", "0.60513705", "0.60506517", "0.60426736", "0.6041057", "0.6039805", "0.6027966", "0.6015748", "0.60072035", "0.5970098", "0.59659165", "0.5962381", "0.5961924", "0.5951916", "0.5951009", "0.594634", "0.5945679", "0.59383327", "0.5934549", "0.5926312", "0.59152275", "0.5906271", "0.59040886", "0.5903218", "0.5903057", "0.58957344", "0.58952916", "0.5889448", "0.5884174", "0.58807975", "0.5873959", "0.5871246", "0.5847542", "0.58327675", "0.58287764", "0.58258426" ]
0.7574992
2
/ Description: Calculates the percentage share of a specific cycle for all delegated contracts on a range of cycles. Param delegatedContracts ([]DelegatedClient): A list of all the delegated contracts Param cycleStart (int): The first cycle we are calculating Param cycleEnd (int): The last cycle we are calculating Returns delegatedContracts ([]DelegatedContract): A list of all the delegated contracts
func CalculateAllContractsForCycles(delegatedContracts []DelegatedContract, cycleStart int, cycleEnd int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){ var err error for cycleStart <= cycleEnd { //fmt.Println(cycleStart) delegatedContracts, err = CalculateAllContractsForCycle(delegatedContracts, cycleStart, rate, spillage, delegateAddr) if (err != nil){ return delegatedContracts, errors.New("Could not calculate all commitments for cycles " + strconv.Itoa(cycleStart) + "-" + strconv.Itoa(cycleEnd) + ":CalculateAllCommitmentsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64) failed: " + err.Error()) } cycleStart = cycleStart + 1 } return delegatedContracts, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func GetDelegatedContractsForCycle(cycle int, delegateAddr string) ([]string, error){\n var rtnString []string\n snapShot, err := GetSnapShot(cycle)\n // fmt.Println(snapShot)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetSnapShot(cycle int) failed: \" + err.Error())\n }\n hash, err:= GetBlockLevelHash(snapShot.AssociatedBlock)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetBlockLevelHash(level int) failed: \" + err.Error())\n }\n // fmt.Println(hash)\n getDelegatedContracts := \"/chains/main/blocks/\" + hash + \"/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n\n s, err := TezosRPCGet(getDelegatedContracts)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1)\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": You have no contracts.\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{\n for _, delegatedContract := range delegatedContracts {\n err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias)\n if (err != nil){\n return errors.New(\"Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: \" + err.Error())\n }\n }\n return nil\n}", "func DelegatorSharesInvariant(k Keeper) sdk.Invariant {\n\treturn func(ctx sdk.Context) (string, bool) {\n\t\tvar (\n\t\t\tmsg string\n\t\t\tbroken bool\n\t\t)\n\n\t\tdefis := k.GetAllDefis(ctx)\n\t\tfor _, defi := range defis {\n\t\t\tdefiTotalDelShares := defi.GetDelegatorShares()\n\t\t\ttotalDelShares := sdk.ZeroDec()\n\n\t\t\tdelegations := k.GetDefiDelegations(ctx, defi.GetOperator())\n\t\t\tfor _, delegation := range delegations {\n\t\t\t\ttotalDelShares = totalDelShares.Add(delegation.Shares)\n\t\t\t}\n\n\t\t\tif !defiTotalDelShares.Equal(totalDelShares) {\n\t\t\t\tbroken = true\n\t\t\t\tmsg += fmt.Sprintf(\"broken delegator shares invariance:\\n\"+\n\t\t\t\t\t\"\\tdefi.DelegatorShares: %v\\n\"+\n\t\t\t\t\t\"\\tsum of Delegator.Shares: %v\\n\", defiTotalDelShares, totalDelShares)\n\t\t\t}\n\t\t}\n\n\t\treturn sdk.FormatInvariant(types.ModuleName, \"delegator shares\", msg), broken\n\t}\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func GetAllDelegatedContracts(delegateAddr string) ([]string, error){\n var rtnString []string\n delegatedContractsCmd := \"/chains/main/blocks/head/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n s, err := TezosRPCGet(delegatedContractsCmd)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts: TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1) //TODO Error checking\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get all delegated contracts: Regex failed\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func calculateRewards(delegationTotal loom.BigUInt, params *Params, totalValidatorDelegations loom.BigUInt) loom.BigUInt {\n\tcycleSeconds := params.ElectionCycleLength\n\treward := CalculateFraction(blockRewardPercentage, delegationTotal)\n\n\t// If totalValidator Delegations are high enough to make simple reward\n\t// calculations result in more rewards given out than the value of `MaxYearlyReward`,\n\t// scale the rewards appropriately\n\tyearlyRewardTotal := CalculateFraction(blockRewardPercentage, totalValidatorDelegations)\n\tif yearlyRewardTotal.Cmp(&params.MaxYearlyReward.Value) > 0 {\n\t\treward.Mul(&reward, &params.MaxYearlyReward.Value)\n\t\treward.Div(&reward, &yearlyRewardTotal)\n\t}\n\n\t// When election cycle = 0, estimate block time at 2 sec\n\tif cycleSeconds == 0 {\n\t\tcycleSeconds = 2\n\t}\n\treward.Mul(&reward, &loom.BigUInt{big.NewInt(cycleSeconds)})\n\treward.Div(&reward, &secondsInYear)\n\n\treturn reward\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func calculateRewardShares(operator string, delegate []byte, epochs string) *RewardShares {\n\tif epochs == \"\" {\n\t\treturn calculateEpochRewardShares(\n\t\t\toperator, delegate, currentEpochNum())\n\t}\n\n\t// parse a range of epochs\n\tresult := NewRewardShares()\n\tresult.SetEpochNum(epochs)\n\tfor epoch := range epochRangeGen(epochs) {\n\t\tfmt.Printf(\"epoch: %v\\n\", epoch)\n\t\treward := calculateEpochRewardShares(operator, delegate, epoch)\n\t\tresult = result.Combine(reward)\n\t}\n\treturn result\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func ProportionalShare(config *pb.Algorithm) Algorithm {\n\tlength, interval := getAlgorithmParams(config)\n\n\treturn func(r Request) Lease {\n\t\tvar (\n\t\t\tcount = r.Store.Count()\n\t\t\told = r.Store.Get(r.Client)\n\t\t\tgets = 0.0\n\t\t)\n\n\t\t// If this is a new client, we adjust the count.\n\t\tif !r.Store.HasClient(r.Client) {\n\t\t\tcount += r.Subclients\n\t\t}\n\n\t\t// This is the equal share that every subclient has an absolute\n\t\t// claim on.\n\t\tequalShare := r.Capacity / float64(count)\n\n\t\t// This is the equal share that should be assigned to the current client\n\t\t// based on the number of its subclients.\n\t\tequalSharePerClient := equalShare * float64(r.Subclients)\n\n\t\t// This is the capacity which is currently unused (assuming that\n\t\t// the requesting client has no capacity). It is the maximum\n\t\t// capacity that this run of the algorithm can assign to the\n\t\t// requesting client.\n\t\tunusedCapacity := r.Capacity - r.Store.SumHas() + old.Has\n\n\t\t// If the client wants less than it equal share or\n\t\t// if the sum of what all clients want together is less\n\t\t// than the available capacity we can give this client what\n\t\t// it wants.\n\t\tif r.Store.SumWants() <= r.Capacity || r.Wants <= equalSharePerClient {\n\t\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\t\tminF(r.Wants, unusedCapacity), r.Wants, r.Subclients)\n\t\t}\n\n\t\t// We now need to determine if we can give a top-up on\n\t\t// the equal share. The capacity for this top up comes\n\t\t// from clients who want less than their equal share,\n\t\t// so we calculate how much capacity this is. We also\n\t\t// calculate the excess need of all the clients, which\n\t\t// is the sum of all the wants over the equal share.\n\t\textraCapacity := 0.0\n\t\textraNeed := 0.0\n\n\t\tr.Store.Map(func(id string, lease Lease) {\n\t\t\tvar wants float64\n\t\t\tvar subclients int64\n\n\t\t\tif id == r.Client {\n\t\t\t\twants = r.Wants\n\t\t\t\tsubclients = r.Subclients\n\t\t\t} else {\n\t\t\t\twants = lease.Wants\n\t\t\t\tsubclients = lease.Subclients\n\t\t\t}\n\n\t\t\t// Every client should receive the resource capacity based on the number\n\t\t\t// of subclients it has.\n\t\t\tequalSharePerClient := equalShare * float64(subclients)\n\t\t\tif wants < equalSharePerClient {\n\t\t\t\textraCapacity += equalSharePerClient - wants\n\t\t\t} else {\n\t\t\t\textraNeed += wants - equalSharePerClient\n\t\t\t}\n\t\t})\n\n\t\t// Every client with a need over the equal share will get\n\t\t// a proportional top-up.\n\t\tgets = equalSharePerClient + (r.Wants-equalSharePerClient)*(extraCapacity/extraNeed)\n\n\t\t// Insert the capacity grant into the lease store. We cannot\n\t\t// give out more than the currently unused capacity. If that\n\t\t// is less than what the algorithm calculated we will\n\t\t// adjust this in the next capacity refreshes.\n\n\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\tminF(gets, unusedCapacity), r.Wants, r.Subclients)\n\t}\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_DelegatableDai *DelegatableDaiSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func SortDelegateContracts(delegatedContracts []DelegatedContract) []DelegatedContract{\n for i, j := 0, len(delegatedContracts)-1; i < j; i, j = i+1, j-1 {\n delegatedContracts[i], delegatedContracts[j] = delegatedContracts[j], delegatedContracts[i]\n }\n return delegatedContracts\n}", "func (s *ArkClient) CalculateVotersProfit(params DelegateQueryParams, shareRatio float64, blocklist string, whitelist string, capBalance bool, balanceCapAmount float64, blockBalanceCap bool) []DelegateDataProfit {\n\tdelegateRes, _, _ := s.GetDelegate(params)\n\tvoters, _, _ := s.GetDelegateVoters(params)\n\taccountRes, _, _ := s.GetAccount(AccountQueryParams{Address: delegateRes.SingleDelegate.Address})\n\n\tdelegateBalance, _ := strconv.ParseFloat(accountRes.Account.Balance, 64)\n\tdelegateBalance = float64(delegateBalance) / SATOSHI\n\n\t//calculating vote weight\n\tvotersProfit := []DelegateDataProfit{}\n\tdelelgateVoteWeight := 0\n\n\t//computing summ of all votes\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tintBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tintBalance = int(balanceCapAmount)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelelgateVoteWeight += intBalance\n\t}\n\n\t//calculating\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tcurrentVoterBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcurrentVoterBalance = balanceCapAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdeleProfit := DelegateDataProfit{\n\t\t\tAddress: element.Address,\n\t\t}\n\t\tdeleProfit.VoteWeight = currentVoterBalance / SATOSHI\n\t\tdeleProfit.VoteWeightShare = float64(currentVoterBalance) / float64(delelgateVoteWeight)\n\t\tdeleProfit.EarnedAmount100 = float64(delegateBalance) * deleProfit.VoteWeightShare\n\t\tdeleProfit.EarnedAmountXX = float64(delegateBalance) * deleProfit.VoteWeightShare * shareRatio\n\t\tdeleProfit.VoteDuration = s.GetVoteDuration(element.Address)\n\t\tvotersProfit = append(votersProfit, deleProfit)\n\t}\n\n\treturn votersProfit\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (_DelegatableDai *DelegatableDaiCaller) Balances(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegatableDai.contract.Call(opts, out, \"balances\", arg0)\n\treturn *ret0, err\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (w *Worker) IncrementShares(sessionDifficulty float64, reward float64) {\n\tp := w.s.Client.pool\n\tcbid := p.cs.CurrentBlock().ID()\n\tblockTarget, _ := p.cs.ChildTarget(cbid)\n\tblockDifficulty, _ := blockTarget.Difficulty().Uint64()\n\n\tsessionTarget, _ := difficultyToTarget(sessionDifficulty)\n\tsiaSessionDifficulty, _ := sessionTarget.Difficulty().Uint64()\n\tshareRatio := caculateRewardRatio(sessionTarget.Difficulty().Big(), blockTarget.Difficulty().Big())\n\tshareReward := shareRatio * reward\n\t// w.log.Printf(\"shareRatio: %f, shareReward: %f\", shareRatio, shareReward)\n\n\tshare := &Share{\n\t\tuserid: w.Parent().cr.clientID,\n\t\tworkerid: w.wr.workerID,\n\t\theight: int64(p.cs.Height()) + 1,\n\t\tvalid: true,\n\t\tdifficulty: sessionDifficulty,\n\t\tshareDifficulty: float64(siaSessionDifficulty),\n\t\treward: reward,\n\t\tblockDifficulty: blockDifficulty,\n\t\tshareReward: shareReward,\n\t\ttime: time.Now(),\n\t}\n\n\tw.s.Shift().IncrementShares(share)\n}", "func (_ConsortiumManagement *ConsortiumManagementCaller) Delegates(opts *bind.CallOpts) ([]common.Address, error) {\n\tvar out []interface{}\n\terr := _ConsortiumManagement.contract.Call(opts, &out, \"delegates\")\n\n\tif err != nil {\n\t\treturn *new([]common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address)\n\n\treturn out0, err\n\n}", "func (m *GraphBaseServiceClient) Contracts()(*ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.ContractsRequestBuilder) {\n return ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.NewContractsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Contracts()(*ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.ContractsRequestBuilder) {\n return ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.NewContractsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (_Cakevault *CakevaultCaller) TotalShares(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"totalShares\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (s *RoundsService) Delegates(ctx context.Context, id int64) (*GetDelegates, *http.Response, error) {\n\turi := fmt.Sprintf(\"rounds/%v/delegates\", id)\n\n\tvar responseStruct *GetDelegates\n\tresp, err := s.client.SendRequest(ctx, \"GET\", uri, nil, nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCallerSession) Digests(arg0 [32]byte) (*big.Int, error) {\n\treturn _BondedECDSAKeep.Contract.Digests(&_BondedECDSAKeep.CallOpts, arg0)\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func GenerateShares(transportPrivateKey *big.Int, transportPublicKey [2]*big.Int, participants ParticipantList, threshold int) ([]*big.Int, []*big.Int, [][2]*big.Int, error) {\n\n\t// create coefficients (private/public)\n\tprivateCoefficients, err := cloudflare.ConstructPrivatePolyCoefs(rand.Reader, threshold)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tpublicCoefficients := cloudflare.GeneratePublicCoefs(privateCoefficients)\n\n\t// create commitments\n\tcommitments := make([][2]*big.Int, len(publicCoefficients))\n\tfor idx, publicCoefficient := range publicCoefficients {\n\t\tcommitments[idx] = bn256.G1ToBigIntArray(publicCoefficient)\n\t}\n\n\t// secret shares\n\ttransportPublicKeyG1, err := bn256.BigIntArrayToG1(transportPublicKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// convert public keys into G1 structs\n\tpublicKeyG1s := []*cloudflare.G1{}\n\tfor idx := 0; idx < len(participants); idx++ {\n\t\tparticipant := participants[idx]\n\t\tlogger.Infof(\"participants[%v]: %v\", idx, participant)\n\t\tif participant != nil && participant.PublicKey[0] != nil && participant.PublicKey[1] != nil {\n\t\t\tpublicKeyG1, err := bn256.BigIntArrayToG1(participant.PublicKey)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\tpublicKeyG1s = append(publicKeyG1s, publicKeyG1)\n\t\t}\n\t}\n\n\t// check for missing data\n\tif len(publicKeyG1s) != len(participants) {\n\t\treturn nil, nil, nil, fmt.Errorf(\"only have %v of %v public keys\", len(publicKeyG1s), len(participants))\n\t}\n\n\tif len(privateCoefficients) != threshold+1 {\n\t\treturn nil, nil, nil, fmt.Errorf(\"only have %v of %v private coefficients\", len(privateCoefficients), threshold+1)\n\t}\n\n\t//\n\tsecretsArray, err := cloudflare.GenerateSecretShares(transportPublicKeyG1, privateCoefficients, publicKeyG1s)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to generate secret shares: %v\", err)\n\t}\n\n\t// final encrypted shares\n\tencryptedShares, err := cloudflare.GenerateEncryptedShares(secretsArray, transportPrivateKey, publicKeyG1s)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to generate encrypted shares: %v\", err)\n\t}\n\n\treturn encryptedShares, privateCoefficients, commitments, nil\n}", "func (_Cakevault *CakevaultCallerSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (_ConsortiumManagement *ConsortiumManagementCallerSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func (acc *Account) Delegations(args *struct {\n\tCursor *Cursor\n\tCount int32\n}) (*DelegationList, error) {\n\t// limit query size; the count can be either positive or negative\n\t// this controls the loading direction\n\targs.Count = listLimitCount(args.Count, listMaxEdgesPerRequest)\n\n\t// pull the list\n\tdl, err := repository.R().DelegationsByAddress(&acc.Address, (*string)(args.Cursor), args.Count)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// convert to resolvable list\n\treturn NewDelegationList(dl), nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) Digests(arg0 [32]byte) (*big.Int, error) {\n\treturn _BondedECDSAKeep.Contract.Digests(&_BondedECDSAKeep.CallOpts, arg0)\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func (_Cakevault *CakevaultSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (ms mainnetSchedule) ConsensusRatio() float64 {\n\treturn mainnetConsensusRatio\n}", "func (s *ArkClient) GetDelegateVoteWeight(params DelegateQueryParams) (int, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\t//calculating vote weight\n\tbalance := 0\n\tif respData.Success {\n\t\tfor _, element := range respData.Accounts {\n\t\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\t\tbalance += intBalance\n\t\t}\n\t}\n\n\treturn balance, resp, err\n}", "func (_ConsortiumManagement *ConsortiumManagementSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) Contracts(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"contracts\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _OwnerProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCaller) Digests(opts *bind.CallOpts, arg0 [32]byte) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BondedECDSAKeep.contract.Call(opts, out, \"digests\", arg0)\n\treturn *ret0, err\n}", "func (k *Keeper) GetAllDecryptionShares(ctx sdk.Context, round uint64) ([]*types.DecryptionShare, sdk.Error) {\n\tstage := k.GetStage(ctx, round)\n\tif stage != stageDSCollecting && stage != stageCompleted {\n\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"wrong round stage: %v. round: %v\", stage, round))\n\t}\n\n\tdsStore := ctx.KVStore(k.storeDecryptionSharesKey)\n\n\tkeyAllShares := []byte(fmt.Sprintf(\"rd_%d\", round))\n\n\tif !dsStore.Has(keyAllShares) {\n\t\treturn []*types.DecryptionShare{}, nil\n\t}\n\n\taddrListBytes := dsStore.Get(keyAllShares)\n\tvar addrList []string\n\terr := k.cdc.UnmarshalJSON(addrListBytes, &addrList)\n\tif err != nil {\n\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"can't unmarshal list of all adderesses from store: %v\", err))\n\t}\n\tdsList := make([]*types.DecryptionShare, 0, len(addrList))\n\tfor _, addrStr := range addrList {\n\t\taddr, err := sdk.AccAddressFromBech32(addrStr)\n\t\tif err != nil {\n\t\t\treturn nil, sdk.ErrUnknownAddress(fmt.Sprintf(\"can't get address from bench32: %v\", err))\n\t\t}\n\t\tkey := createKeyBytesByAddr(round, addr)\n\t\tif !dsStore.Has(key) {\n\t\t\treturn nil, sdk.ErrUnknownRequest(\"addresses list and real decryption share sender doesn't meet\")\n\t\t}\n\t\tdsBytes := dsStore.Get(key)\n\t\tvar dsJSON types.DecryptionShareJSON\n\t\terr = k.cdc.UnmarshalJSON(dsBytes, &dsJSON)\n\t\tif err != nil {\n\t\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"can't unmarthsal decryption share: %v\", err))\n\t\t}\n\t\tds, err1 := dsJSON.Deserialize()\n\t\tif err1 != nil {\n\t\t\treturn nil, err1\n\t\t}\n\t\tdsList = append(dsList, ds)\n\t}\n\treturn dsList, nil\n}", "func (m *GraphBaseServiceClient) Shares()(*i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.SharesRequestBuilder) {\n return i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.NewSharesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Shares()(*i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.SharesRequestBuilder) {\n return i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.NewSharesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRedelegate) (*types.MsgBeginRedelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsrcValidator, found := k.GetValidator(ctx, valSrcAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\tdstValidator, found := k.GetValidator(ctx, valDstAddr)\n\tif !found {\n\t\treturn nil, types.ErrBadRedelegationDst\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, valSrcAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorSrcAddress,\n\t\t)\n\t}\n\n\tsrcShares, err := k.ValidateUnbondAmount(ctx, delegatorAddress, valSrcAddr, msg.Amount.Amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdstShares, err := dstValidator.SharesFromTokensTruncated(msg.Amount.Amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &srcValidator, srcShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// If this delegation from a liquid staker, the delegation on the new validator\n\t// cannot exceed that validator's self-bond cap\n\t// The liquid shares from the source validator should get moved to the destination validator\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &dstValidator, dstShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &srcValidator, srcShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.BeginRedelegation(\n\t\tctx, delegatorAddress, valSrcAddr, valDstAddr, srcShares,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif msg.Amount.Amount.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"redelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(msg.Amount.Amount.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeRedelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeySrcValidator, msg.ValidatorSrcAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDstValidator, msg.ValidatorDstAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgBeginRedelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func ratioAutoConsoCalculator(details model.ClientTotalInfo) float64 {\n\n\ttotalHomeComsuption := details.FromGenToConsumer + details.FromGridToConsumer\n\ttotalPannelProduction := details.FromGenToConsumer + details.FromGenToGrid\n\n\tratio := totalPannelProduction / totalHomeComsuption * 100\n\n\treturn ratio\n}", "func (gc *GovernanceContract) DelegationsBy(args struct{ From common.Address }) ([]common.Address, error) {\n\t// decide by the contract type\n\tswitch gc.Type {\n\tcase \"sfc\":\n\t\treturn gc.sfcDelegationsBy(args.From)\n\t}\n\n\t// no delegations by default\n\tgc.repo.Log().Debugf(\"unknown governance type of %s\", gc.Address.Hex())\n\treturn []common.Address{}, nil\n}", "func FairShare(config *pb.Algorithm) Algorithm {\n\tlength, interval := getAlgorithmParams(config)\n\n\treturn func(r Request) Lease {\n\t\tvar (\n\t\t\tcount = r.Store.Count()\n\t\t\told = r.Store.Get(r.Client)\n\t\t)\n\n\t\t// If this is a new client, we adjust the count.\n\t\tif !r.Store.HasClient(r.Client) {\n\t\t\tcount += r.Subclients\n\t\t}\n\n\t\t// This is the equal share that every subclient should get.\n\t\tequalShare := r.Capacity / float64(count)\n\n\t\t// This is the equal share that should be assigned to the current client\n\t\t// based on the number of its subclients.\n\t\tequalSharePerClient := equalShare * float64(r.Subclients)\n\n\t\t// This is the capacity which is currently unused (assuming that\n\t\t// the requesting client has no capacity). It is the maximum\n\t\t// capacity that this run of the algorithm can assign to the\n\t\t// requesting client.\n\t\tunusedCapacity := r.Capacity - r.Store.SumHas() + old.Has\n\n\t\t// If the client wants less than its equal share or\n\t\t// if the sum of what all clients want together is less\n\t\t// than the available capacity we can give this client what\n\t\t// it wants.\n\t\tif r.Wants <= equalSharePerClient || r.Store.SumWants() <= r.Capacity {\n\t\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\t\tminF(r.Wants, unusedCapacity), r.Wants, r.Subclients)\n\t\t}\n\n\t\t// Map of what each client will get from this algorithm run.\n\t\t// Ultimately we need only determine what this client gets,\n\t\t// but for the algorithm we need to keep track of what\n\t\t// other clients would be getting as well.\n\t\tgets := make(map[string]float64)\n\n\t\t// This list contains all the clients which are still in\n\t\t// the race to get some capacity.\n\t\tclients := list.New()\n\t\tclientsNext := list.New()\n\n\t\t// Puts every client in the list to signify that they all\n\t\t// still need capacity.\n\t\tr.Store.Map(func(id string, lease Lease) {\n\t\t\tclients.PushBack(id)\n\t\t})\n\n\t\t// This is the capacity that can still be divided.\n\t\tavailableCapacity := r.Capacity\n\n\t\t// The clients list now contains all the clients who still need/want\n\t\t// capacity. We are going to divide the capacity in availableCapacity\n\t\t// in iterations until there is nothing more to divide or until we\n\t\t// completely satisfied the client who is making the request.\n\t\tfor availableCapacity > epsilon && gets[r.Client] < r.Wants-epsilon {\n\t\t\t// Calculate number of subclients for the given clients list.\n\t\t\tclientsCopy := *clients\n\t\t\tvar subclients int64\n\t\t\tfor e := clientsCopy.Front(); e != nil; e = e.Next() {\n\t\t\t\tsubclients += r.Store.Subclients(e.Value.(string))\n\t\t\t}\n\n\t\t\t// This is the fair share that is available to all subclients\n\t\t\t// who are still in the race to get capacity.\n\t\t\tfairShare := availableCapacity / float64(subclients)\n\n\t\t\t// Not enough capacity to actually worry about. Prevents\n\t\t\t// an infinite loop.\n\t\t\tif fairShare < epsilon {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// We now process the list of clients and give a topup to\n\t\t\t// every client's capacity. That topup is either the fair\n\t\t\t// share or the capacity still needed to be completely\n\t\t\t// satisfied (in case the client needs less than the\n\t\t\t// fair share to reach its need/wants).\n\t\t\tfor e := clients.Front(); e != nil; e = e.Next() {\n\t\t\t\tid := e.Value.(string)\n\n\t\t\t\t// Determines the wants for this client, which comes\n\t\t\t\t// either from the store, or from the request info if it\n\t\t\t\t// is the client making the request,\n\t\t\t\tvar wants float64\n\t\t\t\tvar subclients int64\n\n\t\t\t\tif id == r.Client {\n\t\t\t\t\twants = r.Wants\n\t\t\t\t\tsubclients = r.Subclients\n\t\t\t\t} else {\n\t\t\t\t\twants = r.Store.Get(id).Wants\n\t\t\t\t\tsubclients = r.Store.Subclients(id)\n\t\t\t\t}\n\n\t\t\t\t// stillNeeds is the capacity this client still needs to\n\t\t\t\t// be completely satisfied.\n\t\t\t\tstillNeeds := wants - gets[id]\n\n\t\t\t\t// Tops up the client's capacity.\n\t\t\t\t// Every client should receive the resource capacity based on\n\t\t\t\t// the number of its subclients.\n\t\t\t\tfairSharePerClient := fairShare * float64(subclients)\n\t\t\t\tif stillNeeds <= fairSharePerClient {\n\t\t\t\t\tgets[id] += stillNeeds\n\t\t\t\t\tavailableCapacity -= stillNeeds\n\t\t\t\t} else {\n\t\t\t\t\tgets[id] += fairSharePerClient\n\t\t\t\t\tavailableCapacity -= fairSharePerClient\n\t\t\t\t}\n\n\t\t\t\t// If the client is not yet satisfied we include it in the next\n\t\t\t\t// generation of the list. If it is completely satisfied we\n\t\t\t\t// don't.\n\t\t\t\tif gets[id] < wants {\n\t\t\t\t\tclientsNext.PushBack(id)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Ready for the next iteration of the loop. Swap the clients with the\n\t\t\t// clientsNext list.\n\t\t\tclients, clientsNext = clientsNext, clients\n\n\t\t\t// Cleans the clientsNext list so that it can be used again.\n\t\t\tclientsNext.Init()\n\t\t}\n\n\t\t// Insert the capacity grant into the lease store. We cannot\n\t\t// give out more than the currently unused capacity. If that\n\t\t// is less than what the algorithm calculated this will get\n\t\t// fixed in the next capacity refreshes.\n\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\tminF(gets[r.Client], unusedCapacity), r.Wants, r.Subclients)\n\t}\n}", "func (c MethodsCollection) ComputeShare() pComputeShare {\n\treturn pComputeShare{\n\t\tMethod: c.MustGet(\"ComputeShare\"),\n\t}\n}", "func (_TransferProxyRegistry *TransferProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _TransferProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (k Keeper) AwardCoinsForRelays(ctx sdk.Ctx, relays int64, toAddr sdk.Address) sdk.BigInt {\n\treturn k.posKeeper.RewardForRelays(ctx, sdk.NewInt(relays), toAddr)\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) Contracts(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"contracts\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tpva.BaseVestingAccount.TrackDelegation(balance, pva.GetVestingCoins(blockTime), amount)\n}", "func ExampleSharesClient_BeginRefresh() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armdataboxedge.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := clientFactory.NewSharesClient().BeginRefresh(ctx, \"testedgedevice\", \"smbshare\", \"GroupForEdgeAutomation\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t_, err = poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n}", "func (instance *Host) GetShares(ctx context.Context) (shares *propertiesv1.HostShares, ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tshares = &propertiesv1.HostShares{}\n\tif valid.IsNil(instance) {\n\t\treturn shares, fail.InvalidInstanceError()\n\t}\n\n\t// instance.RLock()\n\t// defer instance.RUnlock()\n\n\txerr := instance.Inspect(ctx, func(_ data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\treturn props.Inspect(hostproperty.SharesV1, func(clonable data.Clonable) fail.Error {\n\t\t\thostSharesV1, ok := clonable.(*propertiesv1.HostShares)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv1.HostShares' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\tshares = hostSharesV1\n\t\t\treturn nil\n\t\t})\n\t})\n\treturn shares, xerr\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func PercentDiff(matches []Match) []float64 {\n\t// Read in timeseries data, all match results. More data is more better.\n\tvar diffs []float64\n\tfor _, match := range matches {\n\t\td1 := match.P1got / match.P1needs\n\t\td2 := match.P2got / match.P2needs\n\t\tdiffs = append(diffs, d2)\n\t\tdiffs = append(diffs, d1)\n\t}\n\treturn diffs\n}", "func calculateEpochRewardShares(operator string, delegate []byte, epoch_num uint64) *RewardShares {\n\t// get epoch response\n\tgetEpochResponse(epoch_num)\n\n\t// get gravity height\n\tgravity_height := epochGravityHeight()\n\n\t// get number of produced blocks\n\tblocks := delegateProductivity(operator)\n\n\t// get delegate's votes\n\tvotes_distribution, elected, delegate_votes, total_votes := getVotes(delegate, gravity_height)\n\n\t// calculate reward\n\treward := calculateReward(blocks, elected, delegate_votes, total_votes)\n\n\t// populate rewardshare structure\n\treturn NewRewardShares().\n\t\tSetEpochNum(strconv.FormatUint(epoch_num, 10)).\n\t\tSetProductivity(blocks).\n\t\tSetTotalVotes(delegate_votes).\n\t\tSetReward(reward).\n\t\tCalculateShares(votes_distribution, delegate_votes, epoch_num)\n}", "func GenerateShares(secret int64, n int, M *big.Int) []*big.Int {\n\ts := new(big.Int).SetInt64(secret)\n\tsum := new(big.Int)\n\tshares := make([]*big.Int, n)\n\tj := mr.Intn(n)\n\tfor i := 0; i < n; i++ {\n\t\tif i != j {\n\t\t\tshares[i] = getRandom(M)\n\t\t\tsum.Add(sum, shares[i])\n\t\t}\n\t}\n\tshares[j] = s.Sub(s, sum).Mod(s, M)\n\treturn shares\n}", "func (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tcva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount)\n}", "func (c *Client) ListContracts(pageNum, pageSize int, token string) (*ListContractsResponse, error) {\n\tp := listContractsParams{\n\t\tPageNum: fmt.Sprintf(\"%d\", pageNum),\n\t\tPageSize: fmt.Sprintf(\"%d\", pageSize),\n\t}\n\n\tparamMap, err := toMap(p, map[string]string{\n\t\t\"token\": token,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret, err := httpRequest(c, p.URI(), paramMap, nil, func() interface{} {\n\t\treturn &ListContractsResponse{}\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trsp := ret.(*ListContractsResponse)\n\tif err = checkErr(rsp.Code, rsp.SubCode, rsp.Message); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rsp, nil\n}", "func (k Keeper) GetAllDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress) []types.Delegation {\n\tdelegations := make([]types.Delegation, 0)\n\n\tstore := ctx.KVStore(k.storeKey)\n\tdelegatorPrefixKey := types.GetDelegationsKey(delegator)\n\n\titerator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) //smallest to largest\n\tdefer iterator.Close()\n\n\ti := 0\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tdelegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value())\n\t\tdelegations = append(delegations, delegation)\n\t\ti++\n\t}\n\n\treturn delegations\n}", "func DisplayCalculatedVoteRatio() {\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tdeleResp, _, _ := arkclient.GetDelegate(params)\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\tshareRatioStr := strconv.FormatFloat(viper.GetFloat64(\"voters.shareratio\")*100, 'f', -1, 64) + \"%\"\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Displaying voter information for delegate:\", deleResp.SingleDelegate.Username, deleResp.SingleDelegate.Address)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(fmt.Sprintf(\"|%-34s|%18s|%8s|%17s|%17s|%6s|\", \"Voter address\", \"Balance\", \"Weight\", \"Reward-100%\", \"Reward-\"+shareRatioStr, \"Hours\"))\n\tcolor.Set(color.FgCyan)\n\tfor _, element := range votersEarnings {\n\t\ts := fmt.Sprintf(\"|%s|%18.8f|%8.4f|%15.8f A|%15.8f A|%6d|\", element.Address, element.VoteWeight, element.VoteWeightShare, element.EarnedAmount100, element.EarnedAmountXX, element.VoteDuration)\n\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\t}\n\n\t//Cost calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"Available amount:\", sumEarned)\n\tfmt.Println(\"Amount to voters:\", sumShareEarned, viper.GetFloat64(\"voters.shareratio\"))\n\tfmt.Println(\"Amount to costs:\", costAmount, viper.GetFloat64(\"costs.shareratio\"))\n\tfmt.Println(\"Amount to reserve:\", reserveAmount, viper.GetFloat64(\"reserve.shareratio\"))\n\n\tfmt.Println(\"Ratio calc check:\", sumRatio, \"(should be = 1)\")\n\tfmt.Println(\"Ratio share check:\", float64(sumShareEarned)/float64(sumEarned), \"should be=\", viper.GetFloat64(\"voters.shareratio\"))\n\n\tpause()\n}", "func (o DeliveryPipelineSerialPipelineStageStrategyCanaryCanaryDeploymentPtrOutput) Percentages() pulumi.IntArrayOutput {\n\treturn o.ApplyT(func(v *DeliveryPipelineSerialPipelineStageStrategyCanaryCanaryDeployment) []int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Percentages\n\t}).(pulumi.IntArrayOutput)\n}", "func (c *Client) GetContracts(ctx context.Context) (Contracts, error) {\n\tcontracts := make(Contracts, 0)\n\tu := fmt.Sprintf(\"chains/%s/blocks/head/context/contracts\", c.ChainID)\n\tif err := c.Get(ctx, u, &contracts); err != nil {\n\t\treturn nil, err\n\t}\n\treturn contracts, nil\n}", "func (m *Manager) ListReceivedShares(ctx context.Context, filters []*collaboration.Filter) ([]*collaboration.ReceivedShare, error) {\n\tif err := m.initialize(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser, ok := ctxpkg.ContextGetUser(ctx)\n\tif !ok {\n\t\treturn nil, errtypes.UserRequired(\"error getting user from context\")\n\t}\n\n\tresult := []*collaboration.ReceivedShare{}\n\n\tids, err := granteeToIndex(&provider.Grantee{\n\t\tType: provider.GranteeType_GRANTEE_TYPE_USER,\n\t\tId: &provider.Grantee_UserId{UserId: user.Id},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treceivedIds, err := m.indexer.FindBy(&collaboration.Share{},\n\t\tindexer.NewField(\"GranteeId\", ids),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, group := range user.Groups {\n\t\tindex, err := granteeToIndex(&provider.Grantee{\n\t\t\tType: provider.GranteeType_GRANTEE_TYPE_GROUP,\n\t\t\tId: &provider.Grantee_GroupId{GroupId: &groupv1beta1.GroupId{OpaqueId: group}},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgroupIds, err := m.indexer.FindBy(&collaboration.Share{},\n\t\t\tindexer.NewField(\"GranteeId\", index),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treceivedIds = append(receivedIds, groupIds...)\n\t}\n\n\tfor _, id := range receivedIds {\n\t\ts, err := m.getShareByID(ctx, id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !share.MatchesFilters(s, filters) {\n\t\t\tcontinue\n\t\t}\n\t\tmetadata, err := m.downloadMetadata(ctx, s)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(errtypes.NotFound); !ok {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// use default values if the grantee didn't configure anything yet\n\t\t\tmetadata = ReceivedShareMetadata{\n\t\t\t\tState: collaboration.ShareState_SHARE_STATE_PENDING,\n\t\t\t}\n\t\t}\n\t\tresult = append(result, &collaboration.ReceivedShare{\n\t\t\tShare: s,\n\t\t\tState: metadata.State,\n\t\t\tMountPoint: metadata.MountPoint,\n\t\t})\n\t}\n\treturn result, nil\n}", "func ExampleSharesClient_BeginDelete() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armdataboxedge.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := clientFactory.NewSharesClient().BeginDelete(ctx, \"testedgedevice\", \"smbshare\", \"GroupForEdgeAutomation\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t_, err = poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n}", "func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tva.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount)\n}", "func determineChurn(prevConsensus, newConsensus *tor.Consensus) Churn {\n\n\tgoneRelays := prevConsensus.Subtract(newConsensus)\n\tnewRelays := newConsensus.Subtract(prevConsensus)\n\n\tmax := math.Max(float64(prevConsensus.Length()), float64(newConsensus.Length()))\n\tnewChurn := (float64(newRelays.Length()) / max)\n\tgoneChurn := (float64(goneRelays.Length()) / max)\n\n\treturn Churn{newChurn, goneChurn}\n}", "func average_centrality(g Graph, node string) (dis float64) {\n\tdis_from_start := map[string]int{node: 0}\n\topen_list := []string{node}\n\tfor len(open_list) != 0 {\n\t\tcurrent := open_list[0]\n\t\topen_list = open_list[1:]\n\t\tfor neighbor := range g[current] {\n\t\t\tif _, ok := dis_from_start[neighbor]; !ok {\n\t\t\t\tdis_from_start[neighbor] = dis_from_start[current] + 1\n\t\t\t\topen_list = append(open_list, neighbor)\n\t\t\t}\n\t\t}\n\t}\n\tfor _, v := range dis_from_start {\n\t\tdis += float64(v)\n\t}\n\tdis = dis / float64(len(dis_from_start))\n\treturn\n}", "func (dds DelegatorDistributionSchedules) Validate() error {\n\tseenPeriods := make(map[string]bool)\n\tfor _, ds := range dds {\n\t\tif seenPeriods[ds.DistributionSchedule.DepositDenom] {\n\t\t\treturn fmt.Errorf(\"duplicated liquidity provider schedule with deposit denom %s\", ds.DistributionSchedule.DepositDenom)\n\t\t}\n\n\t\tif err := ds.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tseenPeriods[ds.DistributionSchedule.DepositDenom] = true\n\t}\n\n\treturn nil\n}", "func (dds DelegatorDistributionSchedules) Validate() error {\n\tseenPeriods := make(map[string]bool)\n\tfor _, ds := range dds {\n\t\tif seenPeriods[ds.DistributionSchedule.DepositDenom] {\n\t\t\treturn fmt.Errorf(\"duplicated liquidity provider schedule with deposit denom %s\", ds.DistributionSchedule.DepositDenom)\n\t\t}\n\n\t\tif err := ds.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tseenPeriods[ds.DistributionSchedule.DepositDenom] = true\n\t}\n\n\treturn nil\n}", "func (pp *PermuteProtocol) AllocateShares() RefreshShare {\n\treturn RefreshShare{pp.context.ringQ.NewPoly(),\n\t\tpp.context.ringQ.NewPoly()}\n}", "func (refreshProtocol *RefreshProtocol) AllocateShares(levelStart int) (RefreshShareDecrypt, RefreshShareRecrypt) {\n\treturn refreshProtocol.dckksContext.ringQ.NewPolyLvl(levelStart), refreshProtocol.dckksContext.ringQ.NewPoly()\n}", "func SetupContracts(chainURL string, onChainTxTimeout time.Duration) (\n\tadjudicator, asset pwallet.Address, _ error) {\n\tprng := rand.New(rand.NewSource(RandSeedForTestAccs))\n\tws, err := NewWalletSetup(prng, 2)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tonChainCred := perun.Credential{\n\t\tAddr: ws.Accs[0].Address(),\n\t\tWallet: ws.Wallet,\n\t\tKeystore: ws.KeystorePath,\n\t\tPassword: \"\",\n\t}\n\tif !isBlockchainRunning(chainURL) {\n\t\treturn nil, nil, errors.New(\"cannot connect to ganache-cli node at \" + chainURL)\n\t}\n\n\tif adjudicatorAddr == nil && assetAddr == nil {\n\t\tadjudicator = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(onChainCred.Addr), 0))\n\t\tasset = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(onChainCred.Addr), 1))\n\t\tadjudicatorAddr = adjudicator\n\t\tassetAddr = asset\n\t} else {\n\t\tadjudicator = adjudicatorAddr\n\t\tasset = assetAddr\n\t}\n\n\tchain, err := ethereum.NewChainBackend(chainURL, ChainConnTimeout, onChainTxTimeout, onChainCred)\n\tif err != nil {\n\t\treturn nil, nil, errors.WithMessage(err, \"initializaing chain backend\")\n\t}\n\n\terr = chain.ValidateContracts(adjudicator, asset)\n\tif err != nil {\n\t\t// Contracts not yet deployed for this ganache-cli instance.\n\t\tadjudicator, asset, err = deployContracts(chain, onChainCred)\n\t}\n\treturn adjudicator, asset, errors.WithMessage(err, \"initializaing chain backend\")\n}", "func (by *Bybit) GetUSDCContracts(ctx context.Context, symbol currency.Pair, direction string, limit int64) ([]USDCContract, error) {\n\tresp := struct {\n\t\tData []USDCContract `json:\"result\"`\n\t\tUSDCError\n\t}{}\n\n\tparams := url.Values{}\n\tif !symbol.IsEmpty() {\n\t\tsymbolValue, err := by.FormatSymbol(symbol, asset.USDCMarginedFutures)\n\t\tif err != nil {\n\t\t\treturn resp.Data, err\n\t\t}\n\t\tparams.Set(\"symbol\", symbolValue)\n\t}\n\n\tif direction != \"\" {\n\t\tparams.Set(\"direction\", direction)\n\t}\n\tif limit > 0 && limit <= 200 {\n\t\tparams.Set(\"limit\", strconv.FormatInt(limit, 10))\n\t}\n\n\treturn resp.Data, by.SendHTTPRequest(ctx, exchange.RestUSDCMargined, common.EncodeURLValues(usdcfuturesGetContracts, params), usdcPublicRate, &resp)\n}", "func (k *Keeper) GetVaultTotalShares(\n\tctx sdk.Context,\n\tdenom string,\n) (types.VaultShare, bool) {\n\tvault, found := k.GetVaultRecord(ctx, denom)\n\tif !found {\n\t\treturn types.VaultShare{}, false\n\t}\n\n\treturn vault.TotalShares, true\n}", "func (gc *GovernanceContract) sfcDelegationsBy(addr common.Address) ([]common.Address, error) {\n\t// get SFC delegations list\n\tdl, err := gc.repo.DelegationsByAddress(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// prep the result container\n\tres := make([]common.Address, 0)\n\n\t// check if the address is a staker\n\t// if so, it also delegates to itself in the context of the contract\n\tisStaker, err := gc.repo.IsStaker(&addr)\n\tif err == nil && isStaker {\n\t\tres = append(res, addr)\n\t}\n\n\t// loop delegations to make the list\n\tfor _, d := range dl {\n\t\t// is the delegation ok for voting?\n\t\tif nil != d.DeactivatedEpoch && 0 < uint64(*d.DeactivatedEpoch) {\n\t\t\tgc.repo.Log().Debugf(\"delegation to %d from address %s is deactivated\", d.ToStakerId, addr.String())\n\t\t\tcontinue\n\t\t}\n\n\t\t// get the staker info\n\t\tstaker, err := gc.repo.StakerAddress(d.ToStakerId)\n\t\tif err != nil {\n\t\t\tgc.repo.Log().Errorf(\"error loading staker %d info; %s\", d.ToStakerId, addr.String())\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// get the\n\t\tres = append(res, staker)\n\t}\n\n\t// log delegations found\n\tgc.repo.Log().Debugf(\"%d delegations on %s\", len(res), addr.String())\n\treturn res, nil\n}", "func calcdutyCycleFromNeutralCenter(iC *InterfaceConfig, channel int, side string, degreeVal int) int {\n degreeValf := float64(degreeVal)\n var dutyCycle float64 = 0\n if side == \"left\" {\n if iC.StickDir[channel]==\"rev\" {\n if iC.NeutralStickPos[channel]>iC.LeftStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.LeftStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n } else if iC.LeftStickMaxPos[channel]>iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.LeftStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n }\n } else if iC.StickDir[channel]==\"norm\" {\n if iC.NeutralStickPos[channel]<iC.LeftStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.LeftStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n } else if iC.LeftStickMaxPos[channel]<iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.LeftStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n }\n }\n } else if side == \"right\" {\n if iC.StickDir[channel]==\"rev\" {\n if(iC.NeutralStickPos[channel]>iC.RightStickMaxPos[channel]) {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.RightStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n } else if(iC.RightStickMaxPos[channel]>iC.NeutralStickPos[channel]) {\n dutyCycle=float64(iC.RightStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n }\n } else if iC.StickDir[channel]==\"norm\" {\n\n if iC.NeutralStickPos[channel]<iC.RightStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.RightStickMaxPos[channel])\n dutyCycle=dutyCycle/100\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n } else if iC.RightStickMaxPos[channel]<iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.RightStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n }\n }\n }\n println(\"calc Duty cycle: \" + strconv.Itoa(int(dutyCycle)))\n return int(dutyCycle)\n}", "func (_Bep20 *Bep20CallerSession) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func (_BREMICO *BREMICOCaller) Balances(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"balances\", arg0)\n\treturn *ret0, err\n}", "func (k Querier) DelegatorDelegations(ctx context.Context, req *types.QueryDelegatorDelegationsRequest) (*types.QueryDelegatorDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegations, pageRes, err := query.CollectionPaginate(ctx, k.Delegations, req.Pagination,\n\t\tfunc(_ collections.Pair[sdk.AccAddress, sdk.ValAddress], del types.Delegation) (types.Delegation, error) {\n\t\t\treturn del, nil\n\t\t}, query.WithCollectionPaginationPairPrefix[sdk.AccAddress, sdk.ValAddress](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelegationResps, err := delegationsToDelegationResponses(ctx, k.Keeper, delegations)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorDelegationsResponse{DelegationResponses: delegationResps, Pagination: pageRes}, nil\n}", "func (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tdva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), amount)\n}", "func (c *Connector) GetContracts() (*Response, error) {\n\tcontracts, _, err := c.callGet(\"/mediacontract\", \"activate\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not fetch contracts: %s\", err)\n\t}\n\n\treturn contracts, nil\n}", "func (_BREMICO *BREMICOCallerSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _BREMICO.Contract.Balances(&_BREMICO.CallOpts, arg0)\n}", "func (f *Footer) NumOfDelegateEndorsements(delegates []string) int {\n\tif f.endorsements == nil {\n\t\treturn 0\n\t}\n\treturn f.endorsements.NumOfValidEndorsements(\n\t\tmap[endorsement.ConsensusVoteTopic]bool{endorsement.COMMIT: true},\n\t\tdelegates,\n\t)\n}", "func cycles(start string, adj map[string]map[string][]*gographviz.Edge) map[string]bool {\n\treturn dfs(start, start, nil, adj)\n}", "func Percent(value int64, total int64) float64 {\n\tif total == 0 {\n\t\treturn 0\n\t}\n\treturn (float64(value) / float64(total)) * 100\n}", "func (_AccessIndexor *AccessIndexorCaller) Contracts(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _AccessIndexor.contract.Call(opts, &out, \"contracts\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (o DeliveryPipelineSerialPipelineStageStrategyCanaryCanaryDeploymentOutput) Percentages() pulumi.IntArrayOutput {\n\treturn o.ApplyT(func(v DeliveryPipelineSerialPipelineStageStrategyCanaryCanaryDeployment) []int { return v.Percentages }).(pulumi.IntArrayOutput)\n}" ]
[ "0.69740224", "0.6776273", "0.6656224", "0.63475776", "0.5681173", "0.54687977", "0.5309778", "0.5291857", "0.50858015", "0.47683427", "0.4731115", "0.46950582", "0.4671865", "0.46084297", "0.45955548", "0.45724714", "0.4558484", "0.45584065", "0.45495766", "0.45453683", "0.45419672", "0.45383584", "0.45279703", "0.4527256", "0.43421605", "0.4341142", "0.43374294", "0.42910078", "0.42713347", "0.42579618", "0.42542127", "0.42526102", "0.42526102", "0.42511782", "0.42476407", "0.42221472", "0.4221569", "0.4186151", "0.41776153", "0.41696882", "0.41692308", "0.41529608", "0.41212583", "0.4087924", "0.4086599", "0.40760204", "0.4059222", "0.40428945", "0.4040859", "0.40387097", "0.40234134", "0.40210378", "0.40210378", "0.3968685", "0.39684746", "0.39525232", "0.3945722", "0.3942375", "0.3935174", "0.39299527", "0.39288068", "0.39221755", "0.39082012", "0.38947105", "0.3892502", "0.38833967", "0.38781145", "0.38780612", "0.38734555", "0.3864263", "0.38616812", "0.385709", "0.38498464", "0.38418967", "0.38359535", "0.38231024", "0.381878", "0.3812288", "0.38054273", "0.3800002", "0.37896213", "0.37896213", "0.3775607", "0.3773781", "0.37603012", "0.37549064", "0.37497398", "0.37429896", "0.37401527", "0.37334093", "0.37307695", "0.3728045", "0.3725956", "0.37191358", "0.3701758", "0.36948192", "0.3694366", "0.36902806", "0.36836764", "0.36720255" ]
0.6347543
4
/ Description: Calculates the percentage share of a specific cycle for all delegated contracts Param delegatedContracts ([]DelegatedContract): A list of all the delegated contracts Param cycle (int): The cycle we are calculating Param rate (float64): Fee rate of the delegate Param spillage (bool): If the delegate wants to hard cap the payouts at complete rolls Returns delegatedContracts ([]DelegatedContract): A list of all the delegated contracts
func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) { var err error var balance float64 delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr) for index, delegation := range delegatedContracts{ balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle) if (err != nil){ return delegatedContracts, errors.New("Could not calculate all commitments for cycle " + strconv.Itoa(cycle) + ":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: " + err.Error()) } if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){ delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance}) } else{ delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0}) } //fmt.Println(delegatedContracts[index].Contracts) } delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr) if (err != nil){ return delegatedContracts, errors.New("func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: " + err.Error()) } return delegatedContracts, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func CalculateAllContractsForCycles(delegatedContracts []DelegatedContract, cycleStart int, cycleEnd int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var err error\n\n for cycleStart <= cycleEnd {\n //fmt.Println(cycleStart)\n delegatedContracts, err = CalculateAllContractsForCycle(delegatedContracts, cycleStart, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycles \" + strconv.Itoa(cycleStart) + \"-\" + strconv.Itoa(cycleEnd) + \":CalculateAllCommitmentsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64) failed: \" + err.Error())\n }\n cycleStart = cycleStart + 1\n }\n return delegatedContracts, nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func GetDelegatedContractsForCycle(cycle int, delegateAddr string) ([]string, error){\n var rtnString []string\n snapShot, err := GetSnapShot(cycle)\n // fmt.Println(snapShot)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetSnapShot(cycle int) failed: \" + err.Error())\n }\n hash, err:= GetBlockLevelHash(snapShot.AssociatedBlock)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetBlockLevelHash(level int) failed: \" + err.Error())\n }\n // fmt.Println(hash)\n getDelegatedContracts := \"/chains/main/blocks/\" + hash + \"/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n\n s, err := TezosRPCGet(getDelegatedContracts)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1)\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": You have no contracts.\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{\n for _, delegatedContract := range delegatedContracts {\n err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias)\n if (err != nil){\n return errors.New(\"Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: \" + err.Error())\n }\n }\n return nil\n}", "func calculateRewards(delegationTotal loom.BigUInt, params *Params, totalValidatorDelegations loom.BigUInt) loom.BigUInt {\n\tcycleSeconds := params.ElectionCycleLength\n\treward := CalculateFraction(blockRewardPercentage, delegationTotal)\n\n\t// If totalValidator Delegations are high enough to make simple reward\n\t// calculations result in more rewards given out than the value of `MaxYearlyReward`,\n\t// scale the rewards appropriately\n\tyearlyRewardTotal := CalculateFraction(blockRewardPercentage, totalValidatorDelegations)\n\tif yearlyRewardTotal.Cmp(&params.MaxYearlyReward.Value) > 0 {\n\t\treward.Mul(&reward, &params.MaxYearlyReward.Value)\n\t\treward.Div(&reward, &yearlyRewardTotal)\n\t}\n\n\t// When election cycle = 0, estimate block time at 2 sec\n\tif cycleSeconds == 0 {\n\t\tcycleSeconds = 2\n\t}\n\treward.Mul(&reward, &loom.BigUInt{big.NewInt(cycleSeconds)})\n\treward.Div(&reward, &secondsInYear)\n\n\treturn reward\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (s *ArkClient) CalculateVotersProfit(params DelegateQueryParams, shareRatio float64, blocklist string, whitelist string, capBalance bool, balanceCapAmount float64, blockBalanceCap bool) []DelegateDataProfit {\n\tdelegateRes, _, _ := s.GetDelegate(params)\n\tvoters, _, _ := s.GetDelegateVoters(params)\n\taccountRes, _, _ := s.GetAccount(AccountQueryParams{Address: delegateRes.SingleDelegate.Address})\n\n\tdelegateBalance, _ := strconv.ParseFloat(accountRes.Account.Balance, 64)\n\tdelegateBalance = float64(delegateBalance) / SATOSHI\n\n\t//calculating vote weight\n\tvotersProfit := []DelegateDataProfit{}\n\tdelelgateVoteWeight := 0\n\n\t//computing summ of all votes\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tintBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tintBalance = int(balanceCapAmount)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelelgateVoteWeight += intBalance\n\t}\n\n\t//calculating\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tcurrentVoterBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcurrentVoterBalance = balanceCapAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdeleProfit := DelegateDataProfit{\n\t\t\tAddress: element.Address,\n\t\t}\n\t\tdeleProfit.VoteWeight = currentVoterBalance / SATOSHI\n\t\tdeleProfit.VoteWeightShare = float64(currentVoterBalance) / float64(delelgateVoteWeight)\n\t\tdeleProfit.EarnedAmount100 = float64(delegateBalance) * deleProfit.VoteWeightShare\n\t\tdeleProfit.EarnedAmountXX = float64(delegateBalance) * deleProfit.VoteWeightShare * shareRatio\n\t\tdeleProfit.VoteDuration = s.GetVoteDuration(element.Address)\n\t\tvotersProfit = append(votersProfit, deleProfit)\n\t}\n\n\treturn votersProfit\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func calculateRewardShares(operator string, delegate []byte, epochs string) *RewardShares {\n\tif epochs == \"\" {\n\t\treturn calculateEpochRewardShares(\n\t\t\toperator, delegate, currentEpochNum())\n\t}\n\n\t// parse a range of epochs\n\tresult := NewRewardShares()\n\tresult.SetEpochNum(epochs)\n\tfor epoch := range epochRangeGen(epochs) {\n\t\tfmt.Printf(\"epoch: %v\\n\", epoch)\n\t\treward := calculateEpochRewardShares(operator, delegate, epoch)\n\t\tresult = result.Combine(reward)\n\t}\n\treturn result\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func ProportionalShare(config *pb.Algorithm) Algorithm {\n\tlength, interval := getAlgorithmParams(config)\n\n\treturn func(r Request) Lease {\n\t\tvar (\n\t\t\tcount = r.Store.Count()\n\t\t\told = r.Store.Get(r.Client)\n\t\t\tgets = 0.0\n\t\t)\n\n\t\t// If this is a new client, we adjust the count.\n\t\tif !r.Store.HasClient(r.Client) {\n\t\t\tcount += r.Subclients\n\t\t}\n\n\t\t// This is the equal share that every subclient has an absolute\n\t\t// claim on.\n\t\tequalShare := r.Capacity / float64(count)\n\n\t\t// This is the equal share that should be assigned to the current client\n\t\t// based on the number of its subclients.\n\t\tequalSharePerClient := equalShare * float64(r.Subclients)\n\n\t\t// This is the capacity which is currently unused (assuming that\n\t\t// the requesting client has no capacity). It is the maximum\n\t\t// capacity that this run of the algorithm can assign to the\n\t\t// requesting client.\n\t\tunusedCapacity := r.Capacity - r.Store.SumHas() + old.Has\n\n\t\t// If the client wants less than it equal share or\n\t\t// if the sum of what all clients want together is less\n\t\t// than the available capacity we can give this client what\n\t\t// it wants.\n\t\tif r.Store.SumWants() <= r.Capacity || r.Wants <= equalSharePerClient {\n\t\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\t\tminF(r.Wants, unusedCapacity), r.Wants, r.Subclients)\n\t\t}\n\n\t\t// We now need to determine if we can give a top-up on\n\t\t// the equal share. The capacity for this top up comes\n\t\t// from clients who want less than their equal share,\n\t\t// so we calculate how much capacity this is. We also\n\t\t// calculate the excess need of all the clients, which\n\t\t// is the sum of all the wants over the equal share.\n\t\textraCapacity := 0.0\n\t\textraNeed := 0.0\n\n\t\tr.Store.Map(func(id string, lease Lease) {\n\t\t\tvar wants float64\n\t\t\tvar subclients int64\n\n\t\t\tif id == r.Client {\n\t\t\t\twants = r.Wants\n\t\t\t\tsubclients = r.Subclients\n\t\t\t} else {\n\t\t\t\twants = lease.Wants\n\t\t\t\tsubclients = lease.Subclients\n\t\t\t}\n\n\t\t\t// Every client should receive the resource capacity based on the number\n\t\t\t// of subclients it has.\n\t\t\tequalSharePerClient := equalShare * float64(subclients)\n\t\t\tif wants < equalSharePerClient {\n\t\t\t\textraCapacity += equalSharePerClient - wants\n\t\t\t} else {\n\t\t\t\textraNeed += wants - equalSharePerClient\n\t\t\t}\n\t\t})\n\n\t\t// Every client with a need over the equal share will get\n\t\t// a proportional top-up.\n\t\tgets = equalSharePerClient + (r.Wants-equalSharePerClient)*(extraCapacity/extraNeed)\n\n\t\t// Insert the capacity grant into the lease store. We cannot\n\t\t// give out more than the currently unused capacity. If that\n\t\t// is less than what the algorithm calculated we will\n\t\t// adjust this in the next capacity refreshes.\n\n\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\tminF(gets, unusedCapacity), r.Wants, r.Subclients)\n\t}\n}", "func DelegatorSharesInvariant(k Keeper) sdk.Invariant {\n\treturn func(ctx sdk.Context) (string, bool) {\n\t\tvar (\n\t\t\tmsg string\n\t\t\tbroken bool\n\t\t)\n\n\t\tdefis := k.GetAllDefis(ctx)\n\t\tfor _, defi := range defis {\n\t\t\tdefiTotalDelShares := defi.GetDelegatorShares()\n\t\t\ttotalDelShares := sdk.ZeroDec()\n\n\t\t\tdelegations := k.GetDefiDelegations(ctx, defi.GetOperator())\n\t\t\tfor _, delegation := range delegations {\n\t\t\t\ttotalDelShares = totalDelShares.Add(delegation.Shares)\n\t\t\t}\n\n\t\t\tif !defiTotalDelShares.Equal(totalDelShares) {\n\t\t\t\tbroken = true\n\t\t\t\tmsg += fmt.Sprintf(\"broken delegator shares invariance:\\n\"+\n\t\t\t\t\t\"\\tdefi.DelegatorShares: %v\\n\"+\n\t\t\t\t\t\"\\tsum of Delegator.Shares: %v\\n\", defiTotalDelShares, totalDelShares)\n\t\t\t}\n\t\t}\n\n\t\treturn sdk.FormatInvariant(types.ModuleName, \"delegator shares\", msg), broken\n\t}\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (_DelegatableDai *DelegatableDaiSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func DisplayCalculatedVoteRatio() {\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tdeleResp, _, _ := arkclient.GetDelegate(params)\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\tshareRatioStr := strconv.FormatFloat(viper.GetFloat64(\"voters.shareratio\")*100, 'f', -1, 64) + \"%\"\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Displaying voter information for delegate:\", deleResp.SingleDelegate.Username, deleResp.SingleDelegate.Address)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(fmt.Sprintf(\"|%-34s|%18s|%8s|%17s|%17s|%6s|\", \"Voter address\", \"Balance\", \"Weight\", \"Reward-100%\", \"Reward-\"+shareRatioStr, \"Hours\"))\n\tcolor.Set(color.FgCyan)\n\tfor _, element := range votersEarnings {\n\t\ts := fmt.Sprintf(\"|%s|%18.8f|%8.4f|%15.8f A|%15.8f A|%6d|\", element.Address, element.VoteWeight, element.VoteWeightShare, element.EarnedAmount100, element.EarnedAmountXX, element.VoteDuration)\n\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\t}\n\n\t//Cost calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"Available amount:\", sumEarned)\n\tfmt.Println(\"Amount to voters:\", sumShareEarned, viper.GetFloat64(\"voters.shareratio\"))\n\tfmt.Println(\"Amount to costs:\", costAmount, viper.GetFloat64(\"costs.shareratio\"))\n\tfmt.Println(\"Amount to reserve:\", reserveAmount, viper.GetFloat64(\"reserve.shareratio\"))\n\n\tfmt.Println(\"Ratio calc check:\", sumRatio, \"(should be = 1)\")\n\tfmt.Println(\"Ratio share check:\", float64(sumShareEarned)/float64(sumEarned), \"should be=\", viper.GetFloat64(\"voters.shareratio\"))\n\n\tpause()\n}", "func (gc *GovernanceContract) sfcDelegationsBy(addr common.Address) ([]common.Address, error) {\n\t// get SFC delegations list\n\tdl, err := gc.repo.DelegationsByAddress(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// prep the result container\n\tres := make([]common.Address, 0)\n\n\t// check if the address is a staker\n\t// if so, it also delegates to itself in the context of the contract\n\tisStaker, err := gc.repo.IsStaker(&addr)\n\tif err == nil && isStaker {\n\t\tres = append(res, addr)\n\t}\n\n\t// loop delegations to make the list\n\tfor _, d := range dl {\n\t\t// is the delegation ok for voting?\n\t\tif nil != d.DeactivatedEpoch && 0 < uint64(*d.DeactivatedEpoch) {\n\t\t\tgc.repo.Log().Debugf(\"delegation to %d from address %s is deactivated\", d.ToStakerId, addr.String())\n\t\t\tcontinue\n\t\t}\n\n\t\t// get the staker info\n\t\tstaker, err := gc.repo.StakerAddress(d.ToStakerId)\n\t\tif err != nil {\n\t\t\tgc.repo.Log().Errorf(\"error loading staker %d info; %s\", d.ToStakerId, addr.String())\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// get the\n\t\tres = append(res, staker)\n\t}\n\n\t// log delegations found\n\tgc.repo.Log().Debugf(\"%d delegations on %s\", len(res), addr.String())\n\treturn res, nil\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_DelegatableDai *DelegatableDaiCaller) Balances(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegatableDai.contract.Call(opts, out, \"balances\", arg0)\n\treturn *ret0, err\n}", "func (w *Worker) IncrementShares(sessionDifficulty float64, reward float64) {\n\tp := w.s.Client.pool\n\tcbid := p.cs.CurrentBlock().ID()\n\tblockTarget, _ := p.cs.ChildTarget(cbid)\n\tblockDifficulty, _ := blockTarget.Difficulty().Uint64()\n\n\tsessionTarget, _ := difficultyToTarget(sessionDifficulty)\n\tsiaSessionDifficulty, _ := sessionTarget.Difficulty().Uint64()\n\tshareRatio := caculateRewardRatio(sessionTarget.Difficulty().Big(), blockTarget.Difficulty().Big())\n\tshareReward := shareRatio * reward\n\t// w.log.Printf(\"shareRatio: %f, shareReward: %f\", shareRatio, shareReward)\n\n\tshare := &Share{\n\t\tuserid: w.Parent().cr.clientID,\n\t\tworkerid: w.wr.workerID,\n\t\theight: int64(p.cs.Height()) + 1,\n\t\tvalid: true,\n\t\tdifficulty: sessionDifficulty,\n\t\tshareDifficulty: float64(siaSessionDifficulty),\n\t\treward: reward,\n\t\tblockDifficulty: blockDifficulty,\n\t\tshareReward: shareReward,\n\t\ttime: time.Now(),\n\t}\n\n\tw.s.Shift().IncrementShares(share)\n}", "func (gc *GovernanceContract) DelegationsBy(args struct{ From common.Address }) ([]common.Address, error) {\n\t// decide by the contract type\n\tswitch gc.Type {\n\tcase \"sfc\":\n\t\treturn gc.sfcDelegationsBy(args.From)\n\t}\n\n\t// no delegations by default\n\tgc.repo.Log().Debugf(\"unknown governance type of %s\", gc.Address.Hex())\n\treturn []common.Address{}, nil\n}", "func GetAllDelegatedContracts(delegateAddr string) ([]string, error){\n var rtnString []string\n delegatedContractsCmd := \"/chains/main/blocks/head/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n s, err := TezosRPCGet(delegatedContractsCmd)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts: TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1) //TODO Error checking\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get all delegated contracts: Regex failed\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func (s *ArkClient) GetDelegateVoteWeight(params DelegateQueryParams) (int, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\t//calculating vote weight\n\tbalance := 0\n\tif respData.Success {\n\t\tfor _, element := range respData.Accounts {\n\t\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\t\tbalance += intBalance\n\t\t}\n\t}\n\n\treturn balance, resp, err\n}", "func (_ConsortiumManagement *ConsortiumManagementCallerSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func (ms mainnetSchedule) ConsensusRatio() float64 {\n\treturn mainnetConsensusRatio\n}", "func calculateEpochRewardShares(operator string, delegate []byte, epoch_num uint64) *RewardShares {\n\t// get epoch response\n\tgetEpochResponse(epoch_num)\n\n\t// get gravity height\n\tgravity_height := epochGravityHeight()\n\n\t// get number of produced blocks\n\tblocks := delegateProductivity(operator)\n\n\t// get delegate's votes\n\tvotes_distribution, elected, delegate_votes, total_votes := getVotes(delegate, gravity_height)\n\n\t// calculate reward\n\treward := calculateReward(blocks, elected, delegate_votes, total_votes)\n\n\t// populate rewardshare structure\n\treturn NewRewardShares().\n\t\tSetEpochNum(strconv.FormatUint(epoch_num, 10)).\n\t\tSetProductivity(blocks).\n\t\tSetTotalVotes(delegate_votes).\n\t\tSetReward(reward).\n\t\tCalculateShares(votes_distribution, delegate_votes, epoch_num)\n}", "func (k *Keeper) GetAllDecryptionShares(ctx sdk.Context, round uint64) ([]*types.DecryptionShare, sdk.Error) {\n\tstage := k.GetStage(ctx, round)\n\tif stage != stageDSCollecting && stage != stageCompleted {\n\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"wrong round stage: %v. round: %v\", stage, round))\n\t}\n\n\tdsStore := ctx.KVStore(k.storeDecryptionSharesKey)\n\n\tkeyAllShares := []byte(fmt.Sprintf(\"rd_%d\", round))\n\n\tif !dsStore.Has(keyAllShares) {\n\t\treturn []*types.DecryptionShare{}, nil\n\t}\n\n\taddrListBytes := dsStore.Get(keyAllShares)\n\tvar addrList []string\n\terr := k.cdc.UnmarshalJSON(addrListBytes, &addrList)\n\tif err != nil {\n\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"can't unmarshal list of all adderesses from store: %v\", err))\n\t}\n\tdsList := make([]*types.DecryptionShare, 0, len(addrList))\n\tfor _, addrStr := range addrList {\n\t\taddr, err := sdk.AccAddressFromBech32(addrStr)\n\t\tif err != nil {\n\t\t\treturn nil, sdk.ErrUnknownAddress(fmt.Sprintf(\"can't get address from bench32: %v\", err))\n\t\t}\n\t\tkey := createKeyBytesByAddr(round, addr)\n\t\tif !dsStore.Has(key) {\n\t\t\treturn nil, sdk.ErrUnknownRequest(\"addresses list and real decryption share sender doesn't meet\")\n\t\t}\n\t\tdsBytes := dsStore.Get(key)\n\t\tvar dsJSON types.DecryptionShareJSON\n\t\terr = k.cdc.UnmarshalJSON(dsBytes, &dsJSON)\n\t\tif err != nil {\n\t\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"can't unmarthsal decryption share: %v\", err))\n\t\t}\n\t\tds, err1 := dsJSON.Deserialize()\n\t\tif err1 != nil {\n\t\t\treturn nil, err1\n\t\t}\n\t\tdsList = append(dsList, ds)\n\t}\n\treturn dsList, nil\n}", "func FairShare(config *pb.Algorithm) Algorithm {\n\tlength, interval := getAlgorithmParams(config)\n\n\treturn func(r Request) Lease {\n\t\tvar (\n\t\t\tcount = r.Store.Count()\n\t\t\told = r.Store.Get(r.Client)\n\t\t)\n\n\t\t// If this is a new client, we adjust the count.\n\t\tif !r.Store.HasClient(r.Client) {\n\t\t\tcount += r.Subclients\n\t\t}\n\n\t\t// This is the equal share that every subclient should get.\n\t\tequalShare := r.Capacity / float64(count)\n\n\t\t// This is the equal share that should be assigned to the current client\n\t\t// based on the number of its subclients.\n\t\tequalSharePerClient := equalShare * float64(r.Subclients)\n\n\t\t// This is the capacity which is currently unused (assuming that\n\t\t// the requesting client has no capacity). It is the maximum\n\t\t// capacity that this run of the algorithm can assign to the\n\t\t// requesting client.\n\t\tunusedCapacity := r.Capacity - r.Store.SumHas() + old.Has\n\n\t\t// If the client wants less than its equal share or\n\t\t// if the sum of what all clients want together is less\n\t\t// than the available capacity we can give this client what\n\t\t// it wants.\n\t\tif r.Wants <= equalSharePerClient || r.Store.SumWants() <= r.Capacity {\n\t\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\t\tminF(r.Wants, unusedCapacity), r.Wants, r.Subclients)\n\t\t}\n\n\t\t// Map of what each client will get from this algorithm run.\n\t\t// Ultimately we need only determine what this client gets,\n\t\t// but for the algorithm we need to keep track of what\n\t\t// other clients would be getting as well.\n\t\tgets := make(map[string]float64)\n\n\t\t// This list contains all the clients which are still in\n\t\t// the race to get some capacity.\n\t\tclients := list.New()\n\t\tclientsNext := list.New()\n\n\t\t// Puts every client in the list to signify that they all\n\t\t// still need capacity.\n\t\tr.Store.Map(func(id string, lease Lease) {\n\t\t\tclients.PushBack(id)\n\t\t})\n\n\t\t// This is the capacity that can still be divided.\n\t\tavailableCapacity := r.Capacity\n\n\t\t// The clients list now contains all the clients who still need/want\n\t\t// capacity. We are going to divide the capacity in availableCapacity\n\t\t// in iterations until there is nothing more to divide or until we\n\t\t// completely satisfied the client who is making the request.\n\t\tfor availableCapacity > epsilon && gets[r.Client] < r.Wants-epsilon {\n\t\t\t// Calculate number of subclients for the given clients list.\n\t\t\tclientsCopy := *clients\n\t\t\tvar subclients int64\n\t\t\tfor e := clientsCopy.Front(); e != nil; e = e.Next() {\n\t\t\t\tsubclients += r.Store.Subclients(e.Value.(string))\n\t\t\t}\n\n\t\t\t// This is the fair share that is available to all subclients\n\t\t\t// who are still in the race to get capacity.\n\t\t\tfairShare := availableCapacity / float64(subclients)\n\n\t\t\t// Not enough capacity to actually worry about. Prevents\n\t\t\t// an infinite loop.\n\t\t\tif fairShare < epsilon {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// We now process the list of clients and give a topup to\n\t\t\t// every client's capacity. That topup is either the fair\n\t\t\t// share or the capacity still needed to be completely\n\t\t\t// satisfied (in case the client needs less than the\n\t\t\t// fair share to reach its need/wants).\n\t\t\tfor e := clients.Front(); e != nil; e = e.Next() {\n\t\t\t\tid := e.Value.(string)\n\n\t\t\t\t// Determines the wants for this client, which comes\n\t\t\t\t// either from the store, or from the request info if it\n\t\t\t\t// is the client making the request,\n\t\t\t\tvar wants float64\n\t\t\t\tvar subclients int64\n\n\t\t\t\tif id == r.Client {\n\t\t\t\t\twants = r.Wants\n\t\t\t\t\tsubclients = r.Subclients\n\t\t\t\t} else {\n\t\t\t\t\twants = r.Store.Get(id).Wants\n\t\t\t\t\tsubclients = r.Store.Subclients(id)\n\t\t\t\t}\n\n\t\t\t\t// stillNeeds is the capacity this client still needs to\n\t\t\t\t// be completely satisfied.\n\t\t\t\tstillNeeds := wants - gets[id]\n\n\t\t\t\t// Tops up the client's capacity.\n\t\t\t\t// Every client should receive the resource capacity based on\n\t\t\t\t// the number of its subclients.\n\t\t\t\tfairSharePerClient := fairShare * float64(subclients)\n\t\t\t\tif stillNeeds <= fairSharePerClient {\n\t\t\t\t\tgets[id] += stillNeeds\n\t\t\t\t\tavailableCapacity -= stillNeeds\n\t\t\t\t} else {\n\t\t\t\t\tgets[id] += fairSharePerClient\n\t\t\t\t\tavailableCapacity -= fairSharePerClient\n\t\t\t\t}\n\n\t\t\t\t// If the client is not yet satisfied we include it in the next\n\t\t\t\t// generation of the list. If it is completely satisfied we\n\t\t\t\t// don't.\n\t\t\t\tif gets[id] < wants {\n\t\t\t\t\tclientsNext.PushBack(id)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Ready for the next iteration of the loop. Swap the clients with the\n\t\t\t// clientsNext list.\n\t\t\tclients, clientsNext = clientsNext, clients\n\n\t\t\t// Cleans the clientsNext list so that it can be used again.\n\t\t\tclientsNext.Init()\n\t\t}\n\n\t\t// Insert the capacity grant into the lease store. We cannot\n\t\t// give out more than the currently unused capacity. If that\n\t\t// is less than what the algorithm calculated this will get\n\t\t// fixed in the next capacity refreshes.\n\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\tminF(gets[r.Client], unusedCapacity), r.Wants, r.Subclients)\n\t}\n}", "func (_Bindings *BindingsCallerSession) BorrowRatePerBlock() (*big.Int, error) {\n\treturn _Bindings.Contract.BorrowRatePerBlock(&_Bindings.CallOpts)\n}", "func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tpva.BaseVestingAccount.TrackDelegation(balance, pva.GetVestingCoins(blockTime), amount)\n}", "func (_ConsortiumManagement *ConsortiumManagementCaller) Delegates(opts *bind.CallOpts) ([]common.Address, error) {\n\tvar out []interface{}\n\terr := _ConsortiumManagement.contract.Call(opts, &out, \"delegates\")\n\n\tif err != nil {\n\t\treturn *new([]common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address)\n\n\treturn out0, err\n\n}", "func (_Bep20 *Bep20CallerSession) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tva.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount)\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func (s *RoundsService) Delegates(ctx context.Context, id int64) (*GetDelegates, *http.Response, error) {\n\turi := fmt.Sprintf(\"rounds/%v/delegates\", id)\n\n\tvar responseStruct *GetDelegates\n\tresp, err := s.client.SendRequest(ctx, \"GET\", uri, nil, nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func GenerateShares(transportPrivateKey *big.Int, transportPublicKey [2]*big.Int, participants ParticipantList, threshold int) ([]*big.Int, []*big.Int, [][2]*big.Int, error) {\n\n\t// create coefficients (private/public)\n\tprivateCoefficients, err := cloudflare.ConstructPrivatePolyCoefs(rand.Reader, threshold)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tpublicCoefficients := cloudflare.GeneratePublicCoefs(privateCoefficients)\n\n\t// create commitments\n\tcommitments := make([][2]*big.Int, len(publicCoefficients))\n\tfor idx, publicCoefficient := range publicCoefficients {\n\t\tcommitments[idx] = bn256.G1ToBigIntArray(publicCoefficient)\n\t}\n\n\t// secret shares\n\ttransportPublicKeyG1, err := bn256.BigIntArrayToG1(transportPublicKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// convert public keys into G1 structs\n\tpublicKeyG1s := []*cloudflare.G1{}\n\tfor idx := 0; idx < len(participants); idx++ {\n\t\tparticipant := participants[idx]\n\t\tlogger.Infof(\"participants[%v]: %v\", idx, participant)\n\t\tif participant != nil && participant.PublicKey[0] != nil && participant.PublicKey[1] != nil {\n\t\t\tpublicKeyG1, err := bn256.BigIntArrayToG1(participant.PublicKey)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\tpublicKeyG1s = append(publicKeyG1s, publicKeyG1)\n\t\t}\n\t}\n\n\t// check for missing data\n\tif len(publicKeyG1s) != len(participants) {\n\t\treturn nil, nil, nil, fmt.Errorf(\"only have %v of %v public keys\", len(publicKeyG1s), len(participants))\n\t}\n\n\tif len(privateCoefficients) != threshold+1 {\n\t\treturn nil, nil, nil, fmt.Errorf(\"only have %v of %v private coefficients\", len(privateCoefficients), threshold+1)\n\t}\n\n\t//\n\tsecretsArray, err := cloudflare.GenerateSecretShares(transportPublicKeyG1, privateCoefficients, publicKeyG1s)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to generate secret shares: %v\", err)\n\t}\n\n\t// final encrypted shares\n\tencryptedShares, err := cloudflare.GenerateEncryptedShares(secretsArray, transportPrivateKey, publicKeyG1s)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to generate encrypted shares: %v\", err)\n\t}\n\n\treturn encryptedShares, privateCoefficients, commitments, nil\n}", "func ratioAutoConsoCalculator(details model.ClientTotalInfo) float64 {\n\n\ttotalHomeComsuption := details.FromGenToConsumer + details.FromGridToConsumer\n\ttotalPannelProduction := details.FromGenToConsumer + details.FromGenToGrid\n\n\tratio := totalPannelProduction / totalHomeComsuption * 100\n\n\treturn ratio\n}", "func (_ConsortiumManagement *ConsortiumManagementSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tcva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount)\n}", "func (_Bindings *BindingsSession) BorrowRatePerBlock() (*big.Int, error) {\n\treturn _Bindings.Contract.BorrowRatePerBlock(&_Bindings.CallOpts)\n}", "func TestSlashWithRedelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\tbondDenom := app.StakingKeeper.BondDenom(ctx)\n\n\t// set a redelegation\n\trdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)\n\trd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,\n\t\ttime.Unix(0, 0), rdTokens, rdTokens.ToDec())\n\tapp.StakingKeeper.SetRedelegation(ctx, rd)\n\n\t// set the associated delegation\n\tdel := types.NewDelegation(addrDels[0], addrVals[1], rdTokens.ToDec())\n\tapp.StakingKeeper.SetDelegation(ctx, del)\n\n\t// update bonded tokens\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)\n\trdCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdTokens.MulRaw(2)))\n\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), rdCoins))\n\n\tapp.AccountKeeper.SetModuleAccount(ctx, bondedPool)\n\n\toldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\toldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\n\t// slash validator\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) })\n\tburnAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()\n\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// burn bonded tokens from only from delegations\n\tbondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 2 - 4 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 7)\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// seven bonded tokens burned\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 4\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again, by 100%\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(sdk.OneDec()).TruncateInt()\n\tburnAmount = burnAmount.Sub(sdk.OneDec().MulInt(rdTokens).TruncateInt())\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\t// read updated validator\n\t// validator decreased to zero power, should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\t// slash the validator again, by 100%\n\t// no stake remains to be slashed\n\tctx = ctx.WithBlockHeight(12)\n\t// validator still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded, bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\t// power still zero, still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (p *proxy) SfcMaxDelegatedRatio() (*big.Int, error) {\n\t// try cache first\n\tval := p.cache.PullSfcMaxDelegatedRatio()\n\tif val != nil {\n\t\treturn val, nil\n\t}\n\n\t// pull from the SFC contract\n\tval, err := p.rpc.SfcMaxDelegatedRatio()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// store for future use\n\tp.cache.PushSfcMaxDelegatedRatio(val)\n\treturn val, nil\n}", "func (_DelegationController *DelegationControllerCaller) DelegationsByHolder(opts *bind.CallOpts, arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"delegationsByHolder\", arg0, arg1)\n\treturn *ret0, err\n}", "func (_Bindings *BindingsCaller) BorrowRatePerBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"borrowRatePerBlock\")\n\treturn *ret0, err\n}", "func (_Bep20 *Bep20Session) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func CalculateBorrowRate(model types.InterestRateModel, cash, borrows, reserves sdk.Dec) (sdk.Dec, error) {\n\tutilRatio := CalculateUtilizationRatio(cash, borrows, reserves)\n\n\t// Calculate normal borrow rate (under kink)\n\tif utilRatio.LTE(model.Kink) {\n\t\treturn utilRatio.Mul(model.BaseMultiplier).Add(model.BaseRateAPY), nil\n\t}\n\n\t// Calculate jump borrow rate (over kink)\n\tnormalRate := model.Kink.Mul(model.BaseMultiplier).Add(model.BaseRateAPY)\n\texcessUtil := utilRatio.Sub(model.Kink)\n\treturn excessUtil.Mul(model.JumpMultiplier).Add(normalRate), nil\n}", "func (mixerService *MixerService) CyclePool() {\n\tfmt.Println(\"\\nCycling Pool\")\n\t// check pathway deposit addresses for new deposits\n\t// move empty deposit addresses to pool && update pathway debt amount (with 1% cut)\n\tfmt.Println(\"\\n\\nChecking deposit addresses for new deposits\")\n\tmixerService.checkAndEmptyDepositAddresses()\n\n\tfmt.Println(\"\\n\\nPruning Pool (moving funds to members)\")\n\t// go through all pathways with outstanding debt, and \"prune\" each pathway\n\tmixerService.prunePathwayDebt()\n}", "func (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tdva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), amount)\n}", "func TestDonationCase1(t *testing.T) {\n\tassert := assert.New(t)\n\tstore := newReputationStoreOnMock()\n\trep := NewTestReputationImpl(store)\n\tt1 := time.Date(1995, time.February, 5, 11, 11, 0, 0, time.UTC)\n\tt3 := time.Date(1995, time.February, 6, 12, 11, 0, 0, time.UTC)\n\tt4 := time.Date(1995, time.February, 7, 13, 11, 1, 0, time.UTC)\n\tuser1 := \"user1\"\n\tpost1 := \"post1\"\n\tpost2 := \"post2\"\n\n\t// round 2\n\trep.Update(t1.Unix())\n\trep.DonateAt(user1, post1, big.NewInt(100*OneLinoCoin))\n\tassert.Equal(big.NewInt(100*OneLinoCoin), rep.store.GetRoundPostSumStake(2, post1))\n\tassert.Equal(rep.GetReputation(user1), big.NewInt(InitialCustomerScore))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.store.GetRoundSumDp(2)) // bounded by this user's dp\n\n\t// round 3\n\trep.Update(t3.Unix())\n\t// (1 * 9 + 100) / 10\n\tassert.Equal(big.NewInt(1090000), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.GetSumRep(post1))\n\trep.DonateAt(user1, post1, big.NewInt(1*OneLinoCoin)) // does not count\n\trep.DonateAt(user1, post2, big.NewInt(900*OneLinoCoin))\n\trep.Update(t4.Unix())\n\t// (10.9 * 9 + 900) / 10\n\tassert.Equal(big.NewInt(9981000), rep.GetReputation(user1))\n\tassert.Equal([]Pid{post2}, rep.store.GetRoundResult(3))\n\t// round 4\n}", "func (_DelegationController *DelegationControllerCallerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (_DelegationController *DelegationControllerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func SortDelegateContracts(delegatedContracts []DelegatedContract) []DelegatedContract{\n for i, j := 0, len(delegatedContracts)-1; i < j; i, j = i+1, j-1 {\n delegatedContracts[i], delegatedContracts[j] = delegatedContracts[j], delegatedContracts[i]\n }\n return delegatedContracts\n}", "func (_CrToken *CrTokenCallerSession) BorrowRatePerBlock() (*big.Int, error) {\n\treturn _CrToken.Contract.BorrowRatePerBlock(&_CrToken.CallOpts)\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) Delegations(arg0 [32]byte) (common.Address, error) {\n\treturn _PlasmaFramework.Contract.Delegations(&_PlasmaFramework.CallOpts, arg0)\n}", "func (acc *Account) Delegations(args *struct {\n\tCursor *Cursor\n\tCount int32\n}) (*DelegationList, error) {\n\t// limit query size; the count can be either positive or negative\n\t// this controls the loading direction\n\targs.Count = listLimitCount(args.Count, listMaxEdgesPerRequest)\n\n\t// pull the list\n\tdl, err := repository.R().DelegationsByAddress(&acc.Address, (*string)(args.Cursor), args.Count)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// convert to resolvable list\n\treturn NewDelegationList(dl), nil\n}", "func TestDonationCase2(t *testing.T) {\n\tassert := assert.New(t)\n\tstore := newReputationStoreOnMock()\n\trep := NewTestReputationImpl(store)\n\tt1 := time.Date(1995, time.February, 5, 11, 11, 0, 0, time.UTC)\n\tt3 := time.Date(1995, time.February, 6, 12, 11, 0, 0, time.UTC)\n\tt4 := time.Date(1995, time.February, 7, 13, 11, 1, 0, time.UTC)\n\tuser1 := \"user1\"\n\tuser2 := \"user2\"\n\tuser3 := \"user3\"\n\tpost1 := \"post1\"\n\tpost2 := \"post2\"\n\n\t// round 2\n\trep.Update(t1.Unix())\n\tdp1 := rep.DonateAt(user1, post1, big.NewInt(100*OneLinoCoin))\n\tdp2 := rep.DonateAt(user2, post2, big.NewInt(1000*OneLinoCoin))\n\tdp3 := rep.DonateAt(user3, post2, big.NewInt(1000*OneLinoCoin))\n\tassert.Equal(big.NewInt(OneLinoCoin), dp1)\n\tassert.Equal(big.NewInt(OneLinoCoin), dp2)\n\tassert.Equal(big.NewInt(OneLinoCoin), dp3)\n\tassert.Equal(big.NewInt(100*OneLinoCoin), rep.store.GetRoundPostSumStake(2, post1))\n\tassert.Equal(rep.GetReputation(user1), big.NewInt(InitialCustomerScore))\n\tassert.Equal(big.NewInt(3*OneLinoCoin), rep.store.GetRoundSumDp(2)) // bounded by this user's dp\n\n\t// post1, dp, 1\n\t// post2, dp, 2\n\t// round 3\n\trep.Update(t3.Unix())\n\tassert.Equal([]Pid{post2, post1}, rep.store.GetRoundResult(2))\n\tassert.Equal(big.NewInt(1090000), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(13943027), rep.GetReputation(user2))\n\tassert.Equal(big.NewInt(6236972), rep.GetReputation(user3))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.GetSumRep(post1))\n\tassert.Equal(big.NewInt(2*OneLinoCoin), rep.GetSumRep(post2))\n\n\t// user1: 10.9\n\t// user2: 139.43027\n\t// user3: 62.36972\n\tdp1 = rep.DonateAt(user2, post2, big.NewInt(200*OneLinoCoin))\n\tdp2 = rep.DonateAt(user1, post1, big.NewInt(400*OneLinoCoin))\n\t// does not count because rep used up.\n\tdp3 = rep.DonateAt(user1, post1, big.NewInt(900*OneLinoCoin))\n\tdp4 := rep.DonateAt(user3, post1, big.NewInt(500*OneLinoCoin))\n\tassert.Equal(big.NewInt(13943027-OneLinoCoin), dp1)\n\tassert.Equal(big.NewInt(1090000-OneLinoCoin), dp2)\n\tassert.Equal(BigIntZero, dp3)\n\tassert.Equal(big.NewInt(6236972), dp4)\n\n\t// round 4\n\trep.Update(t4.Unix())\n\tassert.Equal([]Pid{post2, post1}, rep.store.GetRoundResult(3))\n\tassert.Equal(big.NewInt(16136841), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(14548724), rep.GetReputation(user2))\n\tassert.Equal(big.NewInt(8457432), rep.GetReputation(user3))\n}", "func (plva *PermanentLockedAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tplva.BaseVestingAccount.TrackDelegation(balance, plva.OriginalVesting, amount)\n}", "func calcTransmissionRisks(cycle Cycle) {\n\tfor i := 0; i < len(Inputs.People); i++ {\n\n\t\t//check people's ids line up\n\t\tthisPerson := Inputs.People[i]\n\t\tif uint(i) != thisPerson.Id {\n\t\t\tfmt.Println(\"Person Id doesn't make position in array\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\t// if uninfected\n\t\tunif_TB_state_id := Query.getStateByName(\"Uninfected TB\").Id\n\t\t// active_TB_state_id := Query.getStateByName(\"Active - untreated\").Id\n\t\t// active_treat_1_state_id := Query.getStateByName(\"Active Treated Month 1\").Id\n\t\t// active_treat_2_state_id := Query.getStateByName(\"Active Treated Month 2\").Id\n\t\ttb_chain := Query.getChainByName(\"TB disease and treatment\")\n\n\t\tthis_person_state_id := thisPerson.get_state_by_chain(tb_chain, cycle).Id\n\n\t\tisUsb := 0\n\t\tif thisPerson.get_state_by_chain(Inputs.Chains[BIRTHPLACE_CHAIN_ID], cycle).Name == \"United States\" {\n\t\t\tisUsb = 1\n\t\t}\n\n\t\trace_state_id := thisPerson.get_state_by_chain(Inputs.Chains[RACE_CHAIN_ID], cycle).Id\n\n\t\tif this_person_state_id == unif_TB_state_id {\n\t\t\tQuery.Num_susceptible_by_cycle_isUsb_and_race[cycle.Id][isUsb][race_state_id] += 1\n\t\t\tQuery.Total_susceptible_by_cycle[cycle.Id] += 1\n\t\t}\n\n\t\t// originally, all people in active + active treat m 1 + active treat m 2 were here\n\t\t// but it's 6 per CASE, not 6 per person. this is a more accurate way, since (almost) everyone\n\t\t// will eventually be treated, and this is only one month of contributing risk\n\t\t// if this_person_state_id == active_treat_1_state_id { //this_person_state_id == active_TB_state_id || || this_person_state_id == active_treat_2_state_id {\n\t\tQuery.Total_active_by_cycle[cycle.Id] += thisPerson.RiskOfProgression\n\n\t\tQuery.Num_active_cases_by_cycle_isUsb_and_race[cycle.Id][isUsb][race_state_id] += thisPerson.RiskOfProgression\n\n\t\t// }\n\n\t}\n\n\t//// -------------------------- NOTE I'VE TAKE OUT TRANSMISSION BY RACE AND BIRTHPLACE FOR NOW\n\n\tgeneralPopulationRisk := float64(Query.Total_active_by_cycle[cycle.Id]) / float64(Query.Total_susceptible_by_cycle[cycle.Id]) * 0.2\n\n\t// fmt.Println(\"In cycle \", cycle.Id, \" we have general population risk of: \", generalPopulationRisk)\n\n\t// calculate risk\n\tfor isUsb := 0; isUsb < 2; isUsb++ {\n\t\tfor r := 0; r < len(Inputs.States); r++ {\n\t\t\tnumSus := Query.Num_susceptible_by_cycle_isUsb_and_race[cycle.Id][isUsb][r]\n\t\t\tif numSus > 0 {\n\t\t\t\tnumActive := Query.Num_active_cases_by_cycle_isUsb_and_race[cycle.Id][isUsb][r]\n\t\t\t\t// todo make real\n\n\t\t\t\t//xyx\n\n\t\t\t\ttrans_adjustment := 0.0\n\t\t\t\tif cycle.Id <= 12 {\n\t\t\t\t\ttrans_adjustment = 1 //2.1\n\t\t\t\t} else if cycle.Id > 12 && cycle.Id <= 24 {\n\t\t\t\t\ttrans_adjustment = 1 //1.1\n\t\t\t\t} else if cycle.Id > 24 && cycle.Id <= 36 {\n\t\t\t\t\ttrans_adjustment = 1 //1.1\n\t\t\t\t} else {\n\t\t\t\t\ttrans_adjustment = 1.0\n\t\t\t\t}\n\n\t\t\t\trisk := ((float64(numActive)/float64(numSus))*0.8 + generalPopulationRisk) * trans_adjustment * NumberOfLtbiCasesCausedByOneActiveCase.Value\n\n\t\t\t\t// if float64(numActive)/float64(numSus) > 0 {\n\t\t\t\t// \tfmt.Println(\"risk in \", Inputs.States[b].Name, Inputs.States[r].Name, \" is \", float64(numActive)/float64(numSus))\n\t\t\t\t// }\n\n\t\t\t\tif risk > 1 {\n\t\t\t\t\trisk = 1\n\t\t\t\t}\n\t\t\t\tQuery.LTBI_risk_by_cycle_isUsb_and_race[cycle.Id][isUsb][r] = risk\n\t\t\t\t// fmt.Println(\"usb \", isUsb, \" race \", Inputs.States[r].Name, \" risk is \", numActive, \" / \", numSus, \" = \", risk)\n\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (k msgServer) RedeemTokensForShares(goCtx context.Context, msg *types.MsgRedeemTokensForShares) (*types.MsgRedeemTokensForSharesResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tshareToken := msg.Amount\n\tbalance := k.bankKeeper.GetBalance(ctx, delegatorAddress, shareToken.Denom)\n\tif balance.Amount.LT(shareToken.Amount) {\n\t\treturn nil, types.ErrNotEnoughBalance\n\t}\n\n\trecord, err := k.GetTokenizeShareRecordByDenom(ctx, shareToken.Denom)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, valErr := sdk.ValAddressFromBech32(record.Validator)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, record.GetModuleAddress(), valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoUnbondingDelegation\n\t}\n\n\t// Similar to undelegations, if the account is attempting to tokenize the full delegation,\n\t// but there's a precision error due to the decimal to int conversion, round up to the\n\t// full decimal amount before modifying the delegation\n\tshares := sdk.NewDecFromInt(shareToken.Amount)\n\tif shareToken.Amount.Equal(delegation.Shares.TruncateInt()) {\n\t\tshares = delegation.Shares\n\t}\n\ttokens := validator.TokensFromShares(shares).TruncateInt()\n\n\t// If this redemption is NOT from a liquid staking provider, decrement the total liquid staked\n\t// If the redemption was from a liquid staking provider, the shares are still considered\n\t// liquid, even in their non-tokenized form (since they are owned by a liquid staking provider)\n\tif !k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.DecreaseTotalLiquidStakedTokens(ctx, tokens); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturnAmount, err := k.Unbond(ctx, record.GetModuleAddress(), valAddr, shares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif validator.IsBonded() {\n\t\tk.bondedTokensToNotBonded(ctx, returnAmount)\n\t}\n\n\t// Note: since delegation object has been changed from unbond call, it gets latest delegation\n\t_, found = k.GetDelegation(ctx, record.GetModuleAddress(), valAddr)\n\tif !found {\n\t\tif k.hooks != nil {\n\t\t\tif err := k.hooks.BeforeTokenizeShareRecordRemoved(ctx, record.Id); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\terr = k.DeleteTokenizeShareRecord(ctx, record.Id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// send share tokens to NotBondedPool and burn\n\terr = k.bankKeeper.SendCoinsFromAccountToModule(ctx, delegatorAddress, types.NotBondedPoolName, sdk.Coins{shareToken})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = k.bankKeeper.BurnCoins(ctx, types.NotBondedPoolName, sdk.Coins{shareToken})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// send equivalent amount of tokens to the delegator\n\treturnCoin := sdk.NewCoin(k.BondDenom(ctx), returnAmount)\n\terr = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.NotBondedPoolName, delegatorAddress, sdk.Coins{returnCoin})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Note: it is needed to get latest validator object to get Keeper.Delegate function work properly\n\tvalidator, found = k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\t// convert the share tokens to delegated status\n\t// Note: Delegate(substractAccount => true) -> DelegateCoinsFromAccountToModule -> TrackDelegation for vesting account\n\t_, err = k.Keeper.Delegate(ctx, delegatorAddress, returnAmount, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeRedeemShares,\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, validator.OperatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyAmount, shareToken.String()),\n\t\t),\n\t)\n\n\treturn &types.MsgRedeemTokensForSharesResponse{\n\t\tAmount: returnCoin,\n\t}, nil\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func (c MethodsCollection) ComputeShare() pComputeShare {\n\treturn pComputeShare{\n\t\tMethod: c.MustGet(\"ComputeShare\"),\n\t}\n}", "func (m *GraphBaseServiceClient) Shares()(*i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.SharesRequestBuilder) {\n return i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.NewSharesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Shares()(*i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.SharesRequestBuilder) {\n return i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.NewSharesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func calcdutyCycleFromNeutralCenter(iC *InterfaceConfig, channel int, side string, degreeVal int) int {\n degreeValf := float64(degreeVal)\n var dutyCycle float64 = 0\n if side == \"left\" {\n if iC.StickDir[channel]==\"rev\" {\n if iC.NeutralStickPos[channel]>iC.LeftStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.LeftStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n } else if iC.LeftStickMaxPos[channel]>iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.LeftStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n }\n } else if iC.StickDir[channel]==\"norm\" {\n if iC.NeutralStickPos[channel]<iC.LeftStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.LeftStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n } else if iC.LeftStickMaxPos[channel]<iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.LeftStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n }\n }\n } else if side == \"right\" {\n if iC.StickDir[channel]==\"rev\" {\n if(iC.NeutralStickPos[channel]>iC.RightStickMaxPos[channel]) {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.RightStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n } else if(iC.RightStickMaxPos[channel]>iC.NeutralStickPos[channel]) {\n dutyCycle=float64(iC.RightStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n }\n } else if iC.StickDir[channel]==\"norm\" {\n\n if iC.NeutralStickPos[channel]<iC.RightStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.RightStickMaxPos[channel])\n dutyCycle=dutyCycle/100\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n } else if iC.RightStickMaxPos[channel]<iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.RightStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n }\n }\n }\n println(\"calc Duty cycle: \" + strconv.Itoa(int(dutyCycle)))\n return int(dutyCycle)\n}", "func (_Bep20 *Bep20Caller) Delegates(opts *bind.CallOpts, delegator common.Address) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"delegates\", delegator)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func DeployPerformanceKeeperContracts(\n\tt *testing.T,\n\tregistryVersion ethereum.KeeperRegistryVersion,\n\tnumberOfContracts int,\n\tupkeepGasLimit uint32,\n\tlinkToken contracts.LinkToken,\n\tcontractDeployer contracts.ContractDeployer,\n\tclient blockchain.EVMClient,\n\tregistrySettings *contracts.KeeperRegistrySettings,\n\tlinkFundsForEachUpkeep *big.Int,\n\tblockRange, // How many blocks to run the test for\n\tblockInterval, // Interval of blocks that upkeeps are expected to be performed\n\tcheckGasToBurn, // How much gas should be burned on checkUpkeep() calls\n\tperformGasToBurn int64, // How much gas should be burned on performUpkeep() calls\n) (contracts.KeeperRegistry, contracts.KeeperRegistrar, []contracts.KeeperConsumerPerformance, []*big.Int) {\n\tef, err := contractDeployer.DeployMockETHLINKFeed(big.NewInt(2e18))\n\trequire.NoError(t, err, \"Deploying mock ETH-Link feed shouldn't fail\")\n\tgf, err := contractDeployer.DeployMockGasFeed(big.NewInt(2e11))\n\trequire.NoError(t, err, \"Deploying mock gas feed shouldn't fail\")\n\terr = client.WaitForEvents()\n\trequire.NoError(t, err, \"Failed waiting for mock feeds to deploy\")\n\n\tregistry := DeployKeeperRegistry(t, contractDeployer, client,\n\t\t&contracts.KeeperRegistryOpts{\n\t\t\tRegistryVersion: registryVersion,\n\t\t\tLinkAddr: linkToken.Address(),\n\t\t\tETHFeedAddr: ef.Address(),\n\t\t\tGasFeedAddr: gf.Address(),\n\t\t\tTranscoderAddr: ZeroAddress.Hex(),\n\t\t\tRegistrarAddr: ZeroAddress.Hex(),\n\t\t\tSettings: *registrySettings,\n\t\t},\n\t)\n\n\t// Fund the registry with 1 LINK * amount of KeeperConsumerPerformance contracts\n\terr = linkToken.Transfer(registry.Address(), big.NewInt(0).Mul(big.NewInt(1e18), big.NewInt(int64(numberOfContracts))))\n\trequire.NoError(t, err, \"Funding keeper registry contract shouldn't fail\")\n\n\tregistrarSettings := contracts.KeeperRegistrarSettings{\n\t\tAutoApproveConfigType: 2,\n\t\tAutoApproveMaxAllowed: math.MaxUint16,\n\t\tRegistryAddr: registry.Address(),\n\t\tMinLinkJuels: big.NewInt(0),\n\t}\n\tregistrar := DeployKeeperRegistrar(t, registryVersion, linkToken, registrarSettings, contractDeployer, client, registry)\n\n\tupkeeps := DeployKeeperConsumersPerformance(\n\t\tt, contractDeployer, client, numberOfContracts, blockRange, blockInterval, checkGasToBurn, performGasToBurn,\n\t)\n\n\tvar upkeepsAddresses []string\n\tfor _, upkeep := range upkeeps {\n\t\tupkeepsAddresses = append(upkeepsAddresses, upkeep.Address())\n\t}\n\n\tupkeepIds := RegisterUpkeepContracts(\n\t\tt, linkToken, linkFundsForEachUpkeep, client, upkeepGasLimit, registry, registrar, numberOfContracts, upkeepsAddresses,\n\t)\n\n\treturn registry, registrar, upkeeps, upkeepIds\n}", "func (pp *PermuteProtocol) GenShares(sk *ring.Poly, ciphertext *bfv.Ciphertext, crs *ring.Poly, permutation []uint64, share RefreshShare) {\n\n\tlevel := len(ciphertext.Value()[1].Coeffs) - 1\n\n\tringQ := pp.context.ringQ\n\tringT := pp.context.ringT\n\tringQP := pp.context.ringQP\n\n\t// h0 = s*ct[1]\n\tringQ.NTTLazy(ciphertext.Value()[1], pp.tmp1)\n\tringQ.MulCoeffsMontgomeryConstant(sk, pp.tmp1, share.RefreshShareDecrypt)\n\tringQ.InvNTTLazy(share.RefreshShareDecrypt, share.RefreshShareDecrypt)\n\n\t// h0 = s*ct[1]*P\n\tringQ.MulScalarBigint(share.RefreshShareDecrypt, pp.context.ringP.ModulusBigint, share.RefreshShareDecrypt)\n\n\t// h0 = s*ct[1]*P + e\n\tpp.gaussianSampler.ReadLvl(len(ringQP.Modulus)-1, pp.tmp1, ringQP, pp.sigma, int(6*pp.sigma))\n\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\n\n\tfor x, i := 0, len(ringQ.Modulus); i < len(pp.context.ringQP.Modulus); x, i = x+1, i+1 {\n\t\ttmphP := pp.hP.Coeffs[x]\n\t\ttmp1 := pp.tmp1.Coeffs[i]\n\t\tfor j := 0; j < ringQ.N; j++ {\n\t\t\ttmphP[j] += tmp1[j]\n\t\t}\n\t}\n\n\t// h0 = (s*ct[1]*P + e)/P\n\tpp.baseconverter.ModDownSplitPQ(level, share.RefreshShareDecrypt, pp.hP, share.RefreshShareDecrypt)\n\n\t// h1 = -s*a\n\tringQP.Neg(crs, pp.tmp1)\n\tringQP.NTTLazy(pp.tmp1, pp.tmp1)\n\tringQP.MulCoeffsMontgomeryConstant(sk, pp.tmp1, pp.tmp2)\n\tringQP.InvNTTLazy(pp.tmp2, pp.tmp2)\n\n\t// h1 = s*a + e'\n\tpp.gaussianSampler.ReadAndAdd(pp.tmp2, ringQP, pp.sigma, int(6*pp.sigma))\n\n\t// h1 = (-s*a + e')/P\n\tpp.baseconverter.ModDownPQ(level, pp.tmp2, share.RefreshShareRecrypt)\n\n\t// mask = (uniform plaintext in [0, T-1]) * floor(Q/T)\n\n\t// Mask in the time domain\n\tcoeffs := pp.uniformSampler.ReadNew()\n\n\t// Multiply by Q/t\n\tlift(coeffs, pp.tmp1, pp.context)\n\n\t// h0 = (s*ct[1]*P + e)/P + mask\n\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\n\n\t// Mask in the spectral domain\n\tringT.NTT(coeffs, coeffs)\n\n\t// Permutation over the mask\n\tpp.permuteWithIndex(coeffs, permutation, pp.tmp1)\n\n\t// Switch back the mask in the time domain\n\tringT.InvNTTLazy(pp.tmp1, coeffs)\n\n\t// Multiply by Q/t\n\tlift(coeffs, pp.tmp1, pp.context)\n\n\t// h1 = (-s*a + e')/P - permute(mask)\n\tringQ.Sub(share.RefreshShareRecrypt, pp.tmp1, share.RefreshShareRecrypt)\n}", "func (cm *ConsensusManager) shareProposal(rs *RoundState) {\n\tprivValidator := cm.PrivValidator()\n\tproposal := rs.Proposal\n\tif privValidator == nil || proposal == nil {\n\t\treturn\n\t}\n\tprivValidator.SignProposal(rs.Round, proposal)\n\tblockParts := proposal.BlockParts()\n\tpeers := cm.sw.Peers().List()\n\tif len(peers) == 0 {\n\t\tlog.Warning(\"Could not propose: no peers\")\n\t\treturn\n\t}\n\tnumBlockParts := uint16(len(blockParts))\n\tkbpMsg := cm.makeKnownBlockPartsMessage(rs)\n\tfor i, peer := range peers {\n\t\tpeerState := cm.getPeerState(peer)\n\t\tif !peerState.IsConnected() {\n\t\t\tcontinue // Peer was disconnected.\n\t\t}\n\t\tstartIndex := uint16((i * len(blockParts)) / len(peers))\n\t\t// Create a function that when called,\n\t\t// starts sending block parts to peer.\n\t\tcb := func(peer *p2p.Peer, startIndex uint16) func() {\n\t\t\treturn func() {\n\t\t\t\t// TODO: if the clocks are off a bit,\n\t\t\t\t// peer may receive this before the round flips.\n\t\t\t\tpeer.Send(KnownPartsCh, kbpMsg)\n\t\t\t\tfor i := uint16(0); i < numBlockParts; i++ {\n\t\t\t\t\tpart := blockParts[(startIndex+i)%numBlockParts]\n\t\t\t\t\t// Ensure round hasn't expired on our end.\n\t\t\t\t\tcurrentRS := cm.cs.RoundState()\n\t\t\t\t\tif currentRS != rs {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// If peer wants the block:\n\t\t\t\t\tif peerState.WantsBlockPart(part) {\n\t\t\t\t\t\tpartMsg := &BlockPartMessage{BlockPart: part}\n\t\t\t\t\t\tpeer.Send(ProposalCh, partMsg)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}(peer, startIndex)\n\t\t// Call immediately or schedule cb for when peer is ready.\n\t\tpeerState.SetRoundCallback(rs.Height, rs.Round, cb)\n\t}\n}", "func (c Contract) CalculateSalary() int {\n return c.basicPay\n}", "func (k Keeper) AwardCoinsForRelays(ctx sdk.Ctx, relays int64, toAddr sdk.Address) sdk.BigInt {\n\treturn k.posKeeper.RewardForRelays(ctx, sdk.NewInt(relays), toAddr)\n}", "func (k Keeper) GetAllDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress) []types.Delegation {\n\tdelegations := make([]types.Delegation, 0)\n\n\tstore := ctx.KVStore(k.storeKey)\n\tdelegatorPrefixKey := types.GetDelegationsKey(delegator)\n\n\titerator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) //smallest to largest\n\tdefer iterator.Close()\n\n\ti := 0\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tdelegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value())\n\t\tdelegations = append(delegations, delegation)\n\t\ti++\n\t}\n\n\treturn delegations\n}", "func (sch *Scheduler) CalClusterBalance(podUsed *[PHYNUM][DIMENSION]float64, podReq []PodRequest) {\n\t//cal the pod sum and used rate\n\tpodLen := len(podReq)\n\tvar podNum [PHYNUM]int\n\tvar podSum int\n\tfor i := 0; i < podLen; i++ {\n\t\tif podReq[i].nodeName != -1 {\n\t\t\tpodSum++\n\t\t\tpodNum[podReq[i].nodeName]++\n\t\t}\n\t}\n\n\tvar podIdle [PHYNUM]float64\n\tvar resIdle [PHYNUM][DIMENSION]float64\n\tvar podVal float64\n\tvar resVal [DIMENSION]float64 // cal the sum and mean value\n\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tpodIdle[i] = 1.0 - (float64)(podNum[i])/(float64)(podSum)\n\t\tpodVal = podVal + podIdle[i]\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tresIdle[i][j] = (sch.reTotal[j] - podUsed[i][j]) / sch.reTotal[j]\n\t\t\tresVal[j] = resVal[j] + resIdle[i][j]\n\t\t}\n\t}\n\t// cal the balance value\n\tpodMean := podVal / (float64)(podSum)\n\tvar resMean [DIMENSION]float64\n\tfor j := 0; j < DIMENSION; j++ {\n\t\tresMean[j] = resVal[j] / (float64)(PHYNUM)\n\t}\n\tvar baIdle float64\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tbaIdle = baIdle + math.Pow((resIdle[i][j]-resMean[j]), 2)\n\t\t}\n\t\tbaIdle = baIdle + math.Pow((podIdle[i]-podMean), 2)\n\t}\n\tbaIdle = math.Sqrt(baIdle)\n\tfmt.Printf(\"The balance value is %.3f \\n\", baIdle)\n}", "func (_CrToken *CrTokenCaller) BorrowRatePerBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"borrowRatePerBlock\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (k Keeper) Delegation(ctx context.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) (types.DelegationI, error) {\n\tbond, err := k.Delegations.Get(ctx, collections.Join(addrDel, addrVal))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bond, nil\n}", "func cashDiscount(s string) string {\n\treturn addFees(s) + \":cashDiscount\"\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (pm *DPoSProtocolManager) syncDelegatedNodeSafely() {\n\tif !pm.isDelegatedNode() {\n\t\t// only candidate node is able to participant to this process.\n\t\treturn;\n\t}\n\tpm.lock.Lock()\n\tdefer pm.lock.Unlock()\n\tlog.Info(\"Preparing for next big period...\");\n\t// pull the newest delegators from voting contract.\n\ta, b, err0 := VotingAccessor.Refresh()\n\tif err0 != nil {\n\t\tlog.Error(err0.Error())\n\t\treturn;\n\t}\n\tDelegatorsTable = a\n\tDelegatorNodeInfo = b\n\tif uint8(len(GigPeriodHistory)) >= BigPeriodHistorySize {\n\t\tGigPeriodHistory = GigPeriodHistory[1:] //remove the first old one.\n\t}\n\tif len(DelegatorsTable) == 0 || pm.ethManager.peers.Len() == 0 {\n\t\tlog.Info(\"Sorry, could not detect any delegator!\");\n\t\treturn;\n\t}\n\tround := uint64(1)\n\tactiveTime := uint64(time.Now().Unix() + int64(GigPeriodInterval))\n\tif NextGigPeriodInstance != nil {\n\t\tif !TestMode {\n\t\t\tgap := int64(NextGigPeriodInstance.activeTime) - time.Now().Unix()\n\t\t\tif gap > 2 || gap < -2 {\n\t\t\t\tlog.Warn(fmt.Sprintf(\"Scheduling of the new electing round is improper! current gap: %v seconds\", gap))\n\t\t\t\t//restart the scheduler\n\t\t\t\tNextElectionInfo = nil;\n\t\t\t\tgo pm.syncDelegatedNodeSafely();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tround = NextGigPeriodInstance.round + 1\n\t\tactiveTime = GigPeriodInstance.activeTime + uint64(GigPeriodInterval)\n\t\t// keep the big period history for block validation.\n\t\tGigPeriodHistory[len(GigPeriodHistory)-1] = *NextGigPeriodInstance;\n\n\t\tGigPeriodInstance = &GigPeriodTable{\n\t\t\tNextGigPeriodInstance.round,\n\t\t\tNextGigPeriodInstance.state,\n\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\tNextGigPeriodInstance.confirmedTickets,\n\t\t\tNextGigPeriodInstance.confirmedBestNode,\n\t\t\tNextGigPeriodInstance.activeTime,\n\t\t};\n\t\tlog.Info(fmt.Sprintf(\"Switched the new big period round. %d \", GigPeriodInstance.round));\n\t}\n\n\t// make sure all delegators are synced at this round.\n\tNextGigPeriodInstance = &GigPeriodTable{\n\t\tround,\n\t\tSTATE_LOOKING,\n\t\tDelegatorsTable,\n\t\tSignCandidates(DelegatorsTable),\n\t\tmake(map[string]uint32),\n\t\tmake(map[string]*GigPeriodTable),\n\t\tactiveTime,\n\t};\n\tpm.trySyncAllDelegators()\n}", "func (_Cakevault *CakevaultCallerSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) Delegations(opts *bind.CallOpts, arg0 [32]byte) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret0, err\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.BalanceOf(&_DelegatableDai.CallOpts, _owner)\n}", "func (_DelegationController *DelegationControllerSession) Confiscate(validatorId *big.Int, amount *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Confiscate(&_DelegationController.TransactOpts, validatorId, amount)\n}", "func (dds DelegatorDistributionSchedules) Validate() error {\n\tseenPeriods := make(map[string]bool)\n\tfor _, ds := range dds {\n\t\tif seenPeriods[ds.DistributionSchedule.DepositDenom] {\n\t\t\treturn fmt.Errorf(\"duplicated liquidity provider schedule with deposit denom %s\", ds.DistributionSchedule.DepositDenom)\n\t\t}\n\n\t\tif err := ds.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tseenPeriods[ds.DistributionSchedule.DepositDenom] = true\n\t}\n\n\treturn nil\n}", "func (dds DelegatorDistributionSchedules) Validate() error {\n\tseenPeriods := make(map[string]bool)\n\tfor _, ds := range dds {\n\t\tif seenPeriods[ds.DistributionSchedule.DepositDenom] {\n\t\t\treturn fmt.Errorf(\"duplicated liquidity provider schedule with deposit denom %s\", ds.DistributionSchedule.DepositDenom)\n\t\t}\n\n\t\tif err := ds.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tseenPeriods[ds.DistributionSchedule.DepositDenom] = true\n\t}\n\n\treturn nil\n}", "func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRedelegate) (*types.MsgBeginRedelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsrcValidator, found := k.GetValidator(ctx, valSrcAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\tdstValidator, found := k.GetValidator(ctx, valDstAddr)\n\tif !found {\n\t\treturn nil, types.ErrBadRedelegationDst\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, valSrcAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorSrcAddress,\n\t\t)\n\t}\n\n\tsrcShares, err := k.ValidateUnbondAmount(ctx, delegatorAddress, valSrcAddr, msg.Amount.Amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdstShares, err := dstValidator.SharesFromTokensTruncated(msg.Amount.Amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &srcValidator, srcShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// If this delegation from a liquid staker, the delegation on the new validator\n\t// cannot exceed that validator's self-bond cap\n\t// The liquid shares from the source validator should get moved to the destination validator\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &dstValidator, dstShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &srcValidator, srcShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.BeginRedelegation(\n\t\tctx, delegatorAddress, valSrcAddr, valDstAddr, srcShares,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif msg.Amount.Amount.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"redelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(msg.Amount.Amount.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeRedelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeySrcValidator, msg.ValidatorSrcAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDstValidator, msg.ValidatorDstAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgBeginRedelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func DeployPerformDataCheckerContracts(\n\tt *testing.T,\n\tregistryVersion ethereum.KeeperRegistryVersion,\n\tnumberOfContracts int,\n\tupkeepGasLimit uint32,\n\tlinkToken contracts.LinkToken,\n\tcontractDeployer contracts.ContractDeployer,\n\tclient blockchain.EVMClient,\n\tregistrySettings *contracts.KeeperRegistrySettings,\n\tlinkFundsForEachUpkeep *big.Int,\n\texpectedData []byte,\n) (contracts.KeeperRegistry, contracts.KeeperRegistrar, []contracts.KeeperPerformDataChecker, []*big.Int) {\n\tef, err := contractDeployer.DeployMockETHLINKFeed(big.NewInt(2e18))\n\trequire.NoError(t, err, \"Deploying mock ETH-Link feed shouldn't fail\")\n\tgf, err := contractDeployer.DeployMockGasFeed(big.NewInt(2e11))\n\trequire.NoError(t, err, \"Deploying mock gas feed shouldn't fail\")\n\terr = client.WaitForEvents()\n\trequire.NoError(t, err, \"Failed waiting for mock feeds to deploy\")\n\n\tregistry := DeployKeeperRegistry(t, contractDeployer, client,\n\t\t&contracts.KeeperRegistryOpts{\n\t\t\tRegistryVersion: registryVersion,\n\t\t\tLinkAddr: linkToken.Address(),\n\t\t\tETHFeedAddr: ef.Address(),\n\t\t\tGasFeedAddr: gf.Address(),\n\t\t\tTranscoderAddr: ZeroAddress.Hex(),\n\t\t\tRegistrarAddr: ZeroAddress.Hex(),\n\t\t\tSettings: *registrySettings,\n\t\t},\n\t)\n\n\t// Fund the registry with 1 LINK * amount of KeeperConsumerPerformance contracts\n\terr = linkToken.Transfer(registry.Address(), big.NewInt(0).Mul(big.NewInt(1e18), big.NewInt(int64(numberOfContracts))))\n\trequire.NoError(t, err, \"Funding keeper registry contract shouldn't fail\")\n\n\tregistrarSettings := contracts.KeeperRegistrarSettings{\n\t\tAutoApproveConfigType: 2,\n\t\tAutoApproveMaxAllowed: math.MaxUint16,\n\t\tRegistryAddr: registry.Address(),\n\t\tMinLinkJuels: big.NewInt(0),\n\t}\n\tregistrar := DeployKeeperRegistrar(t, registryVersion, linkToken, registrarSettings, contractDeployer, client, registry)\n\n\tupkeeps := DeployPerformDataChecker(t, contractDeployer, client, numberOfContracts, expectedData)\n\n\tvar upkeepsAddresses []string\n\tfor _, upkeep := range upkeeps {\n\t\tupkeepsAddresses = append(upkeepsAddresses, upkeep.Address())\n\t}\n\n\tupkeepIds := RegisterUpkeepContracts(\n\t\tt, linkToken, linkFundsForEachUpkeep, client, upkeepGasLimit, registry, registrar, numberOfContracts, upkeepsAddresses,\n\t)\n\n\treturn registry, registrar, upkeeps, upkeepIds\n}" ]
[ "0.7458044", "0.72708255", "0.7165749", "0.6355708", "0.6333262", "0.6289368", "0.6034183", "0.59767526", "0.5350945", "0.5326113", "0.5316944", "0.5293921", "0.5291574", "0.5288858", "0.5181665", "0.50297725", "0.5004145", "0.49968114", "0.4973181", "0.49554932", "0.49168134", "0.49161786", "0.48558745", "0.48348212", "0.4780243", "0.47655225", "0.46690682", "0.46460775", "0.4633421", "0.46214518", "0.46001568", "0.45952874", "0.45596862", "0.45577362", "0.45230243", "0.4510012", "0.4487896", "0.44359645", "0.43783206", "0.43779016", "0.43539724", "0.43507287", "0.43289697", "0.4312587", "0.42917907", "0.42902642", "0.42837957", "0.42696267", "0.4263542", "0.42627075", "0.42598623", "0.42579657", "0.42286202", "0.42082292", "0.4202737", "0.41925418", "0.41888416", "0.41565165", "0.41503036", "0.4148117", "0.41393203", "0.41344815", "0.41251412", "0.41204268", "0.41075897", "0.41043648", "0.40976706", "0.40874535", "0.40812185", "0.40810624", "0.40699378", "0.40511018", "0.40375847", "0.40257558", "0.40231967", "0.40202817", "0.40171948", "0.40171948", "0.40162", "0.40045753", "0.4001422", "0.40011954", "0.398339", "0.3981519", "0.3978679", "0.39728245", "0.3967995", "0.39662254", "0.39633018", "0.396275", "0.39614454", "0.39563745", "0.39504752", "0.394425", "0.39406267", "0.39393657", "0.39384085", "0.39384085", "0.39362255", "0.39217934" ]
0.71483314
3
/ Description: Calculates the share percentage of a cycle over a list of delegated contracts
func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){ var stakingBalance float64 //var balance float64 var err error spillAlert := false stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle) if (err != nil){ return delegatedContracts, errors.New("func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: " + err.Error()) } mod := math.Mod(stakingBalance, 10000) sum := stakingBalance - mod balanceCheck := stakingBalance - mod for index, delegation := range delegatedContracts{ counter := 0 for i, _ := range delegation.Contracts { if (delegatedContracts[index].Contracts[i].Cycle == cycle){ break } counter = counter + 1 } balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount //fmt.Println(stakingBalance) if (spillAlert){ delegatedContracts[index].Contracts[counter].SharePercentage = 0 delegatedContracts[index].Contracts[counter].RollInclusion = 0 } else if (balanceCheck < 0 && spillage){ spillAlert = true delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance } else{ delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount } delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate) delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee } return delegatedContracts, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func CalculateAllContractsForCycles(delegatedContracts []DelegatedContract, cycleStart int, cycleEnd int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var err error\n\n for cycleStart <= cycleEnd {\n //fmt.Println(cycleStart)\n delegatedContracts, err = CalculateAllContractsForCycle(delegatedContracts, cycleStart, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycles \" + strconv.Itoa(cycleStart) + \"-\" + strconv.Itoa(cycleEnd) + \":CalculateAllCommitmentsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64) failed: \" + err.Error())\n }\n cycleStart = cycleStart + 1\n }\n return delegatedContracts, nil\n}", "func ProportionalShare(config *pb.Algorithm) Algorithm {\n\tlength, interval := getAlgorithmParams(config)\n\n\treturn func(r Request) Lease {\n\t\tvar (\n\t\t\tcount = r.Store.Count()\n\t\t\told = r.Store.Get(r.Client)\n\t\t\tgets = 0.0\n\t\t)\n\n\t\t// If this is a new client, we adjust the count.\n\t\tif !r.Store.HasClient(r.Client) {\n\t\t\tcount += r.Subclients\n\t\t}\n\n\t\t// This is the equal share that every subclient has an absolute\n\t\t// claim on.\n\t\tequalShare := r.Capacity / float64(count)\n\n\t\t// This is the equal share that should be assigned to the current client\n\t\t// based on the number of its subclients.\n\t\tequalSharePerClient := equalShare * float64(r.Subclients)\n\n\t\t// This is the capacity which is currently unused (assuming that\n\t\t// the requesting client has no capacity). It is the maximum\n\t\t// capacity that this run of the algorithm can assign to the\n\t\t// requesting client.\n\t\tunusedCapacity := r.Capacity - r.Store.SumHas() + old.Has\n\n\t\t// If the client wants less than it equal share or\n\t\t// if the sum of what all clients want together is less\n\t\t// than the available capacity we can give this client what\n\t\t// it wants.\n\t\tif r.Store.SumWants() <= r.Capacity || r.Wants <= equalSharePerClient {\n\t\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\t\tminF(r.Wants, unusedCapacity), r.Wants, r.Subclients)\n\t\t}\n\n\t\t// We now need to determine if we can give a top-up on\n\t\t// the equal share. The capacity for this top up comes\n\t\t// from clients who want less than their equal share,\n\t\t// so we calculate how much capacity this is. We also\n\t\t// calculate the excess need of all the clients, which\n\t\t// is the sum of all the wants over the equal share.\n\t\textraCapacity := 0.0\n\t\textraNeed := 0.0\n\n\t\tr.Store.Map(func(id string, lease Lease) {\n\t\t\tvar wants float64\n\t\t\tvar subclients int64\n\n\t\t\tif id == r.Client {\n\t\t\t\twants = r.Wants\n\t\t\t\tsubclients = r.Subclients\n\t\t\t} else {\n\t\t\t\twants = lease.Wants\n\t\t\t\tsubclients = lease.Subclients\n\t\t\t}\n\n\t\t\t// Every client should receive the resource capacity based on the number\n\t\t\t// of subclients it has.\n\t\t\tequalSharePerClient := equalShare * float64(subclients)\n\t\t\tif wants < equalSharePerClient {\n\t\t\t\textraCapacity += equalSharePerClient - wants\n\t\t\t} else {\n\t\t\t\textraNeed += wants - equalSharePerClient\n\t\t\t}\n\t\t})\n\n\t\t// Every client with a need over the equal share will get\n\t\t// a proportional top-up.\n\t\tgets = equalSharePerClient + (r.Wants-equalSharePerClient)*(extraCapacity/extraNeed)\n\n\t\t// Insert the capacity grant into the lease store. We cannot\n\t\t// give out more than the currently unused capacity. If that\n\t\t// is less than what the algorithm calculated we will\n\t\t// adjust this in the next capacity refreshes.\n\n\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\tminF(gets, unusedCapacity), r.Wants, r.Subclients)\n\t}\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func FairShare(config *pb.Algorithm) Algorithm {\n\tlength, interval := getAlgorithmParams(config)\n\n\treturn func(r Request) Lease {\n\t\tvar (\n\t\t\tcount = r.Store.Count()\n\t\t\told = r.Store.Get(r.Client)\n\t\t)\n\n\t\t// If this is a new client, we adjust the count.\n\t\tif !r.Store.HasClient(r.Client) {\n\t\t\tcount += r.Subclients\n\t\t}\n\n\t\t// This is the equal share that every subclient should get.\n\t\tequalShare := r.Capacity / float64(count)\n\n\t\t// This is the equal share that should be assigned to the current client\n\t\t// based on the number of its subclients.\n\t\tequalSharePerClient := equalShare * float64(r.Subclients)\n\n\t\t// This is the capacity which is currently unused (assuming that\n\t\t// the requesting client has no capacity). It is the maximum\n\t\t// capacity that this run of the algorithm can assign to the\n\t\t// requesting client.\n\t\tunusedCapacity := r.Capacity - r.Store.SumHas() + old.Has\n\n\t\t// If the client wants less than its equal share or\n\t\t// if the sum of what all clients want together is less\n\t\t// than the available capacity we can give this client what\n\t\t// it wants.\n\t\tif r.Wants <= equalSharePerClient || r.Store.SumWants() <= r.Capacity {\n\t\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\t\tminF(r.Wants, unusedCapacity), r.Wants, r.Subclients)\n\t\t}\n\n\t\t// Map of what each client will get from this algorithm run.\n\t\t// Ultimately we need only determine what this client gets,\n\t\t// but for the algorithm we need to keep track of what\n\t\t// other clients would be getting as well.\n\t\tgets := make(map[string]float64)\n\n\t\t// This list contains all the clients which are still in\n\t\t// the race to get some capacity.\n\t\tclients := list.New()\n\t\tclientsNext := list.New()\n\n\t\t// Puts every client in the list to signify that they all\n\t\t// still need capacity.\n\t\tr.Store.Map(func(id string, lease Lease) {\n\t\t\tclients.PushBack(id)\n\t\t})\n\n\t\t// This is the capacity that can still be divided.\n\t\tavailableCapacity := r.Capacity\n\n\t\t// The clients list now contains all the clients who still need/want\n\t\t// capacity. We are going to divide the capacity in availableCapacity\n\t\t// in iterations until there is nothing more to divide or until we\n\t\t// completely satisfied the client who is making the request.\n\t\tfor availableCapacity > epsilon && gets[r.Client] < r.Wants-epsilon {\n\t\t\t// Calculate number of subclients for the given clients list.\n\t\t\tclientsCopy := *clients\n\t\t\tvar subclients int64\n\t\t\tfor e := clientsCopy.Front(); e != nil; e = e.Next() {\n\t\t\t\tsubclients += r.Store.Subclients(e.Value.(string))\n\t\t\t}\n\n\t\t\t// This is the fair share that is available to all subclients\n\t\t\t// who are still in the race to get capacity.\n\t\t\tfairShare := availableCapacity / float64(subclients)\n\n\t\t\t// Not enough capacity to actually worry about. Prevents\n\t\t\t// an infinite loop.\n\t\t\tif fairShare < epsilon {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// We now process the list of clients and give a topup to\n\t\t\t// every client's capacity. That topup is either the fair\n\t\t\t// share or the capacity still needed to be completely\n\t\t\t// satisfied (in case the client needs less than the\n\t\t\t// fair share to reach its need/wants).\n\t\t\tfor e := clients.Front(); e != nil; e = e.Next() {\n\t\t\t\tid := e.Value.(string)\n\n\t\t\t\t// Determines the wants for this client, which comes\n\t\t\t\t// either from the store, or from the request info if it\n\t\t\t\t// is the client making the request,\n\t\t\t\tvar wants float64\n\t\t\t\tvar subclients int64\n\n\t\t\t\tif id == r.Client {\n\t\t\t\t\twants = r.Wants\n\t\t\t\t\tsubclients = r.Subclients\n\t\t\t\t} else {\n\t\t\t\t\twants = r.Store.Get(id).Wants\n\t\t\t\t\tsubclients = r.Store.Subclients(id)\n\t\t\t\t}\n\n\t\t\t\t// stillNeeds is the capacity this client still needs to\n\t\t\t\t// be completely satisfied.\n\t\t\t\tstillNeeds := wants - gets[id]\n\n\t\t\t\t// Tops up the client's capacity.\n\t\t\t\t// Every client should receive the resource capacity based on\n\t\t\t\t// the number of its subclients.\n\t\t\t\tfairSharePerClient := fairShare * float64(subclients)\n\t\t\t\tif stillNeeds <= fairSharePerClient {\n\t\t\t\t\tgets[id] += stillNeeds\n\t\t\t\t\tavailableCapacity -= stillNeeds\n\t\t\t\t} else {\n\t\t\t\t\tgets[id] += fairSharePerClient\n\t\t\t\t\tavailableCapacity -= fairSharePerClient\n\t\t\t\t}\n\n\t\t\t\t// If the client is not yet satisfied we include it in the next\n\t\t\t\t// generation of the list. If it is completely satisfied we\n\t\t\t\t// don't.\n\t\t\t\tif gets[id] < wants {\n\t\t\t\t\tclientsNext.PushBack(id)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Ready for the next iteration of the loop. Swap the clients with the\n\t\t\t// clientsNext list.\n\t\t\tclients, clientsNext = clientsNext, clients\n\n\t\t\t// Cleans the clientsNext list so that it can be used again.\n\t\t\tclientsNext.Init()\n\t\t}\n\n\t\t// Insert the capacity grant into the lease store. We cannot\n\t\t// give out more than the currently unused capacity. If that\n\t\t// is less than what the algorithm calculated this will get\n\t\t// fixed in the next capacity refreshes.\n\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\tminF(gets[r.Client], unusedCapacity), r.Wants, r.Subclients)\n\t}\n}", "func (w *Worker) IncrementShares(sessionDifficulty float64, reward float64) {\n\tp := w.s.Client.pool\n\tcbid := p.cs.CurrentBlock().ID()\n\tblockTarget, _ := p.cs.ChildTarget(cbid)\n\tblockDifficulty, _ := blockTarget.Difficulty().Uint64()\n\n\tsessionTarget, _ := difficultyToTarget(sessionDifficulty)\n\tsiaSessionDifficulty, _ := sessionTarget.Difficulty().Uint64()\n\tshareRatio := caculateRewardRatio(sessionTarget.Difficulty().Big(), blockTarget.Difficulty().Big())\n\tshareReward := shareRatio * reward\n\t// w.log.Printf(\"shareRatio: %f, shareReward: %f\", shareRatio, shareReward)\n\n\tshare := &Share{\n\t\tuserid: w.Parent().cr.clientID,\n\t\tworkerid: w.wr.workerID,\n\t\theight: int64(p.cs.Height()) + 1,\n\t\tvalid: true,\n\t\tdifficulty: sessionDifficulty,\n\t\tshareDifficulty: float64(siaSessionDifficulty),\n\t\treward: reward,\n\t\tblockDifficulty: blockDifficulty,\n\t\tshareReward: shareReward,\n\t\ttime: time.Now(),\n\t}\n\n\tw.s.Shift().IncrementShares(share)\n}", "func (s *ArkClient) CalculateVotersProfit(params DelegateQueryParams, shareRatio float64, blocklist string, whitelist string, capBalance bool, balanceCapAmount float64, blockBalanceCap bool) []DelegateDataProfit {\n\tdelegateRes, _, _ := s.GetDelegate(params)\n\tvoters, _, _ := s.GetDelegateVoters(params)\n\taccountRes, _, _ := s.GetAccount(AccountQueryParams{Address: delegateRes.SingleDelegate.Address})\n\n\tdelegateBalance, _ := strconv.ParseFloat(accountRes.Account.Balance, 64)\n\tdelegateBalance = float64(delegateBalance) / SATOSHI\n\n\t//calculating vote weight\n\tvotersProfit := []DelegateDataProfit{}\n\tdelelgateVoteWeight := 0\n\n\t//computing summ of all votes\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tintBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tintBalance = int(balanceCapAmount)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelelgateVoteWeight += intBalance\n\t}\n\n\t//calculating\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tcurrentVoterBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcurrentVoterBalance = balanceCapAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdeleProfit := DelegateDataProfit{\n\t\t\tAddress: element.Address,\n\t\t}\n\t\tdeleProfit.VoteWeight = currentVoterBalance / SATOSHI\n\t\tdeleProfit.VoteWeightShare = float64(currentVoterBalance) / float64(delelgateVoteWeight)\n\t\tdeleProfit.EarnedAmount100 = float64(delegateBalance) * deleProfit.VoteWeightShare\n\t\tdeleProfit.EarnedAmountXX = float64(delegateBalance) * deleProfit.VoteWeightShare * shareRatio\n\t\tdeleProfit.VoteDuration = s.GetVoteDuration(element.Address)\n\t\tvotersProfit = append(votersProfit, deleProfit)\n\t}\n\n\treturn votersProfit\n}", "func calculateRewardShares(operator string, delegate []byte, epochs string) *RewardShares {\n\tif epochs == \"\" {\n\t\treturn calculateEpochRewardShares(\n\t\t\toperator, delegate, currentEpochNum())\n\t}\n\n\t// parse a range of epochs\n\tresult := NewRewardShares()\n\tresult.SetEpochNum(epochs)\n\tfor epoch := range epochRangeGen(epochs) {\n\t\tfmt.Printf(\"epoch: %v\\n\", epoch)\n\t\treward := calculateEpochRewardShares(operator, delegate, epoch)\n\t\tresult = result.Combine(reward)\n\t}\n\treturn result\n}", "func PercentDiff(matches []Match) []float64 {\n\t// Read in timeseries data, all match results. More data is more better.\n\tvar diffs []float64\n\tfor _, match := range matches {\n\t\td1 := match.P1got / match.P1needs\n\t\td2 := match.P2got / match.P2needs\n\t\tdiffs = append(diffs, d2)\n\t\tdiffs = append(diffs, d1)\n\t}\n\treturn diffs\n}", "func (d *Download) Percent() float32 {\r\n\treturn float32(d.current) / float32(d.max)\r\n}", "func GenerateShares(transportPrivateKey *big.Int, transportPublicKey [2]*big.Int, participants ParticipantList, threshold int) ([]*big.Int, []*big.Int, [][2]*big.Int, error) {\n\n\t// create coefficients (private/public)\n\tprivateCoefficients, err := cloudflare.ConstructPrivatePolyCoefs(rand.Reader, threshold)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tpublicCoefficients := cloudflare.GeneratePublicCoefs(privateCoefficients)\n\n\t// create commitments\n\tcommitments := make([][2]*big.Int, len(publicCoefficients))\n\tfor idx, publicCoefficient := range publicCoefficients {\n\t\tcommitments[idx] = bn256.G1ToBigIntArray(publicCoefficient)\n\t}\n\n\t// secret shares\n\ttransportPublicKeyG1, err := bn256.BigIntArrayToG1(transportPublicKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// convert public keys into G1 structs\n\tpublicKeyG1s := []*cloudflare.G1{}\n\tfor idx := 0; idx < len(participants); idx++ {\n\t\tparticipant := participants[idx]\n\t\tlogger.Infof(\"participants[%v]: %v\", idx, participant)\n\t\tif participant != nil && participant.PublicKey[0] != nil && participant.PublicKey[1] != nil {\n\t\t\tpublicKeyG1, err := bn256.BigIntArrayToG1(participant.PublicKey)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\tpublicKeyG1s = append(publicKeyG1s, publicKeyG1)\n\t\t}\n\t}\n\n\t// check for missing data\n\tif len(publicKeyG1s) != len(participants) {\n\t\treturn nil, nil, nil, fmt.Errorf(\"only have %v of %v public keys\", len(publicKeyG1s), len(participants))\n\t}\n\n\tif len(privateCoefficients) != threshold+1 {\n\t\treturn nil, nil, nil, fmt.Errorf(\"only have %v of %v private coefficients\", len(privateCoefficients), threshold+1)\n\t}\n\n\t//\n\tsecretsArray, err := cloudflare.GenerateSecretShares(transportPublicKeyG1, privateCoefficients, publicKeyG1s)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to generate secret shares: %v\", err)\n\t}\n\n\t// final encrypted shares\n\tencryptedShares, err := cloudflare.GenerateEncryptedShares(secretsArray, transportPrivateKey, publicKeyG1s)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to generate encrypted shares: %v\", err)\n\t}\n\n\treturn encryptedShares, privateCoefficients, commitments, nil\n}", "func GetDelegatedContractsForCycle(cycle int, delegateAddr string) ([]string, error){\n var rtnString []string\n snapShot, err := GetSnapShot(cycle)\n // fmt.Println(snapShot)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetSnapShot(cycle int) failed: \" + err.Error())\n }\n hash, err:= GetBlockLevelHash(snapShot.AssociatedBlock)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetBlockLevelHash(level int) failed: \" + err.Error())\n }\n // fmt.Println(hash)\n getDelegatedContracts := \"/chains/main/blocks/\" + hash + \"/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n\n s, err := TezosRPCGet(getDelegatedContracts)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1)\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": You have no contracts.\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func Share(mod *big.Int, nPieces int, secret *big.Int) []*big.Int {\n\tif nPieces == 0 {\n\t\tpanic(\"Number of shares must be at least 1\")\n\t} else if nPieces == 1 {\n\t\treturn []*big.Int{secret}\n\t}\n\n\tout := make([]*big.Int, nPieces)\n\n\tacc := new(big.Int)\n\tfor i := 0; i < nPieces-1; i++ {\n\t\tout[i] = utils.RandInt(mod)\n\n\t\tacc.Add(acc, out[i])\n\t}\n\n\tacc.Sub(secret, acc)\n\tacc.Mod(acc, mod)\n\tout[nPieces-1] = acc\n\n\treturn out\n}", "func PercentFor(currency string) int {\r\n\r\n\tif currency == \"UZS\" {\r\n\t\treturn 7 \r\n\t}\r\n\r\n\tif currency == \"USD\" {\r\n\t\treturn 10\r\n\t}\r\n\treturn 0\r\n}", "func ratioAutoConsoCalculator(details model.ClientTotalInfo) float64 {\n\n\ttotalHomeComsuption := details.FromGenToConsumer + details.FromGridToConsumer\n\ttotalPannelProduction := details.FromGenToConsumer + details.FromGenToGrid\n\n\tratio := totalPannelProduction / totalHomeComsuption * 100\n\n\treturn ratio\n}", "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (ms mainnetSchedule) ConsensusRatio() float64 {\n\treturn mainnetConsensusRatio\n}", "func GenerateShares(secret int64, n int, M *big.Int) []*big.Int {\n\ts := new(big.Int).SetInt64(secret)\n\tsum := new(big.Int)\n\tshares := make([]*big.Int, n)\n\tj := mr.Intn(n)\n\tfor i := 0; i < n; i++ {\n\t\tif i != j {\n\t\t\tshares[i] = getRandom(M)\n\t\t\tsum.Add(sum, shares[i])\n\t\t}\n\t}\n\tshares[j] = s.Sub(s, sum).Mod(s, M)\n\treturn shares\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func spread(askPrice, bidPrice float64) float64 {\n\treturn ((askPrice - bidPrice) / askPrice) * 100\n}", "func calculatePercent(count int, totalRows int) (percent float64) {\n\treturn math.Round(float64(count) / float64(totalRows) * 100)\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (c MethodsCollection) ComputeShare() pComputeShare {\n\treturn pComputeShare{\n\t\tMethod: c.MustGet(\"ComputeShare\"),\n\t}\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func calculateRewards(delegationTotal loom.BigUInt, params *Params, totalValidatorDelegations loom.BigUInt) loom.BigUInt {\n\tcycleSeconds := params.ElectionCycleLength\n\treward := CalculateFraction(blockRewardPercentage, delegationTotal)\n\n\t// If totalValidator Delegations are high enough to make simple reward\n\t// calculations result in more rewards given out than the value of `MaxYearlyReward`,\n\t// scale the rewards appropriately\n\tyearlyRewardTotal := CalculateFraction(blockRewardPercentage, totalValidatorDelegations)\n\tif yearlyRewardTotal.Cmp(&params.MaxYearlyReward.Value) > 0 {\n\t\treward.Mul(&reward, &params.MaxYearlyReward.Value)\n\t\treward.Div(&reward, &yearlyRewardTotal)\n\t}\n\n\t// When election cycle = 0, estimate block time at 2 sec\n\tif cycleSeconds == 0 {\n\t\tcycleSeconds = 2\n\t}\n\treward.Mul(&reward, &loom.BigUInt{big.NewInt(cycleSeconds)})\n\treward.Div(&reward, &secondsInYear)\n\n\treturn reward\n}", "func DisplayCalculatedVoteRatio() {\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tdeleResp, _, _ := arkclient.GetDelegate(params)\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\tshareRatioStr := strconv.FormatFloat(viper.GetFloat64(\"voters.shareratio\")*100, 'f', -1, 64) + \"%\"\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Displaying voter information for delegate:\", deleResp.SingleDelegate.Username, deleResp.SingleDelegate.Address)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(fmt.Sprintf(\"|%-34s|%18s|%8s|%17s|%17s|%6s|\", \"Voter address\", \"Balance\", \"Weight\", \"Reward-100%\", \"Reward-\"+shareRatioStr, \"Hours\"))\n\tcolor.Set(color.FgCyan)\n\tfor _, element := range votersEarnings {\n\t\ts := fmt.Sprintf(\"|%s|%18.8f|%8.4f|%15.8f A|%15.8f A|%6d|\", element.Address, element.VoteWeight, element.VoteWeightShare, element.EarnedAmount100, element.EarnedAmountXX, element.VoteDuration)\n\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\t}\n\n\t//Cost calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"Available amount:\", sumEarned)\n\tfmt.Println(\"Amount to voters:\", sumShareEarned, viper.GetFloat64(\"voters.shareratio\"))\n\tfmt.Println(\"Amount to costs:\", costAmount, viper.GetFloat64(\"costs.shareratio\"))\n\tfmt.Println(\"Amount to reserve:\", reserveAmount, viper.GetFloat64(\"reserve.shareratio\"))\n\n\tfmt.Println(\"Ratio calc check:\", sumRatio, \"(should be = 1)\")\n\tfmt.Println(\"Ratio share check:\", float64(sumShareEarned)/float64(sumEarned), \"should be=\", viper.GetFloat64(\"voters.shareratio\"))\n\n\tpause()\n}", "func determineChurn(prevConsensus, newConsensus *tor.Consensus) Churn {\n\n\tgoneRelays := prevConsensus.Subtract(newConsensus)\n\tnewRelays := newConsensus.Subtract(prevConsensus)\n\n\tmax := math.Max(float64(prevConsensus.Length()), float64(newConsensus.Length()))\n\tnewChurn := (float64(newRelays.Length()) / max)\n\tgoneChurn := (float64(goneRelays.Length()) / max)\n\n\treturn Churn{newChurn, goneChurn}\n}", "func (_DelegatableDai *DelegatableDaiSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{\n for _, delegatedContract := range delegatedContracts {\n err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias)\n if (err != nil){\n return errors.New(\"Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: \" + err.Error())\n }\n }\n return nil\n}", "func (sch *Scheduler) CalClusterBalance(podUsed *[PHYNUM][DIMENSION]float64, podReq []PodRequest) {\n\t//cal the pod sum and used rate\n\tpodLen := len(podReq)\n\tvar podNum [PHYNUM]int\n\tvar podSum int\n\tfor i := 0; i < podLen; i++ {\n\t\tif podReq[i].nodeName != -1 {\n\t\t\tpodSum++\n\t\t\tpodNum[podReq[i].nodeName]++\n\t\t}\n\t}\n\n\tvar podIdle [PHYNUM]float64\n\tvar resIdle [PHYNUM][DIMENSION]float64\n\tvar podVal float64\n\tvar resVal [DIMENSION]float64 // cal the sum and mean value\n\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tpodIdle[i] = 1.0 - (float64)(podNum[i])/(float64)(podSum)\n\t\tpodVal = podVal + podIdle[i]\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tresIdle[i][j] = (sch.reTotal[j] - podUsed[i][j]) / sch.reTotal[j]\n\t\t\tresVal[j] = resVal[j] + resIdle[i][j]\n\t\t}\n\t}\n\t// cal the balance value\n\tpodMean := podVal / (float64)(podSum)\n\tvar resMean [DIMENSION]float64\n\tfor j := 0; j < DIMENSION; j++ {\n\t\tresMean[j] = resVal[j] / (float64)(PHYNUM)\n\t}\n\tvar baIdle float64\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tbaIdle = baIdle + math.Pow((resIdle[i][j]-resMean[j]), 2)\n\t\t}\n\t\tbaIdle = baIdle + math.Pow((podIdle[i]-podMean), 2)\n\t}\n\tbaIdle = math.Sqrt(baIdle)\n\tfmt.Printf(\"The balance value is %.3f \\n\", baIdle)\n}", "func PercentOf(part int, total int) float64 {\n\treturn (float64(part) * float64(100.00)) / float64(total)\n}", "func TestFeePercentage(t *testing.T) {\n\tvar (\n\t\tokPPM uint64 = 30000\n\t\tokQuote = &loop.LoopOutQuote{\n\t\t\tSwapFee: 15,\n\t\t\tPrepayAmount: 30,\n\t\t\tMinerFee: 1,\n\t\t}\n\n\t\trec = loop.OutRequest{\n\t\t\tAmount: 7500,\n\t\t\tOutgoingChanSet: loopdb.ChannelSet{chanID1.ToUint64()},\n\t\t\tMaxMinerFee: scaleMaxMinerFee(\n\t\t\t\tscaleMinerFee(testQuote.MinerFee),\n\t\t\t),\n\t\t\tMaxSwapFee: okQuote.SwapFee,\n\t\t\tMaxPrepayAmount: okQuote.PrepayAmount,\n\t\t\tSweepConfTarget: defaultConfTarget,\n\t\t\tInitiator: autoloopSwapInitiator,\n\t\t}\n\t)\n\n\trec.MaxPrepayRoutingFee, rec.MaxSwapRoutingFee = testPPMFees(\n\t\tokPPM, okQuote, 7500,\n\t)\n\n\ttests := []struct {\n\t\tname string\n\t\tfeePPM uint64\n\t\tquote *loop.LoopOutQuote\n\t\tsuggestions *Suggestions\n\t}{\n\t\t{\n\t\t\t// With our limit set to 3% of swap amount 7500, we\n\t\t\t// have a total budget of 225 sat.\n\t\t\tname: \"fees ok\",\n\t\t\tfeePPM: okPPM,\n\t\t\tquote: okQuote,\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\trec,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"swap fee too high\",\n\t\t\tfeePPM: 20000,\n\t\t\tquote: &loop.LoopOutQuote{\n\t\t\t\tSwapFee: 300,\n\t\t\t\tPrepayAmount: 30,\n\t\t\t\tMinerFee: 1,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonSwapFee,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"miner fee too high\",\n\t\t\tfeePPM: 20000,\n\t\t\tquote: &loop.LoopOutQuote{\n\t\t\t\tSwapFee: 80,\n\t\t\t\tPrepayAmount: 30,\n\t\t\t\tMinerFee: 300,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonMinerFee,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"miner and swap too high\",\n\t\t\tfeePPM: 20000,\n\t\t\tquote: &loop.LoopOutQuote{\n\t\t\t\tSwapFee: 60,\n\t\t\t\tPrepayAmount: 30,\n\t\t\t\tMinerFee: 50,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonFeePPMInsufficient,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, testCase := range tests {\n\t\ttestCase := testCase\n\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\tcfg, lnd := newTestConfig()\n\n\t\t\tcfg.LoopOutQuote = func(_ context.Context,\n\t\t\t\t_ *loop.LoopOutQuoteRequest) (*loop.LoopOutQuote,\n\t\t\t\terror) {\n\n\t\t\t\treturn testCase.quote, nil\n\t\t\t}\n\n\t\t\tlnd.Channels = []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t}\n\n\t\t\tparams := defaultParameters\n\t\t\tparams.AutoloopBudgetLastRefresh = testBudgetStart\n\t\t\tparams.FeeLimit = NewFeePortion(testCase.feePPM)\n\t\t\tparams.ChannelRules = map[lnwire.ShortChannelID]*SwapRule{\n\t\t\t\tchanID1: chanRule,\n\t\t\t}\n\n\t\t\ttestSuggestSwaps(\n\t\t\t\tt, newSuggestSwapsSetup(cfg, lnd, params),\n\t\t\t\ttestCase.suggestions, nil,\n\t\t\t)\n\t\t})\n\t}\n}", "func checkFor100Percent(requestInfoObj requestInfo) bool {\n\tvar total float64\n\tfor i := 0; i < len(requestInfoObj.stockInfo_req); i++ {\n\t\ttotal = total + requestInfoObj.stockInfo_req[i].sharePercent\n\t}\n\tif total == 100 {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCallerSession) Digests(arg0 [32]byte) (*big.Int, error) {\n\treturn _BondedECDSAKeep.Contract.Digests(&_BondedECDSAKeep.CallOpts, arg0)\n}", "func (k *Keeper) GetAllDecryptionShares(ctx sdk.Context, round uint64) ([]*types.DecryptionShare, sdk.Error) {\n\tstage := k.GetStage(ctx, round)\n\tif stage != stageDSCollecting && stage != stageCompleted {\n\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"wrong round stage: %v. round: %v\", stage, round))\n\t}\n\n\tdsStore := ctx.KVStore(k.storeDecryptionSharesKey)\n\n\tkeyAllShares := []byte(fmt.Sprintf(\"rd_%d\", round))\n\n\tif !dsStore.Has(keyAllShares) {\n\t\treturn []*types.DecryptionShare{}, nil\n\t}\n\n\taddrListBytes := dsStore.Get(keyAllShares)\n\tvar addrList []string\n\terr := k.cdc.UnmarshalJSON(addrListBytes, &addrList)\n\tif err != nil {\n\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"can't unmarshal list of all adderesses from store: %v\", err))\n\t}\n\tdsList := make([]*types.DecryptionShare, 0, len(addrList))\n\tfor _, addrStr := range addrList {\n\t\taddr, err := sdk.AccAddressFromBech32(addrStr)\n\t\tif err != nil {\n\t\t\treturn nil, sdk.ErrUnknownAddress(fmt.Sprintf(\"can't get address from bench32: %v\", err))\n\t\t}\n\t\tkey := createKeyBytesByAddr(round, addr)\n\t\tif !dsStore.Has(key) {\n\t\t\treturn nil, sdk.ErrUnknownRequest(\"addresses list and real decryption share sender doesn't meet\")\n\t\t}\n\t\tdsBytes := dsStore.Get(key)\n\t\tvar dsJSON types.DecryptionShareJSON\n\t\terr = k.cdc.UnmarshalJSON(dsBytes, &dsJSON)\n\t\tif err != nil {\n\t\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"can't unmarthsal decryption share: %v\", err))\n\t\t}\n\t\tds, err1 := dsJSON.Deserialize()\n\t\tif err1 != nil {\n\t\t\treturn nil, err1\n\t\t}\n\t\tdsList = append(dsList, ds)\n\t}\n\treturn dsList, nil\n}", "func (_DelegatableDai *DelegatableDaiCaller) Balances(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegatableDai.contract.Call(opts, out, \"balances\", arg0)\n\treturn *ret0, err\n}", "func DelegatorSharesInvariant(k Keeper) sdk.Invariant {\n\treturn func(ctx sdk.Context) (string, bool) {\n\t\tvar (\n\t\t\tmsg string\n\t\t\tbroken bool\n\t\t)\n\n\t\tdefis := k.GetAllDefis(ctx)\n\t\tfor _, defi := range defis {\n\t\t\tdefiTotalDelShares := defi.GetDelegatorShares()\n\t\t\ttotalDelShares := sdk.ZeroDec()\n\n\t\t\tdelegations := k.GetDefiDelegations(ctx, defi.GetOperator())\n\t\t\tfor _, delegation := range delegations {\n\t\t\t\ttotalDelShares = totalDelShares.Add(delegation.Shares)\n\t\t\t}\n\n\t\t\tif !defiTotalDelShares.Equal(totalDelShares) {\n\t\t\t\tbroken = true\n\t\t\t\tmsg += fmt.Sprintf(\"broken delegator shares invariance:\\n\"+\n\t\t\t\t\t\"\\tdefi.DelegatorShares: %v\\n\"+\n\t\t\t\t\t\"\\tsum of Delegator.Shares: %v\\n\", defiTotalDelShares, totalDelShares)\n\t\t\t}\n\t\t}\n\n\t\treturn sdk.FormatInvariant(types.ModuleName, \"delegator shares\", msg), broken\n\t}\n}", "func (res *Results) CalculatePct(pct int) float64 {\n slice := res.copyTook()\n\n l := len(slice)\n switch l {\n case 0:\n return float64(0)\n case 1:\n return slice[0]\n case 2:\n return slice[1]\n }\n\n index := int(math.Floor(((float64(l)/100)*float64(pct))+0.5) - 1)\n return slice[index]\n}", "func average_centrality(g Graph, node string) (dis float64) {\n\tdis_from_start := map[string]int{node: 0}\n\topen_list := []string{node}\n\tfor len(open_list) != 0 {\n\t\tcurrent := open_list[0]\n\t\topen_list = open_list[1:]\n\t\tfor neighbor := range g[current] {\n\t\t\tif _, ok := dis_from_start[neighbor]; !ok {\n\t\t\t\tdis_from_start[neighbor] = dis_from_start[current] + 1\n\t\t\t\topen_list = append(open_list, neighbor)\n\t\t\t}\n\t\t}\n\t}\n\tfor _, v := range dis_from_start {\n\t\tdis += float64(v)\n\t}\n\tdis = dis / float64(len(dis_from_start))\n\treturn\n}", "func FindChance(c *httpClient.Client, pairs []string) {\n\t// 0.1% trading feee\n\tvar fee, initialKrw float64 = 0.001, 10000\n\tfor {\n\t\tlog.Printf(\"%v ...\", pairs)\n\t\tstopCurrentRound := false\n\t\ttmp := initialKrw\n\t\tvar orders []httpClient.Order\n\t\tfor _, pair := range pairs {\n\t\t\tr, err := c.GetOrderBookBuyOrSell(pair, \"buy\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error to get order book sell price of %v: %v\", pair, err)\n\t\t\t\tstopCurrentRound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// log.Printf(\"pair %v price - %v, quanlity - %v\", pair, r[0].Rate, r[0].Quantity)\n\t\t\tif tmp <= r[0].Quantity {\n\t\t\t\ttmp = tmp * r[0].Rate * (1 - fee)\n\t\t\t\torder := httpClient.Order{\n\t\t\t\t\tQuantity: tmp,\n\t\t\t\t\tRate: r[0].Rate,\n\t\t\t\t}\n\t\t\t\torders = append(orders, order)\n\t\t\t\t// log.Printf(\"tmp value: %v\", tmp)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"pair %v: the quantily is %v, less then requested %v\", pair, r[0].Quantity, tmp)\n\t\t\t\tstopCurrentRound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif stopCurrentRound {\n\t\t\tcontinue\n\t\t}\n\t\tchangeRate := (tmp - initialKrw) / initialKrw\n\t\tlog.Printf(\"%v: %v\", pairs, changeRate)\n\t\tif changeRate > 0 {\n\t\t\tlog.Printf(\"New balance: %v\", tmp)\n\t\t\tlog.Printf(\"Old balance: %v\", initialKrw)\n\t\t\tlog.Printf(\"Found chance: %v\", changeRate)\n\t\t\texecute(c, pairs, orders)\n\t\t}\n\t\ttime.Sleep(3 * time.Second)\n\t}\n}", "func Percent(value int64, total int64) float64 {\n\tif total == 0 {\n\t\treturn 0\n\t}\n\treturn (float64(value) / float64(total)) * 100\n}", "func calcTransmissionRisks(cycle Cycle) {\n\tfor i := 0; i < len(Inputs.People); i++ {\n\n\t\t//check people's ids line up\n\t\tthisPerson := Inputs.People[i]\n\t\tif uint(i) != thisPerson.Id {\n\t\t\tfmt.Println(\"Person Id doesn't make position in array\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\t// if uninfected\n\t\tunif_TB_state_id := Query.getStateByName(\"Uninfected TB\").Id\n\t\t// active_TB_state_id := Query.getStateByName(\"Active - untreated\").Id\n\t\t// active_treat_1_state_id := Query.getStateByName(\"Active Treated Month 1\").Id\n\t\t// active_treat_2_state_id := Query.getStateByName(\"Active Treated Month 2\").Id\n\t\ttb_chain := Query.getChainByName(\"TB disease and treatment\")\n\n\t\tthis_person_state_id := thisPerson.get_state_by_chain(tb_chain, cycle).Id\n\n\t\tisUsb := 0\n\t\tif thisPerson.get_state_by_chain(Inputs.Chains[BIRTHPLACE_CHAIN_ID], cycle).Name == \"United States\" {\n\t\t\tisUsb = 1\n\t\t}\n\n\t\trace_state_id := thisPerson.get_state_by_chain(Inputs.Chains[RACE_CHAIN_ID], cycle).Id\n\n\t\tif this_person_state_id == unif_TB_state_id {\n\t\t\tQuery.Num_susceptible_by_cycle_isUsb_and_race[cycle.Id][isUsb][race_state_id] += 1\n\t\t\tQuery.Total_susceptible_by_cycle[cycle.Id] += 1\n\t\t}\n\n\t\t// originally, all people in active + active treat m 1 + active treat m 2 were here\n\t\t// but it's 6 per CASE, not 6 per person. this is a more accurate way, since (almost) everyone\n\t\t// will eventually be treated, and this is only one month of contributing risk\n\t\t// if this_person_state_id == active_treat_1_state_id { //this_person_state_id == active_TB_state_id || || this_person_state_id == active_treat_2_state_id {\n\t\tQuery.Total_active_by_cycle[cycle.Id] += thisPerson.RiskOfProgression\n\n\t\tQuery.Num_active_cases_by_cycle_isUsb_and_race[cycle.Id][isUsb][race_state_id] += thisPerson.RiskOfProgression\n\n\t\t// }\n\n\t}\n\n\t//// -------------------------- NOTE I'VE TAKE OUT TRANSMISSION BY RACE AND BIRTHPLACE FOR NOW\n\n\tgeneralPopulationRisk := float64(Query.Total_active_by_cycle[cycle.Id]) / float64(Query.Total_susceptible_by_cycle[cycle.Id]) * 0.2\n\n\t// fmt.Println(\"In cycle \", cycle.Id, \" we have general population risk of: \", generalPopulationRisk)\n\n\t// calculate risk\n\tfor isUsb := 0; isUsb < 2; isUsb++ {\n\t\tfor r := 0; r < len(Inputs.States); r++ {\n\t\t\tnumSus := Query.Num_susceptible_by_cycle_isUsb_and_race[cycle.Id][isUsb][r]\n\t\t\tif numSus > 0 {\n\t\t\t\tnumActive := Query.Num_active_cases_by_cycle_isUsb_and_race[cycle.Id][isUsb][r]\n\t\t\t\t// todo make real\n\n\t\t\t\t//xyx\n\n\t\t\t\ttrans_adjustment := 0.0\n\t\t\t\tif cycle.Id <= 12 {\n\t\t\t\t\ttrans_adjustment = 1 //2.1\n\t\t\t\t} else if cycle.Id > 12 && cycle.Id <= 24 {\n\t\t\t\t\ttrans_adjustment = 1 //1.1\n\t\t\t\t} else if cycle.Id > 24 && cycle.Id <= 36 {\n\t\t\t\t\ttrans_adjustment = 1 //1.1\n\t\t\t\t} else {\n\t\t\t\t\ttrans_adjustment = 1.0\n\t\t\t\t}\n\n\t\t\t\trisk := ((float64(numActive)/float64(numSus))*0.8 + generalPopulationRisk) * trans_adjustment * NumberOfLtbiCasesCausedByOneActiveCase.Value\n\n\t\t\t\t// if float64(numActive)/float64(numSus) > 0 {\n\t\t\t\t// \tfmt.Println(\"risk in \", Inputs.States[b].Name, Inputs.States[r].Name, \" is \", float64(numActive)/float64(numSus))\n\t\t\t\t// }\n\n\t\t\t\tif risk > 1 {\n\t\t\t\t\trisk = 1\n\t\t\t\t}\n\t\t\t\tQuery.LTBI_risk_by_cycle_isUsb_and_race[cycle.Id][isUsb][r] = risk\n\t\t\t\t// fmt.Println(\"usb \", isUsb, \" race \", Inputs.States[r].Name, \" risk is \", numActive, \" / \", numSus, \" = \", risk)\n\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (t *transfer) Percentage() int {\n\t// catch zero values\n\tif t.progress == 0 || t.size == 0 {\n\t\treturn 0\n\t}\n\t// calculate\n\treturn int(100.0 * (float32(t.progress) / float32(t.size)))\n}", "func distribute(total, num int) []int {\n\tres := make([]int, num)\n\tfor i := range res {\n\t\t// Use the average number of remaining connections.\n\t\tdiv := len(res) - i\n\t\tres[i] = (total + div/2) / div\n\t\ttotal -= res[i]\n\t}\n\treturn res\n}", "func (_Cakevault *CakevaultCaller) TotalShares(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"totalShares\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func calculateEpochRewardShares(operator string, delegate []byte, epoch_num uint64) *RewardShares {\n\t// get epoch response\n\tgetEpochResponse(epoch_num)\n\n\t// get gravity height\n\tgravity_height := epochGravityHeight()\n\n\t// get number of produced blocks\n\tblocks := delegateProductivity(operator)\n\n\t// get delegate's votes\n\tvotes_distribution, elected, delegate_votes, total_votes := getVotes(delegate, gravity_height)\n\n\t// calculate reward\n\treward := calculateReward(blocks, elected, delegate_votes, total_votes)\n\n\t// populate rewardshare structure\n\treturn NewRewardShares().\n\t\tSetEpochNum(strconv.FormatUint(epoch_num, 10)).\n\t\tSetProductivity(blocks).\n\t\tSetTotalVotes(delegate_votes).\n\t\tSetReward(reward).\n\t\tCalculateShares(votes_distribution, delegate_votes, epoch_num)\n}", "func (_Ethdkg *EthdkgCaller) ShareDistributionHashes(opts *bind.CallOpts, arg0 common.Address) ([32]byte, error) {\n\tvar (\n\t\tret0 = new([32]byte)\n\t)\n\tout := ret0\n\terr := _Ethdkg.contract.Call(opts, out, \"share_distribution_hashes\", arg0)\n\treturn *ret0, err\n}", "func Percent(current uint64, all uint64) float64 {\n\tpercent := (float64(current) * float64(100)) / float64(all)\n\treturn percent\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) Digests(arg0 [32]byte) (*big.Int, error) {\n\treturn _BondedECDSAKeep.Contract.Digests(&_BondedECDSAKeep.CallOpts, arg0)\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (pp *PermuteProtocol) GenShares(sk *ring.Poly, ciphertext *bfv.Ciphertext, crs *ring.Poly, permutation []uint64, share RefreshShare) {\n\n\tlevel := len(ciphertext.Value()[1].Coeffs) - 1\n\n\tringQ := pp.context.ringQ\n\tringT := pp.context.ringT\n\tringQP := pp.context.ringQP\n\n\t// h0 = s*ct[1]\n\tringQ.NTTLazy(ciphertext.Value()[1], pp.tmp1)\n\tringQ.MulCoeffsMontgomeryConstant(sk, pp.tmp1, share.RefreshShareDecrypt)\n\tringQ.InvNTTLazy(share.RefreshShareDecrypt, share.RefreshShareDecrypt)\n\n\t// h0 = s*ct[1]*P\n\tringQ.MulScalarBigint(share.RefreshShareDecrypt, pp.context.ringP.ModulusBigint, share.RefreshShareDecrypt)\n\n\t// h0 = s*ct[1]*P + e\n\tpp.gaussianSampler.ReadLvl(len(ringQP.Modulus)-1, pp.tmp1, ringQP, pp.sigma, int(6*pp.sigma))\n\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\n\n\tfor x, i := 0, len(ringQ.Modulus); i < len(pp.context.ringQP.Modulus); x, i = x+1, i+1 {\n\t\ttmphP := pp.hP.Coeffs[x]\n\t\ttmp1 := pp.tmp1.Coeffs[i]\n\t\tfor j := 0; j < ringQ.N; j++ {\n\t\t\ttmphP[j] += tmp1[j]\n\t\t}\n\t}\n\n\t// h0 = (s*ct[1]*P + e)/P\n\tpp.baseconverter.ModDownSplitPQ(level, share.RefreshShareDecrypt, pp.hP, share.RefreshShareDecrypt)\n\n\t// h1 = -s*a\n\tringQP.Neg(crs, pp.tmp1)\n\tringQP.NTTLazy(pp.tmp1, pp.tmp1)\n\tringQP.MulCoeffsMontgomeryConstant(sk, pp.tmp1, pp.tmp2)\n\tringQP.InvNTTLazy(pp.tmp2, pp.tmp2)\n\n\t// h1 = s*a + e'\n\tpp.gaussianSampler.ReadAndAdd(pp.tmp2, ringQP, pp.sigma, int(6*pp.sigma))\n\n\t// h1 = (-s*a + e')/P\n\tpp.baseconverter.ModDownPQ(level, pp.tmp2, share.RefreshShareRecrypt)\n\n\t// mask = (uniform plaintext in [0, T-1]) * floor(Q/T)\n\n\t// Mask in the time domain\n\tcoeffs := pp.uniformSampler.ReadNew()\n\n\t// Multiply by Q/t\n\tlift(coeffs, pp.tmp1, pp.context)\n\n\t// h0 = (s*ct[1]*P + e)/P + mask\n\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\n\n\t// Mask in the spectral domain\n\tringT.NTT(coeffs, coeffs)\n\n\t// Permutation over the mask\n\tpp.permuteWithIndex(coeffs, permutation, pp.tmp1)\n\n\t// Switch back the mask in the time domain\n\tringT.InvNTTLazy(pp.tmp1, coeffs)\n\n\t// Multiply by Q/t\n\tlift(coeffs, pp.tmp1, pp.context)\n\n\t// h1 = (-s*a + e')/P - permute(mask)\n\tringQ.Sub(share.RefreshShareRecrypt, pp.tmp1, share.RefreshShareRecrypt)\n}", "func (_Ethdkg *EthdkgTransactor) DistributeShares(opts *bind.TransactOpts, encrypted_shares []*big.Int, commitments [][2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.contract.Transact(opts, \"distribute_shares\", encrypted_shares, commitments)\n}", "func calcdutyCycleFromNeutralCenter(iC *InterfaceConfig, channel int, side string, degreeVal int) int {\n degreeValf := float64(degreeVal)\n var dutyCycle float64 = 0\n if side == \"left\" {\n if iC.StickDir[channel]==\"rev\" {\n if iC.NeutralStickPos[channel]>iC.LeftStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.LeftStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n } else if iC.LeftStickMaxPos[channel]>iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.LeftStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n }\n } else if iC.StickDir[channel]==\"norm\" {\n if iC.NeutralStickPos[channel]<iC.LeftStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.LeftStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n } else if iC.LeftStickMaxPos[channel]<iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.LeftStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n }\n }\n } else if side == \"right\" {\n if iC.StickDir[channel]==\"rev\" {\n if(iC.NeutralStickPos[channel]>iC.RightStickMaxPos[channel]) {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.RightStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n } else if(iC.RightStickMaxPos[channel]>iC.NeutralStickPos[channel]) {\n dutyCycle=float64(iC.RightStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n }\n } else if iC.StickDir[channel]==\"norm\" {\n\n if iC.NeutralStickPos[channel]<iC.RightStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.RightStickMaxPos[channel])\n dutyCycle=dutyCycle/100\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n } else if iC.RightStickMaxPos[channel]<iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.RightStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n }\n }\n }\n println(\"calc Duty cycle: \" + strconv.Itoa(int(dutyCycle)))\n return int(dutyCycle)\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCaller) Digests(opts *bind.CallOpts, arg0 [32]byte) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BondedECDSAKeep.contract.Call(opts, out, \"digests\", arg0)\n\treturn *ret0, err\n}", "func (m *Manager) ListReceivedShares(ctx context.Context, filters []*collaboration.Filter) ([]*collaboration.ReceivedShare, error) {\n\tif err := m.initialize(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser, ok := ctxpkg.ContextGetUser(ctx)\n\tif !ok {\n\t\treturn nil, errtypes.UserRequired(\"error getting user from context\")\n\t}\n\n\tresult := []*collaboration.ReceivedShare{}\n\n\tids, err := granteeToIndex(&provider.Grantee{\n\t\tType: provider.GranteeType_GRANTEE_TYPE_USER,\n\t\tId: &provider.Grantee_UserId{UserId: user.Id},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treceivedIds, err := m.indexer.FindBy(&collaboration.Share{},\n\t\tindexer.NewField(\"GranteeId\", ids),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, group := range user.Groups {\n\t\tindex, err := granteeToIndex(&provider.Grantee{\n\t\t\tType: provider.GranteeType_GRANTEE_TYPE_GROUP,\n\t\t\tId: &provider.Grantee_GroupId{GroupId: &groupv1beta1.GroupId{OpaqueId: group}},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgroupIds, err := m.indexer.FindBy(&collaboration.Share{},\n\t\t\tindexer.NewField(\"GranteeId\", index),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treceivedIds = append(receivedIds, groupIds...)\n\t}\n\n\tfor _, id := range receivedIds {\n\t\ts, err := m.getShareByID(ctx, id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !share.MatchesFilters(s, filters) {\n\t\t\tcontinue\n\t\t}\n\t\tmetadata, err := m.downloadMetadata(ctx, s)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(errtypes.NotFound); !ok {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// use default values if the grantee didn't configure anything yet\n\t\t\tmetadata = ReceivedShareMetadata{\n\t\t\t\tState: collaboration.ShareState_SHARE_STATE_PENDING,\n\t\t\t}\n\t\t}\n\t\tresult = append(result, &collaboration.ReceivedShare{\n\t\t\tShare: s,\n\t\t\tState: metadata.State,\n\t\t\tMountPoint: metadata.MountPoint,\n\t\t})\n\t}\n\treturn result, nil\n}", "func Share(\n\ttrx storage.Transaction,\n\tpreviousTxId merkle.Digest,\n\ttransferTxId merkle.Digest,\n\ttransferBlockNumber uint64,\n\tcurrentOwner *account.Account,\n\tbalance uint64,\n) {\n\n\t// ensure single threaded\n\ttoLock.Lock()\n\tdefer toLock.Unlock()\n\n\t// delete current ownership\n\ttransfer(trx, previousTxId, transferTxId, transferBlockNumber, currentOwner, nil, balance)\n}", "func (c *Controller) getFunds() float64 {\n\treturn c.broker.GetAvailableFunds() / 10\n}", "func PercentageChange(old, new int) float64 {\n\treturn (float64(new-old) / float64(old)) * 100\n}", "func PerUserPercentDiff(matches []Match) map[string][]float64 {\n\t// Read in timeseries data, all match results. More data is more better.\n\tuserDiffs := make(map[string][]float64)\n\tfor _, match := range matches {\n\t\td1 := match.P1got / match.P1needs\n\t\td2 := match.P2got / match.P2needs\n\t\tuserDiffs[match.P1name] = append(userDiffs[match.P1name], d1)\n\t\tuserDiffs[match.P2name] = append(userDiffs[match.P2name], d2)\n\t}\n\treturn userDiffs\n}", "func (no *NetworkOverhead) getAccumulatedCost(scheduledList networkawareutil.ScheduledList, dependencyList []agv1alpha1.DependenciesInfo, nodeName string, region string,\n\tzone string, costMap map[networkawareutil.CostKey]int64) (int64, error) {\n\n\t// keep track of the accumulated cost\n\tvar cost int64 = 0\n\n\t// calculate accumulated shortest path\n\tfor _, podAllocated := range scheduledList { // For each pod already allocated\n\t\tfor _, d := range dependencyList { // For each pod dependency\n\t\t\t// If the pod allocated is not an established dependency, continue.\n\t\t\tif podAllocated.Selector != d.Workload.Selector {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif podAllocated.Hostname == nodeName { // If the Pod hostname is the node being scored\n\t\t\t\tcost += SameHostname\n\t\t\t} else { // If Nodes are not the same\n\t\t\t\t// Get NodeInfo from pod Hostname\n\t\t\t\tpodNodeInfo, err := no.handle.SnapshotSharedLister().NodeInfos().Get(podAllocated.Hostname)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(nil, \"getting pod hostname %q from Snapshot: %v\", podNodeInfo, err)\n\t\t\t\t\treturn cost, err\n\t\t\t\t}\n\t\t\t\t// Get zone and region from Pod Hostname\n\t\t\t\tregionPodNodeInfo := networkawareutil.GetNodeRegion(podNodeInfo.Node())\n\t\t\t\tzonePodNodeInfo := networkawareutil.GetNodeZone(podNodeInfo.Node())\n\n\t\t\t\tif regionPodNodeInfo == \"\" && zonePodNodeInfo == \"\" { // Node has no zone and region defined\n\t\t\t\t\tcost += MaxCost\n\t\t\t\t} else if region == regionPodNodeInfo { // If Nodes belong to the same region\n\t\t\t\t\tif zone == zonePodNodeInfo { // If Nodes belong to the same zone\n\t\t\t\t\t\tcost += SameZone\n\t\t\t\t\t} else { // belong to a different zone\n\t\t\t\t\t\tvalue, ok := costMap[networkawareutil.CostKey{ // Retrieve the cost from the map (origin: zone, destination: pod zoneHostname)\n\t\t\t\t\t\t\tOrigin: zone, // Time Complexity: O(1)\n\t\t\t\t\t\t\tDestination: zonePodNodeInfo,\n\t\t\t\t\t\t}]\n\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\tcost += value // Add the cost to the sum\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcost += MaxCost\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else { // belong to a different region\n\t\t\t\t\tvalue, ok := costMap[networkawareutil.CostKey{ // Retrieve the cost from the map (origin: region, destination: pod regionHostname)\n\t\t\t\t\t\tOrigin: region, // Time Complexity: O(1)\n\t\t\t\t\t\tDestination: regionPodNodeInfo,\n\t\t\t\t\t}]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tcost += value // Add the cost to the sum\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcost += MaxCost\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn cost, nil\n}", "func (_BREMICO *BREMICOCaller) WithdrawFeePercent(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"withdrawFeePercent\")\n\treturn *ret0, err\n}", "func Percent(val, total int) float64 {\n\tif total == 0 {\n\t\treturn float64(0)\n\t}\n\treturn (float64(val) / float64(total)) * 100\n}", "func (_Cakevault *CakevaultCallerSession) GetPricePerFullShare() (*big.Int, error) {\n\treturn _Cakevault.Contract.GetPricePerFullShare(&_Cakevault.CallOpts)\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (_BREM *BREMCaller) WithdrawFeePercent(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREM.contract.Call(opts, out, \"withdrawFeePercent\")\n\treturn *ret0, err\n}", "func Verify_shares(encrypted_shares []ed25519.Point, proof ShareCorrectnessProof, public_keys []ed25519.Point, recovery_threshold int) bool {\n\tnum_nodes := len(public_keys)\n\tcommitments, challenge, responses := proof.commitments, proof.challenge, proof.responses\n\n\tvar G_bytestring []ed25519.Point\n\tfor j := 0; j < num_nodes; j++ {\n\t\tG_bytestring = append(G_bytestring, G)\n\t}\n\t// 1. verify the DLEQ NIZK proof\n\tif !DLEQ_verify(G_bytestring, public_keys, commitments, encrypted_shares, challenge, responses) {\n\t\treturn false\n\t}\n\n\t// 2. verify the validity of the shares by sampling and testing with a random codeword\n\n\tcodeword := Random_codeword(num_nodes, recovery_threshold)\n\t// codeword := Cdword()\n\tproduct := commitments[0].Mul(codeword[0])\n\t// fmt.Println(len(codeword))\n\t// fmt.Println(len(commitments))\n\tfor i := 1; i < num_nodes; i++ {\n\t\tproduct = product.Add(commitments[i].Mul(codeword[i]))\n\t}\n\t// fmt.Println(product)\n\t// fmt.Println(ed25519.ONE)\n\treturn product.Equal(ed25519.ONE)\n\n}", "func (_Ethdkg *EthdkgCallerSession) ShareDistributionHashes(arg0 common.Address) ([32]byte, error) {\n\treturn _Ethdkg.Contract.ShareDistributionHashes(&_Ethdkg.CallOpts, arg0)\n}", "func (m *GraphBaseServiceClient) Shares()(*i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.SharesRequestBuilder) {\n return i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.NewSharesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Shares()(*i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.SharesRequestBuilder) {\n return i07d47a144340607d6d6dbd93575e531530e4f1cc6091c947ea0766f7951ffd34.NewSharesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (covList *CoverageList) Ratio() float32 {\n\tcovList.summarize()\n\treturn covList.Coverage.Ratio()\n}", "func usePercent(total, free uint64) uint64 {\n\tused := (total - free)\n\n\tif total != 0 {\n\t\tu100 := used * 100\n\t\tpct := float64(u100) / float64(total)\n\n\t\treturn uint64(roundFloat(pct, 0))\n\t}\n\n\treturn 0\n}", "func getBalanceTotal(recordCollection []record) (totalBalance time.Duration) {\n\tfor _, r := range recordCollection {\n\t\t_, balance := getWorkedHours(&r)\n\t\ttotalBalance += balance\n\t}\n\treturn totalBalance\n}", "func MilliCPUToShares(milliCPU int64) int64 {\n\treturn 0\n}", "func (_Cakevault *CakevaultCallerSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func ComputeChecksum(list []string) int {\n\ttwo := 0\n\tthree := 0\n\tfor _, n := range list {\n\t\thasTwo, hasThree := CountDuplicates(n)\n\t\tif hasTwo {\n\t\t\ttwo++\n\t\t}\n\t\tif hasThree {\n\t\t\tthree++\n\t\t}\n\t}\n\n\treturn two * three\n}", "func (_Ethdkg *EthdkgSession) ShareDistributionHashes(arg0 common.Address) ([32]byte, error) {\n\treturn _Ethdkg.Contract.ShareDistributionHashes(&_Ethdkg.CallOpts, arg0)\n}", "func funcDivide(ctx wasmlib.ScFuncContext, f *DivideContext) {\n\t// Create an ScBalances proxy to the allowance balances for this\n\t// smart contract.\n\tvar allowance *wasmlib.ScBalances = ctx.Allowance()\n\n\t// Retrieve the allowed amount of plain iota tokens from the account balance.\n\tvar amount uint64 = allowance.BaseTokens()\n\n\t// Retrieve the pre-calculated totalFactor value from the state storage.\n\tvar totalFactor uint64 = f.State.TotalFactor().Value()\n\n\t// Get the proxy to the 'members' map in the state storage.\n\tvar members dividend.MapAddressToMutableUint64 = f.State.Members()\n\n\t// Get the proxy to the 'memberList' array in the state storage.\n\tvar memberList dividend.ArrayOfMutableAddress = f.State.MemberList()\n\n\t// Determine the current length of the memberList array.\n\tvar size uint32 = memberList.Length()\n\n\t// Loop through all indexes of the memberList array.\n\tfor i := uint32(0); i < size; i++ {\n\t\t// Retrieve the next indexed address from the memberList array.\n\t\tvar address wasmtypes.ScAddress = memberList.GetAddress(i).Value()\n\n\t\t// Retrieve the factor associated with the address from the members map.\n\t\tvar factor uint64 = members.GetUint64(address).Value()\n\n\t\t// Calculate the fair share of tokens to disperse to this member based on the\n\t\t// factor we just retrieved. Note that the result will be truncated.\n\t\tvar share uint64 = amount * factor / totalFactor\n\n\t\t// Is there anything to disperse to this member?\n\t\tif share > 0 {\n\t\t\t// Yes, so let's set up an ScTransfer proxy that transfers the\n\t\t\t// calculated amount of tokens.\n\t\t\tvar transfer *wasmlib.ScTransfer = wasmlib.ScTransferFromBaseTokens(share)\n\n\t\t\t// Perform the actual transfer of tokens from the caller allowance\n\t\t\t// to the member account.\n\t\t\tctx.TransferAllowed(address.AsAgentID(), transfer)\n\t\t}\n\t}\n}", "func (mc *MomentClient) Share(db DbRunnerTrans, s *SharesRow, rs []*RecipientsRow) (err error) {\n\tif len(rs) == 0 || s == nil {\n\t\tError.Println(ErrorParameterEmpty)\n\t\terr = ErrorParameterEmpty\n\t\treturn\n\t}\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tError.Println(err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif txerr := tx.Rollback(); txerr != nil {\n\t\t\t\tError.Println(txerr)\n\t\t\t}\n\t\t\tError.Println(err)\n\t\t\treturn\n\t\t}\n\t\ttx.Commit()\n\t}()\n\n\tid, err := insert(tx, s)\n\tif err != nil {\n\t\tError.Println(err)\n\t}\n\ts.sharesID = id\n\n\tfor _, r := range rs {\n\t\tr.setSharesID(id)\n\t\tif err = r.err; err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif _, err = insert(tx, rs); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (_BREMFactory *BREMFactorySession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREMFactory.Contract.WithdrawFeePercent(&_BREMFactory.CallOpts)\n}", "func (_BREMFactory *BREMFactoryCallerSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREMFactory.Contract.WithdrawFeePercent(&_BREMFactory.CallOpts)\n}", "func (svcs *Services) ProcessShareDistribution(state *State, log types.Log) error {\n\tlogger := svcs.logger\n\n\tlogger.Info(strings.Repeat(\"-\", 60))\n\tlogger.Info(\"ProcessShareDistribution()\")\n\tlogger.Info(strings.Repeat(\"-\", 60))\n\n\tif !ETHDKGInProgress(state.ethdkg, log.BlockNumber) {\n\t\tlogger.Warn(\"Ignoring share distribution since we are not participating this round...\")\n\t\treturn ErrCanNotContinue\n\t}\n\n\teth := svcs.eth\n\tc := eth.Contracts()\n\tethdkg := state.ethdkg\n\n\tevent, err := c.Ethdkg.ParseShareDistribution(log)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tethdkg.Commitments[event.Issuer] = event.Commitments\n\tethdkg.EncryptedShares[event.Issuer] = event.EncryptedShares\n\n\treturn nil\n}", "func distributeLockedAmount(ctx coretypes.Sandbox, bets []*BetInfo, totalLockedAmount int64) bool {\n\tsumsByPlayers := make(map[coretypes.AgentID]int64)\n\ttotalWinningAmount := int64(0)\n\tfor _, bet := range bets {\n\t\tif _, ok := sumsByPlayers[bet.Player]; !ok {\n\t\t\tsumsByPlayers[bet.Player] = 0\n\t\t}\n\t\tsumsByPlayers[bet.Player] += bet.Sum\n\t\ttotalWinningAmount += bet.Sum\n\t}\n\n\t// NOTE 1: float64 was avoided for determinism reasons\n\t// NOTE 2: beware overflows\n\n\tfor player, sum := range sumsByPlayers {\n\t\tsumsByPlayers[player] = (totalLockedAmount * sum) / totalWinningAmount\n\t}\n\n\t// make deterministic sequence by sorting. Eliminate possible rounding effects\n\tseqPlayers := make([]coretypes.AgentID, 0, len(sumsByPlayers))\n\tresultSum := int64(0)\n\tfor player, sum := range sumsByPlayers {\n\t\tseqPlayers = append(seqPlayers, player)\n\t\tresultSum += sum\n\t}\n\tsort.Slice(seqPlayers, func(i, j int) bool {\n\t\treturn bytes.Compare(seqPlayers[i][:], seqPlayers[j][:]) < 0\n\t})\n\n\t// ensure we distribute not more than totalLockedAmount iotas\n\tif resultSum > totalLockedAmount {\n\t\tsumsByPlayers[seqPlayers[0]] -= resultSum - totalLockedAmount\n\t}\n\n\t// filter out those who proportionally got 0\n\tfinalWinners := seqPlayers[:0]\n\tfor _, player := range seqPlayers {\n\t\tif sumsByPlayers[player] <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfinalWinners = append(finalWinners, player)\n\t}\n\t// distribute iotas\n\tfor i := range finalWinners {\n\n\t\tavailable := ctx.Balance(balance.ColorIOTA)\n\t\tctx.Event(fmt.Sprintf(\"sending reward iotas %d to the winner %s. Available iotas: %d\",\n\t\t\tsumsByPlayers[finalWinners[i]], finalWinners[i].String(), available))\n\n\t\t//if !ctx.MoveTokens(finalWinners[i], balance.ColorIOTA, sumsByPlayers[finalWinners[i]]) {\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}", "func (_BREMFactory *BREMFactoryCaller) WithdrawFeePercent(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMFactory.contract.Call(opts, out, \"withdrawFeePercent\")\n\treturn *ret0, err\n}", "func (_Cakevault *CakevaultSession) GetPricePerFullShare() (*big.Int, error) {\n\treturn _Cakevault.Contract.GetPricePerFullShare(&_Cakevault.CallOpts)\n}", "func (_Ethdkg *EthdkgSession) DistributeShares(encrypted_shares []*big.Int, commitments [][2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.Contract.DistributeShares(&_Ethdkg.TransactOpts, encrypted_shares, commitments)\n}", "func (bridge *BridgeContract) TransferFunds(recipient common.Address, amount *big.Int) error {\n\terr := bridge.transferFunds(recipient, amount)\n\tfor IsNoPeerErr(err) {\n\t\ttime.Sleep(retryDelay)\n\t\terr = bridge.transferFunds(recipient, amount)\n\t}\n\treturn err\n}", "func (m *Manager) ListShares(ctx context.Context, filters []*collaboration.Filter) ([]*collaboration.Share, error) {\n\tif err := m.initialize(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser, ok := ctxpkg.ContextGetUser(ctx)\n\tif !ok {\n\t\treturn nil, errtypes.UserRequired(\"error getting user from context\")\n\t}\n\tvar rIDs []*provider.ResourceId\n\tif len(filters) != 0 {\n\t\tgrouped := share.GroupFiltersByType(filters)\n\t\tfor _, g := range grouped {\n\t\t\tfor _, f := range g {\n\t\t\t\tif f.GetResourceId() != nil {\n\t\t\t\t\trIDs = append(rIDs, f.GetResourceId())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tvar (\n\t\tcreatedShareIds []string\n\t\terr error\n\t)\n\t// in spaces, always use the resourceId\n\t// We could have more than one resourceID\n\t// which would form a logical OR\n\tif len(rIDs) != 0 {\n\t\tfor _, rID := range rIDs {\n\t\t\tshareIDs, err := m.indexer.FindBy(&collaboration.Share{},\n\t\t\t\tindexer.NewField(\"ResourceId\", resourceIDToIndex(rID)),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcreatedShareIds = append(createdShareIds, shareIDs...)\n\t\t}\n\t} else {\n\t\tcreatedShareIds, err = m.indexer.FindBy(&collaboration.Share{},\n\t\t\tindexer.NewField(\"OwnerId\", userIDToIndex(user.Id)),\n\t\t\tindexer.NewField(\"CreatorId\", userIDToIndex(user.Id)),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// We use shareMem as a temporary lookup store to check which shares were\n\t// already added. This is to prevent duplicates.\n\tshareMem := make(map[string]struct{})\n\tresult := []*collaboration.Share{}\n\tfor _, id := range createdShareIds {\n\t\ts, err := m.getShareByID(ctx, id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif share.MatchesFilters(s, filters) {\n\t\t\tresult = append(result, s)\n\t\t\tshareMem[s.Id.OpaqueId] = struct{}{}\n\t\t}\n\t}\n\n\t// If a user requests to list shares which have not been created by them\n\t// we have to explicitly fetch these shares and check if the user is\n\t// allowed to list the shares.\n\t// Only then can we add these shares to the result.\n\tgrouped := share.GroupFiltersByType(filters)\n\tidFilter, ok := grouped[collaboration.Filter_TYPE_RESOURCE_ID]\n\tif !ok {\n\t\treturn result, nil\n\t}\n\n\tshareIDsByResourceID := make(map[string]*provider.ResourceId)\n\tfor _, filter := range idFilter {\n\t\tresourceID := filter.GetResourceId()\n\t\tshareIDs, err := m.indexer.FindBy(&collaboration.Share{},\n\t\t\tindexer.NewField(\"ResourceId\", resourceIDToIndex(resourceID)),\n\t\t)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, shareID := range shareIDs {\n\t\t\tshareIDsByResourceID[shareID] = resourceID\n\t\t}\n\t}\n\n\t// statMem is used as a local cache to prevent statting resources which\n\t// already have been checked.\n\tstatMem := make(map[string]struct{})\n\tfor shareID, resourceID := range shareIDsByResourceID {\n\t\tif _, handled := shareMem[shareID]; handled {\n\t\t\t// We don't want to add a share multiple times when we added it\n\t\t\t// already.\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, checked := statMem[resourceIDToIndex(resourceID)]; !checked {\n\t\t\tsReq := &provider.StatRequest{\n\t\t\t\tRef: &provider.Reference{ResourceId: resourceID},\n\t\t\t}\n\t\t\tsRes, err := m.gatewayClient.Stat(ctx, sReq)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif sRes.Status.Code != rpcv1beta1.Code_CODE_OK {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !sRes.Info.PermissionSet.ListGrants {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstatMem[resourceIDToIndex(resourceID)] = struct{}{}\n\t\t}\n\n\t\ts, err := m.getShareByID(ctx, shareID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif share.MatchesFilters(s, filters) {\n\t\t\tresult = append(result, s)\n\t\t\tshareMem[s.Id.OpaqueId] = struct{}{}\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func waysToChange(n int) int {\n\tdp := make([]int, n+1)\n\tdp[0] = 1\n\tcoins := []int{1, 5, 10, 25}\n\tfor _, coin := range coins {\n\t\tfor i := coin; i <= n; i++ {\n\t\t\tdp[i] = (dp[i] + dp[i-coin]) % 1000000007\n\t\t}\n\t}\n\treturn dp[n]\n}", "func (m *mgr) ListReceivedShares(ctx context.Context, filters []*collaboration.Filter) ([]*collaboration.ReceivedShare, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tuser := ctxpkg.ContextMustGetUser(ctx)\n\tmem := make(map[string]int)\n\tvar rss []*collaboration.ReceivedShare\n\tfor _, s := range m.model.Shares {\n\t\tif !share.IsCreatedByUser(s, user) &&\n\t\t\tshare.IsGrantedToUser(s, user) &&\n\t\t\tshare.MatchesFilters(s, filters) {\n\n\t\t\trs := m.convert(user.Id, s)\n\t\t\tidx, seen := mem[s.ResourceId.OpaqueId]\n\t\t\tif !seen {\n\t\t\t\trss = append(rss, rs)\n\t\t\t\tmem[s.ResourceId.OpaqueId] = len(rss) - 1\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// When we arrive here there was already a share for this resource.\n\t\t\t// if there is a mix-up of shares of type group and shares of type user we need to deduplicate them, since it points\n\t\t\t// to the same resource. Leave the more explicit and hide the less explicit. In this case we hide the group shares\n\t\t\t// and return the user share to the user.\n\t\t\tother := rss[idx]\n\t\t\tif other.Share.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_GROUP && s.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_USER {\n\t\t\t\tif other.State == rs.State {\n\t\t\t\t\trss[idx] = rs\n\t\t\t\t} else {\n\t\t\t\t\trss = append(rss, rs)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rss, nil\n}", "func (m mathUtil) PercentDifference(v1, v2 float64) float64 {\n\tif v1 == 0 {\n\t\treturn 0\n\t}\n\treturn (v2 - v1) / v1\n}", "func GenerateKeyShare(firstPrivateCoefficients *big.Int) ([2]*big.Int, [2]*big.Int, [4]*big.Int, error) {\n\n\th1Base, err := cloudflare.HashToG1(h1BaseMessage)\n\tif err != nil {\n\t\treturn empty2Big, empty2Big, empty4Big, err\n\t}\n\torderMinus1, _ := new(big.Int).SetString(\"21888242871839275222246405745257275088548364400416034343698204186575808495616\", 10)\n\th2Neg := new(cloudflare.G2).ScalarBaseMult(orderMinus1)\n\n\tif firstPrivateCoefficients == nil {\n\t\treturn empty2Big, empty2Big, empty4Big, errors.New(\"Missing secret value, aka private coefficient[0]\")\n\t}\n\n\tkeyShareG1 := new(cloudflare.G1).ScalarMult(h1Base, firstPrivateCoefficients)\n\tkeyShareG1Big := bn256.G1ToBigIntArray(keyShareG1)\n\n\t// KeyShare G2\n\th2Base := new(cloudflare.G2).ScalarBaseMult(common.Big1)\n\tkeyShareG2 := new(cloudflare.G2).ScalarMult(h2Base, firstPrivateCoefficients)\n\tkeyShareG2Big := bn256.G2ToBigIntArray(keyShareG2)\n\n\t// PairingCheck to ensure keyShareG1 and keyShareG2 form valid pair\n\tvalidPair := cloudflare.PairingCheck([]*cloudflare.G1{keyShareG1, h1Base}, []*cloudflare.G2{h2Neg, keyShareG2})\n\tif !validPair {\n\t\treturn empty2Big, empty2Big, empty4Big, errors.New(\"key shares not a valid pair\")\n\t}\n\n\t// DLEQ Prooof\n\tg1Base := new(cloudflare.G1).ScalarBaseMult(common.Big1)\n\tg1Value := new(cloudflare.G1).ScalarBaseMult(firstPrivateCoefficients)\n\tkeyShareDLEQProof, err := cloudflare.GenerateDLEQProofG1(h1Base, keyShareG1, g1Base, g1Value, firstPrivateCoefficients, rand.Reader)\n\tif err != nil {\n\t\treturn empty2Big, empty2Big, empty4Big, err\n\t}\n\n\t// Verify DLEQ before sending\n\terr = cloudflare.VerifyDLEQProofG1(h1Base, keyShareG1, g1Base, g1Value, keyShareDLEQProof)\n\tif err != nil {\n\t\treturn empty2Big, empty2Big, empty4Big, err\n\t}\n\n\treturn keyShareG1Big, keyShareDLEQProof, keyShareG2Big, nil\n}" ]
[ "0.7843384", "0.71381456", "0.6964019", "0.62306017", "0.6083362", "0.6063362", "0.59958243", "0.5967737", "0.58574754", "0.5563446", "0.55429465", "0.5308287", "0.5242669", "0.5165412", "0.5139594", "0.5115955", "0.51036406", "0.5090927", "0.50872725", "0.5073594", "0.50656694", "0.5006246", "0.49819893", "0.4975846", "0.4973141", "0.49730605", "0.49562004", "0.49458402", "0.49311852", "0.4927478", "0.490575", "0.49008498", "0.49006957", "0.4887704", "0.48847312", "0.4860579", "0.4857214", "0.48374468", "0.4828438", "0.47986493", "0.47790638", "0.47696176", "0.47566867", "0.47525063", "0.47484767", "0.4727914", "0.4707212", "0.470476", "0.4704388", "0.4686183", "0.46757564", "0.46710664", "0.46616971", "0.46548843", "0.46522272", "0.4625809", "0.46207798", "0.46109915", "0.4607062", "0.4606599", "0.46065578", "0.45990613", "0.4598412", "0.45960522", "0.4593093", "0.45906365", "0.45825326", "0.45782533", "0.45544472", "0.45419076", "0.45365223", "0.45316252", "0.4530145", "0.45292526", "0.4525902", "0.45172492", "0.45064616", "0.45064616", "0.45002896", "0.4490203", "0.44851577", "0.44692087", "0.44635195", "0.4456148", "0.44506747", "0.44503313", "0.44499812", "0.4442302", "0.4440031", "0.4427172", "0.44240537", "0.4423773", "0.44173297", "0.44132343", "0.44131663", "0.44124335", "0.4407015", "0.44013602", "0.4395377", "0.43947744" ]
0.7659974
1
/ Description: Retrieves the list of addresses delegated to a delegate Param SnapShot: A SnapShot object describing the desired snap shot. Param delegateAddr: A string that represents a delegators tz address. Returns []string: An array of contracts delegated to the delegator during the snap shot
func GetDelegatedContractsForCycle(cycle int, delegateAddr string) ([]string, error){ var rtnString []string snapShot, err := GetSnapShot(cycle) // fmt.Println(snapShot) if (err != nil){ return rtnString, errors.New("Could not get delegated contracts for cycle " + strconv.Itoa(cycle) + ": GetSnapShot(cycle int) failed: " + err.Error()) } hash, err:= GetBlockLevelHash(snapShot.AssociatedBlock) if (err != nil){ return rtnString, errors.New("Could not get delegated contracts for cycle " + strconv.Itoa(cycle) + ": GetBlockLevelHash(level int) failed: " + err.Error()) } // fmt.Println(hash) getDelegatedContracts := "/chains/main/blocks/" + hash + "/context/delegates/" + delegateAddr + "/delegated_contracts" s, err := TezosRPCGet(getDelegatedContracts) if (err != nil){ return rtnString, errors.New("Could not get delegated contracts for cycle " + strconv.Itoa(cycle) + ": TezosRPCGet(arg string) failed: " + err.Error()) } DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1) if (DelegatedContracts == nil){ return rtnString, errors.New("Could not get delegated contracts for cycle " + strconv.Itoa(cycle) + ": You have no contracts.") } rtnString = addressesToArray(DelegatedContracts) return rtnString, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetAllDelegatedContracts(delegateAddr string) ([]string, error){\n var rtnString []string\n delegatedContractsCmd := \"/chains/main/blocks/head/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n s, err := TezosRPCGet(delegatedContractsCmd)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts: TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1) //TODO Error checking\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get all delegated contracts: Regex failed\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func (_ConsortiumManagement *ConsortiumManagementCaller) Delegates(opts *bind.CallOpts) ([]common.Address, error) {\n\tvar out []interface{}\n\terr := _ConsortiumManagement.contract.Call(opts, &out, \"delegates\")\n\n\tif err != nil {\n\t\treturn *new([]common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address)\n\n\treturn out0, err\n\n}", "func (_ConsortiumManagement *ConsortiumManagementCallerSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func (s *PublicSfcAPI) GetDelegatorsOf(ctx context.Context, stakerID hexutil.Uint64, verbosity hexutil.Uint64) ([]interface{}, error) {\n\tdelegators, err := s.b.GetDelegatorsOf(ctx, idx.StakerID(stakerID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif verbosity == 0 {\n\t\t// Addresses only\n\t\taddresses := make([]interface{}, len(delegators))\n\t\tfor i, it := range delegators {\n\t\t\taddresses[i] = it.Addr.String()\n\t\t}\n\t\treturn addresses, nil\n\t}\n\n\tdelegatorsRPC := make([]interface{}, len(delegators))\n\tfor i, it := range delegators {\n\t\tdelegatorRPC := RPCMarshalDelegator(it)\n\t\tif verbosity >= 2 {\n\t\t\tdelegatorRPC, err = s.addDelegatorMetricFields(ctx, delegatorRPC, it.Addr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tdelegatorsRPC[i] = delegatorRPC\n\t}\n\n\treturn delegatorsRPC, err\n}", "func (_ConsortiumManagement *ConsortiumManagementSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func (_Bep20 *Bep20Caller) Delegates(opts *bind.CallOpts, delegator common.Address) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"delegates\", delegator)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (s *ArkClient) ListDelegates(params DelegateQueryParams) (DelegateResponse, *http.Response, error) {\n\trespData := new(DelegateResponse)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\treturn *respData, resp, err\n}", "func (k Keeper) GetAllDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress) []types.Delegation {\n\tdelegations := make([]types.Delegation, 0)\n\n\tstore := ctx.KVStore(k.storeKey)\n\tdelegatorPrefixKey := types.GetDelegationsKey(delegator)\n\n\titerator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) //smallest to largest\n\tdefer iterator.Close()\n\n\ti := 0\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tdelegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value())\n\t\tdelegations = append(delegations, delegation)\n\t\ti++\n\t}\n\n\treturn delegations\n}", "func GetDelegates(node client.ABCIClient) (map[address.Address][]address.Address, *rpctypes.ResultABCIQuery, error) {\n\t// perform the query\n\tres, err := node.ABCIQuery(query.DelegatesEndpoint, nil)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\tif code.ReturnCode(res.Response.Code) != code.OK {\n\t\tif res.Response.Log != \"\" {\n\t\t\treturn nil, res, errors.New(code.ReturnCode(res.Response.Code).String() + \": \" + res.Response.Log)\n\t\t}\n\t\treturn nil, res, errors.New(code.ReturnCode(res.Response.Code).String())\n\t}\n\n\tdr := query.DelegatesResponse{}\n\t// parse the response\n\t_, err = dr.UnmarshalMsg(res.Response.GetValue())\n\tif err != nil || dr == nil {\n\t\treturn nil, res, errors.Wrap(err, \"unmarshalling delegates response\")\n\t}\n\n\t// transform response into friendly form\n\tdelegates := make(map[address.Address][]address.Address)\n\tfor _, node := range dr {\n\t\tfor _, delegated := range node.Delegated {\n\t\t\tdelegates[node.Node] = append(delegates[node.Node], delegated)\n\t\t}\n\t}\n\treturn delegates, res, err\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) Delegations(opts *bind.CallOpts, arg0 [32]byte) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret0, err\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) Delegations(arg0 [32]byte) (common.Address, error) {\n\treturn _PlasmaFramework.Contract.Delegations(&_PlasmaFramework.CallOpts, arg0)\n}", "func (_Bep20 *Bep20CallerSession) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func (s *PublicSfcAPI) GetDelegator(ctx context.Context, addr common.Address, verbosity hexutil.Uint64) (map[string]interface{}, error) {\n\tdelegator, err := s.b.GetDelegator(ctx, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif delegator == nil {\n\t\treturn nil, nil\n\t}\n\tit := sfctype.SfcDelegatorAndAddr{\n\t\tAddr: addr,\n\t\tDelegator: delegator,\n\t}\n\tdelegatorRPC := RPCMarshalDelegator(it)\n\tif verbosity <= 1 {\n\t\treturn delegatorRPC, nil\n\t}\n\treturn s.addDelegatorMetricFields(ctx, delegatorRPC, addr)\n}", "func (_PlasmaFramework *PlasmaFrameworkSession) Delegations(arg0 [32]byte) (common.Address, error) {\n\treturn _PlasmaFramework.Contract.Delegations(&_PlasmaFramework.CallOpts, arg0)\n}", "func (_Bep20 *Bep20Session) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func (k Querier) DelegatorDelegations(ctx context.Context, req *types.QueryDelegatorDelegationsRequest) (*types.QueryDelegatorDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegations, pageRes, err := query.CollectionPaginate(ctx, k.Delegations, req.Pagination,\n\t\tfunc(_ collections.Pair[sdk.AccAddress, sdk.ValAddress], del types.Delegation) (types.Delegation, error) {\n\t\t\treturn del, nil\n\t\t}, query.WithCollectionPaginationPairPrefix[sdk.AccAddress, sdk.ValAddress](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelegationResps, err := delegationsToDelegationResponses(ctx, k.Keeper, delegations)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorDelegationsResponse{DelegationResponses: delegationResps, Pagination: pageRes}, nil\n}", "func (acc *Account) Delegations(args *struct {\n\tCursor *Cursor\n\tCount int32\n}) (*DelegationList, error) {\n\t// limit query size; the count can be either positive or negative\n\t// this controls the loading direction\n\targs.Count = listLimitCount(args.Count, listMaxEdgesPerRequest)\n\n\t// pull the list\n\tdl, err := repository.R().DelegationsByAddress(&acc.Address, (*string)(args.Cursor), args.Count)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// convert to resolvable list\n\treturn NewDelegationList(dl), nil\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func (gc *GovernanceContract) sfcDelegationsBy(addr common.Address) ([]common.Address, error) {\n\t// get SFC delegations list\n\tdl, err := gc.repo.DelegationsByAddress(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// prep the result container\n\tres := make([]common.Address, 0)\n\n\t// check if the address is a staker\n\t// if so, it also delegates to itself in the context of the contract\n\tisStaker, err := gc.repo.IsStaker(&addr)\n\tif err == nil && isStaker {\n\t\tres = append(res, addr)\n\t}\n\n\t// loop delegations to make the list\n\tfor _, d := range dl {\n\t\t// is the delegation ok for voting?\n\t\tif nil != d.DeactivatedEpoch && 0 < uint64(*d.DeactivatedEpoch) {\n\t\t\tgc.repo.Log().Debugf(\"delegation to %d from address %s is deactivated\", d.ToStakerId, addr.String())\n\t\t\tcontinue\n\t\t}\n\n\t\t// get the staker info\n\t\tstaker, err := gc.repo.StakerAddress(d.ToStakerId)\n\t\tif err != nil {\n\t\t\tgc.repo.Log().Errorf(\"error loading staker %d info; %s\", d.ToStakerId, addr.String())\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// get the\n\t\tres = append(res, staker)\n\t}\n\n\t// log delegations found\n\tgc.repo.Log().Debugf(\"%d delegations on %s\", len(res), addr.String())\n\treturn res, nil\n}", "func (k Keeper) GetDelegatorDefis(\n\tctx sdk.Context, delegatorAddr sdk.AccAddress, maxRetrieve uint32,\n) types.Defis {\n\tdefis := make([]types.Defi, maxRetrieve)\n\n\tstore := ctx.KVStore(k.storeKey)\n\tdelegatorPrefixKey := types.GetDelegationsKey(delegatorAddr)\n\n\titerator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest\n\tdefer iterator.Close()\n\n\ti := 0\n\tfor ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() {\n\t\tdelegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value())\n\n\t\tdefi, found := k.GetDefi(ctx, delegation.GetDefiAddr())\n\t\tif !found {\n\t\t\tpanic(types.ErrNoDefiFound)\n\t\t}\n\n\t\tdefis[i] = defi\n\t\ti++\n\t}\n\n\treturn defis[:i] // trim\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (gc *GovernanceContract) DelegationsBy(args struct{ From common.Address }) ([]common.Address, error) {\n\t// decide by the contract type\n\tswitch gc.Type {\n\tcase \"sfc\":\n\t\treturn gc.sfcDelegationsBy(args.From)\n\t}\n\n\t// no delegations by default\n\tgc.repo.Log().Debugf(\"unknown governance type of %s\", gc.Address.Hex())\n\treturn []common.Address{}, nil\n}", "func (k Querier) ValidatorDelegations(ctx context.Context, req *types.QueryValidatorDelegationsRequest) (*types.QueryValidatorDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tdels types.Delegations\n\t\tpageRes *query.PageResponse\n\t)\n\n\tdels, pageRes, err = query.CollectionPaginate(ctx, k.DelegationsByValidator,\n\t\treq.Pagination, func(key collections.Pair[sdk.ValAddress, sdk.AccAddress], _ []byte) (types.Delegation, error) {\n\t\t\tvalAddr, delAddr := key.K1(), key.K2()\n\t\t\tdelegation, err := k.Delegations.Get(ctx, collections.Join(delAddr, valAddr))\n\t\t\tif err != nil {\n\t\t\t\treturn types.Delegation{}, err\n\t\t\t}\n\n\t\t\treturn delegation, nil\n\t\t}, query.WithCollectionPaginationPairPrefix[sdk.ValAddress, sdk.AccAddress](valAddr),\n\t)\n\n\tif err != nil {\n\t\tdelegations, pageResponse, err := k.getValidatorDelegationsLegacy(ctx, req)\n\t\tif err != nil {\n\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t}\n\n\t\tdels = types.Delegations{}\n\t\tfor _, d := range delegations {\n\t\t\tdels = append(dels, *d)\n\t\t}\n\n\t\tpageRes = pageResponse\n\t}\n\n\tdelResponses, err := delegationsToDelegationResponses(ctx, k.Keeper, dels)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryValidatorDelegationsResponse{\n\t\tDelegationResponses: delResponses, Pagination: pageRes,\n\t}, nil\n}", "func (s *RoundsService) Delegates(ctx context.Context, id int64) (*GetDelegates, *http.Response, error) {\n\turi := fmt.Sprintf(\"rounds/%v/delegates\", id)\n\n\tvar responseStruct *GetDelegates\n\tresp, err := s.client.SendRequest(ctx, \"GET\", uri, nil, nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (k Querier) DelegatorValidators(ctx context.Context, req *types.QueryDelegatorValidatorsRequest) (*types.QueryDelegatorValidatorsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tvar validators types.Validators\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, pageRes, err := query.CollectionPaginate(ctx, k.Delegations, req.Pagination,\n\t\tfunc(_ collections.Pair[sdk.AccAddress, sdk.ValAddress], delegation types.Delegation) (types.Delegation, error) {\n\t\t\tvalAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())\n\t\t\tif err != nil {\n\t\t\t\treturn types.Delegation{}, err\n\t\t\t}\n\t\t\tvalidator, err := k.GetValidator(ctx, valAddr)\n\t\t\tif err != nil {\n\t\t\t\treturn types.Delegation{}, err\n\t\t\t}\n\n\t\t\tvalidators.Validators = append(validators.Validators, validator)\n\t\t\treturn types.Delegation{}, nil\n\t\t}, query.WithCollectionPaginationPairPrefix[sdk.AccAddress, sdk.ValAddress](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorValidatorsResponse{Validators: validators.Validators, Pagination: pageRes}, nil\n}", "func GetDelegates(seedUrl_optional ...string) ([]types.Node, error) {\n\tseedUrl := \"seed.dispatchlabs.io:1975\"\n\tif len(seedUrl_optional) > 0 {\n\t\tseedUrl = seedUrl_optional[0]\n\t}\n\n\t// Get delegates.\n\thttpResponse, err := http.Get(fmt.Sprintf(\"http://%s/v1/delegates\", seedUrl))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer httpResponse.Body.Close()\n\n\t// Read body.\n\tbody, err := ioutil.ReadAll(httpResponse.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Unmarshal response.\n\tvar response *types.Response\n\terr = json.Unmarshal(body, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Status?\n\tif response.Status != types.StatusOk {\n\t\treturn nil, errors.New(fmt.Sprintf(\"%s: %s\", response.Status, response.HumanReadableStatus))\n\t}\n\n\t// Unmarshal to RawMessage.\n\tvar jsonMap map[string]json.RawMessage\n\terr = json.Unmarshal(body, &jsonMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Data?\n\tif jsonMap[\"data\"] == nil {\n\t\treturn nil, errors.Errorf(\"'data' is missing from response\")\n\t}\n\n\t// Unmarshal nodes.\n\tvar nodes []types.Node\n\terr = json.Unmarshal(jsonMap[\"data\"], &nodes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nodes, nil\n}", "func (f *lazyCallReq) RoutingDelegate() []byte {\n\treturn f.delegate\n}", "func (s *ArkClient) GetDelegate(params DelegateQueryParams) (DelegateResponse, *http.Response, error) {\n\trespData := new(DelegateResponse)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/get\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\treturn *respData, resp, err\n}", "func GetDelegationsFor(w http.ResponseWriter, r *http.Request) {\n\n\t// Add header so that received knows they're receiving JSON\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// Retrieving name of node from query request\n\tnodeName := r.URL.Query().Get(\"name\")\n\tconfirmation, socket := checkNodeName(nodeName)\n\tif confirmation == false {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Node name requested doesn't exist\"})\n\t\treturn\n\t}\n\n\t// Retrieving height from query request\n\trecvHeight := r.URL.Query().Get(\"height\")\n\theight := checkHeight(recvHeight)\n\tif height == -1 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Unexpected value found, height needs to be a string representing an int!\"})\n\t\treturn\n\t}\n\n\t// Note Make sure that public key that is being sent is coded properly\n\t// Example A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU+h+blS9pto= should be\n\t// A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU%2Bh%2BblS9pto=\n\t//var pubKey common_signature.PublicKey\n\townerKey := r.URL.Query().Get(\"ownerKey\")\n\tif len(ownerKey) == 0 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tlgr.Warning.Println(\n\t\t\t\"Request at /api/staking/delegationsfor failed, address can't be \" +\n\t\t\t\t\"empty!\")\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"address can't be empty!\"})\n\t\treturn\n\t}\n\n\t// Unmarshal text into public key object\n\t//err := pubKey.UnmarshalText([]byte(ownerKey))\n\t//if err != nil {\n\t//\tlgr.Error.Println(\"Failed to UnmarshalText into Public Key\", err)\n\t//\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t//\t\tError: \"Failed to UnmarshalText into Public Key.\"})\n\t//\treturn\n\t//}\n\n\tvar address staking.Address\n\terr := address.UnmarshalText([]byte(ownerKey))\n\tif err != nil {\n\t\tlgr.Error.Println(\"Failed to UnmarshalText into Address\", err)\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to UnmarshalText into Address.\"})\n\t\treturn\n\t}\n\n\t// Attempt to load connection with staking client\n\tconnection, so := loadStakingClient(socket)\n\n\t// Close connection once code underneath executes\n\tdefer connection.Close()\n\n\t// If null object was retrieved send response\n\tif so == nil {\n\n\t\t// Stop code here faild to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to establish connection using socket : \" + socket})\n\t\treturn\n\t}\n\n\t// Create an owner query to be able to retrieve data with regards to account\n\tquery := staking.OwnerQuery{Height: height, Owner: address}\n\n\t// Return delegations for given account query\n\tdelegationsFor, err := so.DelegationsFor(context.Background(), &query)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to get Delegations!\"})\n\n\t\tlgr.Error.Println(\n\t\t\t\"Request at /api/staking/delegationsfor failed to retrieve \"+\n\t\t\t\t\"Delegations : \", err)\n\t\treturn\n\t}\n\n\t// Respond with delegations for given account query\n\tlgr.Info.Println(\"Request at /api/staking/delegations responding with \" +\n\t\t\"delegations!\")\n\tjson.NewEncoder(w).Encode(responses.DelegationsResponse{Delegations:\n\tdelegationsFor})\n}", "func queryDelegatorProxyCheck(dlgAddr sdk.AccAddress, expIsProxy bool, expHasProxy bool,\n\texpTotalDlgTokens *sdk.Dec, expBoundToProxy *sdk.AccAddress, expBoundDelegators []sdk.AccAddress) actResChecker {\n\treturn func(t *testing.T, beforeStatus, afterStatus IValidatorStatus, resultCtx *ActionResultCtx) bool {\n\n\t\tctx := getNewContext(resultCtx.tc.mockKeeper.MountedStore, resultCtx.tc.currentHeight)\n\n\t\t//query delegator from keeper directly\n\t\tdlg, found := resultCtx.tc.mockKeeper.Keeper.GetDelegator(ctx, dlgAddr)\n\t\trequire.True(t, found)\n\n\t\tb1 := assert.Equal(t, expIsProxy, dlg.IsProxy)\n\t\tb2 := assert.Equal(t, expHasProxy, dlg.HasProxy())\n\t\tb3 := true\n\t\tif expTotalDlgTokens != nil {\n\t\t\tb3 = assert.Equal(t, expTotalDlgTokens.String(), dlg.TotalDelegatedTokens.String(), dlg)\n\t\t}\n\n\t\tvar b4 bool\n\t\tif expBoundToProxy != nil {\n\t\t\tb4 = assert.Equal(t, *expBoundToProxy, dlg.ProxyAddress)\n\t\t} else {\n\t\t\tb4 = dlg.ProxyAddress == nil\n\t\t}\n\n\t\tb5 := true\n\t\tif expBoundDelegators != nil && len(expBoundDelegators) > 0 {\n\t\t\tq := NewQuerier(resultCtx.tc.mockKeeper.Keeper)\n\t\t\tpara := types.NewQueryDelegatorParams(dlgAddr)\n\t\t\tbz, _ := types.ModuleCdc.MarshalJSON(para)\n\t\t\tdata, err := q(ctx, []string{types.QueryProxy}, abci.RequestQuery{Data: bz})\n\t\t\trequire.NoError(t, err)\n\n\t\t\trealProxiedDelegators := []sdk.AccAddress{}\n\t\t\trequire.NoError(t, ModuleCdc.UnmarshalJSON(data, &realProxiedDelegators))\n\n\t\t\tb5 = assert.Equal(t, len(expBoundDelegators), len(realProxiedDelegators))\n\t\t\tif b5 {\n\t\t\t\tcnt := 0\n\t\t\t\tfor _, e := range expBoundDelegators {\n\t\t\t\t\tfor _, r := range realProxiedDelegators {\n\t\t\t\t\t\tif r.Equals(e) {\n\t\t\t\t\t\t\tcnt++\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tb5 = assert.Equal(t, len(expBoundDelegators), cnt)\n\t\t\t}\n\t\t}\n\n\t\t// check if the shares correct\n\t\tb6 := true\n\t\tif len(dlg.GetShareAddedValidatorAddresses()) > 0 {\n\t\t\texpectDlgShares, err := keeper.SimulateWeight(getGlobalContext().BlockTime().Unix(), (dlg.TotalDelegatedTokens.Add(dlg.Tokens)))\n\t\t\tb6 = err == nil\n\t\t\tb6 = b6 && assert.Equal(t, expectDlgShares.String(), dlg.Shares.String(), dlg)\n\t\t} else {\n\t\t\texpectDlgShares := sdk.ZeroDec()\n\t\t\tb6 = assert.Equal(t, expectDlgShares.String(), dlg.Shares.String(), dlg)\n\t\t}\n\n\t\tconstraintCheckRes := delegatorConstraintCheck(dlg)(t, beforeStatus, afterStatus, resultCtx)\n\n\t\tr := b1 && b2 && b3 && b4 && b5 && b6 && constraintCheckRes\n\t\tif !r {\n\t\t\tresultCtx.tc.printParticipantSnapshot(resultCtx.t)\n\t\t}\n\n\t\treturn r\n\t}\n}", "func (s *ArkClient) GetDelegateVoters(params DelegateQueryParams) (DelegateVoters, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\treturn *respData, resp, err\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (rs *rootResolver) DelegationsOf(args *struct {\n\tStaker hexutil.Uint64\n\tCursor *Cursor\n\tCount int32\n}) (*DelegatorList, error) {\n\t// any arguments?\n\tif args == nil {\n\t\treturn nil, fmt.Errorf(\"missing delegations input\")\n\t}\n\n\t// limit query size; the count can be either positive or negative\n\t// this controls the loading direction\n\targs.Count = listLimitCount(args.Count, listMaxEdgesPerRequest)\n\n\t// get the list\n\tdl, err := rs.repo.DelegationsOf(args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// sort by the date of creation\n\tsort.Sort(DelegationsByAge(dl))\n\treturn NewDelegatorList(dl, parseDelegationsCursor(args.Cursor, args.Count, dl), args.Count, rs.repo), nil\n}", "func (t *TezTracker) AccountDelegatorsList(accountID string, limits Limiter) ([]models.AccountListView, int64, error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.Account{DelegateValue: accountID}\n\tcount, err := r.Count(filter)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\taccs, err := r.Filter(filter, limits.Limit(), limits.Offset())\n\treturn accs, count, err\n}", "func (t *TezTracker) AccountDelegatorsList(accountID string, limits Limiter) ([]models.AccountListView, int64, error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.Account{DelegateValue: accountID}\n\tcount, err := r.Count(filter)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\taccs, err := r.Filter(filter, limits.Limit(), limits.Offset())\n\treturn accs, count, err\n}", "func (k Keeper) IterateDelegations(ctx context.Context, delAddr sdk.AccAddress,\n\tfn func(index int64, del types.DelegationI) (stop bool),\n) error {\n\tvar i int64\n\trng := collections.NewPrefixedPairRange[sdk.AccAddress, sdk.ValAddress](delAddr)\n\terr := k.Delegations.Walk(ctx, rng, func(key collections.Pair[sdk.AccAddress, sdk.ValAddress], del types.Delegation) (stop bool, err error) {\n\t\tstop = fn(i, del)\n\t\tif stop {\n\t\t\treturn true, nil\n\t\t}\n\t\ti++\n\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (broadcast *Broadcast) Delegate(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegateMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (o *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams) SetDelegatorAddr(delegatorAddr string) {\n\to.DelegatorAddr = delegatorAddr\n}", "func (k Keeper) GetAllSDKDelegations(ctx context.Context) (delegations []types.Delegation, err error) {\n\tstore := k.storeService.OpenKVStore(ctx)\n\titerator, err := store.Iterator(types.DelegationKey, storetypes.PrefixEndBytes(types.DelegationKey))\n\tif err != nil {\n\t\treturn delegations, err\n\t}\n\tdefer iterator.Close()\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tdelegation, err := types.UnmarshalDelegation(k.cdc, iterator.Value())\n\t\tif err != nil {\n\t\t\treturn delegations, err\n\t\t}\n\t\tdelegations = append(delegations, delegation)\n\t}\n\n\treturn\n}", "func (k Keeper) GetAllUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddress) []types.UnbondingDelegation {\n\tunbondingDelegations := make([]types.UnbondingDelegation, 0)\n\n\tstore := ctx.KVStore(k.storeKey)\n\tdelegatorPrefixKey := types.GetUBDsKey(delegator)\n\n\titerator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest\n\tdefer iterator.Close()\n\n\tfor i := 0; iterator.Valid(); iterator.Next() {\n\t\tunbondingDelegation := types.MustUnmarshalUBD(k.cdc, iterator.Value())\n\t\tunbondingDelegations = append(unbondingDelegations, unbondingDelegation)\n\t\ti++\n\t}\n\n\treturn unbondingDelegations\n}", "func (k Keeper) Delegator(ctx sdk.Context, delAddr sdk.AccAddress) exported.DelegatorI {\n\tdelegator, found := k.GetDelegator(ctx, delAddr)\n\tif !found {\n\t\treturn nil\n\t}\n\n\treturn delegator\n}", "func delegateName(delegate string) []byte {\n\tlength := len(delegate)\n\tif length > 12 {\n\t\treturn []byte(delegate[length-12:])\n\t} else {\n\t\treturn append(make([]byte, 12-length), []byte(delegate)...)\n\t}\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Big\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := repository.R().Delegation(&args.Address, &args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d), nil\n}", "func delegate(native *NativeService, from []byte, contractAddr []byte, to []byte,\n\trole []byte, period uint32, level int) ([]byte, error) {\n\tnull := []byte{}\n\tcontract := native.ContextRef.CurrentContext().ContractAddress\n\tcontractKey := append(contract[:], contractAddr...)\n\n\tret, err := verifySig(native, from)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !ret {\n\t\treturn nil, err\n\t}\n\t//iterate\n\troleP, err := packKey(RoleP, role)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\troleP = append(contractKey, roleP...)\n\n\tnode_to, err := linkedlistGetItem(native, roleP, to)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnode_from, err := linkedlistGetItem(native, roleP, from)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif node_to != nil || node_from == nil {\n\t\treturn nil, err //ignore\n\t}\n\n\tauth := new(AuthToken)\n\terr = auth.deserialize(node_from.payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t//check if 'from' has the permission to delegate\n\tif auth.level >= 2 && level < auth.level && level > 0 {\n\t\t// put `to` in the delegate list\n\t\t// 'role x person' -> [] person is a list of person who gets the auth token\n\t\tser_role_per, err := packKeys(DelegateList, [][]byte{role, from})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tser_role_per = append(contractKey, ser_role_per...)\n\t\tlinkedlistInsert(native, ser_role_per, to, null)\n\n\t\t//insert into the `role -> []person` list\n\t\tauthprime := auth\n\t\tauthprime.expireTime = native.Time + period\n\t\tif authprime.expireTime < native.Time {\n\t\t\treturn nil, errors.NewErr(\"[auth contract] overflow of expire time\")\n\t\t}\n\t\tauthprime.level = level\n\t\tser_authprime, err := authprime.serialize()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpersons := &OntIDsToRoleParam{Role: role, Persons: [][]byte{to}}\n\t\tbf := new(bytes.Buffer)\n\t\terr = persons.Serialize(bf)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnative.Input = bf.Bytes()\n\t\t_, err = assignToRole(native, ser_authprime)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn BYTE_ONE, nil\n}", "func (ctx *rollDPoSCtx) getRollingDelegates(epochNum uint64) ([]string, error) {\n\t// TODO: replace the pseudo roll delegates method with integrating with real delegate pool\n\treturn ctx.pool.RollDelegates(epochNum)\n}", "func (c *Call) RoutingDelegate() string {\n\tif c == nil {\n\t\treturn \"\"\n\t}\n\treturn c.md.RoutingDelegate()\n}", "func (o *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams) WithDelegatorAddr(delegatorAddr string) *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams {\n\to.SetDelegatorAddr(delegatorAddr)\n\treturn o\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Uint64\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := rs.repo.Delegation(args.Address, args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d, rs.repo), nil\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _OwnerProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_DelegationController *DelegationControllerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (k Querier) Redelegations(ctx context.Context, req *types.QueryRedelegationsRequest) (*types.QueryRedelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tvar redels types.Redelegations\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tstore := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))\n\tswitch {\n\tcase req.DelegatorAddr != \"\" && req.SrcValidatorAddr != \"\" && req.DstValidatorAddr != \"\":\n\t\tredels, err = queryRedelegation(ctx, k, req)\n\tcase req.DelegatorAddr == \"\" && req.SrcValidatorAddr != \"\" && req.DstValidatorAddr == \"\":\n\t\tredels, pageRes, err = queryRedelegationsFromSrcValidator(ctx, store, k, req)\n\tdefault:\n\t\tredels, pageRes, err = queryAllRedelegations(ctx, store, k, req)\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\tredelResponses, err := redelegationsToRedelegationResponses(ctx, k.Keeper, redels)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRedelegationsResponse{RedelegationResponses: redelResponses, Pagination: pageRes}, nil\n}", "func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) exported.DelegationI {\n\treturn nil\n}", "func (m Mapper) loadDelegatorCandidates(delegator sdk.Address) (candidateAddrs []sdk.Address) {\n\n\tcandidateBytes := m.store.Get(GetDelegatorBondsKey(delegator, m.cdc))\n\tif candidateBytes == nil {\n\t\treturn nil\n\t}\n\n\terr := m.cdc.UnmarshalJSON(candidateBytes, &candidateAddrs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func (k Keeper) Delegation(ctx context.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) (types.DelegationI, error) {\n\tbond, err := k.Delegations.Get(ctx, collections.Join(addrDel, addrVal))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bond, nil\n}", "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func (_DelegationController *DelegationControllerFilterer) FilterDelegationAccepted(opts *bind.FilterOpts) (*DelegationControllerDelegationAcceptedIterator, error) {\n\n\tlogs, sub, err := _DelegationController.contract.FilterLogs(opts, \"DelegationAccepted\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DelegationControllerDelegationAcceptedIterator{contract: _DelegationController.contract, event: \"DelegationAccepted\", logs: logs, sub: sub}, nil\n}", "func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{\n for _, delegatedContract := range delegatedContracts {\n err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias)\n if (err != nil){\n return errors.New(\"Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: \" + err.Error())\n }\n }\n return nil\n}", "func (_Bep20 *Bep20Transactor) Delegate(opts *bind.TransactOpts, delegatee common.Address) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegate\", delegatee)\n}", "func (d *DelegatorAccessorImpl) Refresh() (delegatorsTable []string, delegatorNodes []*discover.Node, e error) {\n\t// call delegatorList()\n\tdata, err0 := d.dappabi.Pack(\"delegatorList\")\n\tif err0 != nil {\n\t\tlog.Error(\"Error to encode delegatorList function call.\")\n\t\treturn nil,nil, errors.New(\"Error to encode delegatorList function call.\")\n\t}\n\t//var data = common.Hex2Bytes(\"0x61b29d69\")\n\tvar result string;\n\toutput, err0 := d.doCall(data);\n\tif err0 != nil {\n\t\tlog.Error(\"Error to call delegatorList function.\")\n\t\treturn nil,nil, errors.New(\"Error to call delegatorList function.\")\n\t}\n\tif len(output) == 0 {\n\t\t// no result\n\t\treturn nil,nil, errors.New(\"Delegator list must not be empty! the state of this node is incorrect.\")\n\t}\n\terr0 = d.dappabi.Unpack(&result, \"result\", output)\n\tif err0 != nil {\n\t\tlog.Error(\"Error to parse the result of delegatorList function.\")\n\t\treturn nil,nil, errors.New(\"Error to parse the result of delegatorList function.\")\n\t}\n\tif len(result) == 0 {\n\t\tlog.Error(\"Delegator list must not be empty! the state of this node is incorrect.\")\n\t\treturn nil,nil, errors.New(\"Delegator list must not be empty! the state of this node is incorrect.\")\n\t}\n\n\tdelegatorIds := strings.Split(result, \";\")\n\tids := make([]string, len(delegatorIds))\n\tpeerinfo := make([]*discover.Node, len(delegatorIds))\n\tfor i,delegatorId := range delegatorIds {\n\t\t// call delegatorInfo(string) 0x6162630000000000000000000000000000000000000000000000000000000000\n\t\tdata1, err0 := d.dappabi.Pack(\"delegatorInfo\", delegatorId)\n\t\tif err0 != nil {\n\t\t\tlog.Error(\"Error to parse delegatorInfo function.\")\n\t\t\treturn nil,nil, errors.New(\"Error to parse delegatorInfo function.\")\n\t\t}\n\t\toutput1, err0 := d.doCall(data1)\n\t\tif err0 != nil {\n\t\t\tlog.Error(\"Error to call delegatorInfo function.\")\n\t\t\treturn nil,nil, errors.New(\"Error to call delegatorInfo function.\")\n\t\t}\n\t\tvar result DelegatedNodeInfoMapping\n\t\t//string ip, uint port, uint256 ticket\n\t\terr0 = d.dappabi.Unpack(&result, \"result\", output1)\n\t\tif err0 != nil {\n\t\t\tlog.Error(\"Error to parse the result of delegatorInfo function.\")\n\t\t\treturn nil,nil, errors.New(\"Error to parse the result of delegatorInfo function.\")\n\t\t}\n\t\tids[i] = delegatorId\n\t\tpeerinfo[i] = &discover.Node{}\n\t}\n\treturn ids, peerinfo, nil;\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func (_DelegationController *DelegationControllerCallerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (_DelegationController *DelegationControllerSession) DelegationsByValidator(arg0 *big.Int, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByValidator(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (_DelegationController *DelegationControllerCallerSession) DelegationsByValidator(arg0 *big.Int, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByValidator(&_DelegationController.CallOpts, arg0, arg1)\n}", "func bindDelegatableDai(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(DelegatableDaiABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func GetDelegatorBondsKey(delegator crypto.Address) []byte {\n\tres, err := cdc.MarshalJSON(&delegator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn append(DelegatorBondsKeyPrefix, res...)\n}", "func (o *APIServiceAddressParams) SetDelegated(delegated *bool) {\n\to.Delegated = delegated\n}", "func (msg MsgConfirmedDeposit) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\treturn []sdk.CUAddress{msg.From}\n}", "func (p *Protocol) NumDelegates() uint64 {\n\treturn p.numDelegates\n}", "func RPCMarshalDelegator(it sfctype.SfcDelegatorAndAddr) map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"address\": it.Addr,\n\t\t\"toStakerID\": hexutil.Uint64(it.Delegator.ToStakerID),\n\t\t\"amount\": (*hexutil.Big)(it.Delegator.Amount),\n\t\t\"createdEpoch\": hexutil.Uint64(it.Delegator.CreatedEpoch),\n\t\t\"createdTime\": hexutil.Uint64(it.Delegator.CreatedTime),\n\t\t\"deactivatedEpoch\": hexutil.Uint64(it.Delegator.DeactivatedEpoch),\n\t\t\"deactivatedTime\": hexutil.Uint64(it.Delegator.DeactivatedTime),\n\t}\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (_TransferProxyRegistry *TransferProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _TransferProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (p *Protocol) NumCandidateDelegates() uint64 {\n\treturn p.numCandidateDelegates\n}", "func GetDelegatorBondsKey(delegator sdk.Address, cdc *wire.Codec) []byte {\n\tres, err := cdc.MarshalJSON(&delegator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn append(DelegatorBondsKeyPrefix, res...)\n}", "func (o *PostDistributionDelegatorsDelegatorAddrRewardsValidatorAddrBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateBaseReq(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (k Querier) Delegation(ctx context.Context, req *types.QueryDelegationRequest) (*types.QueryDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, err := k.Delegations.Get(ctx, collections.Join(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)))\n\tif err != nil {\n\t\tif errors.Is(err, collections.ErrNotFound) {\n\t\t\treturn nil, status.Errorf(\n\t\t\t\tcodes.NotFound,\n\t\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelResponse, err := delegationToDelegationResponse(ctx, k.Keeper, delegation)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegationResponse{DelegationResponse: &delResponse}, nil\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func Delegate(stub shim.ChaincodeStubInterface, args []string) error {\n\tvar vote entities.Vote\n\terr := json.Unmarshal([]byte(args[0]), &vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpoll, err := validateDelegate(stub, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = addVoteToPoll(stub, poll, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"saving delegate vote\")\n\tutil.UpdateObjectInChain(stub, vote.ID(), util.VotesIndexName, []byte(args[0]))\n\n\tfmt.Println(\"successfully delegated vote to \" + vote.Delegate + \"!\")\n\treturn nil\n}", "func (_Bep20 *Bep20Filterer) FilterDelegateChanged(opts *bind.FilterOpts, delegator []common.Address, fromDelegate []common.Address, toDelegate []common.Address) (*Bep20DelegateChangedIterator, error) {\n\n\tvar delegatorRule []interface{}\n\tfor _, delegatorItem := range delegator {\n\t\tdelegatorRule = append(delegatorRule, delegatorItem)\n\t}\n\tvar fromDelegateRule []interface{}\n\tfor _, fromDelegateItem := range fromDelegate {\n\t\tfromDelegateRule = append(fromDelegateRule, fromDelegateItem)\n\t}\n\tvar toDelegateRule []interface{}\n\tfor _, toDelegateItem := range toDelegate {\n\t\ttoDelegateRule = append(toDelegateRule, toDelegateItem)\n\t}\n\n\tlogs, sub, err := _Bep20.contract.FilterLogs(opts, \"DelegateChanged\", delegatorRule, fromDelegateRule, toDelegateRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Bep20DelegateChangedIterator{contract: _Bep20.contract, event: \"DelegateChanged\", logs: logs, sub: sub}, nil\n}", "func ClientAddrs(addrs []string) func(*Client) {\n\treturn func(c *Client) { c.addrs = addrs }\n}", "func loadDelegatorCandidates(store types.KVStore,\n\tdelegator crypto.Address) (candidates []crypto.PubKey) {\n\n\tcandidateBytes := store.Get(GetDelegatorBondsKey(delegator))\n\tif candidateBytes == nil {\n\t\treturn nil\n\t}\n\n\terr := cdc.UnmarshalJSON(candidateBytes, &candidates)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func DAODrainList() []common.Address {\n\treturn []common.Address{\n\t\tcommon.HexToAddress(\"0xb1080cDd0fF5B0dE78F4B5B470A6b0F4232FC377\"),\n\t\tcommon.HexToAddress(\"0xB7331D9E194A45a45b375fDB9F856FD48551b6eF\"),\n\t\tcommon.HexToAddress(\"0xA3dD8140cb29cAbEB03a8E47254a57656e35fBA7\"),\n\t\tcommon.HexToAddress(\"0xACA35cB8d3dC454816eA2103F6e49532AefA84c0\"),\n\t\tcommon.HexToAddress(\"0x670c89806Cf9C1f1Da9C022977c9dF5eA3baBd17\"),\n\t\tcommon.HexToAddress(\"0xEe3C23dDE5F90441AA1008D8391fc6CDf63F17b2\"),\n\t\tcommon.HexToAddress(\"0x8A4b509FA755419a4962f73D5cAdcA84Fe9e4cb6\"),\n\t\tcommon.HexToAddress(\"0x55f4ac7a4d29928c367035486b87E7E67547c900\"),\n\t\tcommon.HexToAddress(\"0xa52BAF602CDEd73585f17DDF06b621bD0351d691\"),\n\t\tcommon.HexToAddress(\"0x7677079725f513e84917FCBa6b4a32b25B40A26F\"),\n\t\tcommon.HexToAddress(\"0x2eeDC61F5841a3734481708eb4c847d35D184233\"),\n\t\tcommon.HexToAddress(\"0xe93C7fF346822A4284ac2487b09BfF50C5E9da49\"),\n\t\tcommon.HexToAddress(\"0x7702dE477B1120C84C3f7ea87280e0EC5f430dFC\"),\n\t\tcommon.HexToAddress(\"0x485c8C02227cAFDB92f8d4762aA2185652eE5138\"),\n\t\tcommon.HexToAddress(\"0x2D67e63B2bFC0Ce6DDD5C087e046F276323f7Ea9\"),\n\t\tcommon.HexToAddress(\"0xD89D21F9b40c0D91B5112ecbB297FA8EF5ae7042\"),\n\t\tcommon.HexToAddress(\"0x6F7151ec4E934A79A932A159A4d554C8ca8Cb406\"),\n\t\tcommon.HexToAddress(\"0xd3Ba9236767BE744b79EE8145Ed103cF0af46f50\"),\n\t\tcommon.HexToAddress(\"0xE81DD44242CD32E1b3a24D1654F890cdBaCB48F3\"),\n\t\tcommon.HexToAddress(\"0x3a0f2a30d6636afB1E80ce20220C316A6B4473d3\"),\n\t\tcommon.HexToAddress(\"0x960499062081E0723465B451FE4F824A59940b66\"),\n\t\tcommon.HexToAddress(\"0x9bb9167D35AA42Bb814AC7946A138Cb7f2Bebb8f\"),\n\t\tcommon.HexToAddress(\"0x60eB76BE9a9b5c342708891AE23231448DB174B0\"),\n\t\tcommon.HexToAddress(\"0x5E1B7158e29eAC2bDb032170Ad6B3288a640fD41\"),\n\t\tcommon.HexToAddress(\"0xc59Cf2C2E2D142CeD9765B2cc31D871287198DB1\"),\n\t\tcommon.HexToAddress(\"0x7ABfD5C857ee8242c29C8939052baCA93Abb5179\"),\n\t}\n}", "func (k Querier) DelegatorUnbondingDelegations(ctx context.Context, req *types.QueryDelegatorUnbondingDelegationsRequest) (*types.QueryDelegatorUnbondingDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tvar unbondingDelegations types.UnbondingDelegations\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, pageRes, err := query.CollectionPaginate(\n\t\tctx,\n\t\tk.UnbondingDelegations,\n\t\treq.Pagination,\n\t\tfunc(key collections.Pair[[]byte, []byte], value types.UnbondingDelegation) (types.UnbondingDelegation, error) {\n\t\t\tunbondingDelegations = append(unbondingDelegations, value)\n\t\t\treturn value, nil\n\t\t},\n\t\tquery.WithCollectionPaginationPairPrefix[[]byte, []byte](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorUnbondingDelegationsResponse{\n\t\tUnbondingResponses: unbondingDelegations, Pagination: pageRes,\n\t}, nil\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (i *Interest) ForwardingHint() []Delegation {\n\treturn i.forwardingHint\n}", "func GetDelegationsKey(delAddr sdk.AccAddress) []byte {\n\treturn append(DelegationKey, address.MustLengthPrefix(delAddr.Bytes())...)\n}", "func (msg MsgClaimDelegatorReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (o OfflineNotaryRepository) GetDelegationRoles() ([]data.Role, error) {\n\treturn nil, storage.ErrOffline{}\n}", "func (s *Streams) Delegate(data interface{}) {\n\tlisteners := s.Size()\n\n\tif listeners <= 0 {\n\t\treturn\n\t}\n\n\tif s.reverse {\n\t\ts.RevMunch(data)\n\t} else {\n\t\ts.Munch(data)\n\t}\n\n}", "func (rdr *ReplacableDelegatingRouter) Delegate() *pat.Router {\n\treturn rdr.delegate.Load().(*pat.Router)\n}", "func GetDebondingDelegationsFor(w http.ResponseWriter, r *http.Request) {\n\n\t// Add header so that received knows they're receiving JSON\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// Retrieving name of node from query request\n\tnodeName := r.URL.Query().Get(\"name\")\n\tconfirmation, socket := checkNodeName(nodeName)\n\tif !confirmation {\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Node name requested doesn't exist\"})\n\t\treturn\n\t}\n\n\t// Retrieving height from query request\n\trecvHeight := r.URL.Query().Get(\"height\")\n\theight := checkHeight(recvHeight)\n\tif height == -1 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Unexpected value found, height needs to be a string representing an int!\"})\n\t\treturn\n\t}\n\n\t// Note Make sure that public key that is being sent is coded properly\n\t// Example A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU+h+blS9pto= should be\n\t// A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU%2Bh%2BblS9pto=\n\t//var pubKey common_signature.PublicKey\n\townerKey := r.URL.Query().Get(\"ownerKey\")\n\tif len(ownerKey) == 0 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tlgr.Warning.Println(\n\t\t\t\"Request at /api/staking/account failed, address can't be \" +\n\t\t\t\t\"empty!\")\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"address can't be empty!\"})\n\t\treturn\n\t}\n\n\t// Unmarshal text into public key object\n\t//err := pubKey.UnmarshalText([]byte(ownerKey))\n\t//if err != nil {\n\t//\tlgr.Error.Println(\"Failed to UnmarshalText into Public Key\", err)\n\t//\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t//\t\tError: \"Failed to UnmarshalText into Public Key.\"})\n\t//\treturn\n\t//}\n\n\tvar address staking.Address\n\terr := address.UnmarshalText([]byte(ownerKey))\n\tif err != nil {\n\t\tlgr.Error.Println(\"Failed to UnmarshalText into Address\", err)\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to UnmarshalText into Address.\"})\n\t\treturn\n\t}\n\n\t// Attempt to load connection with staking client\n\tconnection, so := loadStakingClient(socket)\n\n\t// Close connection once code underneath executes\n\tdefer connection.Close()\n\n\t// If null object was retrieved send response\n\tif so == nil {\n\n\t\t// Stop code here faild to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to establish connection using socket : \" + socket})\n\t\treturn\n\t}\n\n\t// Query created to retrieved Debonding Delegations for an account\n\tquery := staking.OwnerQuery{Height: height, Owner: address}\n\n\t// Retrieving debonding delegations for an account using above query\n\tdebondingDelegationsFor, err := so.DebondingDelegationsFor(context.Background(),\n\t\t&query)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to get Debonding Delegations!\"})\n\t\tlgr.Error.Println(\n\t\t\t\"Request at /api/staking/debondingdelegationsfor failed to retrieve\"+\n\t\t\t\t\" Debonding Delegations : \", err)\n\t\treturn\n\t}\n\n\t// Responding with debonding delegations for given accounts\n\tlgr.Info.Println(\n\t\t\"Request at /api/staking/debondingdelegationsfor responding with \" +\n\t\t\t\"Debonding Delegations!\")\n\tjson.NewEncoder(w).Encode(responses.DebondingDelegationsResponse{\n\t\tDebondingDelegations: debondingDelegationsFor})\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryTransactor) AddDelegate(opts *bind.TransactOpts, from common.Address) (*types.Transaction, error) {\n\treturn _OwnerProxyRegistry.contract.Transact(opts, \"addDelegate\", from)\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (_Bep20 *Bep20TransactorSession) Delegate(delegatee common.Address) (*types.Transaction, error) {\n\treturn _Bep20.Contract.Delegate(&_Bep20.TransactOpts, delegatee)\n}", "func (c *DPOS) CheckRewardsFromAllValidators(ctx contract.StaticContext, req *CheckDelegatorRewardsRequest) (*CheckDelegatorRewardsResponse, error) {\n\tif req.Delegator == nil {\n\t\treturn nil, logStaticDposError(ctx, errors.New(\"CheckRewardsFromAllValidators called with req.Delegator == nil\"), req.String())\n\t}\n\n\tdelegator := loom.UnmarshalAddressPB(req.Delegator)\n\tdelegations, err := loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to load delegations\")\n\t}\n\n\ttotal := big.NewInt(0)\n\tfor _, d := range delegations {\n\t\tif d.Index != REWARD_DELEGATION_INDEX ||\n\t\t\tloom.UnmarshalAddressPB(d.Delegator).Compare(delegator) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tctx.Logger().Error(\"DPOS CheckRewardsFromAllValidators\", \"error\", err, \"delegator\", delegator)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to load delegation\")\n\t\t}\n\n\t\ttotal.Add(total, delegation.Amount.Value.Int)\n\t}\n\n\tamount := loom.NewBigUInt(total)\n\treturn &CheckDelegatorRewardsResponse{\n\t\tAmount: &types.BigUInt{Value: *amount},\n\t}, nil\n}", "func TestCallSimDelegate(t *testing.T) {\n\t// Roll up our sleeves and swear fealty to the witch-king\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tg, ctx := errgroup.WithContext(ctx)\n\n\tdb := dbm.NewMemDB()\n\tst, err := state.MakeGenesisState(db, genesisDoc)\n\trequire.NoError(t, err)\n\n\tfrom := crypto.PrivateKeyFromSecret(\"raaah\", crypto.CurveTypeEd25519)\n\tcontractAddress := crypto.Address{1, 2, 3, 4, 5}\n\tblockchain := &bcm.Blockchain{}\n\tsink := exec.NewNoopEventSink()\n\n\t// Function to set storage value for later\n\tsetDelegate := func(up state.Updatable, value crypto.Address) error {\n\t\tcall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"setDelegate\", logger, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcache := acmstate.NewCache(st)\n\t\t_, err = evm.Default().Execute(cache, blockchain, sink,\n\t\t\tengine.CallParams{\n\t\t\t\tCallType: exec.CallTypeCall,\n\t\t\t\tOrigin: from.GetAddress(),\n\t\t\t\tCaller: from.GetAddress(),\n\t\t\t\tCallee: contractAddress,\n\t\t\t\tInput: call,\n\t\t\t\tGas: big.NewInt(9999999),\n\t\t\t}, solidity.DeployedBytecode_DelegateProxy)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn cache.Sync(up)\n\t}\n\n\t// Initialise sender smart contract state\n\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\terr = up.UpdateAccount(&acm.Account{\n\t\t\tAddress: from.GetAddress(),\n\t\t\tPublicKey: from.GetPublicKey(),\n\t\t\tBalance: 9999999,\n\t\t\tPermissions: permission.DefaultAccountPermissions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn up.UpdateAccount(&acm.Account{\n\t\t\tAddress: contractAddress,\n\t\t\tEVMCode: solidity.DeployedBytecode_DelegateProxy,\n\t\t})\n\t})\n\trequire.NoError(t, err)\n\n\t// Set a series of values of storage slot so we get a deep version tree (which we need to trigger the bug)\n\tdelegate := crypto.Address{0xBE, 0xEF, 0, 0xFA, 0xCE, 0, 0xBA, 0}\n\tfor i := 0; i < 0xBF; i++ {\n\t\tdelegate[7] = byte(i)\n\t\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\t\treturn setDelegate(up, delegate)\n\t\t})\n\t\trequire.NoError(t, err)\n\t}\n\n\t// This is important in order to illicit the former bug - we need a cold LRU tree cache in MutableForest\n\tst, err = state.LoadState(db, st.Version())\n\trequire.NoError(t, err)\n\n\tgetIntCall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"getDelegate\", logger)\n\trequire.NoError(t, err)\n\tn := 1000\n\n\tfor i := 0; i < n; i++ {\n\t\tg.Go(func() error {\n\t\t\ttxe, err := CallSim(st, blockchain, from.GetAddress(), contractAddress, getIntCall, logger)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = txe.GetException().AsError()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taddress, err := crypto.AddressFromBytes(txe.GetResult().Return[12:])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif address != delegate {\n\t\t\t\t// The bug for which this test was written will return the zero address here since it is accessing\n\t\t\t\t// an uninitialised tree\n\t\t\t\treturn fmt.Errorf(\"getDelegate returned %v but expected %v\", address, delegate)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\trequire.NoError(t, g.Wait())\n}", "func (d *JSONDiscovery) DiscoverVTGateAddrs(ctx context.Context, tags []string) ([]string, error) {\n\tspan, ctx := trace.NewSpan(ctx, \"JSONDiscovery.DiscoverVTGateAddrs\")\n\tdefer span.Finish()\n\n\tgates, err := d.discoverVTGates(ctx, tags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddrs := make([]string, len(gates))\n\tfor i, gate := range gates {\n\t\taddrs[i] = gate.Hostname\n\t}\n\n\treturn addrs, nil\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func ContractAddrs() (adjudicator, asset pwallet.Address) {\n\tprng := rand.New(rand.NewSource(RandSeedForTestAccs))\n\tws, err := NewWalletSetup(prng, 2)\n\tif err != nil {\n\t\tpanic(\"Cannot setup test wallet\")\n\t}\n\tadjudicator = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(ws.Accs[0].Address()), 0))\n\tasset = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(ws.Accs[0].Address()), 1))\n\treturn\n}" ]
[ "0.7558369", "0.6659465", "0.6476398", "0.6460819", "0.6427564", "0.62541723", "0.6195837", "0.6178758", "0.61684823", "0.59371394", "0.58577865", "0.58084106", "0.577678", "0.5767865", "0.5690672", "0.56803244", "0.56599504", "0.56216323", "0.5587401", "0.5545098", "0.553403", "0.55243653", "0.55174935", "0.5486116", "0.5460731", "0.54539835", "0.5405233", "0.53873694", "0.5361591", "0.5353628", "0.52567106", "0.52016044", "0.50946677", "0.5059279", "0.5058916", "0.50557554", "0.50557554", "0.5043653", "0.5042965", "0.503333", "0.5020415", "0.5010052", "0.50044984", "0.4999101", "0.49936095", "0.4975955", "0.49293515", "0.48979682", "0.48661718", "0.48596314", "0.4852119", "0.483657", "0.48256853", "0.48252136", "0.48238197", "0.48180172", "0.48000416", "0.47981077", "0.479239", "0.4768582", "0.47682354", "0.47392365", "0.4734172", "0.47122687", "0.4711288", "0.47026846", "0.4691919", "0.46779683", "0.46779472", "0.46759662", "0.46734038", "0.46710554", "0.4658087", "0.46498936", "0.4649873", "0.46473673", "0.4646813", "0.46390745", "0.46366665", "0.46185488", "0.46112698", "0.4586343", "0.4576406", "0.4570979", "0.45675316", "0.45577586", "0.4548812", "0.45414224", "0.45381585", "0.45219296", "0.45036677", "0.44990677", "0.44987506", "0.44918698", "0.44863176", "0.44680917", "0.44614667", "0.44527245", "0.44423872", "0.4441936" ]
0.6312473
5
/ Description: Gets a list of all of the delegated contacts to a delegator Param delegateAddr (string): string representation of the address of a delegator Returns ([]string): An array of addresses (delegated contracts) that are delegated to the delegator
func GetAllDelegatedContracts(delegateAddr string) ([]string, error){ var rtnString []string delegatedContractsCmd := "/chains/main/blocks/head/context/delegates/" + delegateAddr + "/delegated_contracts" s, err := TezosRPCGet(delegatedContractsCmd) if (err != nil){ return rtnString, errors.New("Could not get delegated contracts: TezosRPCGet(arg string) failed: " + err.Error()) } DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1) //TODO Error checking if (DelegatedContracts == nil){ return rtnString, errors.New("Could not get all delegated contracts: Regex failed") } rtnString = addressesToArray(DelegatedContracts) return rtnString, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_ConsortiumManagement *ConsortiumManagementCaller) Delegates(opts *bind.CallOpts) ([]common.Address, error) {\n\tvar out []interface{}\n\terr := _ConsortiumManagement.contract.Call(opts, &out, \"delegates\")\n\n\tif err != nil {\n\t\treturn *new([]common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address)\n\n\treturn out0, err\n\n}", "func (s *ArkClient) ListDelegates(params DelegateQueryParams) (DelegateResponse, *http.Response, error) {\n\trespData := new(DelegateResponse)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\treturn *respData, resp, err\n}", "func (_ConsortiumManagement *ConsortiumManagementCallerSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func GetDelegates(node client.ABCIClient) (map[address.Address][]address.Address, *rpctypes.ResultABCIQuery, error) {\n\t// perform the query\n\tres, err := node.ABCIQuery(query.DelegatesEndpoint, nil)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\tif code.ReturnCode(res.Response.Code) != code.OK {\n\t\tif res.Response.Log != \"\" {\n\t\t\treturn nil, res, errors.New(code.ReturnCode(res.Response.Code).String() + \": \" + res.Response.Log)\n\t\t}\n\t\treturn nil, res, errors.New(code.ReturnCode(res.Response.Code).String())\n\t}\n\n\tdr := query.DelegatesResponse{}\n\t// parse the response\n\t_, err = dr.UnmarshalMsg(res.Response.GetValue())\n\tif err != nil || dr == nil {\n\t\treturn nil, res, errors.Wrap(err, \"unmarshalling delegates response\")\n\t}\n\n\t// transform response into friendly form\n\tdelegates := make(map[address.Address][]address.Address)\n\tfor _, node := range dr {\n\t\tfor _, delegated := range node.Delegated {\n\t\t\tdelegates[node.Node] = append(delegates[node.Node], delegated)\n\t\t}\n\t}\n\treturn delegates, res, err\n}", "func (_ConsortiumManagement *ConsortiumManagementSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func (s *PublicSfcAPI) GetDelegatorsOf(ctx context.Context, stakerID hexutil.Uint64, verbosity hexutil.Uint64) ([]interface{}, error) {\n\tdelegators, err := s.b.GetDelegatorsOf(ctx, idx.StakerID(stakerID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif verbosity == 0 {\n\t\t// Addresses only\n\t\taddresses := make([]interface{}, len(delegators))\n\t\tfor i, it := range delegators {\n\t\t\taddresses[i] = it.Addr.String()\n\t\t}\n\t\treturn addresses, nil\n\t}\n\n\tdelegatorsRPC := make([]interface{}, len(delegators))\n\tfor i, it := range delegators {\n\t\tdelegatorRPC := RPCMarshalDelegator(it)\n\t\tif verbosity >= 2 {\n\t\t\tdelegatorRPC, err = s.addDelegatorMetricFields(ctx, delegatorRPC, it.Addr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tdelegatorsRPC[i] = delegatorRPC\n\t}\n\n\treturn delegatorsRPC, err\n}", "func (k Keeper) GetAllDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress) []types.Delegation {\n\tdelegations := make([]types.Delegation, 0)\n\n\tstore := ctx.KVStore(k.storeKey)\n\tdelegatorPrefixKey := types.GetDelegationsKey(delegator)\n\n\titerator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) //smallest to largest\n\tdefer iterator.Close()\n\n\ti := 0\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tdelegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value())\n\t\tdelegations = append(delegations, delegation)\n\t\ti++\n\t}\n\n\treturn delegations\n}", "func (k Querier) DelegatorDelegations(ctx context.Context, req *types.QueryDelegatorDelegationsRequest) (*types.QueryDelegatorDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegations, pageRes, err := query.CollectionPaginate(ctx, k.Delegations, req.Pagination,\n\t\tfunc(_ collections.Pair[sdk.AccAddress, sdk.ValAddress], del types.Delegation) (types.Delegation, error) {\n\t\t\treturn del, nil\n\t\t}, query.WithCollectionPaginationPairPrefix[sdk.AccAddress, sdk.ValAddress](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelegationResps, err := delegationsToDelegationResponses(ctx, k.Keeper, delegations)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorDelegationsResponse{DelegationResponses: delegationResps, Pagination: pageRes}, nil\n}", "func (_Bep20 *Bep20Caller) Delegates(opts *bind.CallOpts, delegator common.Address) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"delegates\", delegator)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (acc *Account) Delegations(args *struct {\n\tCursor *Cursor\n\tCount int32\n}) (*DelegationList, error) {\n\t// limit query size; the count can be either positive or negative\n\t// this controls the loading direction\n\targs.Count = listLimitCount(args.Count, listMaxEdgesPerRequest)\n\n\t// pull the list\n\tdl, err := repository.R().DelegationsByAddress(&acc.Address, (*string)(args.Cursor), args.Count)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// convert to resolvable list\n\treturn NewDelegationList(dl), nil\n}", "func (t *TezTracker) AccountDelegatorsList(accountID string, limits Limiter) ([]models.AccountListView, int64, error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.Account{DelegateValue: accountID}\n\tcount, err := r.Count(filter)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\taccs, err := r.Filter(filter, limits.Limit(), limits.Offset())\n\treturn accs, count, err\n}", "func (t *TezTracker) AccountDelegatorsList(accountID string, limits Limiter) ([]models.AccountListView, int64, error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.Account{DelegateValue: accountID}\n\tcount, err := r.Count(filter)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\taccs, err := r.Filter(filter, limits.Limit(), limits.Offset())\n\treturn accs, count, err\n}", "func (k Querier) DelegatorValidators(ctx context.Context, req *types.QueryDelegatorValidatorsRequest) (*types.QueryDelegatorValidatorsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tvar validators types.Validators\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, pageRes, err := query.CollectionPaginate(ctx, k.Delegations, req.Pagination,\n\t\tfunc(_ collections.Pair[sdk.AccAddress, sdk.ValAddress], delegation types.Delegation) (types.Delegation, error) {\n\t\t\tvalAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())\n\t\t\tif err != nil {\n\t\t\t\treturn types.Delegation{}, err\n\t\t\t}\n\t\t\tvalidator, err := k.GetValidator(ctx, valAddr)\n\t\t\tif err != nil {\n\t\t\t\treturn types.Delegation{}, err\n\t\t\t}\n\n\t\t\tvalidators.Validators = append(validators.Validators, validator)\n\t\t\treturn types.Delegation{}, nil\n\t\t}, query.WithCollectionPaginationPairPrefix[sdk.AccAddress, sdk.ValAddress](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorValidatorsResponse{Validators: validators.Validators, Pagination: pageRes}, nil\n}", "func (_Bep20 *Bep20CallerSession) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) Delegations(opts *bind.CallOpts, arg0 [32]byte) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret0, err\n}", "func (k Querier) ValidatorDelegations(ctx context.Context, req *types.QueryValidatorDelegationsRequest) (*types.QueryValidatorDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tdels types.Delegations\n\t\tpageRes *query.PageResponse\n\t)\n\n\tdels, pageRes, err = query.CollectionPaginate(ctx, k.DelegationsByValidator,\n\t\treq.Pagination, func(key collections.Pair[sdk.ValAddress, sdk.AccAddress], _ []byte) (types.Delegation, error) {\n\t\t\tvalAddr, delAddr := key.K1(), key.K2()\n\t\t\tdelegation, err := k.Delegations.Get(ctx, collections.Join(delAddr, valAddr))\n\t\t\tif err != nil {\n\t\t\t\treturn types.Delegation{}, err\n\t\t\t}\n\n\t\t\treturn delegation, nil\n\t\t}, query.WithCollectionPaginationPairPrefix[sdk.ValAddress, sdk.AccAddress](valAddr),\n\t)\n\n\tif err != nil {\n\t\tdelegations, pageResponse, err := k.getValidatorDelegationsLegacy(ctx, req)\n\t\tif err != nil {\n\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t}\n\n\t\tdels = types.Delegations{}\n\t\tfor _, d := range delegations {\n\t\t\tdels = append(dels, *d)\n\t\t}\n\n\t\tpageRes = pageResponse\n\t}\n\n\tdelResponses, err := delegationsToDelegationResponses(ctx, k.Keeper, dels)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryValidatorDelegationsResponse{\n\t\tDelegationResponses: delResponses, Pagination: pageRes,\n\t}, nil\n}", "func (gc *GovernanceContract) DelegationsBy(args struct{ From common.Address }) ([]common.Address, error) {\n\t// decide by the contract type\n\tswitch gc.Type {\n\tcase \"sfc\":\n\t\treturn gc.sfcDelegationsBy(args.From)\n\t}\n\n\t// no delegations by default\n\tgc.repo.Log().Debugf(\"unknown governance type of %s\", gc.Address.Hex())\n\treturn []common.Address{}, nil\n}", "func (gc *GovernanceContract) sfcDelegationsBy(addr common.Address) ([]common.Address, error) {\n\t// get SFC delegations list\n\tdl, err := gc.repo.DelegationsByAddress(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// prep the result container\n\tres := make([]common.Address, 0)\n\n\t// check if the address is a staker\n\t// if so, it also delegates to itself in the context of the contract\n\tisStaker, err := gc.repo.IsStaker(&addr)\n\tif err == nil && isStaker {\n\t\tres = append(res, addr)\n\t}\n\n\t// loop delegations to make the list\n\tfor _, d := range dl {\n\t\t// is the delegation ok for voting?\n\t\tif nil != d.DeactivatedEpoch && 0 < uint64(*d.DeactivatedEpoch) {\n\t\t\tgc.repo.Log().Debugf(\"delegation to %d from address %s is deactivated\", d.ToStakerId, addr.String())\n\t\t\tcontinue\n\t\t}\n\n\t\t// get the staker info\n\t\tstaker, err := gc.repo.StakerAddress(d.ToStakerId)\n\t\tif err != nil {\n\t\t\tgc.repo.Log().Errorf(\"error loading staker %d info; %s\", d.ToStakerId, addr.String())\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// get the\n\t\tres = append(res, staker)\n\t}\n\n\t// log delegations found\n\tgc.repo.Log().Debugf(\"%d delegations on %s\", len(res), addr.String())\n\treturn res, nil\n}", "func (s *PublicSfcAPI) GetDelegator(ctx context.Context, addr common.Address, verbosity hexutil.Uint64) (map[string]interface{}, error) {\n\tdelegator, err := s.b.GetDelegator(ctx, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif delegator == nil {\n\t\treturn nil, nil\n\t}\n\tit := sfctype.SfcDelegatorAndAddr{\n\t\tAddr: addr,\n\t\tDelegator: delegator,\n\t}\n\tdelegatorRPC := RPCMarshalDelegator(it)\n\tif verbosity <= 1 {\n\t\treturn delegatorRPC, nil\n\t}\n\treturn s.addDelegatorMetricFields(ctx, delegatorRPC, addr)\n}", "func (k Keeper) GetDelegatorDefis(\n\tctx sdk.Context, delegatorAddr sdk.AccAddress, maxRetrieve uint32,\n) types.Defis {\n\tdefis := make([]types.Defi, maxRetrieve)\n\n\tstore := ctx.KVStore(k.storeKey)\n\tdelegatorPrefixKey := types.GetDelegationsKey(delegatorAddr)\n\n\titerator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest\n\tdefer iterator.Close()\n\n\ti := 0\n\tfor ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() {\n\t\tdelegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value())\n\n\t\tdefi, found := k.GetDefi(ctx, delegation.GetDefiAddr())\n\t\tif !found {\n\t\t\tpanic(types.ErrNoDefiFound)\n\t\t}\n\n\t\tdefis[i] = defi\n\t\ti++\n\t}\n\n\treturn defis[:i] // trim\n}", "func (_Bep20 *Bep20Session) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) Delegations(arg0 [32]byte) (common.Address, error) {\n\treturn _PlasmaFramework.Contract.Delegations(&_PlasmaFramework.CallOpts, arg0)\n}", "func GetDelegatedContractsForCycle(cycle int, delegateAddr string) ([]string, error){\n var rtnString []string\n snapShot, err := GetSnapShot(cycle)\n // fmt.Println(snapShot)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetSnapShot(cycle int) failed: \" + err.Error())\n }\n hash, err:= GetBlockLevelHash(snapShot.AssociatedBlock)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetBlockLevelHash(level int) failed: \" + err.Error())\n }\n // fmt.Println(hash)\n getDelegatedContracts := \"/chains/main/blocks/\" + hash + \"/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n\n s, err := TezosRPCGet(getDelegatedContracts)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1)\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": You have no contracts.\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func (s *RoundsService) Delegates(ctx context.Context, id int64) (*GetDelegates, *http.Response, error) {\n\turi := fmt.Sprintf(\"rounds/%v/delegates\", id)\n\n\tvar responseStruct *GetDelegates\n\tresp, err := s.client.SendRequest(ctx, \"GET\", uri, nil, nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (s *ArkClient) GetDelegate(params DelegateQueryParams) (DelegateResponse, *http.Response, error) {\n\trespData := new(DelegateResponse)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/get\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\treturn *respData, resp, err\n}", "func GetDelegates(seedUrl_optional ...string) ([]types.Node, error) {\n\tseedUrl := \"seed.dispatchlabs.io:1975\"\n\tif len(seedUrl_optional) > 0 {\n\t\tseedUrl = seedUrl_optional[0]\n\t}\n\n\t// Get delegates.\n\thttpResponse, err := http.Get(fmt.Sprintf(\"http://%s/v1/delegates\", seedUrl))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer httpResponse.Body.Close()\n\n\t// Read body.\n\tbody, err := ioutil.ReadAll(httpResponse.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Unmarshal response.\n\tvar response *types.Response\n\terr = json.Unmarshal(body, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Status?\n\tif response.Status != types.StatusOk {\n\t\treturn nil, errors.New(fmt.Sprintf(\"%s: %s\", response.Status, response.HumanReadableStatus))\n\t}\n\n\t// Unmarshal to RawMessage.\n\tvar jsonMap map[string]json.RawMessage\n\terr = json.Unmarshal(body, &jsonMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Data?\n\tif jsonMap[\"data\"] == nil {\n\t\treturn nil, errors.Errorf(\"'data' is missing from response\")\n\t}\n\n\t// Unmarshal nodes.\n\tvar nodes []types.Node\n\terr = json.Unmarshal(jsonMap[\"data\"], &nodes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nodes, nil\n}", "func (o *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams) SetDelegatorAddr(delegatorAddr string) {\n\to.DelegatorAddr = delegatorAddr\n}", "func (k Keeper) IterateDelegations(ctx context.Context, delAddr sdk.AccAddress,\n\tfn func(index int64, del types.DelegationI) (stop bool),\n) error {\n\tvar i int64\n\trng := collections.NewPrefixedPairRange[sdk.AccAddress, sdk.ValAddress](delAddr)\n\terr := k.Delegations.Walk(ctx, rng, func(key collections.Pair[sdk.AccAddress, sdk.ValAddress], del types.Delegation) (stop bool, err error) {\n\t\tstop = fn(i, del)\n\t\tif stop {\n\t\t\treturn true, nil\n\t\t}\n\t\ti++\n\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_DelegationController *DelegationControllerCallerSession) DelegationsByValidator(arg0 *big.Int, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByValidator(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (_PlasmaFramework *PlasmaFrameworkSession) Delegations(arg0 [32]byte) (common.Address, error) {\n\treturn _PlasmaFramework.Contract.Delegations(&_PlasmaFramework.CallOpts, arg0)\n}", "func (_DelegationController *DelegationControllerSession) DelegationsByValidator(arg0 *big.Int, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByValidator(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (client *Client) ListDelegatedServicesForAccount(request *ListDelegatedServicesForAccountRequest) (_result *ListDelegatedServicesForAccountResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &ListDelegatedServicesForAccountResponse{}\n\t_body, _err := client.ListDelegatedServicesForAccountWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (k Querier) Redelegations(ctx context.Context, req *types.QueryRedelegationsRequest) (*types.QueryRedelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tvar redels types.Redelegations\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tstore := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))\n\tswitch {\n\tcase req.DelegatorAddr != \"\" && req.SrcValidatorAddr != \"\" && req.DstValidatorAddr != \"\":\n\t\tredels, err = queryRedelegation(ctx, k, req)\n\tcase req.DelegatorAddr == \"\" && req.SrcValidatorAddr != \"\" && req.DstValidatorAddr == \"\":\n\t\tredels, pageRes, err = queryRedelegationsFromSrcValidator(ctx, store, k, req)\n\tdefault:\n\t\tredels, pageRes, err = queryAllRedelegations(ctx, store, k, req)\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\tredelResponses, err := redelegationsToRedelegationResponses(ctx, k.Keeper, redels)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRedelegationsResponse{RedelegationResponses: redelResponses, Pagination: pageRes}, nil\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (m Mapper) loadDelegatorCandidates(delegator sdk.Address) (candidateAddrs []sdk.Address) {\n\n\tcandidateBytes := m.store.Get(GetDelegatorBondsKey(delegator, m.cdc))\n\tif candidateBytes == nil {\n\t\treturn nil\n\t}\n\n\terr := m.cdc.UnmarshalJSON(candidateBytes, &candidateAddrs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func (o *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams) WithDelegatorAddr(delegatorAddr string) *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams {\n\to.SetDelegatorAddr(delegatorAddr)\n\treturn o\n}", "func (o *APIServiceAddressParams) SetDelegated(delegated *bool) {\n\to.Delegated = delegated\n}", "func delegate(native *NativeService, from []byte, contractAddr []byte, to []byte,\n\trole []byte, period uint32, level int) ([]byte, error) {\n\tnull := []byte{}\n\tcontract := native.ContextRef.CurrentContext().ContractAddress\n\tcontractKey := append(contract[:], contractAddr...)\n\n\tret, err := verifySig(native, from)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !ret {\n\t\treturn nil, err\n\t}\n\t//iterate\n\troleP, err := packKey(RoleP, role)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\troleP = append(contractKey, roleP...)\n\n\tnode_to, err := linkedlistGetItem(native, roleP, to)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnode_from, err := linkedlistGetItem(native, roleP, from)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif node_to != nil || node_from == nil {\n\t\treturn nil, err //ignore\n\t}\n\n\tauth := new(AuthToken)\n\terr = auth.deserialize(node_from.payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t//check if 'from' has the permission to delegate\n\tif auth.level >= 2 && level < auth.level && level > 0 {\n\t\t// put `to` in the delegate list\n\t\t// 'role x person' -> [] person is a list of person who gets the auth token\n\t\tser_role_per, err := packKeys(DelegateList, [][]byte{role, from})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tser_role_per = append(contractKey, ser_role_per...)\n\t\tlinkedlistInsert(native, ser_role_per, to, null)\n\n\t\t//insert into the `role -> []person` list\n\t\tauthprime := auth\n\t\tauthprime.expireTime = native.Time + period\n\t\tif authprime.expireTime < native.Time {\n\t\t\treturn nil, errors.NewErr(\"[auth contract] overflow of expire time\")\n\t\t}\n\t\tauthprime.level = level\n\t\tser_authprime, err := authprime.serialize()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpersons := &OntIDsToRoleParam{Role: role, Persons: [][]byte{to}}\n\t\tbf := new(bytes.Buffer)\n\t\terr = persons.Serialize(bf)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnative.Input = bf.Bytes()\n\t\t_, err = assignToRole(native, ser_authprime)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn BYTE_ONE, nil\n}", "func (broadcast *Broadcast) Delegate(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegateMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (_Bep20 *Bep20Filterer) FilterDelegateChanged(opts *bind.FilterOpts, delegator []common.Address, fromDelegate []common.Address, toDelegate []common.Address) (*Bep20DelegateChangedIterator, error) {\n\n\tvar delegatorRule []interface{}\n\tfor _, delegatorItem := range delegator {\n\t\tdelegatorRule = append(delegatorRule, delegatorItem)\n\t}\n\tvar fromDelegateRule []interface{}\n\tfor _, fromDelegateItem := range fromDelegate {\n\t\tfromDelegateRule = append(fromDelegateRule, fromDelegateItem)\n\t}\n\tvar toDelegateRule []interface{}\n\tfor _, toDelegateItem := range toDelegate {\n\t\ttoDelegateRule = append(toDelegateRule, toDelegateItem)\n\t}\n\n\tlogs, sub, err := _Bep20.contract.FilterLogs(opts, \"DelegateChanged\", delegatorRule, fromDelegateRule, toDelegateRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Bep20DelegateChangedIterator{contract: _Bep20.contract, event: \"DelegateChanged\", logs: logs, sub: sub}, nil\n}", "func (k Keeper) Delegator(ctx sdk.Context, delAddr sdk.AccAddress) exported.DelegatorI {\n\tdelegator, found := k.GetDelegator(ctx, delAddr)\n\tif !found {\n\t\treturn nil\n\t}\n\n\treturn delegator\n}", "func (rs *rootResolver) DelegationsOf(args *struct {\n\tStaker hexutil.Uint64\n\tCursor *Cursor\n\tCount int32\n}) (*DelegatorList, error) {\n\t// any arguments?\n\tif args == nil {\n\t\treturn nil, fmt.Errorf(\"missing delegations input\")\n\t}\n\n\t// limit query size; the count can be either positive or negative\n\t// this controls the loading direction\n\targs.Count = listLimitCount(args.Count, listMaxEdgesPerRequest)\n\n\t// get the list\n\tdl, err := rs.repo.DelegationsOf(args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// sort by the date of creation\n\tsort.Sort(DelegationsByAge(dl))\n\treturn NewDelegatorList(dl, parseDelegationsCursor(args.Cursor, args.Count, dl), args.Count, rs.repo), nil\n}", "func (_DelegationController *DelegationControllerFilterer) FilterDelegationAccepted(opts *bind.FilterOpts) (*DelegationControllerDelegationAcceptedIterator, error) {\n\n\tlogs, sub, err := _DelegationController.contract.FilterLogs(opts, \"DelegationAccepted\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DelegationControllerDelegationAcceptedIterator{contract: _DelegationController.contract, event: \"DelegationAccepted\", logs: logs, sub: sub}, nil\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func GetDelegatorBondsKey(delegator sdk.Address, cdc *wire.Codec) []byte {\n\tres, err := cdc.MarshalJSON(&delegator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn append(DelegatorBondsKeyPrefix, res...)\n}", "func (k Keeper) GetAllSDKDelegations(ctx context.Context) (delegations []types.Delegation, err error) {\n\tstore := k.storeService.OpenKVStore(ctx)\n\titerator, err := store.Iterator(types.DelegationKey, storetypes.PrefixEndBytes(types.DelegationKey))\n\tif err != nil {\n\t\treturn delegations, err\n\t}\n\tdefer iterator.Close()\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tdelegation, err := types.UnmarshalDelegation(k.cdc, iterator.Value())\n\t\tif err != nil {\n\t\t\treturn delegations, err\n\t\t}\n\t\tdelegations = append(delegations, delegation)\n\t}\n\n\treturn\n}", "func (_Bep20 *Bep20Transactor) Delegate(opts *bind.TransactOpts, delegatee common.Address) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegate\", delegatee)\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func loadDelegatorCandidates(store types.KVStore,\n\tdelegator crypto.Address) (candidates []crypto.PubKey) {\n\n\tcandidateBytes := store.Get(GetDelegatorBondsKey(delegator))\n\tif candidateBytes == nil {\n\t\treturn nil\n\t}\n\n\terr := cdc.UnmarshalJSON(candidateBytes, &candidates)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func (p *Protocol) NumCandidateDelegates() uint64 {\n\treturn p.numCandidateDelegates\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func GetDelegatorBondsKey(delegator crypto.Address) []byte {\n\tres, err := cdc.MarshalJSON(&delegator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn append(DelegatorBondsKeyPrefix, res...)\n}", "func GetDelegationsFor(w http.ResponseWriter, r *http.Request) {\n\n\t// Add header so that received knows they're receiving JSON\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// Retrieving name of node from query request\n\tnodeName := r.URL.Query().Get(\"name\")\n\tconfirmation, socket := checkNodeName(nodeName)\n\tif confirmation == false {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Node name requested doesn't exist\"})\n\t\treturn\n\t}\n\n\t// Retrieving height from query request\n\trecvHeight := r.URL.Query().Get(\"height\")\n\theight := checkHeight(recvHeight)\n\tif height == -1 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Unexpected value found, height needs to be a string representing an int!\"})\n\t\treturn\n\t}\n\n\t// Note Make sure that public key that is being sent is coded properly\n\t// Example A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU+h+blS9pto= should be\n\t// A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU%2Bh%2BblS9pto=\n\t//var pubKey common_signature.PublicKey\n\townerKey := r.URL.Query().Get(\"ownerKey\")\n\tif len(ownerKey) == 0 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tlgr.Warning.Println(\n\t\t\t\"Request at /api/staking/delegationsfor failed, address can't be \" +\n\t\t\t\t\"empty!\")\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"address can't be empty!\"})\n\t\treturn\n\t}\n\n\t// Unmarshal text into public key object\n\t//err := pubKey.UnmarshalText([]byte(ownerKey))\n\t//if err != nil {\n\t//\tlgr.Error.Println(\"Failed to UnmarshalText into Public Key\", err)\n\t//\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t//\t\tError: \"Failed to UnmarshalText into Public Key.\"})\n\t//\treturn\n\t//}\n\n\tvar address staking.Address\n\terr := address.UnmarshalText([]byte(ownerKey))\n\tif err != nil {\n\t\tlgr.Error.Println(\"Failed to UnmarshalText into Address\", err)\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to UnmarshalText into Address.\"})\n\t\treturn\n\t}\n\n\t// Attempt to load connection with staking client\n\tconnection, so := loadStakingClient(socket)\n\n\t// Close connection once code underneath executes\n\tdefer connection.Close()\n\n\t// If null object was retrieved send response\n\tif so == nil {\n\n\t\t// Stop code here faild to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to establish connection using socket : \" + socket})\n\t\treturn\n\t}\n\n\t// Create an owner query to be able to retrieve data with regards to account\n\tquery := staking.OwnerQuery{Height: height, Owner: address}\n\n\t// Return delegations for given account query\n\tdelegationsFor, err := so.DelegationsFor(context.Background(), &query)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to get Delegations!\"})\n\n\t\tlgr.Error.Println(\n\t\t\t\"Request at /api/staking/delegationsfor failed to retrieve \"+\n\t\t\t\t\"Delegations : \", err)\n\t\treturn\n\t}\n\n\t// Respond with delegations for given account query\n\tlgr.Info.Println(\"Request at /api/staking/delegations responding with \" +\n\t\t\"delegations!\")\n\tjson.NewEncoder(w).Encode(responses.DelegationsResponse{Delegations:\n\tdelegationsFor})\n}", "func (s *ArkClient) GetDelegateVoters(params DelegateQueryParams) (DelegateVoters, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\treturn *respData, resp, err\n}", "func queryDelegatorProxyCheck(dlgAddr sdk.AccAddress, expIsProxy bool, expHasProxy bool,\n\texpTotalDlgTokens *sdk.Dec, expBoundToProxy *sdk.AccAddress, expBoundDelegators []sdk.AccAddress) actResChecker {\n\treturn func(t *testing.T, beforeStatus, afterStatus IValidatorStatus, resultCtx *ActionResultCtx) bool {\n\n\t\tctx := getNewContext(resultCtx.tc.mockKeeper.MountedStore, resultCtx.tc.currentHeight)\n\n\t\t//query delegator from keeper directly\n\t\tdlg, found := resultCtx.tc.mockKeeper.Keeper.GetDelegator(ctx, dlgAddr)\n\t\trequire.True(t, found)\n\n\t\tb1 := assert.Equal(t, expIsProxy, dlg.IsProxy)\n\t\tb2 := assert.Equal(t, expHasProxy, dlg.HasProxy())\n\t\tb3 := true\n\t\tif expTotalDlgTokens != nil {\n\t\t\tb3 = assert.Equal(t, expTotalDlgTokens.String(), dlg.TotalDelegatedTokens.String(), dlg)\n\t\t}\n\n\t\tvar b4 bool\n\t\tif expBoundToProxy != nil {\n\t\t\tb4 = assert.Equal(t, *expBoundToProxy, dlg.ProxyAddress)\n\t\t} else {\n\t\t\tb4 = dlg.ProxyAddress == nil\n\t\t}\n\n\t\tb5 := true\n\t\tif expBoundDelegators != nil && len(expBoundDelegators) > 0 {\n\t\t\tq := NewQuerier(resultCtx.tc.mockKeeper.Keeper)\n\t\t\tpara := types.NewQueryDelegatorParams(dlgAddr)\n\t\t\tbz, _ := types.ModuleCdc.MarshalJSON(para)\n\t\t\tdata, err := q(ctx, []string{types.QueryProxy}, abci.RequestQuery{Data: bz})\n\t\t\trequire.NoError(t, err)\n\n\t\t\trealProxiedDelegators := []sdk.AccAddress{}\n\t\t\trequire.NoError(t, ModuleCdc.UnmarshalJSON(data, &realProxiedDelegators))\n\n\t\t\tb5 = assert.Equal(t, len(expBoundDelegators), len(realProxiedDelegators))\n\t\t\tif b5 {\n\t\t\t\tcnt := 0\n\t\t\t\tfor _, e := range expBoundDelegators {\n\t\t\t\t\tfor _, r := range realProxiedDelegators {\n\t\t\t\t\t\tif r.Equals(e) {\n\t\t\t\t\t\t\tcnt++\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tb5 = assert.Equal(t, len(expBoundDelegators), cnt)\n\t\t\t}\n\t\t}\n\n\t\t// check if the shares correct\n\t\tb6 := true\n\t\tif len(dlg.GetShareAddedValidatorAddresses()) > 0 {\n\t\t\texpectDlgShares, err := keeper.SimulateWeight(getGlobalContext().BlockTime().Unix(), (dlg.TotalDelegatedTokens.Add(dlg.Tokens)))\n\t\t\tb6 = err == nil\n\t\t\tb6 = b6 && assert.Equal(t, expectDlgShares.String(), dlg.Shares.String(), dlg)\n\t\t} else {\n\t\t\texpectDlgShares := sdk.ZeroDec()\n\t\t\tb6 = assert.Equal(t, expectDlgShares.String(), dlg.Shares.String(), dlg)\n\t\t}\n\n\t\tconstraintCheckRes := delegatorConstraintCheck(dlg)(t, beforeStatus, afterStatus, resultCtx)\n\n\t\tr := b1 && b2 && b3 && b4 && b5 && b6 && constraintCheckRes\n\t\tif !r {\n\t\t\tresultCtx.tc.printParticipantSnapshot(resultCtx.t)\n\t\t}\n\n\t\treturn r\n\t}\n}", "func (_DelegationController *DelegationControllerCaller) DelegationsByValidator(opts *bind.CallOpts, arg0 *big.Int, arg1 *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"delegationsByValidator\", arg0, arg1)\n\treturn *ret0, err\n}", "func (f *lazyCallReq) RoutingDelegate() []byte {\n\treturn f.delegate\n}", "func (k Keeper) GetAllUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddress) []types.UnbondingDelegation {\n\tunbondingDelegations := make([]types.UnbondingDelegation, 0)\n\n\tstore := ctx.KVStore(k.storeKey)\n\tdelegatorPrefixKey := types.GetUBDsKey(delegator)\n\n\titerator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest\n\tdefer iterator.Close()\n\n\tfor i := 0; iterator.Valid(); iterator.Next() {\n\t\tunbondingDelegation := types.MustUnmarshalUBD(k.cdc, iterator.Value())\n\t\tunbondingDelegations = append(unbondingDelegations, unbondingDelegation)\n\t\ti++\n\t}\n\n\treturn unbondingDelegations\n}", "func (c *Client) ListResourceDelegates(ctx context.Context, params *ListResourceDelegatesInput, optFns ...func(*Options)) (*ListResourceDelegatesOutput, error) {\n\tif params == nil {\n\t\tparams = &ListResourceDelegatesInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListResourceDelegates\", params, optFns, addOperationListResourceDelegatesMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListResourceDelegatesOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (s *DomainsService) ListDelegationSignerRecords(ctx context.Context, accountID string, domainIdentifier string, options *ListOptions) (*DelegationSignerRecordsResponse, error) {\n\tpath := versioned(delegationSignerRecordPath(accountID, domainIdentifier, 0))\n\tdsRecordsResponse := &DelegationSignerRecordsResponse{}\n\n\tpath, err := addURLQueryOptions(path, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.get(ctx, path, dsRecordsResponse)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdsRecordsResponse.HTTPResponse = resp\n\treturn dsRecordsResponse, nil\n}", "func (c *Call) RoutingDelegate() string {\n\tif c == nil {\n\t\treturn \"\"\n\t}\n\treturn c.md.RoutingDelegate()\n}", "func (h *peerStore) peerContacts(ih InfoHash) []string {\n\tpeers := h.get(ih)\n\tif peers == nil {\n\t\treturn nil\n\t}\n\treturn peers.next()\n}", "func (k Querier) Delegation(ctx context.Context, req *types.QueryDelegationRequest) (*types.QueryDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, err := k.Delegations.Get(ctx, collections.Join(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)))\n\tif err != nil {\n\t\tif errors.Is(err, collections.ErrNotFound) {\n\t\t\treturn nil, status.Errorf(\n\t\t\t\tcodes.NotFound,\n\t\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelResponse, err := delegationToDelegationResponse(ctx, k.Keeper, delegation)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegationResponse{DelegationResponse: &delResponse}, nil\n}", "func RPCMarshalDelegator(it sfctype.SfcDelegatorAndAddr) map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"address\": it.Addr,\n\t\t\"toStakerID\": hexutil.Uint64(it.Delegator.ToStakerID),\n\t\t\"amount\": (*hexutil.Big)(it.Delegator.Amount),\n\t\t\"createdEpoch\": hexutil.Uint64(it.Delegator.CreatedEpoch),\n\t\t\"createdTime\": hexutil.Uint64(it.Delegator.CreatedTime),\n\t\t\"deactivatedEpoch\": hexutil.Uint64(it.Delegator.DeactivatedEpoch),\n\t\t\"deactivatedTime\": hexutil.Uint64(it.Delegator.DeactivatedTime),\n\t}\n}", "func ClientAddrs(addrs []string) func(*Client) {\n\treturn func(c *Client) { c.addrs = addrs }\n}", "func (o IntegrationStsOutput) DelegateAccountEmail() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *IntegrationSts) pulumi.StringOutput { return v.DelegateAccountEmail }).(pulumi.StringOutput)\n}", "func (k Querier) DelegatorUnbondingDelegations(ctx context.Context, req *types.QueryDelegatorUnbondingDelegationsRequest) (*types.QueryDelegatorUnbondingDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tvar unbondingDelegations types.UnbondingDelegations\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, pageRes, err := query.CollectionPaginate(\n\t\tctx,\n\t\tk.UnbondingDelegations,\n\t\treq.Pagination,\n\t\tfunc(key collections.Pair[[]byte, []byte], value types.UnbondingDelegation) (types.UnbondingDelegation, error) {\n\t\t\tunbondingDelegations = append(unbondingDelegations, value)\n\t\t\treturn value, nil\n\t\t},\n\t\tquery.WithCollectionPaginationPairPrefix[[]byte, []byte](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorUnbondingDelegationsResponse{\n\t\tUnbondingResponses: unbondingDelegations, Pagination: pageRes,\n\t}, nil\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _OwnerProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func NewDelegatableDaiCaller(address common.Address, caller bind.ContractCaller) (*DelegatableDaiCaller, error) {\n\tcontract, err := bindDelegatableDai(address, caller, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DelegatableDaiCaller{contract: contract}, nil\n}", "func (_Energyconsumption *EnergyconsumptionCaller) GetConsAccntsList(opts *bind.CallOpts) ([]common.Address, error) {\n\tvar (\n\t\tret0 = new([]common.Address)\n\t)\n\tout := ret0\n\terr := _Energyconsumption.contract.Call(opts, out, \"getConsAccntsList\")\n\treturn *ret0, err\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Big\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := repository.R().Delegation(&args.Address, &args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d), nil\n}", "func (_Bep20 *Bep20TransactorSession) Delegate(delegatee common.Address) (*types.Transaction, error) {\n\treturn _Bep20.Contract.Delegate(&_Bep20.TransactOpts, delegatee)\n}", "func (c *CoordinatorHelper) AllAddresses(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n) ([]string, error) {\n\treturn c.keyStorage.GetAllAddressesTransactional(ctx, dbTx)\n}", "func (m *GraphBaseServiceClient) Contacts()(*if51cca2652371587dbc02e65260e291435a6a8f7f2ffb419f26c3b9d2a033f57.ContactsRequestBuilder) {\n return if51cca2652371587dbc02e65260e291435a6a8f7f2ffb419f26c3b9d2a033f57.NewContactsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Contacts()(*if51cca2652371587dbc02e65260e291435a6a8f7f2ffb419f26c3b9d2a033f57.ContactsRequestBuilder) {\n return if51cca2652371587dbc02e65260e291435a6a8f7f2ffb419f26c3b9d2a033f57.NewContactsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *User) GetContacts()([]Contactable) {\n return m.contacts\n}", "func DAODrainList() []common.Address {\n\treturn []common.Address{\n\t\tcommon.HexToAddress(\"0xb1080cDd0fF5B0dE78F4B5B470A6b0F4232FC377\"),\n\t\tcommon.HexToAddress(\"0xB7331D9E194A45a45b375fDB9F856FD48551b6eF\"),\n\t\tcommon.HexToAddress(\"0xA3dD8140cb29cAbEB03a8E47254a57656e35fBA7\"),\n\t\tcommon.HexToAddress(\"0xACA35cB8d3dC454816eA2103F6e49532AefA84c0\"),\n\t\tcommon.HexToAddress(\"0x670c89806Cf9C1f1Da9C022977c9dF5eA3baBd17\"),\n\t\tcommon.HexToAddress(\"0xEe3C23dDE5F90441AA1008D8391fc6CDf63F17b2\"),\n\t\tcommon.HexToAddress(\"0x8A4b509FA755419a4962f73D5cAdcA84Fe9e4cb6\"),\n\t\tcommon.HexToAddress(\"0x55f4ac7a4d29928c367035486b87E7E67547c900\"),\n\t\tcommon.HexToAddress(\"0xa52BAF602CDEd73585f17DDF06b621bD0351d691\"),\n\t\tcommon.HexToAddress(\"0x7677079725f513e84917FCBa6b4a32b25B40A26F\"),\n\t\tcommon.HexToAddress(\"0x2eeDC61F5841a3734481708eb4c847d35D184233\"),\n\t\tcommon.HexToAddress(\"0xe93C7fF346822A4284ac2487b09BfF50C5E9da49\"),\n\t\tcommon.HexToAddress(\"0x7702dE477B1120C84C3f7ea87280e0EC5f430dFC\"),\n\t\tcommon.HexToAddress(\"0x485c8C02227cAFDB92f8d4762aA2185652eE5138\"),\n\t\tcommon.HexToAddress(\"0x2D67e63B2bFC0Ce6DDD5C087e046F276323f7Ea9\"),\n\t\tcommon.HexToAddress(\"0xD89D21F9b40c0D91B5112ecbB297FA8EF5ae7042\"),\n\t\tcommon.HexToAddress(\"0x6F7151ec4E934A79A932A159A4d554C8ca8Cb406\"),\n\t\tcommon.HexToAddress(\"0xd3Ba9236767BE744b79EE8145Ed103cF0af46f50\"),\n\t\tcommon.HexToAddress(\"0xE81DD44242CD32E1b3a24D1654F890cdBaCB48F3\"),\n\t\tcommon.HexToAddress(\"0x3a0f2a30d6636afB1E80ce20220C316A6B4473d3\"),\n\t\tcommon.HexToAddress(\"0x960499062081E0723465B451FE4F824A59940b66\"),\n\t\tcommon.HexToAddress(\"0x9bb9167D35AA42Bb814AC7946A138Cb7f2Bebb8f\"),\n\t\tcommon.HexToAddress(\"0x60eB76BE9a9b5c342708891AE23231448DB174B0\"),\n\t\tcommon.HexToAddress(\"0x5E1B7158e29eAC2bDb032170Ad6B3288a640fD41\"),\n\t\tcommon.HexToAddress(\"0xc59Cf2C2E2D142CeD9765B2cc31D871287198DB1\"),\n\t\tcommon.HexToAddress(\"0x7ABfD5C857ee8242c29C8939052baCA93Abb5179\"),\n\t}\n}", "func (o AdConnectorDirectoryOutput) DnsAddresses() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *AdConnectorDirectory) pulumi.StringArrayOutput { return v.DnsAddresses }).(pulumi.StringArrayOutput)\n}", "func delegateName(delegate string) []byte {\n\tlength := len(delegate)\n\tif length > 12 {\n\t\treturn []byte(delegate[length-12:])\n\t} else {\n\t\treturn append(make([]byte, 12-length), []byte(delegate)...)\n\t}\n}", "func (p *Protocol) NumDelegates() uint64 {\n\treturn p.numDelegates\n}", "func (_GameJam *GameJamCaller) GetAllCompetitorAddresses(opts *bind.CallOpts) ([]common.Address, error) {\n\tvar (\n\t\tret0 = new([]common.Address)\n\t)\n\tout := ret0\n\terr := _GameJam.contract.Call(opts, out, \"getAllCompetitorAddresses\")\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerCallerSession) GetDelegationsByValidatorLength(validatorId *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.GetDelegationsByValidatorLength(&_DelegationController.CallOpts, validatorId)\n}", "func NewDelegatorList(dl []types.Delegator, cursor uint64, count int32, repo repository.Repository) *DelegatorList {\n\treturn &DelegatorList{\n\t\trepo: repo,\n\t\tcursor: cursor,\n\t\tcount: count,\n\t\tlist: dl,\n\t}\n}", "func (_DelegationController *DelegationControllerSession) GetDelegationsByValidatorLength(validatorId *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.GetDelegationsByValidatorLength(&_DelegationController.CallOpts, validatorId)\n}", "func (s *Server) HandleDelegateRequest(cmd string, k8sArgs *types.K8sArgs, cniCmdArgs *skel.CmdArgs, exec invoke.Exec, kubeClient *k8s.ClientInfo, interfaceAttributes *api.DelegateInterfaceAttributes) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\tvar multusConfByte []byte\n\n\tmultusConfByte = bytes.Replace(s.serverConfig, []byte(\",\"), []byte(\"{\"), 1)\n\tmultusConfig := types.GetDefaultNetConf()\n\tif err = json.Unmarshal(multusConfByte, multusConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogging.Verbosef(\"%s starting delegate request %s\", cmd, printCmdArgs(cniCmdArgs))\n\tswitch cmd {\n\tcase \"ADD\":\n\t\tresult, err = cmdDelegateAdd(cniCmdArgs, k8sArgs, exec, kubeClient, multusConfig, interfaceAttributes)\n\tcase \"DEL\":\n\t\terr = cmdDelegateDel(cniCmdArgs, k8sArgs, exec, kubeClient, multusConfig)\n\tcase \"CHECK\":\n\t\terr = cmdDelegateCheck(cniCmdArgs, k8sArgs, exec, kubeClient, multusConfig)\n\tdefault:\n\t\treturn []byte(\"\"), fmt.Errorf(\"unknown cmd type: %s\", cmd)\n\t}\n\tlogging.Verbosef(\"%s finished Delegate request %s, result: %q, err: %v\", cmd, printCmdArgs(cniCmdArgs), string(result), err)\n\tif err != nil {\n\t\t// Prefix errors with request info for easier failure debugging\n\t\treturn nil, fmt.Errorf(\"%s ERRORED: %v\", printCmdArgs(cniCmdArgs), err)\n\t}\n\treturn result, nil\n}", "func (_TransferProxyRegistry *TransferProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _TransferProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func GetDelegationsKey(delAddr sdk.AccAddress) []byte {\n\treturn append(DelegationKey, address.MustLengthPrefix(delAddr.Bytes())...)\n}", "func (c *Config) GetTargetAddresses() []string {\n\taddrs := c.v.GetString(varTargetAddresses)\n\treturn strings.Split(addrs, \",\")\n}", "func (_Bep20 *Bep20Session) Delegate(delegatee common.Address) (*types.Transaction, error) {\n\treturn _Bep20.Contract.Delegate(&_Bep20.TransactOpts, delegatee)\n}", "func (msg MsgConfirmedDeposit) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\treturn []sdk.CUAddress{msg.From}\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryTransactor) AddDelegate(opts *bind.TransactOpts, from common.Address) (*types.Transaction, error) {\n\treturn _OwnerProxyRegistry.contract.Transact(opts, \"addDelegate\", from)\n}", "func (d *DelegatorAccessorImpl) Refresh() (delegatorsTable []string, delegatorNodes []*discover.Node, e error) {\n\t// call delegatorList()\n\tdata, err0 := d.dappabi.Pack(\"delegatorList\")\n\tif err0 != nil {\n\t\tlog.Error(\"Error to encode delegatorList function call.\")\n\t\treturn nil,nil, errors.New(\"Error to encode delegatorList function call.\")\n\t}\n\t//var data = common.Hex2Bytes(\"0x61b29d69\")\n\tvar result string;\n\toutput, err0 := d.doCall(data);\n\tif err0 != nil {\n\t\tlog.Error(\"Error to call delegatorList function.\")\n\t\treturn nil,nil, errors.New(\"Error to call delegatorList function.\")\n\t}\n\tif len(output) == 0 {\n\t\t// no result\n\t\treturn nil,nil, errors.New(\"Delegator list must not be empty! the state of this node is incorrect.\")\n\t}\n\terr0 = d.dappabi.Unpack(&result, \"result\", output)\n\tif err0 != nil {\n\t\tlog.Error(\"Error to parse the result of delegatorList function.\")\n\t\treturn nil,nil, errors.New(\"Error to parse the result of delegatorList function.\")\n\t}\n\tif len(result) == 0 {\n\t\tlog.Error(\"Delegator list must not be empty! the state of this node is incorrect.\")\n\t\treturn nil,nil, errors.New(\"Delegator list must not be empty! the state of this node is incorrect.\")\n\t}\n\n\tdelegatorIds := strings.Split(result, \";\")\n\tids := make([]string, len(delegatorIds))\n\tpeerinfo := make([]*discover.Node, len(delegatorIds))\n\tfor i,delegatorId := range delegatorIds {\n\t\t// call delegatorInfo(string) 0x6162630000000000000000000000000000000000000000000000000000000000\n\t\tdata1, err0 := d.dappabi.Pack(\"delegatorInfo\", delegatorId)\n\t\tif err0 != nil {\n\t\t\tlog.Error(\"Error to parse delegatorInfo function.\")\n\t\t\treturn nil,nil, errors.New(\"Error to parse delegatorInfo function.\")\n\t\t}\n\t\toutput1, err0 := d.doCall(data1)\n\t\tif err0 != nil {\n\t\t\tlog.Error(\"Error to call delegatorInfo function.\")\n\t\t\treturn nil,nil, errors.New(\"Error to call delegatorInfo function.\")\n\t\t}\n\t\tvar result DelegatedNodeInfoMapping\n\t\t//string ip, uint port, uint256 ticket\n\t\terr0 = d.dappabi.Unpack(&result, \"result\", output1)\n\t\tif err0 != nil {\n\t\t\tlog.Error(\"Error to parse the result of delegatorInfo function.\")\n\t\t\treturn nil,nil, errors.New(\"Error to parse the result of delegatorInfo function.\")\n\t\t}\n\t\tids[i] = delegatorId\n\t\tpeerinfo[i] = &discover.Node{}\n\t}\n\treturn ids, peerinfo, nil;\n}", "func (w *Wallet) AllAddress() []string {\n\tadrs := make([]string, 0, len(w.AddressChange)+len(w.AddressPublic))\n\tfor adr := range w.AddressChange {\n\t\tadrs = append(adrs, adr)\n\t}\n\tfor adr := range w.AddressPublic {\n\t\tadrs = append(adrs, adr)\n\t}\n\treturn adrs\n}", "func (c *Client) ListContacts() ([]string, error) {\n\tvar contacts []string\n\tif !c.authenticated {\n\t\treturn contacts, errors.New(\"Not authenticated. Call Authenticate first\")\n\t}\n\n\tvar payload map[string]interface{}\n\tmsg := common.NewMessage(c.userId, \"server\",\n\t\t\"control\", \"list_contacts\", time.Time{},\n\t\tcommon.TEXT, payload)\n\n\tencoded, err := msg.Json()\n\tif err != nil {\n\t\tlog.Println(\"Failed to encode auth message\", err)\n\t\treturn contacts, err\n\t}\n\n\terr = c.transport.SendText(string(encoded))\n\tif err != nil {\n\t\tlog.Println(\"Failed to send auth message\", err)\n\t\treturn contacts, err\n\t}\n\n\tresp := <-c.Out\n\tif resp.Status() == common.STATUS_ERROR {\n\t\terrMsg := resp.Error()\n\t\tlog.Println(\"List contacts response error\", errMsg)\n\t\treturn contacts, errors.New(errMsg)\n\t}\n\n\tcontactsData := resp.GetJsonData(\"contacts\")\n\trawContacts, ok := contactsData.([]interface{})\n\tif !ok {\n\t\treturn contacts, errors.New(\"Failed to parse contacts response\")\n\t}\n\n\tfor _, rawContact := range rawContacts {\n\t\tcontact, ok := rawContact.(string)\n\t\tif !ok {\n\t\t\tlog.Println(\"Failed to parse contact\", rawContact)\n\t\t\tcontinue\n\t\t}\n\n\t\tcontacts = append(contacts, contact)\n\t}\n\n\treturn contacts, nil\n}" ]
[ "0.6751268", "0.65148604", "0.65049374", "0.6462457", "0.64011145", "0.6383402", "0.6363151", "0.61207974", "0.5957197", "0.58731973", "0.58478343", "0.58478343", "0.56725484", "0.5630004", "0.55782485", "0.55580693", "0.55544454", "0.5553972", "0.55465347", "0.5504419", "0.5444517", "0.53744453", "0.53470576", "0.53270143", "0.52758425", "0.52753204", "0.5247155", "0.5239122", "0.52197117", "0.51798874", "0.51513875", "0.51428", "0.5142703", "0.5139103", "0.50989777", "0.505485", "0.50326306", "0.49904448", "0.49884424", "0.4978198", "0.49741974", "0.49342346", "0.49325693", "0.49295047", "0.49271792", "0.49260518", "0.49184236", "0.49115106", "0.49015856", "0.48775685", "0.4877042", "0.48710063", "0.48696503", "0.4863226", "0.4849958", "0.4830662", "0.48292994", "0.482375", "0.48232654", "0.48225164", "0.48160255", "0.47991604", "0.47860226", "0.47847217", "0.47802", "0.47416896", "0.4730705", "0.46944875", "0.4689823", "0.4667632", "0.46623665", "0.46282068", "0.45816422", "0.45755553", "0.45680442", "0.45655337", "0.455065", "0.45452693", "0.45439887", "0.4535511", "0.4535511", "0.4526075", "0.45211303", "0.45149955", "0.45108145", "0.4497804", "0.44942454", "0.44934174", "0.44932523", "0.44911677", "0.44868258", "0.44743377", "0.44725513", "0.44712418", "0.44523653", "0.4450041", "0.44484702", "0.44461876", "0.4441268", "0.4436704" ]
0.72631353
0
/ Description: Takes a commitment, and calculates the GrossPayout, NetPayout, and Fee. Param commitment (Commitment): The commitment we are doing the operation on. Param rate (float64): The delegation percentage fee written as decimal. Param totalNodeRewards: Total rewards for the cyle the commitment represents. //TODO Make function to get total rewards for delegate in cycle Param delegate (bool): Is this the delegate Returns (Commitment): Returns a commitment with the calculations made Note: This function assumes Commitment.SharePercentage is already calculated.
func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{ ////-------------JUST FOR TESTING -------------//// totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11 ////--------------END TESTING ------------------//// grossRewards := contract.SharePercentage * float64(totalNodeRewards) contract.GrossPayout = grossRewards fee := rate * grossRewards contract.Fee = fee var netRewards float64 if (delegate){ netRewards = grossRewards contract.NetPayout = netRewards contract.Fee = 0 } else { netRewards = grossRewards - fee contract.NetPayout = contract.NetPayout + netRewards } return contract }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func calculateRewards(delegationTotal loom.BigUInt, params *Params, totalValidatorDelegations loom.BigUInt) loom.BigUInt {\n\tcycleSeconds := params.ElectionCycleLength\n\treward := CalculateFraction(blockRewardPercentage, delegationTotal)\n\n\t// If totalValidator Delegations are high enough to make simple reward\n\t// calculations result in more rewards given out than the value of `MaxYearlyReward`,\n\t// scale the rewards appropriately\n\tyearlyRewardTotal := CalculateFraction(blockRewardPercentage, totalValidatorDelegations)\n\tif yearlyRewardTotal.Cmp(&params.MaxYearlyReward.Value) > 0 {\n\t\treward.Mul(&reward, &params.MaxYearlyReward.Value)\n\t\treward.Div(&reward, &yearlyRewardTotal)\n\t}\n\n\t// When election cycle = 0, estimate block time at 2 sec\n\tif cycleSeconds == 0 {\n\t\tcycleSeconds = 2\n\t}\n\treward.Mul(&reward, &loom.BigUInt{big.NewInt(cycleSeconds)})\n\treward.Div(&reward, &secondsInYear)\n\n\treturn reward\n}", "func rewardRate(pool sdk.Coins, blocks int64) sdk.Coins {\n\tcoins := make([]sdk.Coin, 0)\n\tif blocks > 0 {\n\t\tfor _, coin := range pool {\n\t\t\tif coin.IsZero() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// divide by blocks, rounding fractions up\n\t\t\t// (coin.Amount - 1)/blocks + 1\n\t\t\trate := coin.Amount.SubRaw(1).QuoRaw(blocks).AddRaw(1)\n\t\t\tcoins = append(coins, sdk.NewCoin(coin.GetDenom(), rate))\n\t\t}\n\t}\n\treturn sdk.NewCoins(coins...)\n}", "func CalculateBorrowRate(model types.InterestRateModel, cash, borrows, reserves sdk.Dec) (sdk.Dec, error) {\n\tutilRatio := CalculateUtilizationRatio(cash, borrows, reserves)\n\n\t// Calculate normal borrow rate (under kink)\n\tif utilRatio.LTE(model.Kink) {\n\t\treturn utilRatio.Mul(model.BaseMultiplier).Add(model.BaseRateAPY), nil\n\t}\n\n\t// Calculate jump borrow rate (over kink)\n\tnormalRate := model.Kink.Mul(model.BaseMultiplier).Add(model.BaseRateAPY)\n\texcessUtil := utilRatio.Sub(model.Kink)\n\treturn excessUtil.Mul(model.JumpMultiplier).Add(normalRate), nil\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (_CrToken *CrTokenCallerSession) BorrowRatePerBlock() (*big.Int, error) {\n\treturn _CrToken.Contract.BorrowRatePerBlock(&_CrToken.CallOpts)\n}", "func (_Smartchef *SmartchefCallerSession) RewardPerBlock() (*big.Int, error) {\n\treturn _Smartchef.Contract.RewardPerBlock(&_Smartchef.CallOpts)\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func (_Smartchef *SmartchefSession) RewardPerBlock() (*big.Int, error) {\n\treturn _Smartchef.Contract.RewardPerBlock(&_Smartchef.CallOpts)\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func (_CrToken *CrTokenSession) BorrowRatePerBlock() (*big.Int, error) {\n\treturn _CrToken.Contract.BorrowRatePerBlock(&_CrToken.CallOpts)\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func (_EtherDelta *EtherDeltaCallerSession) FeeRebate() (*big.Int, error) {\n\treturn _EtherDelta.Contract.FeeRebate(&_EtherDelta.CallOpts)\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func (_EtherDelta *EtherDeltaSession) FeeRebate() (*big.Int, error) {\n\treturn _EtherDelta.Contract.FeeRebate(&_EtherDelta.CallOpts)\n}", "func (k Keeper) calculatePayment(ctx sdk.Context, owed, fees, payment sdk.Coin) (sdk.Coin, sdk.Coin) {\n\t// divides repayment into principal and fee components, with fee payment applied first.\n\n\tfeePayment := sdk.NewCoin(payment.Denom, sdk.ZeroInt())\n\tprincipalPayment := sdk.NewCoin(payment.Denom, sdk.ZeroInt())\n\tvar overpayment sdk.Coin\n\t// return zero value coins if payment amount is invalid\n\tif !payment.Amount.IsPositive() {\n\t\treturn feePayment, principalPayment\n\t}\n\t// check for over payment\n\tif payment.Amount.GT(owed.Amount) {\n\t\toverpayment = payment.Sub(owed)\n\t\tpayment = payment.Sub(overpayment)\n\t}\n\t// if no fees, 100% of payment is principal payment\n\tif fees.IsZero() {\n\t\treturn feePayment, payment\n\t}\n\t// pay fees before repaying principal\n\tif payment.Amount.GT(fees.Amount) {\n\t\tfeePayment = fees\n\t\tprincipalPayment = payment.Sub(fees)\n\t} else {\n\t\tfeePayment = payment\n\t}\n\treturn feePayment, principalPayment\n}", "func (_CrToken *CrTokenCaller) BorrowRatePerBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"borrowRatePerBlock\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Smartchef *SmartchefCaller) RewardPerBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"rewardPerBlock\")\n\treturn *ret0, err\n}", "func computeReward(epoch abi.ChainEpoch, prevTheta, currTheta, simpleTotal, baselineTotal big.Int) abi.TokenAmount {\n\tsimpleReward := big.Mul(simpleTotal, ExpLamSubOne) //Q.0 * Q.128 => Q.128\n\tepochLam := big.Mul(big.NewInt(int64(epoch)), Lambda) // Q.0 * Q.128 => Q.128\n\n\tsimpleReward = big.Mul(simpleReward, big.NewFromGo(math.ExpNeg(epochLam.Int))) // Q.128 * Q.128 => Q.256\n\tsimpleReward = big.Rsh(simpleReward, math.Precision128) // Q.256 >> 128 => Q.128\n\n\tbaselineReward := big.Sub(computeBaselineSupply(currTheta, baselineTotal), computeBaselineSupply(prevTheta, baselineTotal)) // Q.128\n\n\treward := big.Add(simpleReward, baselineReward) // Q.128\n\n\treturn big.Rsh(reward, math.Precision128) // Q.128 => Q.0\n}", "func (_Bindings *BindingsCallerSession) BorrowRatePerBlock() (*big.Int, error) {\n\treturn _Bindings.Contract.BorrowRatePerBlock(&_Bindings.CallOpts)\n}", "func (_EtherDelta *EtherDeltaCaller) FeeRebate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _EtherDelta.contract.Call(opts, out, \"feeRebate\")\n\treturn *ret0, err\n}", "func (node *TreeNode) backpropagateReward(scores [2]float64) {\n\tcurrentNode := node\n\tfor currentNode.Parent != nil {\n\t\tcurrentNode.VisitCount += 1.0\n\t\tcurrentNode.CumulativeScore[0] += scores[0]\n\t\tcurrentNode.CumulativeScore[1] += scores[1]\n\t\tcurrentNode = currentNode.Parent\n\t}\n\t//Increment root node counter\n\tcurrentNode.VisitCount += 1.0\n}", "func (k Keeper) AllocateTokens(ctx sdk.Context, percentVotes sdk.Dec, proposer sdk.ConsAddress) {\n\tlogger := ctx.Logger()\n\t// get the proposer of this block\n\tproposerValidator := k.stakeKeeper.ValidatorByConsAddr(ctx, proposer)\n\n\tif proposerValidator == nil {\n\t\tpanic(fmt.Sprintf(\"Can't find proposer %s in validator set\", proposerValidator.GetConsAddr()))\n\t}\n\n\tproposerDist := k.GetValidatorDistInfo(ctx, proposerValidator.GetOperator())\n\n\t// get the fees which have been getting collected through all the\n\t// transactions in the block\n\tfeesCollected := k.feeKeeper.GetCollectedFees(ctx)\n\tfeesCollectedDec := types.NewDecCoins(feesCollected)\n\n\tlogger.Info(\"Get collected transaction fee token and minted token\", \"collected_token\", feesCollected)\n\n\tfeePool := k.GetFeePool(ctx)\n\tif k.stakeKeeper.GetLastTotalPower(ctx).IsZero() {\n\t\tk.bankKeeper.AddCoins(ctx, auth.CommunityTaxCoinsAccAddr, feesCollected)\n\t\t//\t\tfeePool.CommunityPool = feePool.CommunityPool.Add(feesCollectedDec)\n\t\t//\t\tk.SetFeePool(ctx, feePool)\n\t\tk.feeKeeper.ClearCollectedFees(ctx)\n\t\tctx.CoinFlowTags().AppendCoinFlowTag(ctx, \"\", auth.CommunityTaxCoinsAccAddr.String(), feesCollected.String(), sdk.CommunityTaxCollectFlow, \"\")\n\t\treturn\n\t}\n\n\tvar proposerReward types.DecCoins\n\t// If a validator is jailed, distribute no reward to it\n\t// The jailed validator happen to be a proposer which is a very corner case\n\tvalidator := k.stakeKeeper.Validator(ctx, proposerValidator.GetOperator())\n\tif !validator.GetJailed() {\n\t\t// allocated rewards to proposer\n\t\tlogger.Info(\"Allocate reward to proposer\", \"proposer_address\", proposerValidator.GetOperator().String())\n\t\tbaseProposerReward := k.GetBaseProposerReward(ctx)\n\t\tbonusProposerReward := k.GetBonusProposerReward(ctx)\n\t\tproposerMultiplier := baseProposerReward.Add(bonusProposerReward.Mul(percentVotes))\n\t\tproposerReward = feesCollectedDec.MulDec(proposerMultiplier)\n\n\t\t// apply commission\n\t\tcommission := proposerReward.MulDec(proposerValidator.GetCommission())\n\t\tremaining := proposerReward.Minus(commission)\n\t\tproposerDist.ValCommission = proposerDist.ValCommission.Plus(commission)\n\t\tproposerDist.DelPool = proposerDist.DelPool.Plus(remaining)\n\t\tlogger.Info(\"Allocate commission to proposer commission pool\", \"commission\", commission.ToString())\n\t\tlogger.Info(\"Allocate reward to proposer delegation reward pool\", \"delegation_reward\", remaining.ToString())\n\n\t\t// save validator distribution info\n\t\tk.SetValidatorDistInfo(ctx, proposerDist)\n\t} else {\n\t\tlogger.Info(\"The block proposer is jailed, distribute no reward to it\", \"proposer_address\", proposerValidator.GetOperator().String())\n\t}\n\n\t// allocate community funding\n\tcommunityTax := k.GetCommunityTax(ctx)\n\tcommunityFunding := feesCollectedDec.MulDec(communityTax)\n\n\t//\tfeePool.CommunityPool = feePool.CommunityPool.Add(communityFunding)\n\tfundingCoins, change := communityFunding.TruncateDecimal()\n\tk.bankKeeper.AddCoins(ctx, auth.CommunityTaxCoinsAccAddr, fundingCoins)\n\tctx.CoinFlowTags().AppendCoinFlowTag(ctx, \"\", auth.CommunityTaxCoinsAccAddr.String(), fundingCoins.String(), sdk.CommunityTaxCollectFlow, \"\")\n\n\tcommunityTaxCoins := k.bankKeeper.GetCoins(ctx, auth.CommunityTaxCoinsAccAddr)\n\tcommunityTaxDec := sdk.NewDecFromInt(communityTaxCoins.AmountOf(sdk.IrisAtto))\n\tcommunityTaxFloat, err := strconv.ParseFloat(communityTaxDec.QuoInt(sdk.AttoScaleFactor).String(), 64)\n\t//communityTaxAmount, err := strconv.ParseFloat(feePool.CommunityPool.AmountOf(sdk.IrisAtto).QuoInt(sdk.AttoScaleFactor).String(), 64)\n\tif err == nil {\n\t\tk.metrics.CommunityTax.Set(communityTaxFloat)\n\t}\n\n\tlogger.Info(\"Allocate reward to community tax fund\", \"allocate_amount\", fundingCoins.String(), \"total_community_tax\", communityTaxCoins.String())\n\n\t// set the global pool within the distribution module\n\tpoolReceived := feesCollectedDec.Minus(proposerReward).Minus(communityFunding).Plus(change)\n\tfeePool.ValPool = feePool.ValPool.Plus(poolReceived)\n\tk.SetFeePool(ctx, feePool)\n\n\tlogger.Info(\"Allocate reward to global validator pool\", \"allocate_amount\", poolReceived.ToString(), \"total_global_validator_pool\", feePool.ValPool.ToString())\n\n\t// clear the now distributed fees\n\tk.feeKeeper.ClearCollectedFees(ctx)\n}", "func DisplayCalculatedVoteRatio() {\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tdeleResp, _, _ := arkclient.GetDelegate(params)\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\tshareRatioStr := strconv.FormatFloat(viper.GetFloat64(\"voters.shareratio\")*100, 'f', -1, 64) + \"%\"\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Displaying voter information for delegate:\", deleResp.SingleDelegate.Username, deleResp.SingleDelegate.Address)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(fmt.Sprintf(\"|%-34s|%18s|%8s|%17s|%17s|%6s|\", \"Voter address\", \"Balance\", \"Weight\", \"Reward-100%\", \"Reward-\"+shareRatioStr, \"Hours\"))\n\tcolor.Set(color.FgCyan)\n\tfor _, element := range votersEarnings {\n\t\ts := fmt.Sprintf(\"|%s|%18.8f|%8.4f|%15.8f A|%15.8f A|%6d|\", element.Address, element.VoteWeight, element.VoteWeightShare, element.EarnedAmount100, element.EarnedAmountXX, element.VoteDuration)\n\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\t}\n\n\t//Cost calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"Available amount:\", sumEarned)\n\tfmt.Println(\"Amount to voters:\", sumShareEarned, viper.GetFloat64(\"voters.shareratio\"))\n\tfmt.Println(\"Amount to costs:\", costAmount, viper.GetFloat64(\"costs.shareratio\"))\n\tfmt.Println(\"Amount to reserve:\", reserveAmount, viper.GetFloat64(\"reserve.shareratio\"))\n\n\tfmt.Println(\"Ratio calc check:\", sumRatio, \"(should be = 1)\")\n\tfmt.Println(\"Ratio share check:\", float64(sumShareEarned)/float64(sumEarned), \"should be=\", viper.GetFloat64(\"voters.shareratio\"))\n\n\tpause()\n}", "func (u *utxoNursery) incubator(newBlockChan *chainntnfs.BlockEpochEvent,\n\tstartingHeight uint32) {\n\n\tdefer u.wg.Done()\n\tdefer newBlockChan.Cancel()\n\n\tcurrentHeight := startingHeight\nout:\n\tfor {\n\t\tselect {\n\n\t\tcase preschoolRequest := <-u.requests:\n\t\t\tutxnLog.Infof(\"Incubating %v new outputs\",\n\t\t\t\tlen(preschoolRequest.outputs))\n\n\t\t\tfor _, output := range preschoolRequest.outputs {\n\t\t\t\t// We'll skip any zero value'd outputs as this\n\t\t\t\t// indicates we don't have a settled balance\n\t\t\t\t// within the commitment transaction.\n\t\t\t\tif output.amt == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tsourceTxid := output.outPoint.Hash\n\n\t\t\t\tif err := output.enterPreschool(u.db); err != nil {\n\t\t\t\t\tutxnLog.Errorf(\"unable to add kidOutput to preschool: %v, %v \",\n\t\t\t\t\t\toutput, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Register for a notification that will\n\t\t\t\t// trigger graduation from preschool to\n\t\t\t\t// kindergarten when the channel close\n\t\t\t\t// transaction has been confirmed.\n\t\t\t\tconfChan, err := u.notifier.RegisterConfirmationsNtfn(\n\t\t\t\t\t&sourceTxid, 1, currentHeight,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tutxnLog.Errorf(\"unable to register output for confirmation: %v\",\n\t\t\t\t\t\tsourceTxid)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Launch a dedicated goroutine that will move\n\t\t\t\t// the output from the preschool bucket to the\n\t\t\t\t// kindergarten bucket once the channel close\n\t\t\t\t// transaction has been confirmed.\n\t\t\t\tgo output.waitForPromotion(u.db, confChan)\n\t\t\t}\n\n\t\tcase epoch, ok := <-newBlockChan.Epochs:\n\t\t\t// If the epoch channel has been closed, then the\n\t\t\t// ChainNotifier is exiting which means the daemon is\n\t\t\t// as well. Therefore, we exit early also in order to\n\t\t\t// ensure the daemon shuts down gracefully, yet\n\t\t\t// swiftly.\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// TODO(roasbeef): if the BlockChainIO is rescanning\n\t\t\t// will give stale data\n\n\t\t\t// A new block has just been connected to the main\n\t\t\t// chain which means we might be able to graduate some\n\t\t\t// outputs out of the kindergarten bucket. Graduation\n\t\t\t// entails successfully sweeping a time-locked output.\n\t\t\theight := uint32(epoch.Height)\n\t\t\tcurrentHeight = height\n\t\t\tif err := u.graduateKindergarten(height); err != nil {\n\t\t\t\tutxnLog.Errorf(\"error while graduating \"+\n\t\t\t\t\t\"kindergarten outputs: %v\", err)\n\t\t\t}\n\n\t\tcase <-u.quit:\n\t\t\tbreak out\n\t\t}\n\t}\n}", "func payout(delegate string, operator string) string {\n\t// get operator's address\n\toperator_addr, err := alias.Address(operator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// get delegate's name to 12-byte array\n\tdelegate_name := delegateName(delegate)\n\n\trs := calculateRewardShares(operator_addr, delegate_name, epochToQuery)\n\n\t// prepare input for multisend\n\t// https://member.iotex.io/multi-send\n\tvar voters []string\n\tvar rewards []string\n\n\tstradd := func(a string, b string, c string) string {\n\t\taa, _ := new(big.Int).SetString(a, 10)\n\t\tbb, _ := new(big.Int).SetString(b, 10)\n\t\tcc, _ := new(big.Int).SetString(c, 10)\n\t\treturn cc.Add(aa.Add(aa, bb), cc).Text(10)\n\t}\n\n\tfor _, share := range rs.Shares {\n\t\tvoters = append(voters, \"0x\" + share.ETHAddr)\n\t\trewards = append(rewards, stradd(\n\t\t\t\t\t\tshare.Reward.Block,\n\t\t\t\t\t\tshare.Reward.FoundationBonus,\n\t\t\t\t\t\tshare.Reward.EpochBonus))\n\t}\n\n\tvar sent []MultisendReward\n\tfor i, a := range rewards {\n\t\tamount, _ := new(big.Int).SetString(a, 10)\n\t\tsent = append(sent, MultisendReward{voters[i],\n\t\t\t\t\tutil.RauToString(amount, util.IotxDecimalNum)})\n\t}\n\ts, _ := json.Marshal(sent)\n\tfmt.Println(string(s))\n\n\treturn rs.String()\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_Bindings *BindingsSession) BorrowRatePerBlock() (*big.Int, error) {\n\treturn _Bindings.Contract.BorrowRatePerBlock(&_Bindings.CallOpts)\n}", "func (c *ETHController) Reveal(opts *bind.TransactOpts, domain string, owner common.Address, secret [32]byte) (*types.Transaction, error) {\n\tname, err := UnqualifiedName(domain, c.domain)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid name %s\", domain)\n\t}\n\n\tif opts == nil {\n\t\treturn nil, errors.New(\"transaction options required\")\n\t}\n\tif opts.Value == nil {\n\t\treturn nil, errors.New(\"no ether supplied with transaction\")\n\t}\n\n\tcommitTS, err := c.CommitmentTime(name, owner, secret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif commitTS.Cmp(big.NewInt(0)) == 0 {\n\t\treturn nil, errors.New(\"no commitment present\")\n\t}\n\tcommit := time.Unix(commitTS.Int64(), 0)\n\n\tminCommitIntervalTS, err := c.MinCommitmentInterval()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tminCommitInterval := time.Duration(minCommitIntervalTS.Int64()) * time.Second\n\tminRevealTime := commit.Add(minCommitInterval)\n\tif time.Now().Before(minRevealTime) {\n\t\treturn nil, errors.New(\"commitment too young to reveal\")\n\t}\n\n\tmaxCommitIntervalTS, err := c.MaxCommitmentInterval()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmaxCommitInterval := time.Duration(maxCommitIntervalTS.Int64()) * time.Second\n\tmaxRevealTime := commit.Add(maxCommitInterval)\n\tif time.Now().After(maxRevealTime) {\n\t\treturn nil, errors.New(\"commitment too old to reveal\")\n\t}\n\n\t// Calculate the duration given the rent cost and the value\n\tcostPerSecond, err := c.RentCost(domain)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to obtain rent cost\")\n\t}\n\tduration := new(big.Int).Div(opts.Value, costPerSecond)\n\n\t// Ensure duration is greater than minimum duration\n\tminDuration, err := c.MinRegistrationDuration()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif big.NewInt(int64(minDuration.Seconds())).Cmp(duration) >= 0 {\n\t\treturn nil, fmt.Errorf(\"not enough funds to cover minimum duration of %v\", minDuration)\n\t}\n\n\treturn c.Contract.Register(opts, name, owner, duration, secret)\n}", "func (dcr *ExchangeWallet) feeRate(confTarget uint64) (uint64, error) {\n\t// estimatesmartfee 1 returns extremely high rates on DCR.\n\tif confTarget < 2 {\n\t\tconfTarget = 2\n\t}\n\tdcrPerKB, err := dcr.node.EstimateSmartFee(dcr.ctx, int64(confTarget), chainjson.EstimateSmartFeeConservative)\n\tif err != nil {\n\t\treturn 0, translateRPCCancelErr(err)\n\t}\n\tatomsPerKB, err := dcrutil.NewAmount(dcrPerKB) // satPerKB is 0 when err != nil\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t// Add 1 extra atom/byte, which is both extra conservative and prevents a\n\t// zero value if the atoms/KB is less than 1000.\n\treturn 1 + uint64(atomsPerKB)/1000, nil // dcrPerKB * 1e8 / 1e3\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func (_CrToken *CrTokenTransactor) RepayBorrow(opts *bind.TransactOpts, repayAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.contract.Transact(opts, \"repayBorrow\", repayAmount)\n}", "func calculateEpochRewardShares(operator string, delegate []byte, epoch_num uint64) *RewardShares {\n\t// get epoch response\n\tgetEpochResponse(epoch_num)\n\n\t// get gravity height\n\tgravity_height := epochGravityHeight()\n\n\t// get number of produced blocks\n\tblocks := delegateProductivity(operator)\n\n\t// get delegate's votes\n\tvotes_distribution, elected, delegate_votes, total_votes := getVotes(delegate, gravity_height)\n\n\t// calculate reward\n\treward := calculateReward(blocks, elected, delegate_votes, total_votes)\n\n\t// populate rewardshare structure\n\treturn NewRewardShares().\n\t\tSetEpochNum(strconv.FormatUint(epoch_num, 10)).\n\t\tSetProductivity(blocks).\n\t\tSetTotalVotes(delegate_votes).\n\t\tSetReward(reward).\n\t\tCalculateShares(votes_distribution, delegate_votes, epoch_num)\n}", "func (k Keeper) CalculateCollateralToDebtRatio(ctx sdk.Context, collateral sdk.Coins, debt sdk.Coins) sdk.Dec {\n\tdebtTotal := sdk.ZeroDec()\n\tfor _, dc := range debt {\n\t\tdebtBaseUnits := k.convertDebtToBaseUnits(ctx, dc)\n\t\tdebtTotal = debtTotal.Add(debtBaseUnits)\n\t}\n\n\tif debtTotal.IsZero() || debtTotal.GTE(types.MaxSortableDec) {\n\t\treturn types.MaxSortableDec.Sub(sdk.SmallestDec())\n\t}\n\n\tcollateralBaseUnits := k.convertCollateralToBaseUnits(ctx, collateral[0])\n\treturn collateralBaseUnits.Quo(debtTotal)\n}", "func calculateRewardShares(operator string, delegate []byte, epochs string) *RewardShares {\n\tif epochs == \"\" {\n\t\treturn calculateEpochRewardShares(\n\t\t\toperator, delegate, currentEpochNum())\n\t}\n\n\t// parse a range of epochs\n\tresult := NewRewardShares()\n\tresult.SetEpochNum(epochs)\n\tfor epoch := range epochRangeGen(epochs) {\n\t\tfmt.Printf(\"epoch: %v\\n\", epoch)\n\t\treward := calculateEpochRewardShares(operator, delegate, epoch)\n\t\tresult = result.Combine(reward)\n\t}\n\treturn result\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {\n\t// TODO: implement mining rewards\n}", "func AnnualBalanceUpdate(balance float64) float64 {\n\treturn balance + Interest(balance)\n}", "func (_Lmc *LmcCallerSession) RewardPerBlock(arg0 *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.RewardPerBlock(&_Lmc.CallOpts, arg0)\n}", "func calcBumpedRate(baseRate uint64, bump *float64) (uint64, error) {\n\tif bump == nil {\n\t\treturn baseRate, nil\n\t}\n\tuserBump := *bump\n\tif userBump > 2.0 {\n\t\treturn baseRate, fmt.Errorf(\"fee bump %f is higher than the 2.0 limit\", userBump)\n\t}\n\tif userBump < 1.0 {\n\t\treturn baseRate, fmt.Errorf(\"fee bump %f is lower than 1\", userBump)\n\t}\n\treturn uint64(math.Round(float64(baseRate) * userBump)), nil\n}", "func (_Lmc *LmcSession) RewardPerBlock(arg0 *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.RewardPerBlock(&_Lmc.CallOpts, arg0)\n}", "func EstimateReward(reward, pr, gamma float64) float64 {\n\tret := reward / (pr + gamma)\n\tlog.Logf(MABLogLevel, \"MAB Estimate Reward: %v / (%v + %v) = %v\\n\",\n\t\treward, pr, gamma, ret)\n\treturn ret\n}", "func (_Dospayment *DospaymentCaller) NodeFeeBalance(opts *bind.CallOpts, nodeAddr common.Address, tokenAddr common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Dospayment.contract.Call(opts, out, \"nodeFeeBalance\", nodeAddr, tokenAddr)\n\treturn *ret0, err\n}", "func (_CrToken *CrTokenTransactorSession) RepayBorrow(repayAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.RepayBorrow(&_CrToken.TransactOpts, repayAmount)\n}", "func (s *ArkClient) CalculateVotersProfit(params DelegateQueryParams, shareRatio float64, blocklist string, whitelist string, capBalance bool, balanceCapAmount float64, blockBalanceCap bool) []DelegateDataProfit {\n\tdelegateRes, _, _ := s.GetDelegate(params)\n\tvoters, _, _ := s.GetDelegateVoters(params)\n\taccountRes, _, _ := s.GetAccount(AccountQueryParams{Address: delegateRes.SingleDelegate.Address})\n\n\tdelegateBalance, _ := strconv.ParseFloat(accountRes.Account.Balance, 64)\n\tdelegateBalance = float64(delegateBalance) / SATOSHI\n\n\t//calculating vote weight\n\tvotersProfit := []DelegateDataProfit{}\n\tdelelgateVoteWeight := 0\n\n\t//computing summ of all votes\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tintBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tintBalance = int(balanceCapAmount)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelelgateVoteWeight += intBalance\n\t}\n\n\t//calculating\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tcurrentVoterBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcurrentVoterBalance = balanceCapAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdeleProfit := DelegateDataProfit{\n\t\t\tAddress: element.Address,\n\t\t}\n\t\tdeleProfit.VoteWeight = currentVoterBalance / SATOSHI\n\t\tdeleProfit.VoteWeightShare = float64(currentVoterBalance) / float64(delelgateVoteWeight)\n\t\tdeleProfit.EarnedAmount100 = float64(delegateBalance) * deleProfit.VoteWeightShare\n\t\tdeleProfit.EarnedAmountXX = float64(delegateBalance) * deleProfit.VoteWeightShare * shareRatio\n\t\tdeleProfit.VoteDuration = s.GetVoteDuration(element.Address)\n\t\tvotersProfit = append(votersProfit, deleProfit)\n\t}\n\n\treturn votersProfit\n}", "func (k Keeper) RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, denom string, payment sdk.Coins) error {\n\t// validation\n\tcdp, found := k.GetCdpByOwnerAndDenom(ctx, owner, denom)\n\tif !found {\n\t\treturn sdkerrors.Wrapf(types.ErrCdpNotFound, \"owner %s, denom %s\", owner, denom)\n\t}\n\n\terr := k.ValidatePaymentCoins(ctx, cdp, payment, cdp.Principal.Add(cdp.AccumulatedFees...))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// calculate fee and principal payment\n\tfeePayment, principalPayment := k.calculatePayment(ctx, cdp.Principal.Add(cdp.AccumulatedFees...), cdp.AccumulatedFees, payment)\n\n\t// send the payment from the sender to the cpd module\n\terr = k.supplyKeeper.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, feePayment.Add(principalPayment...))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// burn the payment coins\n\terr = k.supplyKeeper.BurnCoins(ctx, types.ModuleName, feePayment.Add(principalPayment...))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// burn the corresponding amount of debt coins\n\tcdpDebt := k.getModAccountDebt(ctx, types.ModuleName)\n\tpaymentAmount := sdk.ZeroInt()\n\tfor _, c := range feePayment.Add(principalPayment...) {\n\t\tpaymentAmount = paymentAmount.Add(c.Amount)\n\t}\n\tcoinsToBurn := sdk.NewCoins(sdk.NewCoin(k.GetDebtDenom(ctx), paymentAmount))\n\tif paymentAmount.GT(cdpDebt) {\n\t\tcoinsToBurn = sdk.NewCoins(sdk.NewCoin(k.GetDebtDenom(ctx), cdpDebt))\n\t}\n\terr = k.BurnDebtCoins(ctx, types.ModuleName, k.GetDebtDenom(ctx), coinsToBurn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// emit repayment event\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCdpRepay,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, feePayment.Add(principalPayment...).String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t),\n\t)\n\n\t// remove the old collateral:debt ratio index\n\toldCollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Principal.Add(cdp.AccumulatedFees...))\n\tk.RemoveCdpCollateralRatioIndex(ctx, denom, cdp.ID, oldCollateralToDebtRatio)\n\n\t// update cdp state\n\tif !principalPayment.IsZero() {\n\t\tcdp.Principal = cdp.Principal.Sub(principalPayment)\n\t}\n\tcdp.AccumulatedFees = cdp.AccumulatedFees.Sub(feePayment)\n\tcdp.FeesUpdated = ctx.BlockTime()\n\n\t// decrement the total principal for the input collateral type\n\tk.DecrementTotalPrincipal(ctx, denom, feePayment.Add(principalPayment...))\n\n\t// if the debt is fully paid, return collateral to depositors,\n\t// and remove the cdp and indexes from the store\n\tif cdp.Principal.IsZero() && cdp.AccumulatedFees.IsZero() {\n\t\tk.ReturnCollateral(ctx, cdp)\n\t\tk.DeleteCDP(ctx, cdp)\n\t\tk.RemoveCdpOwnerIndex(ctx, cdp)\n\n\t\t// emit cdp close event\n\t\tctx.EventManager().EmitEvent(\n\t\t\tsdk.NewEvent(\n\t\t\t\ttypes.EventTypeCdpClose,\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t\t),\n\t\t)\n\t\treturn nil\n\t}\n\n\t// set cdp state and update indexes\n\tcollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Principal.Add(cdp.AccumulatedFees...))\n\tk.SetCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio)\n\treturn nil\n}", "func (_XStaking *XStakingCaller) RewardRate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewardRate\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func MiningRewardBalance(block consensus.Block, account []byte) *RTU {\n//\tif bytes, err := block.Lookup([]byte(bytesToHexString(account))); err == nil {\n\tif bytes, err := block.Lookup(account); err == nil {\n\t\treturn BytesToRtu(bytes)\n\t}\n\treturn BytesToRtu(nil)\n}", "func (_Bindings *BindingsTransactor) RepayBorrow(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Bindings.contract.Transact(opts, \"repayBorrow\")\n}", "func PaymentAmount(response http.ResponseWriter, request *http.Request) {\n\tif assertMethod(response, request, http.MethodGet) {\n\t\tparams := request.URL.Query()\n\t\tprincipal, err := currency.Parse(params.Get(\"askingPrice\"))\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(response, \"Invalid asking price %v (reason: %v)\", params.Get(\"askingPrice\"), err)\n\t\t}\n\t\tpaymentYears, err := currency.Parse(params.Get(\"paymentSchedule\"))\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(response, \"Invalid payment schedule %v (reason: %v)\", params.Get(\"paymentSchedule\"), err)\n\t\t}\n\n\t\tvar yearlyInterest float32 = 0.05\n\t\t// yearDuration := time.Hour * 24 * 365\n\t\tperiods := 12 * uint32(paymentYears)\n\t\tresponse.Header().Add(\"Content-Type\", \"text/html; charset=utf-8\")\n\t\tfmt.Fprintf(response, \"<tt>mortgage.CalculatePayments(%v, %v, %v)</tt>\", currency.UAmount(principal), yearlyInterest/float32(periods), periods)\n\t\tpayment := mortgage.CalculatePayments(currency.UAmount(principal), yearlyInterest/12, periods)\n\t\tfmt.Fprintf(response, \"You are paying <tt>%v</tt> over <tt>%v</tt> periods.\", payment, periods)\n\t}\n\n}", "func (k Keeper) DistributeSavingsRate(ctx sdk.Context, debtDenom string) error {\n\tdp, found := k.GetDebtParam(ctx, debtDenom)\n\tif !found {\n\t\treturn sdkerrors.Wrap(types.ErrDebtNotSupported, debtDenom)\n\t}\n\tsavingsRateMacc := k.supplyKeeper.GetModuleAccount(ctx, types.SavingsRateMacc)\n\tsurplusToDistribute := savingsRateMacc.GetCoins().AmountOf(dp.Denom)\n\tif surplusToDistribute.IsZero() {\n\t\treturn nil\n\t}\n\n\tmodAccountCoins := k.getModuleAccountCoins(ctx, dp.Denom)\n\ttotalSupplyLessModAccounts := k.supplyKeeper.GetSupply(ctx).GetTotal().Sub(modAccountCoins)\n\tsurplusDistributed := sdk.ZeroInt()\n\tvar iterationErr error\n\tk.accountKeeper.IterateAccounts(ctx, func(acc authexported.Account) (stop bool) {\n\t\t_, ok := acc.(supplyexported.ModuleAccountI)\n\t\tif ok {\n\t\t\t// don't distribute savings rate to module accounts\n\t\t\treturn false\n\t\t}\n\t\tdebtAmount := acc.GetCoins().AmountOf(debtDenom)\n\t\tif !debtAmount.IsPositive() {\n\t\t\treturn false\n\t\t}\n\t\t// (balance * rewardToDisribute) / totalSupply\n\t\t// interest is the ratable fraction of savings rate owed to that account, rounded using bankers rounding\n\t\tinterest := (sdk.NewDecFromInt(debtAmount).Mul(sdk.NewDecFromInt(surplusToDistribute))).Quo(sdk.NewDecFromInt(totalSupplyLessModAccounts.AmountOf(debtDenom))).RoundInt()\n\t\t// sanity check, if we are going to over-distribute due to rounding, distribute only the remaining savings rate that hasn't been distributed.\n\t\tif interest.GT(surplusToDistribute.Sub(surplusDistributed)) {\n\t\t\tinterest = surplusToDistribute.Sub(surplusDistributed)\n\t\t}\n\t\t// sanity check - don't send saving rate if the rounded amount is zero\n\t\tif !interest.IsPositive() {\n\t\t\treturn false\n\t\t}\n\t\tinterestCoins := sdk.NewCoins(sdk.NewCoin(debtDenom, interest))\n\t\terr := k.supplyKeeper.SendCoinsFromModuleToAccount(ctx, types.SavingsRateMacc, acc.GetAddress(), interestCoins)\n\t\tif err != nil {\n\t\t\titerationErr = err\n\t\t\treturn true\n\t\t}\n\t\tsurplusDistributed = surplusDistributed.Add(interest)\n\t\treturn false\n\t})\n\treturn iterationErr\n}", "func (_Bindings *BindingsCaller) BorrowRatePerBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"borrowRatePerBlock\")\n\treturn *ret0, err\n}", "func (rf *Raft) FollowerCommit(leaderCommit int, m int) {\n\t//fmt.Printf(\"hi:%v \\n\", p)\n\tp := rf.commitIndex\n\tif leaderCommit > rf.commitIndex {\n\t\tif leaderCommit < m {\n\t\t\trf.commitIndex = leaderCommit\n\t\t} else {\n\t\t\trf.commitIndex = m\n\t\t}\n\t}else{\n\t\t//fmt.Printf(\"leaderCommit:%v rf.commitIndex:%v \\n\", leaderCommit, rf.commitIndex)\n\t}\n\tfor p++; p <= rf.commitIndex; p++ {\n\t\trf.applyCh <- ApplyMsg{Index:p, Command:rf.log[p-rf.log[0].Index].Command}\n\t\trf.lastApplied = p\n\t}\n\t//fmt.Printf(\"done \\n\")\n\t//fmt.Printf(\"server %v term %v role %v last append %v \\n\", rf.me, rf.currentTerm, rf.role, rf.lastApplied)\n}", "func (t *trusteeImpl) NewMiningRewardTx(block consensus.Block) *consensus.Transaction {\n\tvar tx *consensus.Transaction\n\t// build list of miner nodes for uncle blocks\n\tuncleMiners := make([][]byte, len(block.UncleMiners()))\n\tfor i, uncleMiner := range block.UncleMiners() {\n\t\tuncleMiners[i] = uncleMiner\n\t}\n\t\n\tops := make([]Op, 1 + len(uncleMiners))\n\t// first add self's mining reward\n\tops[0] = *t.myReward\n\t\n\t// now add award for each uncle\n\tfor i, uncleMiner := range uncleMiners {\n\t\top := NewOp(OpReward)\n\t\top.Params[ParamUncle] = bytesToHexString(uncleMiner)\n\t\top.Params[ParamAward] = UncleAward\n\t\tops[i+1] = *op \n\t}\n\t// serialize ops into payload\n\tif payload,err := common.Serialize(ops); err != nil {\n\t\tt.log.Error(\"Failed to serialize ops into payload: %s\", err)\n\t\treturn nil\n\t} else {\n\t\t// make a signed transaction out of payload\n\t\tif signature := t.sign(payload); len(signature) > 0 {\n\t\t\t// return the signed transaction\n\t\t\ttx = consensus.NewTransaction(payload, signature, t.myAddress)\n\t\t\tblock.AddTransaction(tx)\n\t\t\tt.process(block, tx)\n\t\t}\n\t}\n\treturn tx\n}", "func (o ReservationResponseOutput) Commitment() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ReservationResponse) string { return v.Commitment }).(pulumi.StringOutput)\n}", "func (btc *ExchangeWallet) Redeem(redemptions []*asset.Redemption) ([]dex.Bytes, asset.Coin, error) {\n\t// Create a transaction that spends the referenced contract.\n\tmsgTx := wire.NewMsgTx(wire.TxVersion)\n\tvar totalIn uint64\n\tvar contracts [][]byte\n\tvar addresses []btcutil.Address\n\tfor _, r := range redemptions {\n\t\tcinfo, ok := r.Spends.(*auditInfo)\n\t\tif !ok {\n\t\t\treturn nil, nil, fmt.Errorf(\"Redemption contract info of wrong type\")\n\t\t}\n\t\t// Extract the swap contract recipient and secret hash and check the secret\n\t\t// hash against the hash of the provided secret.\n\t\t_, receiver, _, secretHash, err := dexbtc.ExtractSwapDetails(cinfo.output.redeem, btc.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error extracting swap addresses: %v\", err)\n\t\t}\n\t\tcheckSecretHash := sha256.Sum256(r.Secret)\n\t\tif !bytes.Equal(checkSecretHash[:], secretHash) {\n\t\t\treturn nil, nil, fmt.Errorf(\"secret hash mismatch\")\n\t\t}\n\t\taddresses = append(addresses, receiver)\n\t\tcontracts = append(contracts, cinfo.output.redeem)\n\t\tprevOut := wire.NewOutPoint(&cinfo.output.txHash, cinfo.output.vout)\n\t\ttxIn := wire.NewTxIn(prevOut, []byte{}, nil)\n\t\t// Enable locktime\n\t\t// https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki#Spending_wallet_policy\n\t\ttxIn.Sequence = wire.MaxTxInSequenceNum - 1\n\t\tmsgTx.AddTxIn(txIn)\n\t\ttotalIn += cinfo.output.value\n\t}\n\n\t// Calculate the size and the fees.\n\tsize := msgTx.SerializeSize() + dexbtc.RedeemSwapSigScriptSize*len(redemptions) + dexbtc.P2WPKHOutputSize\n\tfeeRate := btc.feeRateWithFallback()\n\tfee := feeRate * uint64(size)\n\tif fee > totalIn {\n\t\treturn nil, nil, fmt.Errorf(\"redeem tx not worth the fees\")\n\t}\n\t// Send the funds back to the exchange wallet.\n\tredeemAddr, err := btc.wallet.ChangeAddress()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error getting new address from the wallet: %v\", err)\n\t}\n\tpkScript, err := txscript.PayToAddrScript(redeemAddr)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error creating change script: %v\", err)\n\t}\n\ttxOut := wire.NewTxOut(int64(totalIn-fee), pkScript)\n\t// One last check for dust.\n\tif dexbtc.IsDust(txOut, feeRate) {\n\t\treturn nil, nil, fmt.Errorf(\"redeem output is dust\")\n\t}\n\tmsgTx.AddTxOut(txOut)\n\t// Sign the inputs.\n\tfor i, r := range redemptions {\n\t\tcontract := contracts[i]\n\t\tredeemSig, redeemPubKey, err := btc.createSig(msgTx, i, contract, addresses[i])\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tredeemSigScript, err := dexbtc.RedeemP2SHContract(contract, redeemSig, redeemPubKey, r.Secret)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tmsgTx.TxIn[i].SignatureScript = redeemSigScript\n\t}\n\t// Send the transaction.\n\tcheckHash := msgTx.TxHash()\n\ttxHash, err := btc.node.SendRawTransaction(msgTx, false)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif *txHash != checkHash {\n\t\treturn nil, nil, fmt.Errorf(\"redemption sent, but received unexpected transaction ID back from RPC server. \"+\n\t\t\t\"expected %s, got %s\", *txHash, checkHash)\n\t}\n\t// Log the change output.\n\tbtc.addChange(txHash.String(), 0)\n\tcoinIDs := make([]dex.Bytes, 0, len(redemptions))\n\tfor i := range redemptions {\n\t\tcoinIDs = append(coinIDs, toCoinID(txHash, uint32(i)))\n\t}\n\treturn coinIDs, newOutput(btc.node, txHash, 0, uint64(txOut.Value), nil), nil\n}", "func EstimatedRewards(request []string) (float64, error) {\n\tcoinId, err := strconv.ParseUint(request[0], 10, 64)\n\tif err != nil {\n\t\treturn 0.00, errors.New(\"Invalid coinid format\")\n\t}\n\n\twtmClient := NewWhatToMineClient(nil, BASE, userAgent)\n\twtmClient.SetDebug(debug)\n\tstatus, err := wtmClient.GetCoin(coinId, 1000000, 0, 0)\n\tif err != nil {\n\t\treturn 0.00, err\n\t}\n\treturn status.EstimatedRewards, nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) DepositRedelegatedAmount(opts *bind.CallOpts, operator common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"depositRedelegatedAmount\", operator)\n\treturn *ret0, err\n}", "func (u *utxoNursery) graduateKindergarten(blockHeight uint32) error {\n\t// First fetch the set of outputs that we can \"graduate\" at this\n\t// particular block height. We can graduate an output once we've\n\t// reached its height maturity.\n\tkgtnOutputs, err := fetchGraduatingOutputs(u.db, u.wallet, blockHeight)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If we're able to graduate any outputs, then create a single\n\t// transaction which sweeps them all into the wallet.\n\tif len(kgtnOutputs) > 0 {\n\t\terr := sweepGraduatingOutputs(u.wallet, kgtnOutputs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Now that the sweeping transaction has been broadcast, for\n\t\t// each of the immature outputs, we'll mark them as being fully\n\t\t// closed within the database.\n\t\tfor _, closedChan := range kgtnOutputs {\n\t\t\terr := u.db.MarkChanFullyClosed(&closedChan.originChanPoint)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Using a re-org safety margin of 6-blocks, delete any outputs which\n\t// have graduated 6 blocks ago.\n\tdeleteHeight := blockHeight - 6\n\tif err := deleteGraduatedOutputs(u.db, deleteHeight); err != nil {\n\t\treturn err\n\t}\n\n\t// Finally, record the last height at which we graduated outputs so we\n\t// can reconcile our state with that of the main-chain during restarts.\n\treturn putLastHeightGraduated(u.db, blockHeight)\n}", "func CalculateUtilizationRatio(cash, borrows, reserves sdk.Dec) sdk.Dec {\n\t// Utilization rate is 0 when there are no borrows\n\tif borrows.Equal(sdk.ZeroDec()) {\n\t\treturn sdk.ZeroDec()\n\t}\n\n\ttotalSupply := cash.Add(borrows).Sub(reserves)\n\tif totalSupply.IsNegative() {\n\t\treturn sdk.OneDec()\n\t}\n\n\treturn sdk.MinDec(sdk.OneDec(), borrows.Quo(totalSupply))\n}", "func (v *MembershipVerifier) recomputeCommitments(p *MembershipProof) (*MembershipCommitment, error) {\n\tpsv := &POKVerifier{P: v.P, Q: v.Q, PK: v.PK}\n\tc := &MembershipCommitment{}\n\n\tpsp := &POK{\n\t\tChallenge: p.Challenge,\n\t\tSignature: p.Signature,\n\t\tMessages: []*bn256.Zr{p.Value},\n\t\tHash: p.Hash,\n\t\tBlindingFactor: p.SigBlindingFactor,\n\t}\n\tvar err error\n\tc.Signature, err = psv.RecomputeCommitment(psp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tver := &common.SchnorrVerifier{PedParams: v.PedersenParams}\n\tzkp := &common.SchnorrProof{Statement: v.CommitmentToValue, Proof: []*bn256.Zr{p.Value, p.ComBlindingFactor}, Challenge: p.Challenge}\n\tc.CommitmentToValue = ver.RecomputeCommitment(zkp)\n\n\treturn c, nil\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func TestDonationCase1(t *testing.T) {\n\tassert := assert.New(t)\n\tstore := newReputationStoreOnMock()\n\trep := NewTestReputationImpl(store)\n\tt1 := time.Date(1995, time.February, 5, 11, 11, 0, 0, time.UTC)\n\tt3 := time.Date(1995, time.February, 6, 12, 11, 0, 0, time.UTC)\n\tt4 := time.Date(1995, time.February, 7, 13, 11, 1, 0, time.UTC)\n\tuser1 := \"user1\"\n\tpost1 := \"post1\"\n\tpost2 := \"post2\"\n\n\t// round 2\n\trep.Update(t1.Unix())\n\trep.DonateAt(user1, post1, big.NewInt(100*OneLinoCoin))\n\tassert.Equal(big.NewInt(100*OneLinoCoin), rep.store.GetRoundPostSumStake(2, post1))\n\tassert.Equal(rep.GetReputation(user1), big.NewInt(InitialCustomerScore))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.store.GetRoundSumDp(2)) // bounded by this user's dp\n\n\t// round 3\n\trep.Update(t3.Unix())\n\t// (1 * 9 + 100) / 10\n\tassert.Equal(big.NewInt(1090000), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.GetSumRep(post1))\n\trep.DonateAt(user1, post1, big.NewInt(1*OneLinoCoin)) // does not count\n\trep.DonateAt(user1, post2, big.NewInt(900*OneLinoCoin))\n\trep.Update(t4.Unix())\n\t// (10.9 * 9 + 900) / 10\n\tassert.Equal(big.NewInt(9981000), rep.GetReputation(user1))\n\tassert.Equal([]Pid{post2}, rep.store.GetRoundResult(3))\n\t// round 4\n}", "func (dcr *ExchangeWallet) Redeem(redemptions []*asset.Redemption) ([]dex.Bytes, asset.Coin, uint64, error) {\n\t// Create a transaction that spends the referenced contract.\n\tmsgTx := wire.NewMsgTx()\n\tvar totalIn uint64\n\tvar contracts [][]byte\n\tvar addresses []dcrutil.Address\n\tfor _, r := range redemptions {\n\t\tcinfo, ok := r.Spends.(*auditInfo)\n\t\tif !ok {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"Redemption contract info of wrong type\")\n\t\t}\n\t\t// Extract the swap contract recipient and secret hash and check the secret\n\t\t// hash against the hash of the provided secret.\n\t\tcontract := r.Spends.Contract()\n\t\t_, receiver, _, secretHash, err := dexdcr.ExtractSwapDetails(contract, chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error extracting swap addresses: %w\", err)\n\t\t}\n\t\tcheckSecretHash := sha256.Sum256(r.Secret)\n\t\tif !bytes.Equal(checkSecretHash[:], secretHash) {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"secret hash mismatch. %x != %x\", checkSecretHash[:], secretHash)\n\t\t}\n\t\taddresses = append(addresses, receiver)\n\t\tcontracts = append(contracts, contract)\n\t\tprevOut := cinfo.output.wireOutPoint()\n\t\ttxIn := wire.NewTxIn(prevOut, int64(cinfo.output.value), []byte{})\n\t\t// Sequence = 0xffffffff - 1 is special value that marks the transaction as\n\t\t// irreplaceable and enables the use of lock time.\n\t\t//\n\t\t// https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki#Spending_wallet_policy\n\t\ttxIn.Sequence = wire.MaxTxInSequenceNum - 1\n\t\tmsgTx.AddTxIn(txIn)\n\t\ttotalIn += cinfo.output.value\n\t}\n\n\t// Calculate the size and the fees.\n\tsize := msgTx.SerializeSize() + dexdcr.RedeemSwapSigScriptSize*len(redemptions) + dexdcr.P2PKHOutputSize\n\tfeeRate := dcr.feeRateWithFallback(dcr.redeemConfTarget)\n\tfee := feeRate * uint64(size)\n\tif fee > totalIn {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redeem tx not worth the fees\")\n\t}\n\t// Send the funds back to the exchange wallet.\n\ttxOut, _, err := dcr.makeChangeOut(totalIn - fee)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\t// One last check for dust.\n\tif dexdcr.IsDust(txOut, feeRate) {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redeem output is dust\")\n\t}\n\tmsgTx.AddTxOut(txOut)\n\t// Sign the inputs.\n\tfor i, r := range redemptions {\n\t\tcontract := contracts[i]\n\t\tredeemSig, redeemPubKey, err := dcr.createSig(msgTx, i, contract, addresses[i])\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tredeemSigScript, err := dexdcr.RedeemP2SHContract(contract, redeemSig, redeemPubKey, r.Secret)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tmsgTx.TxIn[i].SignatureScript = redeemSigScript\n\t}\n\t// Send the transaction.\n\tcheckHash := msgTx.TxHash()\n\ttxHash, err := dcr.node.SendRawTransaction(dcr.ctx, msgTx, false)\n\tif err != nil {\n\t\treturn nil, nil, 0, translateRPCCancelErr(err)\n\t}\n\tif *txHash != checkHash {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redemption sent, but received unexpected transaction ID back from RPC server. \"+\n\t\t\t\"expected %s, got %s\", *txHash, checkHash)\n\t}\n\tcoinIDs := make([]dex.Bytes, 0, len(redemptions))\n\tfor i := range redemptions {\n\t\tcoinIDs = append(coinIDs, toCoinID(txHash, uint32(i)))\n\t}\n\n\treturn coinIDs, newOutput(txHash, 0, uint64(txOut.Value), wire.TxTreeRegular), fee, nil\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}", "func (k Keeper) RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateralType string, payment sdk.Coin) error {\n\t// validation\n\tcdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrCdpNotFound, \"owner %s, denom %s\", owner, collateralType)\n\t}\n\n\terr := k.ValidatePaymentCoins(ctx, cdp, payment)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = k.ValidateBalance(ctx, payment, owner)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.hooks.BeforeCDPModified(ctx, cdp)\n\tcdp = k.SynchronizeInterest(ctx, cdp)\n\n\t// Note: assumes cdp.Principal and cdp.AccumulatedFees don't change during calculations\n\ttotalPrincipal := cdp.GetTotalPrincipal()\n\n\t// calculate fee and principal payment\n\tfeePayment, principalPayment := k.calculatePayment(ctx, totalPrincipal, cdp.AccumulatedFees, payment)\n\n\terr = k.validatePrincipalPayment(ctx, cdp, principalPayment)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// send the payment from the sender to the cpd module\n\terr = k.bankKeeper.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, sdk.NewCoins(feePayment.Add(principalPayment)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// burn the payment coins\n\terr = k.bankKeeper.BurnCoins(ctx, types.ModuleName, sdk.NewCoins(feePayment.Add(principalPayment)))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// burn the corresponding amount of debt coins\n\tcdpDebt := k.getModAccountDebt(ctx, types.ModuleName)\n\tpaymentAmount := feePayment.Add(principalPayment).Amount\n\n\tdebtDenom := k.GetDebtDenom(ctx)\n\tcoinsToBurn := sdk.NewCoin(debtDenom, paymentAmount)\n\n\tif paymentAmount.GT(cdpDebt) {\n\t\tcoinsToBurn = sdk.NewCoin(debtDenom, cdpDebt)\n\t}\n\n\terr = k.BurnDebtCoins(ctx, types.ModuleName, debtDenom, coinsToBurn)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// emit repayment event\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCdpRepay,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, feePayment.Add(principalPayment).String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t),\n\t)\n\n\t// remove the old collateral:debt ratio index\n\n\t// update cdp state\n\tif !principalPayment.IsZero() {\n\t\tcdp.Principal = cdp.Principal.Sub(principalPayment)\n\t}\n\tcdp.AccumulatedFees = cdp.AccumulatedFees.Sub(feePayment)\n\n\t// decrement the total principal for the input collateral type\n\tk.DecrementTotalPrincipal(ctx, cdp.Type, feePayment.Add(principalPayment))\n\n\t// if the debt is fully paid, return collateral to depositors,\n\t// and remove the cdp and indexes from the store\n\tif cdp.Principal.IsZero() && cdp.AccumulatedFees.IsZero() {\n\t\tk.ReturnCollateral(ctx, cdp)\n\t\tk.RemoveCdpOwnerIndex(ctx, cdp)\n\t\terr := k.DeleteCdpAndCollateralRatioIndex(ctx, cdp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// emit cdp close event\n\t\tctx.EventManager().EmitEvent(\n\t\t\tsdk.NewEvent(\n\t\t\t\ttypes.EventTypeCdpClose,\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t\t),\n\t\t)\n\t\treturn nil\n\t}\n\n\t// set cdp state and update indexes\n\tcollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal())\n\treturn k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio)\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (_MintableToken *MintableTokenCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) {\n\treturn _MintableToken.Contract.BalanceOf(&_MintableToken.CallOpts, _owner)\n}", "func (_XStaking *XStakingCallerSession) RewardRate() (*big.Int, error) {\n\treturn _XStaking.Contract.RewardRate(&_XStaking.CallOpts)\n}", "func (dcr *ExchangeWallet) feeRate(confTarget uint64) (uint64, error) {\n\tif feeEstimator, is := dcr.wallet.(FeeRateEstimator); is && !dcr.wallet.SpvMode() {\n\t\tdcrPerKB, err := feeEstimator.EstimateSmartFeeRate(dcr.ctx, int64(confTarget), chainjson.EstimateSmartFeeConservative)\n\t\tif err == nil && dcrPerKB > 0 {\n\t\t\treturn dcrPerKBToAtomsPerByte(dcrPerKB)\n\t\t}\n\t\tif err != nil {\n\t\t\tdcr.log.Warnf(\"Failed to get local fee rate estimate: %v\", err)\n\t\t} else { // dcrPerKB == 0\n\t\t\tdcr.log.Warnf(\"Local fee estimate is zero.\")\n\t\t}\n\t}\n\n\t// Either SPV wallet or EstimateSmartFeeRate failed.\n\tif !dcr.apiFeeFallback {\n\t\treturn 0, fmt.Errorf(\"fee rate estimation unavailable and external API is disabled\")\n\t}\n\n\tnow := time.Now()\n\n\tdcr.oracleFeesMtx.Lock()\n\tdefer dcr.oracleFeesMtx.Unlock()\n\toracleFee := dcr.oracleFees[confTarget]\n\tif now.Sub(oracleFee.stamp) < freshFeeAge {\n\t\treturn oracleFee.rate, nil\n\t}\n\tif dcr.oracleFailing {\n\t\treturn 0, errors.New(\"fee rate oracle is in a temporary failing state\")\n\t}\n\n\tdcr.log.Debugf(\"Retrieving fee rate from external fee oracle for %d target blocks\", confTarget)\n\tdcrPerKB, err := fetchFeeFromOracle(dcr.ctx, dcr.network, confTarget)\n\tif err != nil {\n\t\t// Flag the oracle as failing so subsequent requests don't also try and\n\t\t// fail after the request timeout. Remove the flag after a bit.\n\t\tdcr.oracleFailing = true\n\t\ttime.AfterFunc(freshFeeAge, func() {\n\t\t\tdcr.oracleFeesMtx.Lock()\n\t\t\tdcr.oracleFailing = false\n\t\t\tdcr.oracleFeesMtx.Unlock()\n\t\t})\n\t\treturn 0, fmt.Errorf(\"external fee rate API failure: %v\", err)\n\t}\n\tif dcrPerKB <= 0 {\n\t\treturn 0, fmt.Errorf(\"invalid fee rate %f from fee oracle\", dcrPerKB)\n\t}\n\t// Convert to atoms/B and error if it is greater than fee rate limit.\n\tatomsPerByte, err := dcrPerKBToAtomsPerByte(dcrPerKB)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif atomsPerByte > dcr.feeRateLimit {\n\t\treturn 0, fmt.Errorf(\"fee rate from external API greater than fee rate limit: %v > %v\",\n\t\t\tatomsPerByte, dcr.feeRateLimit)\n\t}\n\tdcr.oracleFees[confTarget] = feeStamped{atomsPerByte, now}\n\treturn atomsPerByte, nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (n *Node) BecomeDelegator(genesisAmount uint64, seedAmount uint64, delegatorAmount uint64, txFee uint64, stakerNodeID string) *Node {\n\n\t// exports AVAX from the X Chain\n\texportTxID, err := n.client.XChainAPI().ExportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tseedAmount+txFee,\n\t\tn.PAddress,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to export AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the XChain\n\terr = chainhelper.XChain().AwaitTransactionAcceptance(n.client, exportTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// imports the amount to the P Chain\n\timportTxID, err := n.client.PChainAPI().ImportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tconstants.XChainID.String(),\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed import AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the PChain\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, importTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// verify the PChain balance (seedAmount+txFee-txFee)\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, seedAmount)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance of seedAmount exists in the PChain\"))\n\t\treturn n\n\t}\n\n\t// verify the XChain balance of genesisAmount - seedAmount - txFee - txFee (import PChain)\n\terr = chainhelper.XChain().CheckBalance(n.client, n.XAddress, \"AVAX\", genesisAmount-seedAmount-2*txFee)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance XChain balance of genesisAmount-seedAmount-txFee\"))\n\t\treturn n\n\t}\n\n\tdelegatorStartTime := time.Now().Add(20 * time.Second)\n\tstartTime := uint64(delegatorStartTime.Unix())\n\tendTime := uint64(delegatorStartTime.Add(36 * time.Hour).Unix())\n\taddDelegatorTxID, err := n.client.PChainAPI().AddDelegator(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tstakerNodeID,\n\t\tdelegatorAmount,\n\t\tstartTime,\n\t\tendTime,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to add delegator %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, addDelegatorTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to accept AddDelegator tx: %s\", addDelegatorTxID))\n\t\treturn n\n\t}\n\n\t// Sleep until delegator starts validating\n\ttime.Sleep(time.Until(delegatorStartTime) + 3*time.Second)\n\n\texpectedDelegatorBalance := seedAmount - delegatorAmount\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, expectedDelegatorBalance)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Unexpected P Chain Balance after adding a new delegator to the network.\"))\n\t\treturn n\n\t}\n\tlogrus.Infof(\"Added delegator to subnet and verified the expected P Chain balance.\")\n\n\treturn n\n}", "func (_CommitteeManager *CommitteeManagerTransactorSession) CreateSetRateProposal(participatesRate uint8, winRate uint8, blockNumberInterval *big.Int) (*types.Transaction, *types.Receipt, error) {\n\treturn _CommitteeManager.Contract.CreateSetRateProposal(&_CommitteeManager.TransactOpts, participatesRate, winRate, blockNumberInterval)\n}", "func (sch *Scheduler) CalClusterBalance(podUsed *[PHYNUM][DIMENSION]float64, podReq []PodRequest) {\n\t//cal the pod sum and used rate\n\tpodLen := len(podReq)\n\tvar podNum [PHYNUM]int\n\tvar podSum int\n\tfor i := 0; i < podLen; i++ {\n\t\tif podReq[i].nodeName != -1 {\n\t\t\tpodSum++\n\t\t\tpodNum[podReq[i].nodeName]++\n\t\t}\n\t}\n\n\tvar podIdle [PHYNUM]float64\n\tvar resIdle [PHYNUM][DIMENSION]float64\n\tvar podVal float64\n\tvar resVal [DIMENSION]float64 // cal the sum and mean value\n\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tpodIdle[i] = 1.0 - (float64)(podNum[i])/(float64)(podSum)\n\t\tpodVal = podVal + podIdle[i]\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tresIdle[i][j] = (sch.reTotal[j] - podUsed[i][j]) / sch.reTotal[j]\n\t\t\tresVal[j] = resVal[j] + resIdle[i][j]\n\t\t}\n\t}\n\t// cal the balance value\n\tpodMean := podVal / (float64)(podSum)\n\tvar resMean [DIMENSION]float64\n\tfor j := 0; j < DIMENSION; j++ {\n\t\tresMean[j] = resVal[j] / (float64)(PHYNUM)\n\t}\n\tvar baIdle float64\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tbaIdle = baIdle + math.Pow((resIdle[i][j]-resMean[j]), 2)\n\t\t}\n\t\tbaIdle = baIdle + math.Pow((podIdle[i]-podMean), 2)\n\t}\n\tbaIdle = math.Sqrt(baIdle)\n\tfmt.Printf(\"The balance value is %.3f \\n\", baIdle)\n}", "func getAccumulatedRewards(ctx sdk.Context, distKeeper types.DistributionKeeper, delegation stakingtypes.Delegation) ([]wasmvmtypes.Coin, error) {\n\t// Try to get *delegator* reward info!\n\tparams := distributiontypes.QueryDelegationRewardsRequest{\n\t\tDelegatorAddress: delegation.DelegatorAddress,\n\t\tValidatorAddress: delegation.ValidatorAddress,\n\t}\n\tcache, _ := ctx.CacheContext()\n\tqres, err := distKeeper.DelegationRewards(sdk.WrapSDKContext(cache), &params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// now we have it, convert it into wasmvm types\n\trewards := make([]wasmvmtypes.Coin, len(qres.Rewards))\n\tfor i, r := range qres.Rewards {\n\t\trewards[i] = wasmvmtypes.Coin{\n\t\t\tDenom: r.Denom,\n\t\t\tAmount: r.Amount.TruncateInt().String(),\n\t\t}\n\t}\n\treturn rewards, nil\n}", "func (_BREMICO *BREMICOCallerSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREMICO.Contract.WithdrawFeePercent(&_BREMICO.CallOpts)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (_MonsterOwnership *MonsterOwnershipCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) {\n\treturn _MonsterOwnership.Contract.BalanceOf(&_MonsterOwnership.CallOpts, _owner)\n}", "func (_BREMToken *BREMTokenCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) {\n\treturn _BREMToken.Contract.BalanceOf(&_BREMToken.CallOpts, _owner)\n}", "func (_CommitteeManager *CommitteeManagerSession) CreateSetRateProposal(participatesRate uint8, winRate uint8, blockNumberInterval *big.Int) (*types.Transaction, *types.Receipt, error) {\n\treturn _CommitteeManager.Contract.CreateSetRateProposal(&_CommitteeManager.TransactOpts, participatesRate, winRate, blockNumberInterval)\n}", "func (sch *Scheduler) CalResourceRate(podUsed *[PHYNUM][DIMENSION]float64) {\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tfmt.Printf(\"%s\", \"node\"+strconv.Itoa(i)+\": \")\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tfmt.Printf(\"%.3f \", podUsed[i][j]/sch.reTotal[j])\n\t\t}\n\t\tfmt.Println()\n\t}\n}", "func (_Bindings *BindingsTransactorSession) RepayBorrow() (*types.Transaction, error) {\n\treturn _Bindings.Contract.RepayBorrow(&_Bindings.TransactOpts)\n}", "func NewRateEnforcer(o RateEnforcerOptions, eh *astiencoder.EventHandler, c *astikit.Closer) (r *RateEnforcer) {\n\t// Extend node metadata\n\tcount := atomic.AddUint64(&countRateEnforcer, uint64(1))\n\to.Node.Metadata = o.Node.Metadata.Extend(fmt.Sprintf(\"rate_enforcer_%d\", count), fmt.Sprintf(\"Rate Enforcer #%d\", count), \"Enforces rate\", \"rate enforcer\")\n\n\t// Create rate enforcer\n\tr = &RateEnforcer{\n\t\tc: astikit.NewChan(astikit.ChanOptions{\n\t\t\tAddStrategy: astikit.ChanAddStrategyBlockWhenStarted,\n\t\t\tProcessAll: true,\n\t\t}),\n\t\teh: eh,\n\t\tm: &sync.Mutex{},\n\t\toutputCtx: o.OutputCtx,\n\t\tp: newFramePool(c),\n\t\tperiod: time.Duration(float64(1e9) / o.FrameRate.ToDouble()),\n\t\trestamper: o.Restamper,\n\t\tslots: []*rateEnforcerSlot{nil},\n\t\tslotsCount: int(math.Max(float64(o.Delay), 1)),\n\t\tstatDelayAvg: astikit.NewCounterAvgStat(),\n\t\tstatIncomingRate: astikit.NewCounterRateStat(),\n\t\tstatRepeatedRate: astikit.NewCounterRateStat(),\n\t\tstatWorkRatio: astikit.NewDurationPercentageStat(),\n\t\ttimeBase: avutil.NewRational(o.FrameRate.Den(), o.FrameRate.Num()),\n\t}\n\tr.BaseNode = astiencoder.NewBaseNode(o.Node, astiencoder.NewEventGeneratorNode(r), eh)\n\tr.d = newFrameDispatcher(r, eh, c)\n\tr.addStats()\n\treturn\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (_BurnableToken *BurnableTokenCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) {\n\treturn _BurnableToken.Contract.BalanceOf(&_BurnableToken.CallOpts, _owner)\n}", "func (_BurnableToken *BurnableTokenCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) {\n\treturn _BurnableToken.Contract.BalanceOf(&_BurnableToken.CallOpts, _owner)\n}", "func (u *utxoNursery) NurseryReport(chanPoint *wire.OutPoint) (*contractMaturityReport, error) {\n\tvar report *contractMaturityReport\n\tif err := u.db.View(func(tx *bolt.Tx) error {\n\t\t// First we'll examine the preschool bucket as the target\n\t\t// contract may not yet have been confirmed.\n\t\tpsclBucket := tx.Bucket(preschoolBucket)\n\t\tif psclBucket == nil {\n\t\t\treturn nil\n\t\t}\n\t\tpsclIndex := tx.Bucket(preschoolIndex)\n\t\tif psclIndex == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tvar b bytes.Buffer\n\t\tif err := writeOutpoint(&b, chanPoint); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tchanPointBytes := b.Bytes()\n\n\t\tvar outputReader *bytes.Reader\n\n\t\t// If the target contract hasn't been confirmed yet, then we\n\t\t// can just construct the report from this information.\n\t\tif outPoint := psclIndex.Get(chanPointBytes); outPoint != nil {\n\t\t\t// The channel entry hasn't yet been fully confirmed\n\t\t\t// yet, so we'll dig into the preschool bucket to fetch\n\t\t\t// the channel information.\n\t\t\toutputBytes := psclBucket.Get(outPoint)\n\t\t\tif outputBytes == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\toutputReader = bytes.NewReader(outputBytes)\n\t\t} else {\n\t\t\t// Otherwise, we'll have to consult out contract index,\n\t\t\t// so fetch that bucket as well as the kindergarten\n\t\t\t// bucket.\n\t\t\tindexBucket := tx.Bucket(contractIndex)\n\t\t\tif indexBucket == nil {\n\t\t\t\treturn fmt.Errorf(\"contract not found, \" +\n\t\t\t\t\t\"contract index not populated\")\n\t\t\t}\n\t\t\tkgtnBucket := tx.Bucket(kindergartenBucket)\n\t\t\tif kgtnBucket == nil {\n\t\t\t\treturn fmt.Errorf(\"contract not found, \" +\n\t\t\t\t\t\"kindergarten bucket not populated\")\n\t\t\t}\n\n\t\t\t// Attempt to query the index to see if we have an\n\t\t\t// entry for this particular contract.\n\t\t\tindexInfo := indexBucket.Get(chanPointBytes)\n\t\t\tif indexInfo == nil {\n\t\t\t\treturn ErrContractNotFound\n\t\t\t}\n\n\t\t\t// If an entry is found, then using the height store in\n\t\t\t// the first 4 bytes, we'll fetch the height that this\n\t\t\t// entry matures at.\n\t\t\theight := indexInfo[:4]\n\t\t\theightRow := kgtnBucket.Get(height)\n\t\t\tif heightRow == nil {\n\t\t\t\treturn ErrContractNotFound\n\t\t\t}\n\n\t\t\t// Once we have the entry itself, we'll slice of the\n\t\t\t// last for bytes so we can seek into this row to fetch\n\t\t\t// the contract's information.\n\t\t\toffset := byteOrder.Uint32(indexInfo[4:])\n\t\t\toutputReader = bytes.NewReader(heightRow[offset:])\n\t\t}\n\n\t\t// With the proper set of bytes received, we'll deserialize the\n\t\t// information for this immature output.\n\t\timmatureOutput, err := deserializeKidOutput(outputReader)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// TODO(roasbeef): should actually be list of outputs\n\t\treport = &contractMaturityReport{\n\t\t\tchanPoint: *chanPoint,\n\t\t\tlimboBalance: immatureOutput.amt,\n\t\t\tmaturityRequirement: immatureOutput.blocksToMaturity,\n\t\t}\n\n\t\t// If the confirmation height is set, then this means the\n\t\t// contract has been confirmed, and we know the final maturity\n\t\t// height.\n\t\tif immatureOutput.confHeight != 0 {\n\t\t\treport.confirmationHeight = immatureOutput.confHeight\n\t\t\treport.maturityHeight = (immatureOutput.blocksToMaturity +\n\t\t\t\timmatureOutput.confHeight)\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn report, nil\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (_XStaking *XStakingSession) RewardRate() (*big.Int, error) {\n\treturn _XStaking.Contract.RewardRate(&_XStaking.CallOpts)\n}", "func GenerateGetTotalCommitmentBalanceWithoutDelegatorsScript(env Environment) []byte {\n\tcode := assets.MustAssetString(getTotalCommitmentWithoutDelegatorsFilename)\n\n\treturn []byte(replaceAddresses(code, env))\n}", "func weighted_reward(w map[int]float64, allocation vrp.Allocation) float64 {\n\tvar reward float64\n\tfor id, _ := range allocation {\n\t\treward += w[id] * allocation[id]\n\t}\n\treturn reward\n}", "func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetEarnClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_TokensNetwork *TokensNetworkSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (_CrToken *CrTokenSession) RepayBorrow(repayAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.RepayBorrow(&_CrToken.TransactOpts, repayAmount)\n}", "func (_Dospayment *DospaymentCallerSession) NodeFeeBalance(nodeAddr common.Address, tokenAddr common.Address) (*big.Int, error) {\n\treturn _Dospayment.Contract.NodeFeeBalance(&_Dospayment.CallOpts, nodeAddr, tokenAddr)\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}" ]
[ "0.5923048", "0.5468286", "0.52752644", "0.52367705", "0.48951933", "0.4865", "0.48394552", "0.48002872", "0.47924343", "0.4744759", "0.47437388", "0.473917", "0.47347444", "0.47052506", "0.46965125", "0.46817634", "0.4661282", "0.46388462", "0.46133858", "0.45926782", "0.45915624", "0.45785078", "0.45453665", "0.45328483", "0.45156655", "0.4515161", "0.45069116", "0.45028457", "0.45007616", "0.44875532", "0.44673705", "0.4466794", "0.44606948", "0.4454575", "0.44465747", "0.44424313", "0.44392964", "0.44327906", "0.44150937", "0.44134155", "0.44094732", "0.43729588", "0.4369725", "0.43644974", "0.43579614", "0.43356684", "0.43342915", "0.43256074", "0.42987144", "0.42908388", "0.42864636", "0.42836764", "0.4281978", "0.42750767", "0.42730168", "0.4240157", "0.4236137", "0.42330584", "0.4228129", "0.4227461", "0.42190394", "0.42122778", "0.42058983", "0.4202043", "0.4191914", "0.41884366", "0.41803035", "0.41751543", "0.41709426", "0.41662157", "0.41643813", "0.41625744", "0.41574755", "0.41549373", "0.4151745", "0.41502193", "0.41478583", "0.41416398", "0.4140315", "0.41400763", "0.41390628", "0.41389257", "0.413181", "0.41229436", "0.4117555", "0.410882", "0.41061872", "0.41061872", "0.40917504", "0.40915513", "0.40859148", "0.40833616", "0.40827203", "0.40825713", "0.4073676", "0.4062695", "0.40570286", "0.4052861", "0.4050937", "0.4045335" ]
0.67595404
0
/ Description: Calculates all the fees for each contract and adds them to the delegates net payout
func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{ var delegateIndex int for index, delegate := range delegatedContracts{ if (delegate.Delegate){ delegateIndex = index } } for _, delegate := range delegatedContracts{ if (!delegate.Delegate){ delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee } } return delegatedContracts }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func totalFees(block *model.Block, receipts []*model.Receipt) *big.Float {\n\tfeesWei := new(big.Int)\n\tfor i, tx := range block.Transactions() {\n\t\tminerFee, _ := tx.EffectiveGasTip(block.BaseFee())\n\t\tfeesWei.Add(feesWei, new(big.Int).Mul(new(big.Int).SetUint64(receipts[i].GasUsed), minerFee))\n\t}\n\treturn new(big.Float).Quo(new(big.Float).SetInt(feesWei), new(big.Float).SetInt(big.NewInt(config.Ether)))\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{\n for _, delegatedContract := range delegatedContracts {\n err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias)\n if (err != nil){\n return errors.New(\"Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: \" + err.Error())\n }\n }\n return nil\n}", "func CalculateFee(tx []byte, fees Fees) (uint64, error) {\n\tt := trace.New().Source(\"transaction.go\", \"\", \"CalculateFee\")\n\tsize := len(tx)\n\tlog.Println(trace.Info(\"TX size\").UTC().Add(\"bytes len\", fmt.Sprintf(\"%d\", size)).Append(t))\n\tstandardFee, err := fees.GetStandardFee()\n\tif err != nil {\n\t\tlog.Println(trace.Alert(\"no standard fee avaliable\").UTC().Error(err).Append(t))\n\t\treturn 0, fmt.Errorf(\"no standard fee available: %w\", err)\n\t}\n\tminingFee := (float64(size) / float64(standardFee.MiningFee.Bytes)) * float64(standardFee.MiningFee.Satoshis)\n\t// relayFee := (float64(size) / float64(standardFee.RelayFee.Bytes)) * float64(standardFee.RelayFee.Satoshis)\n\trelayFee := 0.0\n\ttotalFee := uint64(math.Ceil(miningFee + relayFee))\n\tlog.Println(trace.Info(\"calculating fee\").UTC().Add(\"size\", fmt.Sprintf(\"%d\", size)).Add(\"miningFee\", fmt.Sprintf(\"%.9f\", miningFee)).Add(\"relayFee\", fmt.Sprintf(\"%.9f\", relayFee)).Add(\"totalFee\", fmt.Sprintf(\"%d\", totalFee)).Append(t))\n\treturn uint64(totalFee), nil\n}", "func (l *loopOutSwapSuggestion) fees() btcutil.Amount {\n\treturn worstCaseOutFees(\n\t\tl.OutRequest.MaxPrepayRoutingFee, l.OutRequest.MaxSwapRoutingFee,\n\t\tl.OutRequest.MaxSwapFee, l.OutRequest.MaxMinerFee,\n\t)\n}", "func (_Dospayment *DospaymentCallerSession) FeeLists(arg0 common.Address) (struct {\n\tSubmitterCut *big.Int\n\tGuardianFee *big.Int\n}, error) {\n\treturn _Dospayment.Contract.FeeLists(&_Dospayment.CallOpts, arg0)\n}", "func (_Dospayment *DospaymentSession) FeeLists(arg0 common.Address) (struct {\n\tSubmitterCut *big.Int\n\tGuardianFee *big.Int\n}, error) {\n\treturn _Dospayment.Contract.FeeLists(&_Dospayment.CallOpts, arg0)\n}", "func (l *loopInSwapSuggestion) fees() btcutil.Amount {\n\treturn worstCaseInFees(\n\t\tl.LoopInRequest.MaxMinerFee, l.LoopInRequest.MaxSwapFee,\n\t\tdefaultLoopInSweepFee,\n\t)\n}", "func (_Dospayment *DospaymentCaller) FeeLists(opts *bind.CallOpts, arg0 common.Address) (struct {\n\tSubmitterCut *big.Int\n\tGuardianFee *big.Int\n}, error) {\n\tret := new(struct {\n\t\tSubmitterCut *big.Int\n\t\tGuardianFee *big.Int\n\t})\n\tout := ret\n\terr := _Dospayment.contract.Call(opts, out, \"feeLists\", arg0)\n\treturn *ret, err\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func (e *Event) CalculateTotalFee() {\n\tvar total float64\n\n\tfor _, reservation := range e.Reservations {\n\t\ttotal += reservation.totalFee()\n\t}\n\n\te.TotalFee = total\n}", "func CalculateAllContractsForCycles(delegatedContracts []DelegatedContract, cycleStart int, cycleEnd int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var err error\n\n for cycleStart <= cycleEnd {\n //fmt.Println(cycleStart)\n delegatedContracts, err = CalculateAllContractsForCycle(delegatedContracts, cycleStart, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycles \" + strconv.Itoa(cycleStart) + \"-\" + strconv.Itoa(cycleEnd) + \":CalculateAllCommitmentsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64) failed: \" + err.Error())\n }\n cycleStart = cycleStart + 1\n }\n return delegatedContracts, nil\n}", "func (_Caller *CallerCallerSession) Fees(arg0 common.Address) (*big.Int, error) {\n\treturn _Caller.Contract.Fees(&_Caller.CallOpts, arg0)\n}", "func (_Caller *CallerSession) Fees(arg0 common.Address) (*big.Int, error) {\n\treturn _Caller.Contract.Fees(&_Caller.CallOpts, arg0)\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (f *Factory) Fees() sdk.Coins { return f.fees }", "func (b Block) CalculateMinerFees() Currency {\n\tfees := NewCurrency64(0)\n\tfor _, txn := range b.Transactions {\n\t\tfor _, fee := range txn.MinerFees {\n\t\t\tfees = fees.Add(fee)\n\t\t}\n\t}\n\treturn fees\n}", "func (f *feeCalculator) Fee(amountInSat int64, feeRateInSatsPerVByte float64, takeFeeFromAmount bool) int64 {\n\tif amountInSat == 0 {\n\t\treturn 0\n\t}\n\tif takeFeeFromAmount {\n\t\treturn f.feeFromAmount(amountInSat, feeRateInSatsPerVByte)\n\t} else {\n\t\treturn f.feeFromRemainingBalance(amountInSat, feeRateInSatsPerVByte)\n\t}\n}", "func fees(s string) string {\n\treturn addFees(s) + \":fees\"\n}", "func totalExpenses(salCalc []SalaryCalculator) {\n\texpense := 0\n\tfor _, v := range salCalc {\n\t\texpense = expense + v.CalculateSalary()\n\t}\n\n\tfmt.Printf(\"Total Expense per Month $%d\\n\", expense)\n}", "func (_L1Block *L1BlockCaller) Basefee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _L1Block.contract.Call(opts, &out, \"basefee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (suite *FeeTestSuite) TestUpdateFees() {\n\t// this helper function creates two CDPs with id 1 and 2 respectively, each with zero fees\n\tsuite.createCdps()\n\n\t// move the context forward in time so that cdps will have fees accumulate if CalculateFees is called\n\t// note - time must be moved forward by a sufficient amount in order for additional\n\t// fees to accumulate, in this example 600 seconds\n\toldtime := suite.ctx.BlockTime()\n\tsuite.ctx = suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(time.Second * 600))\n\terr := suite.keeper.UpdateFeesForAllCdps(suite.ctx, \"xrp\")\n\tsuite.NoError(err) // check that we don't have any error\n\n\t// cdp we expect fees to accumulate for\n\tcdp1, _ := suite.keeper.GetCDP(suite.ctx, \"xrp\", 1)\n\t// check fees are not zero\n\t// check that the fees have been updated\n\tsuite.False(cdp1.AccumulatedFees.Empty())\n\t// now check that we have the correct amount of fees overall (22 USDX for this scenario)\n\tsuite.Equal(sdk.NewInt(22), cdp1.AccumulatedFees.AmountOf(\"usdx\"))\n\tsuite.Equal(suite.ctx.BlockTime(), cdp1.FeesUpdated)\n\t// cdp we expect fees to not accumulate for because of rounding to zero\n\tcdp2, _ := suite.keeper.GetCDP(suite.ctx, \"xrp\", 2)\n\n\t// check fees are zero\n\tsuite.True(cdp2.AccumulatedFees.Empty())\n\tsuite.Equal(oldtime, cdp2.FeesUpdated)\n}", "func (suite *FeeTestSuite) TestUpdateFees() {\n\t// this helper function creates two CDPs with id 1 and 2 respectively, each with zero fees\n\tsuite.createCdps()\n\n\t// move the context forward in time so that cdps will have fees accumulate if CalculateFees is called\n\t// note - time must be moved forward by a sufficient amount in order for additional\n\t// fees to accumulate, in this example 600 seconds\n\toldtime := suite.ctx.BlockTime()\n\tsuite.ctx = suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(time.Second * 600))\n\terr := suite.keeper.UpdateFeesForAllCdps(suite.ctx, \"xrp\")\n\tsuite.NoError(err) // check that we don't have any error\n\n\t// cdp we expect fees to accumulate for\n\tcdp1, found := suite.keeper.GetCDP(suite.ctx, \"xrp\", 1)\n\tsuite.True(found)\n\t// check fees are not zero\n\t// check that the fees have been updated\n\tsuite.False(cdp1.AccumulatedFees.IsZero())\n\t// now check that we have the correct amount of fees overall (22 JPYX for this scenario)\n\tsuite.Equal(sdk.NewInt(22), cdp1.AccumulatedFees.Amount)\n\tsuite.Equal(suite.ctx.BlockTime(), cdp1.FeesUpdated)\n\t// cdp we expect fees to not accumulate for because of rounding to zero\n\tcdp2, found := suite.keeper.GetCDP(suite.ctx, \"xrp\", 2)\n\tsuite.True(found)\n\t// check fees are zero\n\tsuite.True(cdp2.AccumulatedFees.IsZero())\n\tsuite.Equal(oldtime, cdp2.FeesUpdated)\n}", "func CalculateFee(basic_op_fee int64, len_memo int64) int64 {\n\n\tvar basic_memo_fee int64 = 1\n\treturn basic_op_fee + len_memo*basic_memo_fee\n}", "func (_Authority *AuthorityCaller) Fee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Authority.contract.Call(opts, out, \"fee\")\n\treturn *ret0, err\n}", "func totalExpense(s []SalaryCalculator) {\n expense := 0\n for _, v := range s {\n expense = expense + v.CalculateSalary()\n }\n fmt.Printf(\"Total Expense Per Month $%d\", expense)\n}", "func (_EtherDelta *EtherDeltaCaller) FeeMake(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _EtherDelta.contract.Call(opts, out, \"feeMake\")\n\treturn *ret0, err\n}", "func totalExpense(s []SalaryCalculator) {\n\texpense := 0\n\tfor _, v := range s {\n\t\texpense = expense + v.CalculateSalary()\n\t}\n\tfmt.Printf(\"\\n Total Expense Per Month $%d\", expense)\n}", "func FlowFees(fungibleTokenAddress, flowTokenAddress string) []byte {\n\tcode := assets.MustAssetString(flowFeesFilename)\n\n\tcode = strings.ReplaceAll(\n\t\tcode,\n\t\tplaceholderFungibleTokenAddress,\n\t\twithHexPrefix(fungibleTokenAddress),\n\t)\n\n\tcode = strings.ReplaceAll(\n\t\tcode,\n\t\tplaceholderFlowTokenAddress,\n\t\twithHexPrefix(flowTokenAddress),\n\t)\n\n\treturn []byte(code)\n}", "func addFees(s string) string {\n\treturn fmt.Sprintf(\"%s:flatfee:%f:txfee:%d\", s, defaultFlatRateFee, defaultPerTransactionFee)\n}", "func totalExpense(s []SalaryCalculator) {\n\texpense := 0\n\tfor _, v := range s {\n\t\texpense = expense + v.CalculateSalary()\n\t}\n\tfmt.Printf(\"Total Expense Per Month $%d\", expense)\n}", "func (sb *Student) PayFee() {\n\tpanic(\"Implement me\")\n}", "func (_Caller *CallerTransactor) WithdrawFees(opts *bind.TransactOpts, to common.Address) (*types.Transaction, error) {\n\treturn _Caller.contract.Transact(opts, \"withdrawFees\", to)\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (r *Reservation) totalFee() float64 {\n\t// we have to calculate the total fee per night\n\tcost := (float64(r.Adults) * r.AdultFee) + (float64(r.Minors) * r.MinorFee)\n\n\t// we have to calculate the total fee\n\ttotal := float64(r.nights()) * cost\n\n\treturn total\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func (_Contract *ContractCaller) ProposalBurntFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"proposalBurntFee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func DeductFees(blockTime time.Time, acc Account, fee StdFee) (Account, sdk.Result) {\n\tcoins := acc.GetCoins()\n\tfeeAmount := fee.Amount()\n\n\tif !feeAmount.IsValid() {\n\t\treturn nil, sdk.ErrInsufficientFee(fmt.Sprintf(\"invalid fee amount: %s\", feeAmount)).Result()\n\t}\n\n\t// get the resulting coins deducting the fees\n\tnewCoins, ok := coins.SafeSub(feeAmount)\n\tif ok {\n\t\treturn nil, sdk.ErrInsufficientFunds(\n\t\t\tfmt.Sprintf(\"insufficient funds to pay for fees; %s < %s\", coins, feeAmount),\n\t\t).Result()\n\t}\n\n\t// Validate the account has enough \"spendable\" coins as this will cover cases\n\t// such as vesting accounts.\n\tspendableCoins := acc.SpendableCoins(blockTime)\n\tif _, hasNeg := spendableCoins.SafeSub(feeAmount); hasNeg {\n\t\treturn nil, sdk.ErrInsufficientFunds(\n\t\t\tfmt.Sprintf(\"insufficient funds to pay for fees; %s < %s\", spendableCoins, feeAmount),\n\t\t).Result()\n\t}\n\n\tif err := acc.SetCoins(newCoins); err != nil {\n\t\treturn nil, sdk.ErrInternal(err.Error()).Result()\n\t}\n\n\treturn acc, sdk.Result{}\n}", "func calcTotalExpense(employees []Employee) float64 {\n\texpense := 0.0\n\tfor _, employee := range employees {\n\t\texpense += employee.CalcSalary()\n\t}\n\treturn expense\n}", "func (_ElvTradable *ElvTradableCaller) BaseTransferFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ElvTradable.contract.Call(opts, &out, \"baseTransferFee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func CalculateFeeForTx(tx *bt.Tx, standardRate, dataRate *bt.Fee) uint64 {\n\n\t// Set the totals\n\tvar totalFee int\n\tvar totalDataBytes int\n\n\t// Set defaults if not found\n\tif standardRate == nil {\n\t\tstandardRate = bt.DefaultStandardFee()\n\t}\n\tif dataRate == nil {\n\t\tdataRate = bt.DefaultStandardFee()\n\t\t// todo: adjusted to 5/10 for now, since all miners accept that rate\n\t\tdataRate.FeeType = bt.FeeTypeData\n\t}\n\n\t// Set the total bytes of the tx\n\ttotalBytes := len(tx.ToBytes())\n\n\t// Loop all outputs and accumulate size (find data related outputs)\n\tfor _, out := range tx.GetOutputs() {\n\t\toutHexString := out.GetLockingScriptHexString()\n\t\tif strings.HasPrefix(outHexString, \"006a\") || strings.HasPrefix(outHexString, \"6a\") {\n\t\t\ttotalDataBytes += len(out.ToBytes())\n\t\t}\n\t}\n\n\t// Got some data bytes?\n\tif totalDataBytes > 0 {\n\t\ttotalBytes = totalBytes - totalDataBytes\n\t\ttotalFee += (dataRate.MiningFee.Satoshis * totalDataBytes) / dataRate.MiningFee.Bytes\n\t}\n\n\t// Still have regular standard bytes?\n\tif totalBytes > 0 {\n\t\ttotalFee += (standardRate.MiningFee.Satoshis * totalBytes) / standardRate.MiningFee.Bytes\n\t}\n\n\t// Safety check (possible division by zero?)\n\tif totalFee == 0 {\n\t\ttotalFee = 1\n\t}\n\n\t// Return the total fee as a uint (easier to use with satoshi values)\n\treturn uint64(totalFee)\n}", "func TestInsertContractTotalCost(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\n\trenterPayout := types.SiacoinPrecision\n\ttxnFee := types.SiacoinPrecision.Mul64(2)\n\tfc := types.FileContract{\n\t\tValidProofOutputs: []types.SiacoinOutput{\n\t\t\t{}, {},\n\t\t},\n\t\tMissedProofOutputs: []types.SiacoinOutput{\n\t\t\t{}, {},\n\t\t},\n\t}\n\tfc.SetValidRenterPayout(renterPayout)\n\n\ttxn := types.Transaction{\n\t\tFileContractRevisions: []types.FileContractRevision{\n\t\t\t{\n\t\t\t\tNewValidProofOutputs: fc.ValidProofOutputs,\n\t\t\t\tNewMissedProofOutputs: fc.MissedProofOutputs,\n\t\t\t\tUnlockConditions: types.UnlockConditions{\n\t\t\t\t\tPublicKeys: []types.SiaPublicKey{\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\trc := modules.RecoverableContract{\n\t\tFileContract: fc,\n\t\tTxnFee: txnFee,\n\t}\n\n\t// get the dir of the contractset.\n\ttestDir := build.TempDir(t.Name())\n\tif err := os.MkdirAll(testDir, modules.DefaultDirPerm); err != nil {\n\t\tt.Fatal(err)\n\t}\n\trl := ratelimit.NewRateLimit(0, 0, 0)\n\tcs, err := NewContractSet(testDir, rl, modules.ProdDependencies)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Insert the contract and check its total cost and fee.\n\tcontract, err := cs.InsertContract(rc, txn, []crypto.Hash{}, crypto.SecretKey{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !contract.TxnFee.Equals(txnFee) {\n\t\tt.Fatal(\"wrong fee\", contract.TxnFee, txnFee)\n\t}\n\texpectedTotalCost := renterPayout.Add(txnFee)\n\tif !contract.TotalCost.Equals(expectedTotalCost) {\n\t\tt.Fatal(\"wrong TotalCost\", contract.TotalCost, expectedTotalCost)\n\t}\n}", "func (_Cakevault *CakevaultCaller) CallFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"callFee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_L1Block *L1BlockCallerSession) Basefee() (*big.Int, error) {\n\treturn _L1Block.Contract.Basefee(&_L1Block.CallOpts)\n}", "func (s *BlocksService) Fees(ctx context.Context) (*BlocksFees, *http.Response, error) {\n\tvar responseStruct *BlocksFees\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/getFees\", nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (_ElvTradableLocal *ElvTradableLocalCaller) BaseTransferFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ElvTradableLocal.contract.Call(opts, &out, \"baseTransferFee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_EtherDelta *EtherDeltaCallerSession) FeeMake() (*big.Int, error) {\n\treturn _EtherDelta.Contract.FeeMake(&_EtherDelta.CallOpts)\n}", "func main() {\n\n\tconst (\n\t\turl = `http://dev:8888`\n\t\twif = `5JP1fUXwPxuKuNryh5BEsFhZqnh59yVtpHqHxMMTmtjcni48bqC`\n\t)\n\n\t// error helper\n\tlog.SetFlags(log.LstdFlags | log.Lshortfile)\n\tfatal := func(err error) {\n\t\tif err != nil {\n\t\t\ttrace := log.Output(2, err.Error())\n\t\t\tlog.Fatal(trace)\n\t\t}\n\t}\n\n\taccount, api, opts, err := fio.NewWifConnect(wif, url)\n\tfatal(err)\n\n\taction := fio.NewSetFeeVote(defaultRatios(), account.Actor).ToEos() // note casting to *eos.Action\n\n\t// this is a large tx, without compression it might fail\n\topts.Compress = fio.CompressionZlib\n\t// overriding the default compression requires a using different function\n\tresp, err := api.SignPushActionsWithOpts([]*eos.Action{action}, &opts.TxOptions)\n\tfatal(err)\n\n\t// print result\n\tj, _ := json.MarshalIndent(resp, \"\", \" \")\n\tfmt.Println(string(j))\n\n\t// Now set the fee multiplier\n\tvar (\n\t\ttokenPriceUsd float64 = 0.08 // for the example assume 1 FIO is worth 8 cents\n\t\ttargetUsd float64 = 2.00 // and the goal is for regaddress to cost $2.00\n\t\tregaddressFeeValue float64 = 2000000000 / 1_000_000_000 // and the current fee value is set to 2 FIO (in SUF)\n\t)\n\n\t// 12.5\n\tmultiplier := targetUsd / (regaddressFeeValue * tokenPriceUsd)\n\n\t// submit and print the result\n\tresp, err = api.SignPushActions(fio.NewSetFeeMult(multiplier, account.Actor))\n\tfatal(err)\n\tj, _ = json.MarshalIndent(resp, \"\", \" \")\n\tfmt.Println(string(j))\n\n\t// it's also important that computefees is called frequently, the on-chain fees don't change automatically without it\n\t// this call won't always have any work to do, so it's safe to ignore errors.\n\tresp, err = api.SignPushActions(fio.NewComputeFees(account.Actor))\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tj, _ = json.MarshalIndent(resp, \"\", \" \")\n\tfmt.Println(string(j))\n\n}", "func (_Caller *CallerCaller) Fees(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Caller.contract.Call(opts, &out, \"fees\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_IUniswapV2Factory *IUniswapV2FactorySession) FeeTo() (common.Address, error) {\r\n\treturn _IUniswapV2Factory.Contract.FeeTo(&_IUniswapV2Factory.CallOpts)\r\n}", "func (s *ArkClient) CalculateVotersProfit(params DelegateQueryParams, shareRatio float64, blocklist string, whitelist string, capBalance bool, balanceCapAmount float64, blockBalanceCap bool) []DelegateDataProfit {\n\tdelegateRes, _, _ := s.GetDelegate(params)\n\tvoters, _, _ := s.GetDelegateVoters(params)\n\taccountRes, _, _ := s.GetAccount(AccountQueryParams{Address: delegateRes.SingleDelegate.Address})\n\n\tdelegateBalance, _ := strconv.ParseFloat(accountRes.Account.Balance, 64)\n\tdelegateBalance = float64(delegateBalance) / SATOSHI\n\n\t//calculating vote weight\n\tvotersProfit := []DelegateDataProfit{}\n\tdelelgateVoteWeight := 0\n\n\t//computing summ of all votes\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tintBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tintBalance = int(balanceCapAmount)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelelgateVoteWeight += intBalance\n\t}\n\n\t//calculating\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tcurrentVoterBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcurrentVoterBalance = balanceCapAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdeleProfit := DelegateDataProfit{\n\t\t\tAddress: element.Address,\n\t\t}\n\t\tdeleProfit.VoteWeight = currentVoterBalance / SATOSHI\n\t\tdeleProfit.VoteWeightShare = float64(currentVoterBalance) / float64(delelgateVoteWeight)\n\t\tdeleProfit.EarnedAmount100 = float64(delegateBalance) * deleProfit.VoteWeightShare\n\t\tdeleProfit.EarnedAmountXX = float64(delegateBalance) * deleProfit.VoteWeightShare * shareRatio\n\t\tdeleProfit.VoteDuration = s.GetVoteDuration(element.Address)\n\t\tvotersProfit = append(votersProfit, deleProfit)\n\t}\n\n\treturn votersProfit\n}", "func (_IUniswapV2Factory *IUniswapV2FactoryCallerSession) FeeTo() (common.Address, error) {\r\n\treturn _IUniswapV2Factory.Contract.FeeTo(&_IUniswapV2Factory.CallOpts)\r\n}", "func (c *DataCache) GetFeeRates(N int) (uint32, int64, int, []float64) {\n\tc.mtx.RLock()\n\tdefer c.mtx.RUnlock()\n\n\tnumFees := len(c.allFeeRates)\n\n\t//var fees []float64\n\tfees := []float64{}\n\tif N == 0 {\n\t\treturn c.height, c.timestamp.Unix(), numFees, fees\n\t}\n\n\tif N < 0 || N >= numFees {\n\t\tfees = make([]float64, numFees)\n\t\tcopy(fees, c.allFeeRates)\n\t} else if N < numFees {\n\t\t// fees are in ascending order, take from end of slice\n\t\tsmallestFeeInd := numFees - N\n\t\tfees = make([]float64, N)\n\t\tcopy(fees, c.allFeeRates[smallestFeeInd:])\n\t}\n\n\treturn c.height, c.timestamp.Unix(), numFees, fees\n}", "func (_EtherDelta *EtherDeltaSession) FeeMake() (*big.Int, error) {\n\treturn _EtherDelta.Contract.FeeMake(&_EtherDelta.CallOpts)\n}", "func (_L1Block *L1BlockSession) Basefee() (*big.Int, error) {\n\treturn _L1Block.Contract.Basefee(&_L1Block.CallOpts)\n}", "func (_EtherDelta *EtherDeltaCaller) FeeRebate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _EtherDelta.contract.Call(opts, out, \"feeRebate\")\n\treturn *ret0, err\n}", "func TestFeeBudget(t *testing.T) {\n\tquote := &loop.LoopOutQuote{\n\t\tSwapFee: btcutil.Amount(1),\n\t\tPrepayAmount: btcutil.Amount(500),\n\t\tMinerFee: btcutil.Amount(50),\n\t}\n\n\tchan1 := applyFeeCategoryQuote(\n\t\tchan1Rec, 5000, defaultPrepayRoutingFeePPM,\n\t\tdefaultRoutingFeePPM, *quote,\n\t)\n\tchan2 := applyFeeCategoryQuote(\n\t\tchan2Rec, 5000, defaultPrepayRoutingFeePPM,\n\t\tdefaultRoutingFeePPM, *quote,\n\t)\n\n\ttests := []struct {\n\t\tname string\n\n\t\t// budget is our autoloop budget.\n\t\tbudget btcutil.Amount\n\n\t\t// maxMinerFee is the maximum miner fee we will pay for swaps.\n\t\tmaxMinerFee btcutil.Amount\n\n\t\t// existingSwaps represents our existing swaps, mapping their\n\t\t// last update time to their total cost.\n\t\texistingSwaps map[time.Time]btcutil.Amount\n\n\t\t// suggestions is the set of swaps we expect to be suggested.\n\t\tsuggestions *Suggestions\n\t}{\n\t\t{\n\t\t\t// Two swaps will cost (78+5000)*2, set exactly 10156\n\t\t\t// budget.\n\t\t\tname: \"budget for 2 swaps, no existing\",\n\t\t\tbudget: 10156,\n\t\t\tmaxMinerFee: 5000,\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1, chan2,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Two swaps will cost (78+5000)*2, set 10155 so we can\n\t\t\t// only afford one swap.\n\t\t\tname: \"budget for 1 swaps, no existing\",\n\t\t\tbudget: 10155,\n\t\t\tmaxMinerFee: 5000,\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID2: ReasonBudgetInsufficient,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Set an existing swap which would limit us to a single\n\t\t\t// swap if it were in our period.\n\t\t\tname: \"existing swaps, before budget period\",\n\t\t\tbudget: 10156,\n\t\t\tmaxMinerFee: 5000,\n\t\t\texistingSwaps: map[time.Time]btcutil.Amount{\n\t\t\t\ttestBudgetStart.Add(time.Hour * -1): 200,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1, chan2,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Add an existing swap in our budget period such that\n\t\t\t// we only have budget left for one more swap.\n\t\t\tname: \"existing swaps, in budget period\",\n\t\t\tbudget: 10156,\n\t\t\tmaxMinerFee: 5000,\n\t\t\texistingSwaps: map[time.Time]btcutil.Amount{\n\t\t\t\ttestBudgetStart.Add(time.Hour): 500,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID2: ReasonBudgetInsufficient,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"existing swaps, budget used\",\n\t\t\tbudget: 500,\n\t\t\tmaxMinerFee: 1000,\n\t\t\texistingSwaps: map[time.Time]btcutil.Amount{\n\t\t\t\ttestBudgetStart.Add(time.Hour): 500,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonBudgetElapsed,\n\t\t\t\t\tchanID2: ReasonBudgetElapsed,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, testCase := range tests {\n\t\ttestCase := testCase\n\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\tcfg, lnd := newTestConfig()\n\n\t\t\t// Create a swap set of existing swaps with our set of\n\t\t\t// existing swap timestamps.\n\t\t\tswaps := make(\n\t\t\t\t[]*loopdb.LoopOut, 0,\n\t\t\t\tlen(testCase.existingSwaps),\n\t\t\t)\n\n\t\t\t// Add an event with the timestamp and budget set by\n\t\t\t// our test case.\n\t\t\tfor ts, amt := range testCase.existingSwaps {\n\t\t\t\tevent := &loopdb.LoopEvent{\n\t\t\t\t\tSwapStateData: loopdb.SwapStateData{\n\t\t\t\t\t\tCost: loopdb.SwapCost{\n\t\t\t\t\t\t\tServer: amt,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tState: loopdb.StateSuccess,\n\t\t\t\t\t},\n\t\t\t\t\tTime: ts,\n\t\t\t\t}\n\n\t\t\t\tswaps = append(swaps, &loopdb.LoopOut{\n\t\t\t\t\tLoop: loopdb.Loop{\n\t\t\t\t\t\tEvents: []*loopdb.LoopEvent{\n\t\t\t\t\t\t\tevent,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tContract: autoOutContract,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tcfg.ListLoopOut = func(context.Context) ([]*loopdb.LoopOut, error) {\n\t\t\t\treturn swaps, nil\n\t\t\t}\n\n\t\t\tcfg.LoopOutQuote = func(_ context.Context,\n\t\t\t\t_ *loop.LoopOutQuoteRequest) (*loop.LoopOutQuote,\n\t\t\t\terror) {\n\n\t\t\t\treturn quote, nil\n\t\t\t}\n\n\t\t\t// Set two channels that need swaps.\n\t\t\tlnd.Channels = []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t\tchannel2,\n\t\t\t}\n\n\t\t\tparams := defaultParameters\n\t\t\tparams.ChannelRules = map[lnwire.ShortChannelID]*SwapRule{\n\t\t\t\tchanID1: chanRule,\n\t\t\t\tchanID2: chanRule,\n\t\t\t}\n\t\t\tparams.AutoFeeBudget = testCase.budget\n\t\t\tparams.AutoFeeRefreshPeriod = testBudgetRefresh\n\t\t\tparams.AutoloopBudgetLastRefresh = testBudgetStart\n\t\t\tparams.MaxAutoInFlight = 2\n\t\t\tparams.FeeLimit = NewFeeCategoryLimit(\n\t\t\t\tdefaultSwapFeePPM, defaultRoutingFeePPM,\n\t\t\t\tdefaultPrepayRoutingFeePPM,\n\t\t\t\ttestCase.maxMinerFee, defaultMaximumPrepay,\n\t\t\t\tdefaultSweepFeeRateLimit,\n\t\t\t)\n\n\t\t\t// Set our custom max miner fee on each expected swap,\n\t\t\t// rather than having to create multiple vars for\n\t\t\t// different rates.\n\t\t\tfor i := range testCase.suggestions.OutSwaps {\n\t\t\t\ttestCase.suggestions.OutSwaps[i].MaxMinerFee =\n\t\t\t\t\ttestCase.maxMinerFee\n\t\t\t}\n\n\t\t\ttestSuggestSwaps(\n\t\t\t\tt, newSuggestSwapsSetup(cfg, lnd, params),\n\t\t\t\ttestCase.suggestions, nil,\n\t\t\t)\n\t\t})\n\t}\n}", "func (_SushiV2Factory *SushiV2FactoryCaller) FeeTo(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _SushiV2Factory.contract.Call(opts, &out, \"feeTo\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}", "func calculateFeeAddresses(xpubStr string, params *chaincfg.Params) (map[string]struct{}, error) {\n\tend := uint32(10000)\n\n\tlog.Infof(\"Please wait, deriving %v stake pool fees addresses \"+\n\t\t\"for extended public key %s\", end, xpubStr)\n\n\t// Parse the extended public key and ensure it's the right network.\n\tkey, err := hdkeychain.NewKeyFromString(xpubStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !key.IsForNet(params) {\n\t\treturn nil, fmt.Errorf(\"extended public key is for wrong network\")\n\t}\n\n\t// Derive from external branch\n\tbranchKey, err := key.Child(udb.ExternalBranch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Derive the addresses from [0, end) for this extended public key.\n\taddrs, err := deriveChildAddresses(branchKey, 0, end+1, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddrMap := make(map[string]struct{})\n\tfor i := range addrs {\n\t\taddrMap[addrs[i].EncodeAddress()] = struct{}{}\n\t}\n\n\treturn addrMap, nil\n}", "func (s *BlocksService) Fee(ctx context.Context) (*BlocksFee, *http.Response, error) {\n\tvar responseStruct *BlocksFee\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/getFee\", nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func ComputeFeesWithBaseReq(\n\tclientCtx client.Context, br rest.BaseReq, msgs ...sdk.Msg) (*legacytx.StdFee, error) {\n\n\tgasSetting, err := flags.ParseGasSetting(br.Gas)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgasAdj, err := ParseFloat64(br.GasAdjustment, flags.DefaultGasAdjustment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgas := gasSetting.Gas\n\tif gasSetting.Simulate {\n\t\ttxf := tx.Factory{}.\n\t\t\tWithFees(br.Fees.String()).\n\t\t\tWithGasPrices(br.GasPrices.String()).\n\t\t\tWithGas(gasSetting.Gas).\n\t\t\tWithGasAdjustment(gasAdj).\n\t\t\tWithAccountNumber(br.AccountNumber).\n\t\t\tWithSequence(br.Sequence).\n\t\t\tWithMemo(br.Memo).\n\t\t\tWithChainID(br.ChainID).\n\t\t\tWithSimulateAndExecute(br.Simulate || gasSetting.Simulate).\n\t\t\tWithTxConfig(clientCtx.TxConfig).\n\t\t\tWithTimeoutHeight(br.TimeoutHeight).\n\t\t\tWithAccountRetriever(clientCtx.AccountRetriever)\n\n\t\t// Prepare AccountNumber & SequenceNumber when not given\n\t\tclientCtx.FromAddress, err = sdk.AccAddressFromBech32(br.From)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttxf, err := prepareFactory(clientCtx, txf)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t_, adj, err := tx.CalculateGas(clientCtx, txf, msgs...)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tgas = adj\n\t}\n\n\t// Computes taxes of the msgs\n\ttaxes, err := FilterMsgAndComputeTax(clientCtx, msgs...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfees := br.Fees.Add(taxes...)\n\tgasPrices := br.GasPrices\n\n\tif !gasPrices.IsZero() {\n\t\tglDec := sdk.NewDec(int64(gas))\n\n\t\t// Derive the fees based on the provided gas prices, where\n\t\t// fee = ceil(gasPrice * gasLimit).\n\t\tgasFees := make(sdk.Coins, len(gasPrices))\n\t\tfor i, gp := range gasPrices {\n\t\t\tfee := gp.Amount.Mul(glDec)\n\t\t\tgasFees[i] = sdk.NewCoin(gp.Denom, fee.Ceil().RoundInt())\n\t\t}\n\n\t\tfees = fees.Add(gasFees.Sort()...)\n\t}\n\n\treturn &legacytx.StdFee{\n\t\tAmount: fees,\n\t\tGas: gas,\n\t}, nil\n}", "func (account *Account) ethGasStationFeeTargets() ([]*feeTarget, error) {\n\t// TODO: Use timeout.\n\t// Docs: https://docs.ethgasstation.info/gas-price#gas-price\n\tresponse, err := account.httpClient.Get(\"https://ethgasstation.info/api/ethgasAPI.json?api-key=\" + ethGasStationAPIKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close() //nolint:errcheck\n\tif response.StatusCode != http.StatusOK {\n\t\treturn nil, errp.Newf(\"ethgasstation returned status code %d\", response.StatusCode)\n\t}\n\tvar responseDecoded struct {\n\t\t// Values are in Gwei*10\n\t\tAverage int64 `json:\"average\"`\n\t\tFast int64 `json:\"fast\"`\n\t\tFastest int64 `json:\"fastest\"`\n\t\tSafeLow int64 `json:\"safeLow\"`\n\t}\n\tif err := json.NewDecoder(response.Body).Decode(&responseDecoded); err != nil {\n\t\treturn nil, err\n\t}\n\t// Conversion from 10x Gwei to Wei.\n\tfactor := big.NewInt(1e8)\n\treturn []*feeTarget{\n\t\t{\n\t\t\tcode: accounts.FeeTargetCodeHigh,\n\t\t\tgasPrice: new(big.Int).Mul(big.NewInt(responseDecoded.Fastest), factor),\n\t\t},\n\t\t{\n\t\t\tcode: accounts.FeeTargetCodeNormal,\n\t\t\tgasPrice: new(big.Int).Mul(big.NewInt(responseDecoded.Fast), factor),\n\t\t},\n\t\t{\n\t\t\tcode: accounts.FeeTargetCodeLow,\n\t\t\tgasPrice: new(big.Int).Mul(big.NewInt(responseDecoded.Average), factor),\n\t\t},\n\t\t{\n\t\t\tcode: accounts.FeeTargetCodeEconomy,\n\t\t\tgasPrice: new(big.Int).Mul(big.NewInt(responseDecoded.SafeLow), factor),\n\t\t},\n\t}, nil\n}", "func (_SushiV2Factory *SushiV2FactoryCaller) FeeToSetter(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _SushiV2Factory.contract.Call(opts, &out, \"feeToSetter\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_IUniswapV2Factory *IUniswapV2FactoryCaller) FeeToSetter(opts *bind.CallOpts) (common.Address, error) {\r\n\tvar out []interface{}\r\n\terr := _IUniswapV2Factory.contract.Call(opts, &out, \"feeToSetter\")\r\n\r\n\tif err != nil {\r\n\t\treturn *new(common.Address), err\r\n\t}\r\n\r\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\r\n\r\n\treturn out0, err\r\n\r\n}", "func (hdb *HostDB) priceAdjustments(entry modules.HostDBEntry, allowance modules.Allowance, txnFees types.Currency) float64 {\n\t// Divide by zero mitigation.\n\tif allowance.Hosts == 0 {\n\t\tallowance.Hosts = 1\n\t}\n\tif allowance.Period == 0 {\n\t\tallowance.Period = 1\n\t}\n\tif allowance.ExpectedStorage == 0 {\n\t\tallowance.ExpectedStorage = 1\n\t}\n\tif allowance.ExpectedUpload == 0 {\n\t\tallowance.ExpectedUpload = 1\n\t}\n\tif allowance.ExpectedDownload == 0 {\n\t\tallowance.ExpectedDownload = 1\n\t}\n\tif allowance.ExpectedRedundancy == 0 {\n\t\tallowance.ExpectedRedundancy = 1\n\t}\n\n\t// Convert each element of the allowance into a number of resources that we\n\t// expect to use in this contract.\n\tcontractExpectedDownload := types.NewCurrency64(allowance.ExpectedDownload).Mul64(uint64(allowance.Period)).Div64(allowance.Hosts)\n\tcontractExpectedFunds := allowance.Funds.Div64(allowance.Hosts)\n\tcontractExpectedStorage := uint64(float64(allowance.ExpectedStorage) * allowance.ExpectedRedundancy / float64(allowance.Hosts))\n\tcontractExpectedStorageTime := types.NewCurrency64(contractExpectedStorage).Mul64(uint64(allowance.Period))\n\tcontractExpectedUpload := types.NewCurrency64(allowance.ExpectedUpload).Mul64(uint64(allowance.Period)).MulFloat(allowance.ExpectedRedundancy).Div64(allowance.Hosts)\n\n\t// Calculate the hostCollateral the renter would expect the host to put\n\t// into a contract.\n\t//\n\tcontractTxnFees := txnFees.Mul64(modules.EstimatedFileContractTransactionSetSize)\n\t_, _, _, err := modules.RenterPayouts(entry, contractExpectedFunds, contractTxnFees, types.ZeroCurrency, types.ZeroCurrency, allowance.Period, contractExpectedStorage)\n\tif err != nil {\n\t\tinfo := fmt.Sprintf(\"Error while estimating collateral for host: Host %v, ContractPrice %v, TxnFees %v, Funds %v\",\n\t\t\tentry.PublicKey.String(), entry.ContractPrice.HumanString(), txnFees.HumanString(), allowance.Funds.HumanString())\n\t\thdb.log.Debugln(errors.AddContext(err, info))\n\t\treturn 0\n\t}\n\n\t// Determine the pricing for each type of resource in the contract. We have\n\t// already converted the resources into absolute terms for this contract.\n\t//\n\t// The contract price and transaction fees get doubled because we expect\n\t// that there will be on average one early renewal per contract, due to\n\t// spending all of the contract's money.\n\tcontractPrice := entry.ContractPrice.Add(txnFees).Mul64(2)\n\tdownloadPrice := entry.DownloadBandwidthPrice.Mul(contractExpectedDownload)\n\tstoragePrice := entry.StoragePrice.Mul(contractExpectedStorageTime)\n\tuploadPrice := entry.UploadBandwidthPrice.Mul(contractExpectedUpload)\n\ttotalPrice := contractPrice.Add(downloadPrice).Add(storagePrice).Add(uploadPrice)\n\n\t// Determine a cutoff for whether the total price is considered a high price\n\t// or a low price. This cutoff attempts to determine where the price becomes\n\t// insignificant.\n\tcutoff := contractExpectedFunds.MulFloat(priceFloor)\n\n\t// Convert the price and cutoff to floats.\n\tprice64, _ := totalPrice.Float64()\n\tcutoff64, _ := cutoff.Float64()\n\t// If the total price is less than the cutoff, set the cutoff equal to the\n\t// price. This ensures that the ratio (totalPrice / cutoff) can never be\n\t// less than 1.\n\tif price64 < cutoff64 {\n\t\tcutoff64 = price64\n\t}\n\n\t// Check for less-than-one.\n\tif price64 < 1 {\n\t\tprice64 = 1\n\t}\n\tif cutoff64 < 1 {\n\t\tcutoff64 = 1\n\t}\n\t// Perform this check one more time after all of the conversions, just in\n\t// case there was some sort of rounding error.\n\tif price64 < cutoff64 {\n\t\tcutoff64 = price64\n\t}\n\tratio := price64 / cutoff64\n\n\tsmallWeight := math.Pow(cutoff64, priceExponentiationSmall)\n\tlargeWeight := math.Pow(ratio, priceExponentiationLarge)\n\n\treturn 1 / (smallWeight * largeWeight)\n}", "func (_SushiV2Factory *SushiV2FactorySession) FeeTo() (common.Address, error) {\n\treturn _SushiV2Factory.Contract.FeeTo(&_SushiV2Factory.CallOpts)\n}", "func (_IUniswapV2Factory *IUniswapV2FactoryCallerSession) FeeToSetter() (common.Address, error) {\r\n\treturn _IUniswapV2Factory.Contract.FeeToSetter(&_IUniswapV2Factory.CallOpts)\r\n}", "func (k Keeper) RefundServiceFees(ctx sdk.Context) error {\n\titerator := k.ActiveAllRequestQueueIterator(ctx)\n\tdefer iterator.Close()\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tvar request types.SvcRequest\n\t\tk.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &request)\n\n\t\terr := k.sk.SendCoinsFromModuleToAccount(ctx, types.RequestAccName, request.Consumer, request.ServiceFee)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tb *transactionBuilder) FundContract(amount types.Currency) ([]types.SiacoinOutput, error) {\n\t// dustThreshold has to be obtained separate from the lock\n\tdustThreshold, err := tb.wallet.DustThreshold()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tconsensusHeight, err := dbGetConsensusHeight(tb.wallet.dbTx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tso, err := tb.wallet.getSortedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tvar spentScoids []types.SiacoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that the output can be spent.\n\t\tif err := tb.wallet.checkOutput(tb.wallet.dbTx, consensusHeight, scoid, sco, dustThreshold); err != nil {\n\t\t\tif err == errSpendHeightTooHigh {\n\t\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tkey, ok := tb.wallet.keys[sco.UnlockHash]\n\t\tif !ok {\n\t\t\treturn nil, errMissingOutputKey\n\t\t}\n\n\t\t// Add a siacoin input for this output.\n\t\tsci := types.SiacoinInput{\n\t\t\tParentID: scoid,\n\t\t\tUnlockConditions: key.UnlockConditions,\n\t\t}\n\t\ttb.siacoinInputs = append(tb.siacoinInputs, len(tb.transaction.SiacoinInputs))\n\t\ttb.transaction.SiacoinInputs = append(tb.transaction.SiacoinInputs, sci)\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn nil, modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn nil, modules.ErrLowBalance\n\t}\n\tvar refundOutput types.SiacoinOutput\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\trefundUnlockConditions, err := tb.wallet.nextPrimarySeedAddress(tb.wallet.dbTx)\n\t\tif err != nil {\n\t\t\trefundUnlockConditions, err = tb.wallet.GetAddress() // try get address if generate address failed when funding contracts\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\trefundOutput = types.SiacoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tUnlockHash: refundUnlockConditions.UnlockHash(),\n\t\t}\n\t\ttb.transaction.SiacoinOutputs = append(tb.transaction.SiacoinOutputs, refundOutput)\n\t}\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\terr = dbPutSpentOutput(tb.wallet.dbTx, types.OutputID(scoid), consensusHeight)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn []types.SiacoinOutput{refundOutput}, nil\n}", "func (_SushiV2Factory *SushiV2FactoryCallerSession) FeeTo() (common.Address, error) {\n\treturn _SushiV2Factory.Contract.FeeTo(&_SushiV2Factory.CallOpts)\n}", "func (_Authority *AuthorityCallerSession) Fee() (*big.Int, error) {\n\treturn _Authority.Contract.Fee(&_Authority.CallOpts)\n}", "func (f Fortune) Total() decimal.Decimal { return f.active.Add(f.saving) }", "func (_BREM *BREMTransactor) WithdrawFees(opts *bind.TransactOpts, _value *big.Int) (*types.Transaction, error) {\n\treturn _BREM.contract.Transact(opts, \"withdrawFees\", _value)\n}", "func (_IUniswapV2Factory *IUniswapV2FactorySession) FeeToSetter() (common.Address, error) {\r\n\treturn _IUniswapV2Factory.Contract.FeeToSetter(&_IUniswapV2Factory.CallOpts)\r\n}", "func ComputeMonthlyBotFees(months uint8, oneCoin types.Currency) types.Currency {\n\tmultiplier := uint64(months) * BotMonthlyFeeMultiplier\n\tif months < 12 {\n\t\t// return plain monthly fees without discounts\n\t\treturn oneCoin.Mul64(multiplier)\n\t}\n\tfees := big.NewFloat(float64(multiplier))\n\tfees.Mul(fees, new(big.Float).SetInt(oneCoin.Big()))\n\tif months < 24 {\n\t\t// return plain monthly fees with 30% discount applied to the total\n\t\ti, _ := fees.Mul(fees, big.NewFloat(0.7)).Int(nil)\n\t\treturn types.NewCurrency(i)\n\t}\n\t// return plain monthly fees with 50% discount applied to the total\n\ti, _ := fees.Mul(fees, big.NewFloat(0.5)).Int(nil)\n\treturn types.NewCurrency(i)\n}", "func TestFeePercentage(t *testing.T) {\n\tvar (\n\t\tokPPM uint64 = 30000\n\t\tokQuote = &loop.LoopOutQuote{\n\t\t\tSwapFee: 15,\n\t\t\tPrepayAmount: 30,\n\t\t\tMinerFee: 1,\n\t\t}\n\n\t\trec = loop.OutRequest{\n\t\t\tAmount: 7500,\n\t\t\tOutgoingChanSet: loopdb.ChannelSet{chanID1.ToUint64()},\n\t\t\tMaxMinerFee: scaleMaxMinerFee(\n\t\t\t\tscaleMinerFee(testQuote.MinerFee),\n\t\t\t),\n\t\t\tMaxSwapFee: okQuote.SwapFee,\n\t\t\tMaxPrepayAmount: okQuote.PrepayAmount,\n\t\t\tSweepConfTarget: defaultConfTarget,\n\t\t\tInitiator: autoloopSwapInitiator,\n\t\t}\n\t)\n\n\trec.MaxPrepayRoutingFee, rec.MaxSwapRoutingFee = testPPMFees(\n\t\tokPPM, okQuote, 7500,\n\t)\n\n\ttests := []struct {\n\t\tname string\n\t\tfeePPM uint64\n\t\tquote *loop.LoopOutQuote\n\t\tsuggestions *Suggestions\n\t}{\n\t\t{\n\t\t\t// With our limit set to 3% of swap amount 7500, we\n\t\t\t// have a total budget of 225 sat.\n\t\t\tname: \"fees ok\",\n\t\t\tfeePPM: okPPM,\n\t\t\tquote: okQuote,\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\trec,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"swap fee too high\",\n\t\t\tfeePPM: 20000,\n\t\t\tquote: &loop.LoopOutQuote{\n\t\t\t\tSwapFee: 300,\n\t\t\t\tPrepayAmount: 30,\n\t\t\t\tMinerFee: 1,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonSwapFee,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"miner fee too high\",\n\t\t\tfeePPM: 20000,\n\t\t\tquote: &loop.LoopOutQuote{\n\t\t\t\tSwapFee: 80,\n\t\t\t\tPrepayAmount: 30,\n\t\t\t\tMinerFee: 300,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonMinerFee,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"miner and swap too high\",\n\t\t\tfeePPM: 20000,\n\t\t\tquote: &loop.LoopOutQuote{\n\t\t\t\tSwapFee: 60,\n\t\t\t\tPrepayAmount: 30,\n\t\t\t\tMinerFee: 50,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonFeePPMInsufficient,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, testCase := range tests {\n\t\ttestCase := testCase\n\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\tcfg, lnd := newTestConfig()\n\n\t\t\tcfg.LoopOutQuote = func(_ context.Context,\n\t\t\t\t_ *loop.LoopOutQuoteRequest) (*loop.LoopOutQuote,\n\t\t\t\terror) {\n\n\t\t\t\treturn testCase.quote, nil\n\t\t\t}\n\n\t\t\tlnd.Channels = []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t}\n\n\t\t\tparams := defaultParameters\n\t\t\tparams.AutoloopBudgetLastRefresh = testBudgetStart\n\t\t\tparams.FeeLimit = NewFeePortion(testCase.feePPM)\n\t\t\tparams.ChannelRules = map[lnwire.ShortChannelID]*SwapRule{\n\t\t\t\tchanID1: chanRule,\n\t\t\t}\n\n\t\t\ttestSuggestSwaps(\n\t\t\t\tt, newSuggestSwapsSetup(cfg, lnd, params),\n\t\t\t\ttestCase.suggestions, nil,\n\t\t\t)\n\t\t})\n\t}\n}", "func (httpServer *HttpServer) handleEstimateFee(params interface{}, closeChan <-chan struct{}) (interface{}, *rpcservice.RPCError) {\n\tLogger.log.Debugf(\"handleEstimateFee params: %+v\", params)\n\t/******* START Fetch all component to ******/\n\t// all component\n\tarrayParams := common.InterfaceSlice(params)\n\tif arrayParams == nil || len(arrayParams) < 4 {\n\t\treturn nil, rpcservice.NewRPCError(rpcservice.RPCInvalidParamsError, errors.New(\"Not enough params\"))\n\t}\n\t// param #1: private key of sender\n\tsenderKeyParam, ok := arrayParams[0].(string)\n\tif !ok {\n\t\treturn nil, rpcservice.NewRPCError(rpcservice.RPCInvalidParamsError, errors.New(\"Sender private key is invalid\"))\n\t}\n\t// param #3: estimation fee coin per kb\n\tdefaultFeeCoinPerKbtemp, ok := arrayParams[2].(float64)\n\tif !ok {\n\t\treturn nil, rpcservice.NewRPCError(rpcservice.RPCInvalidParamsError, errors.New(\"Default FeeCoinPerKbtemp is invalid\"))\n\t}\n\tdefaultFeeCoinPerKb := int64(defaultFeeCoinPerKbtemp)\n\t// param #4: hasPrivacy flag for PRV\n\thashPrivacyTemp, ok := arrayParams[3].(float64)\n\tif !ok {\n\t\treturn nil, rpcservice.NewRPCError(rpcservice.RPCInvalidParamsError, errors.New(\"hasPrivacy is invalid\"))\n\t}\n\thasPrivacy := int(hashPrivacyTemp) > 0\n\n\tsenderKeySet, shardIDSender, err := rpcservice.GetKeySetFromPrivateKeyParams(senderKeyParam)\n\tif err != nil {\n\t\treturn nil, rpcservice.NewRPCError(rpcservice.InvalidSenderPrivateKeyError, err)\n\t}\n\n\toutCoins, err := httpServer.outputCoinService.ListOutputCoinsByKeySet(senderKeySet, shardIDSender)\n\tif err != nil {\n\t\treturn nil, rpcservice.NewRPCError(rpcservice.GetOutputCoinError, err)\n\t}\n\n\t// remove out coin in mem pool\n\toutCoins, err = httpServer.txMemPoolService.FilterMemPoolOutcoinsToSpent(outCoins)\n\tif err != nil {\n\t\treturn nil, rpcservice.NewRPCError(rpcservice.GetOutputCoinError, err)\n\t}\n\n\testimateFeeCoinPerKb := uint64(0)\n\testimateTxSizeInKb := uint64(0)\n\tif len(outCoins) > 0 {\n\t\t// param #2: list receiver\n\t\treceiversPaymentAddressStrParam := make(map[string]interface{})\n\t\tif arrayParams[1] != nil {\n\t\t\treceiversPaymentAddressStrParam, ok = arrayParams[1].(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, rpcservice.NewRPCError(rpcservice.RPCInvalidParamsError, errors.New(\"receivers payment address is invalid\"))\n\t\t\t}\n\t\t}\n\n\t\tpaymentInfos, err := rpcservice.NewPaymentInfosFromReceiversParam(receiversPaymentAddressStrParam)\n\t\tif err != nil {\n\t\t\treturn nil, rpcservice.NewRPCError(rpcservice.InvalidReceiverPaymentAddressError, err)\n\t\t}\n\n\t\t// Check custom token param\n\t\tvar customTokenParams *transaction.CustomTokenParamTx\n\t\tvar customPrivacyTokenParam *transaction.CustomTokenPrivacyParamTx\n\t\tisGetPTokenFee := false\n\t\tif len(arrayParams) > 4 {\n\t\t\t// param #5: token params\n\t\t\ttokenParamsRaw, ok := arrayParams[4].(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, rpcservice.NewRPCError(rpcservice.RPCInvalidParamsError, errors.New(\"token param is invalid\"))\n\t\t\t}\n\n\t\t\tcustomTokenParams, customPrivacyTokenParam, err = httpServer.txService.BuildTokenParam(tokenParamsRaw, senderKeySet, shardIDSender)\n\t\t\tif err.(*rpcservice.RPCError) != nil {\n\t\t\t\treturn nil, err.(*rpcservice.RPCError)\n\t\t\t}\n\t\t}\n\n\t\tbeaconState, err := httpServer.blockService.BlockChain.BestState.GetClonedBeaconBestState()\n\t\tbeaconHeight := beaconState.BeaconHeight\n\n\t\tvar err2 error\n\t\t_, estimateFeeCoinPerKb, estimateTxSizeInKb, err2 = httpServer.txService.EstimateFee(\n\t\t\tdefaultFeeCoinPerKb, isGetPTokenFee, outCoins, paymentInfos, shardIDSender, 8, hasPrivacy, nil,\n\t\t\tcustomTokenParams, customPrivacyTokenParam, *httpServer.config.Database, int64(beaconHeight))\n\t\tif err2 != nil{\n\t\t\treturn nil, rpcservice.NewRPCError(rpcservice.RejectInvalidFeeError, err2)\n\t\t}\n\t}\n\tresult := jsonresult.NewEstimateFeeResult(estimateFeeCoinPerKb, estimateTxSizeInKb)\n\tLogger.log.Debugf(\"handleEstimateFee result: %+v\", result)\n\treturn result, nil\n}", "func (_Cakevault *CakevaultCaller) WithdrawFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"withdrawFee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (tx *Tx) CalculateFee(f *FeeQuote) (uint64, error) {\r\n\ttotal := tx.TotalInputSatoshis() - tx.TotalOutputSatoshis()\r\n\tsats, _, err := tx.change(nil, f, false)\r\n\tif err != nil {\r\n\t\treturn 0, err\r\n\t}\r\n\treturn total - sats, nil\r\n}", "func (account *Account) feeTargets() []*feeTarget {\n\tethGasStationTargets, err := account.ethGasStationFeeTargets()\n\tif err == nil {\n\t\treturn ethGasStationTargets\n\t}\n\taccount.log.WithError(err).Error(\"Could not get fee targets from eth gas station, falling back to RPC eth_gasPrice\")\n\tsuggestedGasPrice, err := account.coin.client.SuggestGasPrice(context.TODO())\n\tif err != nil {\n\t\taccount.log.WithError(err).Error(\"Fallback to RPC eth_gasPrice failed\")\n\t\treturn nil\n\t}\n\treturn []*feeTarget{\n\t\t{\n\t\t\tcode: accounts.FeeTargetCodeNormal,\n\t\t\tgasPrice: suggestedGasPrice,\n\t\t},\n\t}\n}", "func (_IUniswapV2Factory *IUniswapV2FactoryCaller) FeeTo(opts *bind.CallOpts) (common.Address, error) {\r\n\tvar out []interface{}\r\n\terr := _IUniswapV2Factory.contract.Call(opts, &out, \"feeTo\")\r\n\r\n\tif err != nil {\r\n\t\treturn *new(common.Address), err\r\n\t}\r\n\r\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\r\n\r\n\treturn out0, err\r\n\r\n}", "func (rpcServer RpcServer) handleEstimateFee(params interface{}, closeChan <-chan struct{}) (interface{}, *RPCError) {\n\tLogger.log.Infof(\"handleEstimateFee params: %+v\", params)\n\t/******* START Fetch all component to ******/\n\t// all component\n\tarrayParams := common.InterfaceSlice(params)\n\tif len(arrayParams) < 5 {\n\t\treturn nil, NewRPCError(ErrRPCInvalidParams, errors.New(\"Not enough params\"))\n\t}\n\t// param #1: private key of sender\n\tsenderKeyParam, ok := arrayParams[0].(string)\n\tif !ok {\n\t\treturn nil, NewRPCError(ErrRPCInvalidParams, errors.New(\"Sender private key is invalid\"))\n\t}\n\t// param #3: estimation fee coin per kb\n\tdefaultFeeCoinPerKbtemp, ok := arrayParams[2].(float64)\n\tif !ok {\n\t\treturn nil, NewRPCError(ErrRPCInvalidParams, errors.New(\"Default FeeCoinPerKbtemp is invalid\"))\n\t}\n\tdefaultFeeCoinPerKb := int64(defaultFeeCoinPerKbtemp)\n\t// param #4: hasPrivacy flag for constant\n\thashPrivacyTemp, ok := arrayParams[3].(float64)\n\tif !ok {\n\t\treturn nil, NewRPCError(ErrRPCInvalidParams, errors.New(\"hasPrivacy is invalid\"))\n\t}\n\thasPrivacy := int(hashPrivacyTemp) > 0\n\n\tsenderKeySet, err := rpcServer.GetKeySetFromPrivateKeyParams(senderKeyParam)\n\tif err != nil {\n\t\treturn nil, NewRPCError(ErrInvalidSenderPrivateKey, err)\n\t}\n\tlastByte := senderKeySet.PaymentAddress.Pk[len(senderKeySet.PaymentAddress.Pk)-1]\n\tshardIDSender := common.GetShardIDFromLastByte(lastByte)\n\t//fmt.Printf(\"Done param #1: keyset: %+v\\n\", senderKeySet)\n\n\tconstantTokenID := &common.Hash{}\n\tconstantTokenID.SetBytes(common.ConstantID[:])\n\toutCoins, err := rpcServer.config.BlockChain.GetListOutputCoinsByKeyset(senderKeySet, shardIDSender, constantTokenID)\n\tif err != nil {\n\t\treturn nil, NewRPCError(ErrGetOutputCoin, err)\n\t}\n\t// remove out coin in mem pool\n\toutCoins, err = rpcServer.filterMemPoolOutCoinsToSpent(outCoins)\n\tif err != nil {\n\t\treturn nil, NewRPCError(ErrGetOutputCoin, err)\n\t}\n\n\testimateFeeCoinPerKb := uint64(0)\n\testimateTxSizeInKb := uint64(0)\n\tif len(outCoins) > 0 {\n\t\t// param #2: list receiver\n\t\treceiversPaymentAddressStrParam := make(map[string]interface{})\n\t\tif arrayParams[1] != nil {\n\t\t\treceiversPaymentAddressStrParam = arrayParams[1].(map[string]interface{})\n\t\t}\n\t\tpaymentInfos := make([]*privacy.PaymentInfo, 0)\n\t\tfor paymentAddressStr, amount := range receiversPaymentAddressStrParam {\n\t\t\tkeyWalletReceiver, err := wallet.Base58CheckDeserialize(paymentAddressStr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, NewRPCError(ErrInvalidReceiverPaymentAddress, err)\n\t\t\t}\n\t\t\tpaymentInfo := &privacy.PaymentInfo{\n\t\t\t\tAmount: uint64(amount.(float64)),\n\t\t\t\tPaymentAddress: keyWalletReceiver.KeySet.PaymentAddress,\n\t\t\t}\n\t\t\tpaymentInfos = append(paymentInfos, paymentInfo)\n\t\t}\n\n\t\t// Check custom token param\n\t\tvar customTokenParams *transaction.CustomTokenParamTx\n\t\tvar customPrivacyTokenParam *transaction.CustomTokenPrivacyParamTx\n\t\tif len(arrayParams) > 4 {\n\t\t\t// param #5: token params\n\t\t\ttokenParamsRaw := arrayParams[4].(map[string]interface{})\n\t\t\tprivacy := tokenParamsRaw[\"Privacy\"].(bool)\n\t\t\tif !privacy {\n\t\t\t\t// Check normal custom token param\n\t\t\t\tcustomTokenParams, _, err = rpcServer.buildCustomTokenParam(tokenParamsRaw, senderKeySet)\n\t\t\t\tif err.(*RPCError) != nil {\n\t\t\t\t\treturn nil, err.(*RPCError)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Check privacy custom token param\n\t\t\t\tcustomPrivacyTokenParam, _, _, err = rpcServer.buildPrivacyCustomTokenParam(tokenParamsRaw, senderKeySet, shardIDSender)\n\t\t\t\tif err.(*RPCError) != nil {\n\t\t\t\t\treturn nil, err.(*RPCError)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// check real fee(nano constant) per tx\n\t\t_, estimateFeeCoinPerKb, estimateTxSizeInKb = rpcServer.estimateFee(defaultFeeCoinPerKb, outCoins, paymentInfos, shardIDSender, 8, hasPrivacy, nil, customTokenParams, customPrivacyTokenParam)\n\t}\n\tresult := jsonresult.EstimateFeeResult{\n\t\tEstimateFeeCoinPerKb: estimateFeeCoinPerKb,\n\t\tEstimateTxSizeInKb: estimateTxSizeInKb,\n\t}\n\tLogger.log.Infof(\"handleEstimateFee result: %+v\", result)\n\treturn result, nil\n}", "func (_Caller *CallerTransactorSession) WithdrawFees(to common.Address) (*types.Transaction, error) {\n\treturn _Caller.Contract.WithdrawFees(&_Caller.TransactOpts, to)\n}", "func (f *feeService) setFee(fee chainfee.SatPerKWeight) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tf.Fees[feeServiceTarget] = uint32(fee.FeePerKVByte())\n}", "func (income Income) CalculateNetIncome(employee *employee.Employee, ic []IncomeSource) {\n\tfor _, income := range ic {\n\t\tfmt.Printf(\"Income From %s = $%d\\n\", income.source(), income.calculate())\n\t\tincome.netincome += income.calculate()\n\t}\n\tfmt.Printf(\"Net income of organisation = $%d\", netincome)\n}", "func setChainInfo(ctx iscp.Sandbox) (dict.Dict, error) {\n\ta := assert.NewAssert(ctx.Log())\n\ta.Require(governance.CheckAuthorizationByChainOwner(ctx.State(), ctx.Caller()), \"governance.setContractFee: not authorized\")\n\n\tparams := kvdecoder.New(ctx.Params(), ctx.Log())\n\n\t// max blob size\n\tmaxBlobSize := params.MustGetUint32(governance.ParamMaxBlobSize, 0)\n\tif maxBlobSize > 0 {\n\t\tctx.State().Set(governance.VarMaxBlobSize, codec.Encode(maxBlobSize))\n\t\tctx.Event(fmt.Sprintf(\"[updated chain config] max blob size: %d\", maxBlobSize))\n\t}\n\n\t// max event size\n\tmaxEventSize := params.MustGetUint16(governance.ParamMaxEventSize, 0)\n\tif maxEventSize > 0 {\n\t\tif maxEventSize < governance.MinEventSize {\n\t\t\t// don't allow to set less than MinEventSize to prevent chain owner from bricking the chain\n\t\t\tmaxEventSize = governance.MinEventSize\n\t\t}\n\t\tctx.State().Set(governance.VarMaxEventSize, codec.Encode(maxEventSize))\n\t\tctx.Event(fmt.Sprintf(\"[updated chain config] max event size: %d\", maxEventSize))\n\t}\n\n\t// max events per request\n\tmaxEventsPerReq := params.MustGetUint16(governance.ParamMaxEventsPerRequest, 0)\n\tif maxEventsPerReq > 0 {\n\t\tif maxEventsPerReq < governance.MinEventsPerRequest {\n\t\t\tmaxEventsPerReq = governance.MinEventsPerRequest\n\t\t}\n\t\tctx.State().Set(governance.VarMaxEventsPerReq, codec.Encode(maxEventsPerReq))\n\t\tctx.Event(fmt.Sprintf(\"[updated chain config] max eventsPerRequest: %d\", maxEventsPerReq))\n\t}\n\n\t// default owner fee\n\townerFee := params.MustGetInt64(governance.ParamOwnerFee, -1)\n\tif ownerFee >= 0 {\n\t\tctx.State().Set(governance.VarDefaultOwnerFee, codec.EncodeInt64(ownerFee))\n\t\tctx.Event(fmt.Sprintf(\"[updated chain config] default owner fee: %d\", ownerFee))\n\t}\n\n\t// default validator fee\n\tvalidatorFee := params.MustGetInt64(governance.ParamValidatorFee, -1)\n\tif validatorFee >= 0 {\n\t\tctx.State().Set(governance.VarDefaultValidatorFee, codec.EncodeInt64(validatorFee))\n\t\tctx.Event(fmt.Sprintf(\"[updated chain config] default validator fee: %d\", validatorFee))\n\t}\n\treturn nil, nil\n}", "func defaultRatios() []*fio.FeeValue {\n\treturn []*fio.FeeValue{\n\t\t{\n\t\t\tEndPoint: \"register_fio_domain\",\n\t\t\tValue: 40000000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"register_fio_address\",\n\t\t\tValue: 2000000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"renew_fio_domain\",\n\t\t\tValue: 40000000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"renew_fio_address\",\n\t\t\tValue: 2000000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"add_pub_address\",\n\t\t\tValue: 30000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"transfer_tokens_pub_key\",\n\t\t\tValue: 100000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"new_funds_request\",\n\t\t\tValue: 60000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"reject_funds_request\",\n\t\t\tValue: 30000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"record_obt_data\",\n\t\t\tValue: 60000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"set_fio_domain_public\",\n\t\t\tValue: 30000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"register_producer\",\n\t\t\tValue: 10000000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"register_proxy\",\n\t\t\tValue: 1000000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"unregister_proxy\",\n\t\t\tValue: 20000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"unregister_producer\",\n\t\t\tValue: 20000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"proxy_vote\",\n\t\t\tValue: 30000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"vote_producer\",\n\t\t\tValue: 30000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"add_to_whitelist\",\n\t\t\tValue: 30000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"remove_from_whitelist\",\n\t\t\tValue: 30000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"submit_bundled_transaction\",\n\t\t\tValue: 30000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"auth_delete\",\n\t\t\tValue: 20000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"auth_link\",\n\t\t\tValue: 20000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"auth_update\",\n\t\t\tValue: 50000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"msig_propose\",\n\t\t\tValue: 50000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"msig_approve\",\n\t\t\tValue: 20000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"msig_unapprove\",\n\t\t\tValue: 20000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"msig_cancel\",\n\t\t\tValue: 20000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"msig_exec\",\n\t\t\tValue: 20000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"msig_invalidate\",\n\t\t\tValue: 20000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"cancel_funds_request\",\n\t\t\tValue: 60000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"remove_pub_address\",\n\t\t\tValue: 60000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"remove_all_pub_addresses\",\n\t\t\tValue: 60000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"transfer_fio_domain\",\n\t\t\tValue: 100000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"transfer_fio_address\",\n\t\t\tValue: 60000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"submit_fee_multiplier\",\n\t\t\tValue: 60000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"submit_fee_ratios\",\n\t\t\tValue: 20000000,\n\t\t},\n\t\t{\n\t\t\tEndPoint: \"burn_fio_address\",\n\t\t\tValue: 60000000,\n\t\t},\n\t}\n}", "func GetTransactionFees(transactionResultDto dto.TransactionResultDto) (map[string][]map[string]interface{}, error) {\n\tvar feeDicts = map[string][]map[string]interface{}{}\n\teventLogs := transactionResultDto.Logs\n\tif len(eventLogs) == 0 {\n\t\treturn nil, errors.New(\"transaction Result Dto not found Logs error\")\n\t}\n\tfor _, log := range eventLogs {\n\t\tnonIndexedBytes, _ := util.Base64DecodeBytes(log.NonIndexed)\n\t\tif log.Name == \"TransactionFeeCharged\" {\n\t\t\tvar feeCharged = new(pb.TransactionFeeCharged)\n\t\t\tproto.Unmarshal(nonIndexedBytes, feeCharged)\n\t\t\tvar feeMap = map[string]interface{}{feeCharged.Symbol: feeCharged.Amount}\n\t\t\tfeeDicts[\"TransactionFeeCharged\"] = append(feeDicts[\"TransactionFeeCharged\"], feeMap)\n\t\t}\n\n\t\tif log.Name == \"ResourceTokenCharged\" {\n\t\t\tvar tokenCharged = new(pb.ResourceTokenCharged)\n\t\t\tproto.Unmarshal(nonIndexedBytes, tokenCharged)\n\t\t\tvar feeMap = map[string]interface{}{tokenCharged.Symbol: tokenCharged.Amount}\n\t\t\tfeeDicts[\"ResourceTokenCharged\"] = append(feeDicts[\"ResourceTokenCharged\"], feeMap)\n\t\t}\n\t}\n\treturn feeDicts, nil\n}", "func totalExpense(s []SalaryCalculator) int {\n expense := 0\n for _, v := range s {\n expense += v.CalculateSalary()\n }\n\n return expense\n}", "func (_Caller *CallerSession) WithdrawFees(to common.Address) (*types.Transaction, error) {\n\treturn _Caller.Contract.WithdrawFees(&_Caller.TransactOpts, to)\n}", "func (_Authority *AuthoritySession) Fee() (*big.Int, error) {\n\treturn _Authority.Contract.Fee(&_Authority.CallOpts)\n}", "func (_EtherDelta *EtherDeltaCaller) FeeAccount(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _EtherDelta.contract.Call(opts, out, \"feeAccount\")\n\treturn *ret0, err\n}", "func listTransactions(tx walletdb.ReadTx, details *wtxmgr.TxDetails, addrMgr *waddrmgr.Manager,\n\tsyncHeight int32, net *chaincfg.Params) []btcjson.ListTransactionsResult {\n\n\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\n\tvar (\n\t\tblockHashStr string\n\t\tblockTime int64\n\t\tconfirmations int64\n\t)\n\tif details.Block.Height != -1 {\n\t\tblockHashStr = details.Block.Hash.String()\n\t\tblockTime = details.Block.Time.Unix()\n\t\tconfirmations = int64(confirms(details.Block.Height, syncHeight))\n\t}\n\n\tresults := []btcjson.ListTransactionsResult{}\n\ttxHashStr := details.Hash.String()\n\treceived := details.Received.Unix()\n\tgenerated := blockchain.IsCoinBaseTx(&details.MsgTx)\n\trecvCat := RecvCategory(details, syncHeight, net).String()\n\n\tsend := len(details.Debits) != 0\n\n\t// Fee can only be determined if every input is a debit.\n\tvar feeF64 float64\n\tif len(details.Debits) == len(details.MsgTx.TxIn) {\n\t\tvar debitTotal btcutil.Amount\n\t\tfor _, deb := range details.Debits {\n\t\t\tdebitTotal += deb.Amount\n\t\t}\n\t\tvar outputTotal btcutil.Amount\n\t\tfor _, output := range details.MsgTx.TxOut {\n\t\t\toutputTotal += btcutil.Amount(output.Value)\n\t\t}\n\t\t// Note: The actual fee is debitTotal - outputTotal. However,\n\t\t// this RPC reports negative numbers for fees, so the inverse\n\t\t// is calculated.\n\t\tfeeF64 = (outputTotal - debitTotal).ToBTC()\n\t}\n\noutputs:\n\tfor i, output := range details.MsgTx.TxOut {\n\t\t// Determine if this output is a credit, and if so, determine\n\t\t// its spentness.\n\t\tvar isCredit bool\n\t\tvar spentCredit bool\n\t\tfor _, cred := range details.Credits {\n\t\t\tif cred.Index == uint32(i) {\n\t\t\t\t// Change outputs are ignored.\n\t\t\t\tif cred.Change {\n\t\t\t\t\tcontinue outputs\n\t\t\t\t}\n\n\t\t\t\tisCredit = true\n\t\t\t\tspentCredit = cred.Spent\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tvar address string\n\t\tvar accountName string\n\t\t_, addrs, _, _ := txscript.ExtractPkScriptAddrs(output.PkScript, net)\n\t\tif len(addrs) == 1 {\n\t\t\taddr := addrs[0]\n\t\t\taddress = addr.EncodeAddress()\n\t\t\tmgr, account, err := addrMgr.AddrAccount(addrmgrNs, addrs[0])\n\t\t\tif err == nil {\n\t\t\t\taccountName, err = mgr.AccountName(addrmgrNs, account)\n\t\t\t\tif err != nil {\n\t\t\t\t\taccountName = \"\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tamountF64 := btcutil.Amount(output.Value).ToBTC()\n\t\tresult := btcjson.ListTransactionsResult{\n\t\t\t// Fields left zeroed:\n\t\t\t// InvolvesWatchOnly\n\t\t\t// BlockIndex\n\t\t\t//\n\t\t\t// Fields set below:\n\t\t\t// Account (only for non-\"send\" categories)\n\t\t\t// Category\n\t\t\t// Amount\n\t\t\t// Fee\n\t\t\tAddress: address,\n\t\t\tVout: uint32(i),\n\t\t\tConfirmations: confirmations,\n\t\t\tGenerated: generated,\n\t\t\tBlockHash: blockHashStr,\n\t\t\tBlockTime: blockTime,\n\t\t\tTxID: txHashStr,\n\t\t\tWalletConflicts: []string{},\n\t\t\tTime: received,\n\t\t\tTimeReceived: received,\n\t\t}\n\n\t\t// Add a received/generated/immature result if this is a credit.\n\t\t// If the output was spent, create a second result under the\n\t\t// send category with the inverse of the output amount. It is\n\t\t// therefore possible that a single output may be included in\n\t\t// the results set zero, one, or two times.\n\t\t//\n\t\t// Since credits are not saved for outputs that are not\n\t\t// controlled by this wallet, all non-credits from transactions\n\t\t// with debits are grouped under the send category.\n\n\t\tif send || spentCredit {\n\t\t\tresult.Category = \"send\"\n\t\t\tresult.Amount = -amountF64\n\t\t\tresult.Fee = &feeF64\n\t\t\tresults = append(results, result)\n\t\t}\n\t\tif isCredit {\n\t\t\tresult.Account = accountName\n\t\t\tresult.Category = recvCat\n\t\t\tresult.Amount = amountF64\n\t\t\tresult.Fee = nil\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\treturn results\n}", "func (_Cakevault *CakevaultCaller) PerformanceFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"performanceFee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_EtherDelta *EtherDeltaCallerSession) FeeRebate() (*big.Int, error) {\n\treturn _EtherDelta.Contract.FeeRebate(&_EtherDelta.CallOpts)\n}", "func (_SushiV2Factory *SushiV2FactorySession) FeeToSetter() (common.Address, error) {\n\treturn _SushiV2Factory.Contract.FeeToSetter(&_SushiV2Factory.CallOpts)\n}" ]
[ "0.70768136", "0.6866969", "0.6616119", "0.6568297", "0.6410797", "0.6196392", "0.61555874", "0.61294425", "0.60383624", "0.6034756", "0.6001134", "0.59999985", "0.5971211", "0.5826443", "0.58024466", "0.57845014", "0.5776646", "0.5761574", "0.56208384", "0.561799", "0.55858964", "0.5520113", "0.55004096", "0.54802793", "0.5466517", "0.54632884", "0.5450585", "0.5443362", "0.5387112", "0.5363221", "0.53509897", "0.53493184", "0.5336972", "0.5330964", "0.53293365", "0.53147703", "0.53067374", "0.5304332", "0.53024447", "0.5297301", "0.5290911", "0.52412504", "0.52236086", "0.5182792", "0.5181999", "0.51759255", "0.51644695", "0.5158789", "0.51482564", "0.5147881", "0.51415634", "0.5138752", "0.51287645", "0.51221794", "0.5119026", "0.5113762", "0.5108465", "0.5105038", "0.5100437", "0.50966495", "0.509573", "0.50931233", "0.5090435", "0.508285", "0.5068457", "0.50529695", "0.50404817", "0.50360054", "0.50328535", "0.50288", "0.50219864", "0.501053", "0.5010484", "0.5005362", "0.50038993", "0.50027174", "0.50025064", "0.4997063", "0.49797204", "0.49596143", "0.49554655", "0.49539718", "0.4950592", "0.49499014", "0.49488428", "0.49466816", "0.49334663", "0.49326885", "0.4927561", "0.492575", "0.49256667", "0.49233693", "0.49189112", "0.4895804", "0.48940432", "0.48927277", "0.4891187", "0.4890497", "0.48821545", "0.48758644" ]
0.6894167
1
/ Description: A function to Payout rewards for all contracts in delegatedContracts Param delegatedContracts ([]DelegatedClient): List of all contracts to be paid out Param alias (string): The alias name to your known delegation wallet on your node WARNING If not using the ledger there is nothing stopping this from actually sending Tezos. With the ledger you have to physically confirm the transaction, without the ledger you don't. BE CAREFUL WHEN CALLING THIS FUNCTION!!!!! WARNING
func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{ for _, delegatedContract := range delegatedContracts { err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias) if (err != nil){ return errors.New("Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: " + err.Error()) } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func GetDelegatedContractsForCycle(cycle int, delegateAddr string) ([]string, error){\n var rtnString []string\n snapShot, err := GetSnapShot(cycle)\n // fmt.Println(snapShot)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetSnapShot(cycle int) failed: \" + err.Error())\n }\n hash, err:= GetBlockLevelHash(snapShot.AssociatedBlock)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetBlockLevelHash(level int) failed: \" + err.Error())\n }\n // fmt.Println(hash)\n getDelegatedContracts := \"/chains/main/blocks/\" + hash + \"/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n\n s, err := TezosRPCGet(getDelegatedContracts)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1)\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": You have no contracts.\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func GetAllDelegatedContracts(delegateAddr string) ([]string, error){\n var rtnString []string\n delegatedContractsCmd := \"/chains/main/blocks/head/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n s, err := TezosRPCGet(delegatedContractsCmd)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts: TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1) //TODO Error checking\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get all delegated contracts: Regex failed\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func (k Keeper) AwardCoinsForRelays(ctx sdk.Ctx, relays int64, toAddr sdk.Address) sdk.BigInt {\n\treturn k.posKeeper.RewardForRelays(ctx, sdk.NewInt(relays), toAddr)\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func payout(delegate string, operator string) string {\n\t// get operator's address\n\toperator_addr, err := alias.Address(operator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// get delegate's name to 12-byte array\n\tdelegate_name := delegateName(delegate)\n\n\trs := calculateRewardShares(operator_addr, delegate_name, epochToQuery)\n\n\t// prepare input for multisend\n\t// https://member.iotex.io/multi-send\n\tvar voters []string\n\tvar rewards []string\n\n\tstradd := func(a string, b string, c string) string {\n\t\taa, _ := new(big.Int).SetString(a, 10)\n\t\tbb, _ := new(big.Int).SetString(b, 10)\n\t\tcc, _ := new(big.Int).SetString(c, 10)\n\t\treturn cc.Add(aa.Add(aa, bb), cc).Text(10)\n\t}\n\n\tfor _, share := range rs.Shares {\n\t\tvoters = append(voters, \"0x\" + share.ETHAddr)\n\t\trewards = append(rewards, stradd(\n\t\t\t\t\t\tshare.Reward.Block,\n\t\t\t\t\t\tshare.Reward.FoundationBonus,\n\t\t\t\t\t\tshare.Reward.EpochBonus))\n\t}\n\n\tvar sent []MultisendReward\n\tfor i, a := range rewards {\n\t\tamount, _ := new(big.Int).SetString(a, 10)\n\t\tsent = append(sent, MultisendReward{voters[i],\n\t\t\t\t\tutil.RauToString(amount, util.IotxDecimalNum)})\n\t}\n\ts, _ := json.Marshal(sent)\n\tfmt.Println(string(s))\n\n\treturn rs.String()\n}", "func (_ConsortiumManagement *ConsortiumManagementCaller) Delegates(opts *bind.CallOpts) ([]common.Address, error) {\n\tvar out []interface{}\n\terr := _ConsortiumManagement.contract.Call(opts, &out, \"delegates\")\n\n\tif err != nil {\n\t\treturn *new([]common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address)\n\n\treturn out0, err\n\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func (_ConsortiumManagement *ConsortiumManagementCallerSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (_ConsortiumManagement *ConsortiumManagementSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func Redeem(contract []byte, contractTx wire.MsgTx, secret []byte, currency string, autopublish bool) (api.RedeemResponse, error) {\n\tnetwork := RetrieveNetwork(currency)\n\tclient := GetRPCClient(currency)\n\n\tdefer func() {\n\t\tclient.Shutdown()\n\t\tclient.WaitForShutdown()\n\t}()\n\n\tpushes, err := txscript.ExtractAtomicSwapDataPushes(0, contract)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tif pushes == nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, errors.New(\"contract is not an atomic swap script recognized by this tool\")\n\t}\n\n\trecipientAddr, err := diviutil.NewAddressPubKeyHash(pushes.RecipientHash160[:], network)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tcontractHash := diviutil.Hash160(contract)\n\tcontractOut := -1\n\tfor i, out := range contractTx.TxOut {\n\t\tsc, addrs, _, _ := txscript.ExtractPkScriptAddrs(out.PkScript, network)\n\t\tif sc == txscript.ScriptHashTy &&\n\t\t\tbytes.Equal(addrs[0].(*diviutil.AddressScriptHash).Hash160()[:], contractHash) {\n\t\t\tcontractOut = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif contractOut == -1 {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, errors.New(\"transaction does not contain a contract output\")\n\t}\n\n\taddr, err := RawChangeAddress(client, currency)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\toutScript, err := txscript.PayToAddrScript(addr)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\n\tcontractTxHash := contractTx.TxHash()\n\tcontractOutPoint := wire.OutPoint{\n\t\tHash: contractTxHash,\n\t\tIndex: uint32(contractOut),\n\t}\n\n\tfeePerKb, minFeePerKb, err := GetFees(client, currency)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\n\tredeemTx := wire.NewMsgTx(util.TXVersion)\n\tredeemTx.LockTime = uint32(pushes.LockTime)\n\tredeemTx.AddTxIn(wire.NewTxIn(&contractOutPoint, nil, nil))\n\tredeemTx.AddTxOut(wire.NewTxOut(0, outScript)) // amount set below\n\tredeemSize := util.EstimateRedeemSerializeSize(contract, redeemTx.TxOut)\n\tfee := txrules.FeeForSerializeSize(feePerKb, redeemSize)\n\tredeemTx.TxOut[0].Value = contractTx.TxOut[contractOut].Value - int64(fee)\n\tif txrules.IsDustOutput(redeemTx.TxOut[0], minFeePerKb) {\n\t\tpanic(fmt.Errorf(\"redeem output value of %v is dust\", diviutil.Amount(redeemTx.TxOut[0].Value)))\n\t}\n\n\tredeemSig, redeemPubKey, err := CreateSig(redeemTx, 0, contract, recipientAddr, client)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tredeemSigScript, err := RedeemP2SHContract(contract, redeemSig, redeemPubKey, secret)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tredeemTx.TxIn[0].SignatureScript = redeemSigScript\n\n\tredeemTxHash := redeemTx.TxHash()\n\tredeemFeePerKb := CalcFeePerKb(fee, redeemTx.SerializeSize())\n\n\tvar buf bytes.Buffer\n\tbuf.Grow(redeemTx.SerializeSize())\n\tredeemTx.Serialize(&buf)\n\n\tif autopublish == false {\n\t\tfmt.Printf(\"Redeem fee: %v (%0.8f BTC/kB)\\n\\n\", fee, redeemFeePerKb)\n\t\tfmt.Printf(\"Redeem transaction (%v):\\n\", &redeemTxHash)\n\t\tfmt.Printf(\"%x\\n\\n\", buf.Bytes())\n\t}\n\n\tif util.Verify {\n\t\te, err := txscript.NewEngine(contractTx.TxOut[contractOutPoint.Index].PkScript,\n\t\t\tredeemTx, 0, txscript.StandardVerifyFlags, txscript.NewSigCache(10),\n\t\t\ttxscript.NewTxSigHashes(redeemTx), contractTx.TxOut[contractOut].Value)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = e.Execute()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tPromptPublishTx(client, redeemTx, \"redeem\", autopublish)\n\n\treturn api.RedeemResponse{\n\t\tfee.String(),\n\t\tredeemTxHash.String(),\n\t\tstruct{}{},\n\t\tnil,\n\t\t51200,\n\t}, nil\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UnlockDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"unlockDelegate\", token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (dcr *ExchangeWallet) Redeem(redemptions []*asset.Redemption) ([]dex.Bytes, asset.Coin, uint64, error) {\n\t// Create a transaction that spends the referenced contract.\n\tmsgTx := wire.NewMsgTx()\n\tvar totalIn uint64\n\tvar contracts [][]byte\n\tvar addresses []dcrutil.Address\n\tfor _, r := range redemptions {\n\t\tcinfo, ok := r.Spends.(*auditInfo)\n\t\tif !ok {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"Redemption contract info of wrong type\")\n\t\t}\n\t\t// Extract the swap contract recipient and secret hash and check the secret\n\t\t// hash against the hash of the provided secret.\n\t\tcontract := r.Spends.Contract()\n\t\t_, receiver, _, secretHash, err := dexdcr.ExtractSwapDetails(contract, chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error extracting swap addresses: %w\", err)\n\t\t}\n\t\tcheckSecretHash := sha256.Sum256(r.Secret)\n\t\tif !bytes.Equal(checkSecretHash[:], secretHash) {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"secret hash mismatch. %x != %x\", checkSecretHash[:], secretHash)\n\t\t}\n\t\taddresses = append(addresses, receiver)\n\t\tcontracts = append(contracts, contract)\n\t\tprevOut := cinfo.output.wireOutPoint()\n\t\ttxIn := wire.NewTxIn(prevOut, int64(cinfo.output.value), []byte{})\n\t\t// Sequence = 0xffffffff - 1 is special value that marks the transaction as\n\t\t// irreplaceable and enables the use of lock time.\n\t\t//\n\t\t// https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki#Spending_wallet_policy\n\t\ttxIn.Sequence = wire.MaxTxInSequenceNum - 1\n\t\tmsgTx.AddTxIn(txIn)\n\t\ttotalIn += cinfo.output.value\n\t}\n\n\t// Calculate the size and the fees.\n\tsize := msgTx.SerializeSize() + dexdcr.RedeemSwapSigScriptSize*len(redemptions) + dexdcr.P2PKHOutputSize\n\tfeeRate := dcr.feeRateWithFallback(dcr.redeemConfTarget)\n\tfee := feeRate * uint64(size)\n\tif fee > totalIn {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redeem tx not worth the fees\")\n\t}\n\t// Send the funds back to the exchange wallet.\n\ttxOut, _, err := dcr.makeChangeOut(totalIn - fee)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\t// One last check for dust.\n\tif dexdcr.IsDust(txOut, feeRate) {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redeem output is dust\")\n\t}\n\tmsgTx.AddTxOut(txOut)\n\t// Sign the inputs.\n\tfor i, r := range redemptions {\n\t\tcontract := contracts[i]\n\t\tredeemSig, redeemPubKey, err := dcr.createSig(msgTx, i, contract, addresses[i])\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tredeemSigScript, err := dexdcr.RedeemP2SHContract(contract, redeemSig, redeemPubKey, r.Secret)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tmsgTx.TxIn[i].SignatureScript = redeemSigScript\n\t}\n\t// Send the transaction.\n\tcheckHash := msgTx.TxHash()\n\ttxHash, err := dcr.node.SendRawTransaction(dcr.ctx, msgTx, false)\n\tif err != nil {\n\t\treturn nil, nil, 0, translateRPCCancelErr(err)\n\t}\n\tif *txHash != checkHash {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redemption sent, but received unexpected transaction ID back from RPC server. \"+\n\t\t\t\"expected %s, got %s\", *txHash, checkHash)\n\t}\n\tcoinIDs := make([]dex.Bytes, 0, len(redemptions))\n\tfor i := range redemptions {\n\t\tcoinIDs = append(coinIDs, toCoinID(txHash, uint32(i)))\n\t}\n\n\treturn coinIDs, newOutput(txHash, 0, uint64(txOut.Value), wire.TxTreeRegular), fee, nil\n}", "func redeem (stub shim.ChaincodeStubInterface, args []string) ([]byte,error){\n\n\tif len(args) != 5 {\n\t\t\tfmt.Println(\" Incorrect number of arguments sent to redeem. Expecting 5. Received \" + strconv.Itoa(len(args)))\n\t\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 5\")\n\t\t}\n\n\t\t_, err := LoyaltyPkg.RedeemPoints(stub, args)\n\n\tif err != nil {\n\n\t\tfmt.Println(err)\n\t\treturn nil, errors.New(\"Errors while creating wallet for user \" + args[0])\n\t}\n\n\tlogger.Info(\"Successfully redeemed points for user \" + args[0])\n\n\treturn nil, nil\n\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (_Gatekeeper *GatekeeperTransactorSession) Payout(_proof []byte, _root *big.Int, _from common.Address, _txNumber *big.Int, _value *big.Int) (*types.Transaction, error) {\n\treturn _Gatekeeper.Contract.Payout(&_Gatekeeper.TransactOpts, _proof, _root, _from, _txNumber, _value)\n}", "func (btc *ExchangeWallet) Redeem(redemptions []*asset.Redemption) ([]dex.Bytes, asset.Coin, error) {\n\t// Create a transaction that spends the referenced contract.\n\tmsgTx := wire.NewMsgTx(wire.TxVersion)\n\tvar totalIn uint64\n\tvar contracts [][]byte\n\tvar addresses []btcutil.Address\n\tfor _, r := range redemptions {\n\t\tcinfo, ok := r.Spends.(*auditInfo)\n\t\tif !ok {\n\t\t\treturn nil, nil, fmt.Errorf(\"Redemption contract info of wrong type\")\n\t\t}\n\t\t// Extract the swap contract recipient and secret hash and check the secret\n\t\t// hash against the hash of the provided secret.\n\t\t_, receiver, _, secretHash, err := dexbtc.ExtractSwapDetails(cinfo.output.redeem, btc.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error extracting swap addresses: %v\", err)\n\t\t}\n\t\tcheckSecretHash := sha256.Sum256(r.Secret)\n\t\tif !bytes.Equal(checkSecretHash[:], secretHash) {\n\t\t\treturn nil, nil, fmt.Errorf(\"secret hash mismatch\")\n\t\t}\n\t\taddresses = append(addresses, receiver)\n\t\tcontracts = append(contracts, cinfo.output.redeem)\n\t\tprevOut := wire.NewOutPoint(&cinfo.output.txHash, cinfo.output.vout)\n\t\ttxIn := wire.NewTxIn(prevOut, []byte{}, nil)\n\t\t// Enable locktime\n\t\t// https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki#Spending_wallet_policy\n\t\ttxIn.Sequence = wire.MaxTxInSequenceNum - 1\n\t\tmsgTx.AddTxIn(txIn)\n\t\ttotalIn += cinfo.output.value\n\t}\n\n\t// Calculate the size and the fees.\n\tsize := msgTx.SerializeSize() + dexbtc.RedeemSwapSigScriptSize*len(redemptions) + dexbtc.P2WPKHOutputSize\n\tfeeRate := btc.feeRateWithFallback()\n\tfee := feeRate * uint64(size)\n\tif fee > totalIn {\n\t\treturn nil, nil, fmt.Errorf(\"redeem tx not worth the fees\")\n\t}\n\t// Send the funds back to the exchange wallet.\n\tredeemAddr, err := btc.wallet.ChangeAddress()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error getting new address from the wallet: %v\", err)\n\t}\n\tpkScript, err := txscript.PayToAddrScript(redeemAddr)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error creating change script: %v\", err)\n\t}\n\ttxOut := wire.NewTxOut(int64(totalIn-fee), pkScript)\n\t// One last check for dust.\n\tif dexbtc.IsDust(txOut, feeRate) {\n\t\treturn nil, nil, fmt.Errorf(\"redeem output is dust\")\n\t}\n\tmsgTx.AddTxOut(txOut)\n\t// Sign the inputs.\n\tfor i, r := range redemptions {\n\t\tcontract := contracts[i]\n\t\tredeemSig, redeemPubKey, err := btc.createSig(msgTx, i, contract, addresses[i])\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tredeemSigScript, err := dexbtc.RedeemP2SHContract(contract, redeemSig, redeemPubKey, r.Secret)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tmsgTx.TxIn[i].SignatureScript = redeemSigScript\n\t}\n\t// Send the transaction.\n\tcheckHash := msgTx.TxHash()\n\ttxHash, err := btc.node.SendRawTransaction(msgTx, false)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif *txHash != checkHash {\n\t\treturn nil, nil, fmt.Errorf(\"redemption sent, but received unexpected transaction ID back from RPC server. \"+\n\t\t\t\"expected %s, got %s\", *txHash, checkHash)\n\t}\n\t// Log the change output.\n\tbtc.addChange(txHash.String(), 0)\n\tcoinIDs := make([]dex.Bytes, 0, len(redemptions))\n\tfor i := range redemptions {\n\t\tcoinIDs = append(coinIDs, toCoinID(txHash, uint32(i)))\n\t}\n\treturn coinIDs, newOutput(btc.node, txHash, 0, uint64(txOut.Value), nil), nil\n}", "func (_Gatekeeper *GatekeeperTransactor) Payout(opts *bind.TransactOpts, _proof []byte, _root *big.Int, _from common.Address, _txNumber *big.Int, _value *big.Int) (*types.Transaction, error) {\n\treturn _Gatekeeper.contract.Transact(opts, \"Payout\", _proof, _root, _from, _txNumber, _value)\n}", "func (_TokensNetwork *TokensNetworkSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (_Bep20 *Bep20Caller) Delegates(opts *bind.CallOpts, delegator common.Address) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"delegates\", delegator)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_Gatekeeper *GatekeeperSession) Payout(_proof []byte, _root *big.Int, _from common.Address, _txNumber *big.Int, _value *big.Int) (*types.Transaction, error) {\n\treturn _Gatekeeper.Contract.Payout(&_Gatekeeper.TransactOpts, _proof, _root, _from, _txNumber, _value)\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProofDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProofDelegate\", token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (c *DPOS) ClaimRewardsFromAllValidators(ctx contract.Context, req *ClaimDelegatorRewardsRequest) (*ClaimDelegatorRewardsResponse, error) {\n\tif ctx.FeatureEnabled(features.DPOSVersion3_6, false) {\n\t\treturn c.claimRewardsFromAllValidators2(ctx, req)\n\t}\n\n\tdelegator := ctx.Message().Sender\n\tvalidators, err := ValidatorList(ctx)\n\tif err != nil {\n\t\treturn nil, logStaticDposError(ctx, err, req.String())\n\t}\n\n\ttotal := big.NewInt(0)\n\tchainID := ctx.Block().ChainID\n\tvar claimedFromValidators []*types.Address\n\tvar amounts []*types.BigUInt\n\tfor _, v := range validators {\n\t\tvalAddress := loom.Address{ChainID: chainID, Local: loom.LocalAddressFromPublicKey(v.PubKey)}\n\t\tdelegation, err := GetDelegation(ctx, REWARD_DELEGATION_INDEX, *valAddress.MarshalPB(), *delegator.MarshalPB())\n\t\tif err == contract.ErrNotFound {\n\t\t\t// Skip reward delegations that were not found.\n\t\t\tctx.Logger().Error(\"DPOS ClaimRewardsFromAllValidators\", \"error\", err, \"delegator\", delegator)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to load delegation\")\n\t\t}\n\n\t\tclaimedFromValidators = append(claimedFromValidators, valAddress.MarshalPB())\n\t\tamounts = append(amounts, delegation.Amount)\n\n\t\t// Set to UNBONDING and UpdateAmount == Amount, to fully unbond it.\n\t\tdelegation.State = UNBONDING\n\t\tdelegation.UpdateAmount = delegation.Amount\n\n\t\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to update delegation\")\n\t\t}\n\n\t\terr = c.emitDelegatorUnbondsEvent(ctx, delegation)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Add to the sum\n\t\ttotal.Add(total, delegation.Amount.Value.Int)\n\t}\n\n\tamount := &types.BigUInt{Value: *loom.NewBigUInt(total)}\n\n\terr = c.emitDelegatorClaimsRewardsEvent(ctx, delegator.MarshalPB(), claimedFromValidators, amounts, amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ClaimDelegatorRewardsResponse{\n\t\tAmount: amount,\n\t}, nil\n}", "func (_Bep20 *Bep20CallerSession) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (dcr *ExchangeWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin, uint64, error) {\n\tvar totalOut uint64\n\t// Start with an empty MsgTx.\n\tbaseTx := wire.NewMsgTx()\n\t// Add the funding utxos.\n\ttotalIn, err := dcr.addInputCoins(baseTx, swaps.Inputs)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tcontracts := make([][]byte, 0, len(swaps.Contracts))\n\t// Add the contract outputs.\n\tfor _, contract := range swaps.Contracts {\n\t\ttotalOut += contract.Value\n\t\t// revokeAddrV2 is the address that will receive the refund if the\n\t\t// contract is abandoned.\n\t\trevokeAddrV2, err := dcr.node.GetNewAddressGapPolicy(dcr.ctx, dcr.acct, dcrwallet.GapPolicyIgnore)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error creating revocation address: %w\", translateRPCCancelErr(err))\n\t\t}\n\t\t// Create the contract, a P2SH redeem script.\n\t\tcontractScript, err := dexdcr.MakeContract(contract.Address, revokeAddrV2.String(), contract.SecretHash, int64(contract.LockTime), chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"unable to create pubkey script for address %s: %w\", contract.Address, err)\n\t\t}\n\t\tcontracts = append(contracts, contractScript)\n\t\t// Make the P2SH address and pubkey script.\n\t\tscriptAddr, err := dcrutil.NewAddressScriptHash(contractScript, chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error encoding script address: %w\", err)\n\t\t}\n\t\tp2shScript, err := txscript.PayToAddrScript(scriptAddr)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error creating P2SH script: %w\", err)\n\t\t}\n\t\t// Add the transaction output.\n\t\ttxOut := wire.NewTxOut(int64(contract.Value), p2shScript)\n\t\tbaseTx.AddTxOut(txOut)\n\t}\n\tif totalIn < totalOut {\n\t\treturn nil, nil, 0, fmt.Errorf(\"unfunded contract. %d < %d\", totalIn, totalOut)\n\t}\n\n\t// Ensure we have enough outputs before broadcasting.\n\tswapCount := len(swaps.Contracts)\n\tif len(baseTx.TxOut) < swapCount {\n\t\treturn nil, nil, 0, fmt.Errorf(\"fewer outputs than swaps. %d < %d\", len(baseTx.TxOut), swapCount)\n\t}\n\n\t// Add change, sign, and send the transaction.\n\tdcr.fundingMtx.Lock() // before generating change output\n\tdefer dcr.fundingMtx.Unlock() // hold until after returnCoins and lockFundingCoins(change)\n\tmsgTx, change, changeAddr, fees, err := dcr.sendWithReturn(baseTx, swaps.FeeRate, -1)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\n\t// Return spent outputs.\n\terr = dcr.returnCoins(swaps.Inputs)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"error unlocking swapped coins\", swaps.Inputs)\n\t}\n\n\t// Lock the change coin, if requested.\n\tif swaps.LockChange {\n\t\tdcr.log.Debugf(\"locking change coin %s\", change)\n\t\terr = dcr.lockFundingCoins([]*fundingCoin{{\n\t\t\top: change,\n\t\t\taddr: changeAddr,\n\t\t}})\n\t\tif err != nil {\n\t\t\tdcr.log.Warnf(\"Failed to lock dcr change coin %s\", change)\n\t\t}\n\t}\n\n\treceipts := make([]asset.Receipt, 0, swapCount)\n\ttxHash := msgTx.TxHash()\n\tfor i, contract := range swaps.Contracts {\n\t\treceipts = append(receipts, &swapReceipt{\n\t\t\toutput: newOutput(&txHash, uint32(i), contract.Value, wire.TxTreeRegular),\n\t\t\tcontract: contracts[i],\n\t\t\texpiration: time.Unix(int64(contract.LockTime), 0).UTC(),\n\t\t})\n\t}\n\n\t// If change is nil, return a nil asset.Coin.\n\tvar changeCoin asset.Coin\n\tif change != nil {\n\t\tchangeCoin = change\n\t}\n\treturn receipts, changeCoin, fees, nil\n}", "func (_TokensNetwork *TokensNetworkSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (_GameJam *GameJamTransactor) PayoutWinner(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _GameJam.contract.Transact(opts, \"payoutWinner\")\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) DepositRedelegatedAmount(opts *bind.CallOpts, operator common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"depositRedelegatedAmount\", operator)\n\treturn *ret0, err\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func SetupContracts(chainURL string, onChainTxTimeout time.Duration) (\n\tadjudicator, asset pwallet.Address, _ error) {\n\tprng := rand.New(rand.NewSource(RandSeedForTestAccs))\n\tws, err := NewWalletSetup(prng, 2)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tonChainCred := perun.Credential{\n\t\tAddr: ws.Accs[0].Address(),\n\t\tWallet: ws.Wallet,\n\t\tKeystore: ws.KeystorePath,\n\t\tPassword: \"\",\n\t}\n\tif !isBlockchainRunning(chainURL) {\n\t\treturn nil, nil, errors.New(\"cannot connect to ganache-cli node at \" + chainURL)\n\t}\n\n\tif adjudicatorAddr == nil && assetAddr == nil {\n\t\tadjudicator = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(onChainCred.Addr), 0))\n\t\tasset = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(onChainCred.Addr), 1))\n\t\tadjudicatorAddr = adjudicator\n\t\tassetAddr = asset\n\t} else {\n\t\tadjudicator = adjudicatorAddr\n\t\tasset = assetAddr\n\t}\n\n\tchain, err := ethereum.NewChainBackend(chainURL, ChainConnTimeout, onChainTxTimeout, onChainCred)\n\tif err != nil {\n\t\treturn nil, nil, errors.WithMessage(err, \"initializaing chain backend\")\n\t}\n\n\terr = chain.ValidateContracts(adjudicator, asset)\n\tif err != nil {\n\t\t// Contracts not yet deployed for this ganache-cli instance.\n\t\tadjudicator, asset, err = deployContracts(chain, onChainCred)\n\t}\n\treturn adjudicator, asset, errors.WithMessage(err, \"initializaing chain backend\")\n}", "func (n *Node) BecomeDelegator(genesisAmount uint64, seedAmount uint64, delegatorAmount uint64, txFee uint64, stakerNodeID string) *Node {\n\n\t// exports AVAX from the X Chain\n\texportTxID, err := n.client.XChainAPI().ExportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tseedAmount+txFee,\n\t\tn.PAddress,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to export AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the XChain\n\terr = chainhelper.XChain().AwaitTransactionAcceptance(n.client, exportTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// imports the amount to the P Chain\n\timportTxID, err := n.client.PChainAPI().ImportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tconstants.XChainID.String(),\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed import AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the PChain\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, importTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// verify the PChain balance (seedAmount+txFee-txFee)\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, seedAmount)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance of seedAmount exists in the PChain\"))\n\t\treturn n\n\t}\n\n\t// verify the XChain balance of genesisAmount - seedAmount - txFee - txFee (import PChain)\n\terr = chainhelper.XChain().CheckBalance(n.client, n.XAddress, \"AVAX\", genesisAmount-seedAmount-2*txFee)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance XChain balance of genesisAmount-seedAmount-txFee\"))\n\t\treturn n\n\t}\n\n\tdelegatorStartTime := time.Now().Add(20 * time.Second)\n\tstartTime := uint64(delegatorStartTime.Unix())\n\tendTime := uint64(delegatorStartTime.Add(36 * time.Hour).Unix())\n\taddDelegatorTxID, err := n.client.PChainAPI().AddDelegator(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tstakerNodeID,\n\t\tdelegatorAmount,\n\t\tstartTime,\n\t\tendTime,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to add delegator %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, addDelegatorTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to accept AddDelegator tx: %s\", addDelegatorTxID))\n\t\treturn n\n\t}\n\n\t// Sleep until delegator starts validating\n\ttime.Sleep(time.Until(delegatorStartTime) + 3*time.Second)\n\n\texpectedDelegatorBalance := seedAmount - delegatorAmount\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, expectedDelegatorBalance)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Unexpected P Chain Balance after adding a new delegator to the network.\"))\n\t\treturn n\n\t}\n\tlogrus.Infof(\"Added delegator to subnet and verified the expected P Chain balance.\")\n\n\treturn n\n}", "func (dcr *ExchangeWallet) Redeem(form *asset.RedeemForm) ([]dex.Bytes, asset.Coin, uint64, error) {\n\t// Create a transaction that spends the referenced contract.\n\tmsgTx := wire.NewMsgTx()\n\tvar totalIn uint64\n\tvar contracts [][]byte\n\tvar addresses []stdaddr.Address\n\tfor _, r := range form.Redemptions {\n\t\tif r.Spends == nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"no audit info\")\n\t\t}\n\n\t\tcinfo, err := convertAuditInfo(r.Spends, dcr.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\n\t\t// Extract the swap contract recipient and secret hash and check the secret\n\t\t// hash against the hash of the provided secret.\n\t\tcontract := cinfo.contract\n\t\t_, receiver, _, secretHash, err := dexdcr.ExtractSwapDetails(contract, dcr.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error extracting swap addresses: %w\", err)\n\t\t}\n\t\tcheckSecretHash := sha256.Sum256(r.Secret)\n\t\tif !bytes.Equal(checkSecretHash[:], secretHash) {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"secret hash mismatch. %x != %x\", checkSecretHash[:], secretHash)\n\t\t}\n\t\taddresses = append(addresses, receiver)\n\t\tcontracts = append(contracts, contract)\n\t\tprevOut := cinfo.output.wireOutPoint()\n\t\ttxIn := wire.NewTxIn(prevOut, int64(cinfo.output.value), []byte{})\n\t\tmsgTx.AddTxIn(txIn)\n\t\ttotalIn += cinfo.output.value\n\t}\n\n\t// Calculate the size and the fees.\n\tsize := msgTx.SerializeSize() + dexdcr.RedeemSwapSigScriptSize*len(form.Redemptions) + dexdcr.P2PKHOutputSize\n\n\tcustomCfg := new(redeemOptions)\n\terr := config.Unmapify(form.Options, customCfg)\n\tif err != nil {\n\t\treturn nil, nil, 0, fmt.Errorf(\"error parsing selected swap options: %w\", err)\n\t}\n\n\trawFeeRate := dcr.targetFeeRateWithFallback(dcr.redeemConfTarget, form.FeeSuggestion)\n\tfeeRate, err := calcBumpedRate(rawFeeRate, customCfg.FeeBump)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"calcBumpRate error: %v\", err)\n\t}\n\tfee := feeRate * uint64(size)\n\tif fee > totalIn {\n\t\t// Double check that the fee bump isn't the issue.\n\t\tfeeRate = rawFeeRate\n\t\tfee = feeRate * uint64(size)\n\t\tif fee > totalIn {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"redeem tx not worth the fees\")\n\t\t}\n\t\tdcr.log.Warnf(\"Ignoring fee bump (%v) resulting in fees > redemption\", float64PtrStr(customCfg.FeeBump))\n\t}\n\n\t// Send the funds back to the exchange wallet.\n\ttxOut, _, err := dcr.makeChangeOut(dcr.depositAccount(), totalIn-fee)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\t// One last check for dust.\n\tif dexdcr.IsDust(txOut, feeRate) {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redeem output is dust\")\n\t}\n\tmsgTx.AddTxOut(txOut)\n\t// Sign the inputs.\n\tfor i, r := range form.Redemptions {\n\t\tcontract := contracts[i]\n\t\tredeemSig, redeemPubKey, err := dcr.createSig(msgTx, i, contract, addresses[i])\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tredeemSigScript, err := dexdcr.RedeemP2SHContract(contract, redeemSig, redeemPubKey, r.Secret)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tmsgTx.TxIn[i].SignatureScript = redeemSigScript\n\t}\n\t// Send the transaction.\n\tcheckHash := msgTx.TxHash()\n\ttxHash, err := dcr.wallet.SendRawTransaction(dcr.ctx, msgTx, false)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tif *txHash != checkHash {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redemption sent, but received unexpected transaction ID back from RPC server. \"+\n\t\t\t\"expected %s, got %s\", *txHash, checkHash)\n\t}\n\tcoinIDs := make([]dex.Bytes, 0, len(form.Redemptions))\n\tfor i := range form.Redemptions {\n\t\tcoinIDs = append(coinIDs, toCoinID(txHash, uint32(i)))\n\t}\n\n\treturn coinIDs, newOutput(txHash, 0, uint64(txOut.Value), wire.TxTreeRegular), fee, nil\n}", "func (btc *ExchangeWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin, error) {\n\tvar contracts [][]byte\n\tvar totalOut, totalIn uint64\n\t// Start with an empty MsgTx.\n\tbaseTx := wire.NewMsgTx(wire.TxVersion)\n\t// Add the funding utxos.\n\topIDs := make([]string, 0, len(swaps.Inputs))\n\tfor _, coin := range swaps.Inputs {\n\t\toutput, err := btc.convertCoin(coin)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tif output.value == 0 {\n\t\t\treturn nil, nil, fmt.Errorf(\"zero-valued output detected for %s:%d\", output.txHash, output.vout)\n\t\t}\n\t\ttotalIn += output.value\n\t\tprevOut := wire.NewOutPoint(&output.txHash, output.vout)\n\t\ttxIn := wire.NewTxIn(prevOut, []byte{}, nil)\n\t\tbaseTx.AddTxIn(txIn)\n\t\topIDs = append(opIDs, outpointID(output.txHash.String(), output.vout))\n\t}\n\t// Add the contract outputs.\n\t// TODO: Make P2WSH contract and P2WPKH change outputs instead of\n\t// legacy/non-segwit swap contracts pkScripts.\n\tfor _, contract := range swaps.Contracts {\n\t\ttotalOut += contract.Value\n\t\t// revokeAddr is the address that will receive the refund if the contract is\n\t\t// abandoned.\n\t\trevokeAddr, err := btc.wallet.AddressPKH()\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error creating revocation address: %v\", err)\n\t\t}\n\t\t// Create the contract, a P2SH redeem script.\n\t\tpkScript, err := dexbtc.MakeContract(contract.Address, revokeAddr.String(), contract.SecretHash, int64(contract.LockTime), btc.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"unable to create pubkey script for address %s: %v\", contract.Address, err)\n\t\t}\n\t\tcontracts = append(contracts, pkScript)\n\t\t// Make the P2SH address and pubkey script.\n\t\tscriptAddr, err := btcutil.NewAddressScriptHash(pkScript, btc.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error encoding script address: %v\", err)\n\t\t}\n\t\tp2shScript, err := txscript.PayToAddrScript(scriptAddr)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error creating P2SH script: %v\", err)\n\t\t}\n\t\t// Add the transaction output.\n\t\ttxOut := wire.NewTxOut(int64(contract.Value), p2shScript)\n\t\tbaseTx.AddTxOut(txOut)\n\t}\n\tif totalIn < totalOut {\n\t\treturn nil, nil, fmt.Errorf(\"unfunded contract. %d < %d\", totalIn, totalOut)\n\t}\n\t// Grab a change address.\n\tchangeAddr, err := btc.wallet.ChangeAddress()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error creating change address: %v\", err)\n\t}\n\t// Prepare the receipts.\n\tswapCount := len(swaps.Contracts)\n\tif len(baseTx.TxOut) < swapCount {\n\t\treturn nil, nil, fmt.Errorf(\"fewer outputs than swaps. %d < %d\", len(baseTx.TxOut), swapCount)\n\t}\n\t// Sign, add change, and send the transaction.\n\tmsgTx, change, err := btc.sendWithReturn(baseTx, changeAddr, totalIn, totalOut, swaps.FeeRate)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treceipts := make([]asset.Receipt, 0, swapCount)\n\ttxHash := msgTx.TxHash()\n\tfor i, contract := range swaps.Contracts {\n\t\treceipts = append(receipts, &swapReceipt{\n\t\t\toutput: newOutput(btc.node, &txHash, uint32(i), contract.Value, contracts[i]),\n\t\t\texpiration: time.Unix(int64(contract.LockTime), 0).UTC(),\n\t\t})\n\t}\n\t// Delete the utxos from the cache.\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor i := range opIDs {\n\t\tdelete(btc.fundingCoins, opIDs[i])\n\t}\n\treturn receipts, change, nil\n}", "func ContractAddrs() (adjudicator, asset pwallet.Address) {\n\tprng := rand.New(rand.NewSource(RandSeedForTestAccs))\n\tws, err := NewWalletSetup(prng, 2)\n\tif err != nil {\n\t\tpanic(\"Cannot setup test wallet\")\n\t}\n\tadjudicator = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(ws.Accs[0].Address()), 0))\n\tasset = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(ws.Accs[0].Address()), 1))\n\treturn\n}", "func (_Bep20 *Bep20Session) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func (dcr *ExchangeWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin, uint64, error) {\n\tvar totalOut uint64\n\t// Start with an empty MsgTx.\n\tbaseTx := wire.NewMsgTx()\n\t// Add the funding utxos.\n\ttotalIn, err := dcr.addInputCoins(baseTx, swaps.Inputs)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\n\tcustomCfg := new(swapOptions)\n\terr = config.Unmapify(swaps.Options, customCfg)\n\tif err != nil {\n\t\treturn nil, nil, 0, fmt.Errorf(\"error parsing swap options: %w\", err)\n\t}\n\n\tcontracts := make([][]byte, 0, len(swaps.Contracts))\n\trefundAddrs := make([]stdaddr.Address, 0, len(swaps.Contracts))\n\t// Add the contract outputs.\n\tfor _, contract := range swaps.Contracts {\n\t\ttotalOut += contract.Value\n\t\t// revokeAddrV2 is the address belonging to the key that will be\n\t\t// used to sign and refund a swap past its encoded refund locktime.\n\t\trevokeAddrV2, err := dcr.wallet.ExternalAddress(dcr.ctx, dcr.depositAccount())\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error creating revocation address: %w\", err)\n\t\t}\n\t\trefundAddrs = append(refundAddrs, revokeAddrV2)\n\t\t// Create the contract, a P2SH redeem script.\n\t\tcontractScript, err := dexdcr.MakeContract(contract.Address, revokeAddrV2.String(), contract.SecretHash, int64(contract.LockTime), dcr.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"unable to create pubkey script for address %s: %w\", contract.Address, err)\n\t\t}\n\t\tcontracts = append(contracts, contractScript)\n\t\t// Make the P2SH address and pubkey script.\n\t\tscriptAddr, err := stdaddr.NewAddressScriptHashV0(contractScript, dcr.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error encoding script address: %w\", err)\n\t\t}\n\t\tp2shScriptVer, p2shScript := scriptAddr.PaymentScript()\n\t\t// Add the transaction output.\n\t\ttxOut := newTxOut(int64(contract.Value), p2shScriptVer, p2shScript)\n\t\tbaseTx.AddTxOut(txOut)\n\t}\n\tif totalIn < totalOut {\n\t\treturn nil, nil, 0, fmt.Errorf(\"unfunded contract. %d < %d\", totalIn, totalOut)\n\t}\n\n\t// Ensure we have enough outputs before broadcasting.\n\tswapCount := len(swaps.Contracts)\n\tif len(baseTx.TxOut) < swapCount {\n\t\treturn nil, nil, 0, fmt.Errorf(\"fewer outputs than swaps. %d < %d\", len(baseTx.TxOut), swapCount)\n\t}\n\n\tfeeRate, err := calcBumpedRate(swaps.FeeRate, customCfg.FeeBump)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"ignoring invalid fee bump factor, %s: %v\", float64PtrStr(customCfg.FeeBump), err)\n\t}\n\n\t// Add change, sign, and send the transaction.\n\tdcr.fundingMtx.Lock() // before generating change output\n\tdefer dcr.fundingMtx.Unlock() // hold until after returnCoins and lockFundingCoins(change)\n\t// Sign the tx but don't send the transaction yet until\n\t// the individual swap refund txs are prepared and signed.\n\tchangeAcct := dcr.depositAccount()\n\tif swaps.LockChange && dcr.tradingAccount != \"\" {\n\t\t// Change will likely be used to fund more swaps, send to trading\n\t\t// account.\n\t\tchangeAcct = dcr.tradingAccount\n\t}\n\tmsgTx, change, changeAddr, fees, err := dcr.signTxAndAddChange(baseTx, feeRate, -1, changeAcct)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\n\treceipts := make([]asset.Receipt, 0, swapCount)\n\ttxHash := msgTx.TxHash()\n\tfor i, contract := range swaps.Contracts {\n\t\toutput := newOutput(&txHash, uint32(i), contract.Value, wire.TxTreeRegular)\n\t\tsignedRefundTx, err := dcr.refundTx(output.ID(), contracts[i], contract.Value, refundAddrs[i], swaps.FeeRate)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error creating refund tx: %w\", err)\n\t\t}\n\t\trefundB, err := signedRefundTx.Bytes()\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error serializing refund tx: %w\", err)\n\t\t}\n\t\treceipts = append(receipts, &swapReceipt{\n\t\t\toutput: output,\n\t\t\tcontract: contracts[i],\n\t\t\texpiration: time.Unix(int64(contract.LockTime), 0).UTC(),\n\t\t\tsignedRefund: refundB,\n\t\t})\n\t}\n\n\t// Refund txs prepared and signed. Can now broadcast the swap(s).\n\terr = dcr.broadcastTx(msgTx)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\n\t// Return spent outputs.\n\t_, err = dcr.returnCoins(swaps.Inputs)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"error unlocking swapped coins\", swaps.Inputs)\n\t}\n\n\t// Lock the change coin, if requested.\n\tif swaps.LockChange {\n\t\tdcr.log.Debugf(\"locking change coin %s\", change)\n\t\terr = dcr.lockFundingCoins([]*fundingCoin{{\n\t\t\top: change,\n\t\t\taddr: changeAddr,\n\t\t}})\n\t\tif err != nil {\n\t\t\tdcr.log.Warnf(\"Failed to lock dcr change coin %s\", change)\n\t\t}\n\t}\n\n\t// If change is nil, return a nil asset.Coin.\n\tvar changeCoin asset.Coin\n\tif change != nil {\n\t\tchangeCoin = change\n\t}\n\treturn receipts, changeCoin, fees, nil\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_DelegatableDai *DelegatableDaiSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _DelegatableDai.Contract.Approve(&_DelegatableDai.TransactOpts, _spender, _value)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowFilterer) FilterDepositRedelegated(opts *bind.FilterOpts, previousOperator []common.Address, newOperator []common.Address, grantId []*big.Int) (*TokenStakingEscrowDepositRedelegatedIterator, error) {\n\n\tvar previousOperatorRule []interface{}\n\tfor _, previousOperatorItem := range previousOperator {\n\t\tpreviousOperatorRule = append(previousOperatorRule, previousOperatorItem)\n\t}\n\tvar newOperatorRule []interface{}\n\tfor _, newOperatorItem := range newOperator {\n\t\tnewOperatorRule = append(newOperatorRule, newOperatorItem)\n\t}\n\tvar grantIdRule []interface{}\n\tfor _, grantIdItem := range grantId {\n\t\tgrantIdRule = append(grantIdRule, grantIdItem)\n\t}\n\n\tlogs, sub, err := _TokenStakingEscrow.contract.FilterLogs(opts, \"DepositRedelegated\", previousOperatorRule, newOperatorRule, grantIdRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokenStakingEscrowDepositRedelegatedIterator{contract: _TokenStakingEscrow.contract, event: \"DepositRedelegated\", logs: logs, sub: sub}, nil\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (_GameJam *GameJamTransactorSession) PayoutWinner() (*types.Transaction, error) {\n\treturn _GameJam.Contract.PayoutWinner(&_GameJam.TransactOpts)\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) Delegations(opts *bind.CallOpts, arg0 [32]byte) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret0, err\n}", "func (_GameJam *GameJamSession) PayoutWinner() (*types.Transaction, error) {\n\treturn _GameJam.Contract.PayoutWinner(&_GameJam.TransactOpts)\n}", "func (_DelegatableDai *DelegatableDaiTransactorSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _DelegatableDai.Contract.Approve(&_DelegatableDai.TransactOpts, _spender, _value)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (broadcast *Broadcast) DelegatorWithdraw(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegatorWithdrawMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (t *TaskChaincode) confirmPay(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n\t// 0\n\t// \"$taskId\",\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\t/*fmt.Println(\"ConfirmPay starts!\")\n\tif len(args[0]) <= 0 {\n\t\treturn shim.Error(\"1st argument must be a non-empty string\")\n\t}\n\tif len(args[1]) <= 0 {\n\t\treturn shim.Error(\"2nd argument must be a non-empty string\")\n\t}\n\n\tpayee := args[0]\n\tvalue, err := strconv.ParseFloat(args[1], 64)\n\tif err != nil {\n\t\treturn shim.Error(\"2nd argument must be a numeric string\")\n\t}*/\n\n\ttaskId := args[0];\n\n\tobjectType := \"agreement\"\n\n\t/*queryString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"objectType\\\":\\\"%s\\\",\\\"taskId\\\":\\\"%s\\\"}}\", objectType, taskId)\n\tqueryResults, err := getResultForQueryString(stub, queryString)\n\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}*/\n\n\tscasArgs := [][]byte{[]byte(\"queryByObjectType\"),[]byte(taskId),[]byte(objectType)}\n\tagreementResponse := stub.InvokeChaincode(\"task\", scasArgs, \"softwarechannel\");\n\n\tif agreementResponse.Status != 200 {\n\t\treturn agreementResponse;\n\t}\n\tqueryResults := agreementResponse.Payload;\n\n\n\tvar agreements []agreement\n\terr := json.Unmarshal(queryResults, &agreements)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tif len(agreements) <= 0 {\n\t\treturn shim.Error(\"no agreement for the task \" + taskId)\n\t}\n\n\tagreement := agreements[0]\n\t//fmt.Println(agreement.Provider)\n\tpayee := agreement.Provider\n\tvalue := agreement.FinalPrice\n\texpireTime := agreement.ExpireTime\n\n\t// ==== Check if payee exists ====\n payeeAsBytes, err := stub.GetState(payee)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get the payee \" + payee)\n\t}\n\tif payeeAsBytes == nil {\n\t\treturn shim.Error(\"payee \" + payee + \" not found\")\n\t}\n\n\tvar idStr string\n id, err := iw.NextId()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t} else {\n\t\tidStr = strconv.FormatInt(id, 10)\n\t}\n\n txTime := time.Now()\n\n //允许提前几秒确定支付\n threshold := 5.0\n\t//离expireTime还有多久\n\t//timeDiff := expireTime.Sub(txTime).Seconds\n\n if (expireTime.Sub(txTime).Seconds()) >= threshold {\n\t\ttxTimeString := txTime.Format(\"02 Jan 2006 15:04:05 -0700\")\n\t\texpireTimeString := expireTime.Format(\"02 Jan 2006 15:04:05 -0700\")\n\t\treturn shim.Error(\"cannot confirm pay! Now is \" + txTimeString + \", but the expireTime is \" + expireTimeString)\n\t}\n\n\t//txTimeStr := time.Now().Format(\"02 Jan 2006 15:04:05 -0700\")\n\t//txTime, err := time.Parse(\"02 Jan 2006 15:04:05 -0700\", txTimeStr)\n\t//if err != nil {\n\t//\treturn shim.Error(\"Failed to convert the txTime into type time.Time\")\n\t//}\n\n payer := \"contract\";\n txJSON := &payTX{\"PayTX\", txTime, idStr, taskId, payer, payee, value}\n\ttxJSONasBytes, err := json.Marshal(txJSON)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t// ==== Save Transaction ====\n err = stub.PutState(idStr, txJSONasBytes)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to save transaction \" + string(txJSONasBytes))\n\t}\n\n fmt.Println(txJSON)\n\tfmt.Println(\"confirmPay ends!\")\n\treturn shim.Success(txJSONasBytes)\n}", "func DeployKeeperContracts(\n\tt *testing.T,\n\tregistryVersion ethereum.KeeperRegistryVersion,\n\tregistrySettings contracts.KeeperRegistrySettings,\n\tnumberOfUpkeeps int,\n\tupkeepGasLimit uint32,\n\tlinkToken contracts.LinkToken,\n\tcontractDeployer contracts.ContractDeployer,\n\tclient blockchain.EVMClient,\n\tlinkFundsForEachUpkeep *big.Int,\n) (contracts.KeeperRegistry, contracts.KeeperRegistrar, []contracts.KeeperConsumer, []*big.Int) {\n\tef, err := contractDeployer.DeployMockETHLINKFeed(big.NewInt(2e18))\n\trequire.NoError(t, err, \"Deploying mock ETH-Link feed shouldn't fail\")\n\tgf, err := contractDeployer.DeployMockGasFeed(big.NewInt(2e11))\n\trequire.NoError(t, err, \"Deploying mock gas feed shouldn't fail\")\n\terr = client.WaitForEvents()\n\trequire.NoError(t, err, \"Failed waiting for mock feeds to deploy\")\n\n\t// Deploy the transcoder here, and then set it to the registry\n\ttranscoder := DeployUpkeepTranscoder(t, contractDeployer, client)\n\tregistry := DeployKeeperRegistry(t, contractDeployer, client,\n\t\t&contracts.KeeperRegistryOpts{\n\t\t\tRegistryVersion: registryVersion,\n\t\t\tLinkAddr: linkToken.Address(),\n\t\t\tETHFeedAddr: ef.Address(),\n\t\t\tGasFeedAddr: gf.Address(),\n\t\t\tTranscoderAddr: transcoder.Address(),\n\t\t\tRegistrarAddr: ZeroAddress.Hex(),\n\t\t\tSettings: registrySettings,\n\t\t},\n\t)\n\n\t// Fund the registry with 1 LINK * amount of KeeperConsumerPerformance contracts\n\terr = linkToken.Transfer(registry.Address(), big.NewInt(0).Mul(big.NewInt(1e18), big.NewInt(int64(numberOfUpkeeps))))\n\trequire.NoError(t, err, \"Funding keeper registry contract shouldn't fail\")\n\n\tregistrarSettings := contracts.KeeperRegistrarSettings{\n\t\tAutoApproveConfigType: 2,\n\t\tAutoApproveMaxAllowed: math.MaxUint16,\n\t\tRegistryAddr: registry.Address(),\n\t\tMinLinkJuels: big.NewInt(0),\n\t}\n\tregistrar := DeployKeeperRegistrar(t, registryVersion, linkToken, registrarSettings, contractDeployer, client, registry)\n\n\tupkeeps := DeployKeeperConsumers(t, contractDeployer, client, numberOfUpkeeps)\n\tvar upkeepsAddresses []string\n\tfor _, upkeep := range upkeeps {\n\t\tupkeepsAddresses = append(upkeepsAddresses, upkeep.Address())\n\t}\n\tupkeepIds := RegisterUpkeepContracts(\n\t\tt, linkToken, linkFundsForEachUpkeep, client, upkeepGasLimit, registry, registrar, numberOfUpkeeps, upkeepsAddresses,\n\t)\n\terr = client.WaitForEvents()\n\trequire.NoError(t, err, \"Error waiting for events\")\n\n\treturn registry, registrar, upkeeps, upkeepIds\n}", "func GetDebondingDelegationsFor(w http.ResponseWriter, r *http.Request) {\n\n\t// Add header so that received knows they're receiving JSON\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// Retrieving name of node from query request\n\tnodeName := r.URL.Query().Get(\"name\")\n\tconfirmation, socket := checkNodeName(nodeName)\n\tif !confirmation {\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Node name requested doesn't exist\"})\n\t\treturn\n\t}\n\n\t// Retrieving height from query request\n\trecvHeight := r.URL.Query().Get(\"height\")\n\theight := checkHeight(recvHeight)\n\tif height == -1 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Unexpected value found, height needs to be a string representing an int!\"})\n\t\treturn\n\t}\n\n\t// Note Make sure that public key that is being sent is coded properly\n\t// Example A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU+h+blS9pto= should be\n\t// A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU%2Bh%2BblS9pto=\n\t//var pubKey common_signature.PublicKey\n\townerKey := r.URL.Query().Get(\"ownerKey\")\n\tif len(ownerKey) == 0 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tlgr.Warning.Println(\n\t\t\t\"Request at /api/staking/account failed, address can't be \" +\n\t\t\t\t\"empty!\")\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"address can't be empty!\"})\n\t\treturn\n\t}\n\n\t// Unmarshal text into public key object\n\t//err := pubKey.UnmarshalText([]byte(ownerKey))\n\t//if err != nil {\n\t//\tlgr.Error.Println(\"Failed to UnmarshalText into Public Key\", err)\n\t//\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t//\t\tError: \"Failed to UnmarshalText into Public Key.\"})\n\t//\treturn\n\t//}\n\n\tvar address staking.Address\n\terr := address.UnmarshalText([]byte(ownerKey))\n\tif err != nil {\n\t\tlgr.Error.Println(\"Failed to UnmarshalText into Address\", err)\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to UnmarshalText into Address.\"})\n\t\treturn\n\t}\n\n\t// Attempt to load connection with staking client\n\tconnection, so := loadStakingClient(socket)\n\n\t// Close connection once code underneath executes\n\tdefer connection.Close()\n\n\t// If null object was retrieved send response\n\tif so == nil {\n\n\t\t// Stop code here faild to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to establish connection using socket : \" + socket})\n\t\treturn\n\t}\n\n\t// Query created to retrieved Debonding Delegations for an account\n\tquery := staking.OwnerQuery{Height: height, Owner: address}\n\n\t// Retrieving debonding delegations for an account using above query\n\tdebondingDelegationsFor, err := so.DebondingDelegationsFor(context.Background(),\n\t\t&query)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to get Debonding Delegations!\"})\n\t\tlgr.Error.Println(\n\t\t\t\"Request at /api/staking/debondingdelegationsfor failed to retrieve\"+\n\t\t\t\t\" Debonding Delegations : \", err)\n\t\treturn\n\t}\n\n\t// Responding with debonding delegations for given accounts\n\tlgr.Info.Println(\n\t\t\"Request at /api/staking/debondingdelegationsfor responding with \" +\n\t\t\t\"Debonding Delegations!\")\n\tjson.NewEncoder(w).Encode(responses.DebondingDelegationsResponse{\n\t\tDebondingDelegations: debondingDelegationsFor})\n}", "func (s *RoundsService) Delegates(ctx context.Context, id int64) (*GetDelegates, *http.Response, error) {\n\turi := fmt.Sprintf(\"rounds/%v/delegates\", id)\n\n\tvar responseStruct *GetDelegates\n\tresp, err := s.client.SendRequest(ctx, \"GET\", uri, nil, nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func SortDelegateContracts(delegatedContracts []DelegatedContract) []DelegatedContract{\n for i, j := 0, len(delegatedContracts)-1; i < j; i, j = i+1, j-1 {\n delegatedContracts[i], delegatedContracts[j] = delegatedContracts[j], delegatedContracts[i]\n }\n return delegatedContracts\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (c *swapCoin) Confirmations(_ context.Context) (int64, error) {\n\tswap, err := c.backend.node.swap(c.backend.rpcCtx, c.secretHash)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\tswitch c.sct {\n\tcase sctRedeem:\n\t\t// There should be no need to check the counter party, or value\n\t\t// as a swap with a specific secret hash that has been redeemed\n\t\t// wouldn't have been redeemed without ensuring the initiator\n\t\t// is the expected address and value was also as expected. Also\n\t\t// not validating the locktime, as the swap is redeemed and\n\t\t// locktime no longer relevant.\n\t\tss := dexeth.SwapStep(swap.State)\n\t\tif ss == dexeth.SSRedeemed {\n\t\t\t// While not completely accurate, we know that if the\n\t\t\t// swap is redeemed the redemption has at least one\n\t\t\t// confirmation.\n\t\t\treturn 1, nil\n\t\t}\n\t\t// If swap is in the Initiated state, the transaction may be\n\t\t// unmined.\n\t\tif ss == dexeth.SSInitiated {\n\t\t\t// Assume the tx still has a chance of being mined.\n\t\t\treturn 0, nil\n\t\t}\n\t\t// If swap is in None state, then the redemption can't possibly\n\t\t// succeed as the swap must already be in the Initialized state\n\t\t// to redeem. If the swap is in the Refunded state, then the\n\t\t// redemption either failed or never happened.\n\t\treturn -1, fmt.Errorf(\"redemption in failed state with swap at %s state\", ss)\n\n\tcase sctInit:\n\t\t// Uninitiated state is zero confs. It could still be in mempool.\n\t\t// It is important to only trust confirmations according to the\n\t\t// swap contract. Until there are confirmations we cannot be sure\n\t\t// that initiation happened successfully.\n\t\tif dexeth.SwapStep(swap.State) == dexeth.SSNone {\n\t\t\t// Assume the tx still has a chance of being mined.\n\t\t\treturn 0, nil\n\t\t}\n\t\t// Any other swap state is ok. We are sure that initialization\n\t\t// happened.\n\n\t\t// The swap initiation transaction has some number of\n\t\t// confirmations, and we are sure the secret hash belongs to\n\t\t// this swap. Assert that the value, receiver, and locktime are\n\t\t// as expected.\n\t\tvalue, err := dexeth.ToGwei(new(big.Int).Set(swap.Value))\n\t\tif err != nil {\n\t\t\treturn -1, fmt.Errorf(\"unable to convert value: %v\", err)\n\t\t}\n\t\tif value != c.value {\n\t\t\treturn -1, fmt.Errorf(\"expected swap val (%dgwei) does not match expected (%dgwei)\",\n\t\t\t\tc.value, value)\n\t\t}\n\t\tif swap.Participant != c.counterParty {\n\t\t\treturn -1, fmt.Errorf(\"expected swap participant %q does not match expected %q\",\n\t\t\t\tc.counterParty, swap.Participant)\n\t\t}\n\t\tif !swap.RefundBlockTimestamp.IsInt64() {\n\t\t\treturn -1, errors.New(\"swap locktime is larger than expected\")\n\t\t}\n\t\tlocktime := swap.RefundBlockTimestamp.Int64()\n\t\tif locktime != c.locktime {\n\t\t\treturn -1, fmt.Errorf(\"expected swap locktime (%d) does not match expected (%d)\",\n\t\t\t\tc.locktime, locktime)\n\t\t}\n\n\t\tbn, err := c.backend.node.blockNumber(c.backend.rpcCtx)\n\t\tif err != nil {\n\t\t\treturn 0, fmt.Errorf(\"unable to fetch block number: %v\", err)\n\t\t}\n\t\treturn int64(bn - swap.InitBlockNumber.Uint64()), nil\n\t}\n\n\treturn -1, fmt.Errorf(\"unsupported swap type for confirmations: %d\", c.sct)\n}", "func sendToNextSettlementContract(ctx context.Context,\r\n\tw *node.ResponseWriter,\r\n\trk *wallet.Key,\r\n\titx *inspector.Transaction,\r\n\ttransferTx *inspector.Transaction,\r\n\ttransfer *actions.Transfer,\r\n\tsettleTx *txbuilder.TxBuilder,\r\n\tsettlement *actions.Settlement,\r\n\tsettlementRequest *messages.SettlementRequest,\r\n\ttracer *filters.Tracer) error {\r\n\tctx, span := trace.StartSpan(ctx, \"handlers.Transfer.sendToNextSettlementContract\")\r\n\tdefer span.End()\r\n\r\n\tboomerangIndex := uint32(0xffffffff)\r\n\tif !bytes.Equal(itx.Hash[:], transferTx.Hash[:]) {\r\n\t\t// If already an M1, use only output\r\n\t\tboomerangIndex = 0\r\n\t} else {\r\n\t\tboomerangIndex = findBoomerangIndex(transferTx, transfer, rk.Address)\r\n\t}\r\n\r\n\tif boomerangIndex == 0xffffffff {\r\n\t\treturn fmt.Errorf(\"Multi-Contract Transfer missing boomerang output\")\r\n\t}\r\n\tnode.LogVerbose(ctx, \"Boomerang output index : %d\", boomerangIndex)\r\n\r\n\t// Find next contract\r\n\tnextContractIndex := uint32(0x0000ffff)\r\n\tcurrentFound := false\r\n\tcompletedContracts := make(map[bitcoin.Hash20]bool)\r\n\tfor _, asset := range transfer.Assets {\r\n\t\tif asset.ContractIndex == uint32(0x0000ffff) {\r\n\t\t\tcontinue // Asset transfer doesn't have a contract (probably BSV transfer).\r\n\t\t}\r\n\r\n\t\tif int(asset.ContractIndex) >= len(transferTx.Outputs) {\r\n\t\t\treturn errors.New(\"Transfer contract index out of range\")\r\n\t\t}\r\n\r\n\t\thash, err := transferTx.Outputs[asset.ContractIndex].Address.Hash()\r\n\t\tif err != nil {\r\n\t\t\treturn errors.Wrap(err, \"Transfer contract address invalid\")\r\n\t\t}\r\n\r\n\t\tif !currentFound {\r\n\t\t\tcompletedContracts[*hash] = true\r\n\t\t\tif transferTx.Outputs[asset.ContractIndex].Address.Equal(rk.Address) {\r\n\t\t\t\tcurrentFound = true\r\n\t\t\t}\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\t// Contracts can be used more than once, so ensure this contract wasn't referenced before\r\n\t\t// the current contract.\r\n\t\t_, complete := completedContracts[*hash]\r\n\t\tif !complete {\r\n\t\t\tnextContractIndex = asset.ContractIndex\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\r\n\tif nextContractIndex == 0xffff {\r\n\t\treturn fmt.Errorf(\"Next contract not found in multi-contract transfer\")\r\n\t}\r\n\r\n\tnode.Log(ctx, \"Sending settlement offer to %s\",\r\n\t\tbitcoin.NewAddressFromRawAddress(transferTx.Outputs[nextContractIndex].Address,\r\n\t\t\tw.Config.Net))\r\n\r\n\t// Setup M1 response\r\n\tvar err error\r\n\terr = w.SetUTXOs(ctx, []bitcoin.UTXO{itx.Outputs[boomerangIndex].UTXO})\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\t// Add output to next contract.\r\n\t// Mark as change so it gets everything except the tx fee.\r\n\terr = w.AddChangeOutput(ctx, transferTx.Outputs[nextContractIndex].Address)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\t// Serialize settlement tx for Message payload.\r\n\tsettlementRequest.Settlement, err = protocol.Serialize(settlement, w.Config.IsTest)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\t// Setup Message\r\n\tvar payBuf bytes.Buffer\r\n\terr = settlementRequest.Serialize(&payBuf)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tmessage := actions.Message{\r\n\t\tReceiverIndexes: []uint32{0}, // First output is receiver of message\r\n\t\tMessageCode: settlementRequest.Code(),\r\n\t\tMessagePayload: payBuf.Bytes(),\r\n\t}\r\n\r\n\tif err := node.RespondSuccess(ctx, w, itx, rk, &message); err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tif bytes.Equal(itx.Hash[:], transferTx.Hash[:]) {\r\n\t\toutpoint := wire.OutPoint{Hash: *itx.Hash, Index: boomerangIndex}\r\n\t\ttracer.Add(ctx, &outpoint)\r\n\t}\r\n\treturn nil\r\n}", "func CalculateAllContractsForCycles(delegatedContracts []DelegatedContract, cycleStart int, cycleEnd int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var err error\n\n for cycleStart <= cycleEnd {\n //fmt.Println(cycleStart)\n delegatedContracts, err = CalculateAllContractsForCycle(delegatedContracts, cycleStart, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycles \" + strconv.Itoa(cycleStart) + \"-\" + strconv.Itoa(cycleEnd) + \":CalculateAllCommitmentsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64) failed: \" + err.Error())\n }\n cycleStart = cycleStart + 1\n }\n return delegatedContracts, nil\n}", "func (s *ArkClient) CalculateVotersProfit(params DelegateQueryParams, shareRatio float64, blocklist string, whitelist string, capBalance bool, balanceCapAmount float64, blockBalanceCap bool) []DelegateDataProfit {\n\tdelegateRes, _, _ := s.GetDelegate(params)\n\tvoters, _, _ := s.GetDelegateVoters(params)\n\taccountRes, _, _ := s.GetAccount(AccountQueryParams{Address: delegateRes.SingleDelegate.Address})\n\n\tdelegateBalance, _ := strconv.ParseFloat(accountRes.Account.Balance, 64)\n\tdelegateBalance = float64(delegateBalance) / SATOSHI\n\n\t//calculating vote weight\n\tvotersProfit := []DelegateDataProfit{}\n\tdelelgateVoteWeight := 0\n\n\t//computing summ of all votes\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tintBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tintBalance = int(balanceCapAmount)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelelgateVoteWeight += intBalance\n\t}\n\n\t//calculating\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tcurrentVoterBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcurrentVoterBalance = balanceCapAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdeleProfit := DelegateDataProfit{\n\t\t\tAddress: element.Address,\n\t\t}\n\t\tdeleProfit.VoteWeight = currentVoterBalance / SATOSHI\n\t\tdeleProfit.VoteWeightShare = float64(currentVoterBalance) / float64(delelgateVoteWeight)\n\t\tdeleProfit.EarnedAmount100 = float64(delegateBalance) * deleProfit.VoteWeightShare\n\t\tdeleProfit.EarnedAmountXX = float64(delegateBalance) * deleProfit.VoteWeightShare * shareRatio\n\t\tdeleProfit.VoteDuration = s.GetVoteDuration(element.Address)\n\t\tvotersProfit = append(votersProfit, deleProfit)\n\t}\n\n\treturn votersProfit\n}", "func (_Bep20 *Bep20Transactor) Delegate(opts *bind.TransactOpts, delegatee common.Address) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegate\", delegatee)\n}", "func testSwapContract(segwit bool) ([]byte, btcutil.Address, btcutil.Address) {\n\tlockTime := time.Now().Add(time.Hour * 8).Unix()\n\tsecretHash := randomBytes(32)\n\t_, receiverPKH := genPubkey()\n\t_, senderPKH := genPubkey()\n\tcontract, err := txscript.NewScriptBuilder().\n\t\tAddOps([]byte{\n\t\t\ttxscript.OP_IF,\n\t\t\ttxscript.OP_SIZE,\n\t\t}).AddInt64(32).\n\t\tAddOps([]byte{\n\t\t\ttxscript.OP_EQUALVERIFY,\n\t\t\ttxscript.OP_SHA256,\n\t\t}).AddData(secretHash).\n\t\tAddOps([]byte{\n\t\t\ttxscript.OP_EQUALVERIFY,\n\t\t\ttxscript.OP_DUP,\n\t\t\ttxscript.OP_HASH160,\n\t\t}).AddData(receiverPKH).\n\t\tAddOp(txscript.OP_ELSE).\n\t\tAddInt64(lockTime).AddOps([]byte{\n\t\ttxscript.OP_CHECKLOCKTIMEVERIFY,\n\t\ttxscript.OP_DROP,\n\t\ttxscript.OP_DUP,\n\t\ttxscript.OP_HASH160,\n\t}).AddData(senderPKH).\n\t\tAddOps([]byte{\n\t\t\ttxscript.OP_ENDIF,\n\t\t\ttxscript.OP_EQUALVERIFY,\n\t\t\ttxscript.OP_CHECKSIG,\n\t\t}).Script()\n\tif err != nil {\n\t\tfmt.Printf(\"testSwapContract error: %v\\n\", err)\n\t}\n\tvar receiverAddr, refundAddr btcutil.Address\n\tif segwit {\n\t\treceiverAddr, _ = btcutil.NewAddressWitnessPubKeyHash(receiverPKH, testParams)\n\t\trefundAddr, _ = btcutil.NewAddressWitnessPubKeyHash(senderPKH, testParams)\n\t} else {\n\t\treceiverAddr, _ = btcutil.NewAddressPubKeyHash(receiverPKH, testParams)\n\t\trefundAddr, _ = btcutil.NewAddressPubKeyHash(senderPKH, testParams)\n\t}\n\n\treturn contract, receiverAddr, refundAddr\n}", "func (_DelegatableDai *DelegatableDaiCaller) Balances(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegatableDai.contract.Call(opts, out, \"balances\", arg0)\n\treturn *ret0, err\n}", "func (broadcast *Broadcast) Delegate(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegateMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (s2 *S2BlockGrader) Payout(index int) int64 {\n\treturn S1Payout(index)\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) Delegations(arg0 [32]byte) (common.Address, error) {\n\treturn _PlasmaFramework.Contract.Delegations(&_PlasmaFramework.CallOpts, arg0)\n}", "func (m *Mantle) replenishBalances() {\n\tfor _, w := range m.wallets {\n\t\tm.replenishBalance(w)\n\t}\n}", "func (_DelegatableDai *DelegatableDaiTransactor) Approve(opts *bind.TransactOpts, _spender common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _DelegatableDai.contract.Transact(opts, \"approve\", _spender, _value)\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func (c *DPOS) CheckRewardsFromAllValidators(ctx contract.StaticContext, req *CheckDelegatorRewardsRequest) (*CheckDelegatorRewardsResponse, error) {\n\tif req.Delegator == nil {\n\t\treturn nil, logStaticDposError(ctx, errors.New(\"CheckRewardsFromAllValidators called with req.Delegator == nil\"), req.String())\n\t}\n\n\tdelegator := loom.UnmarshalAddressPB(req.Delegator)\n\tdelegations, err := loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to load delegations\")\n\t}\n\n\ttotal := big.NewInt(0)\n\tfor _, d := range delegations {\n\t\tif d.Index != REWARD_DELEGATION_INDEX ||\n\t\t\tloom.UnmarshalAddressPB(d.Delegator).Compare(delegator) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tctx.Logger().Error(\"DPOS CheckRewardsFromAllValidators\", \"error\", err, \"delegator\", delegator)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to load delegation\")\n\t\t}\n\n\t\ttotal.Add(total, delegation.Amount.Value.Int)\n\t}\n\n\tamount := loom.NewBigUInt(total)\n\treturn &CheckDelegatorRewardsResponse{\n\t\tAmount: &types.BigUInt{Value: *amount},\n\t}, nil\n}", "func (s *Server) RelayTxn(t *transaction.Transaction) error {\n\terr := s.verifyAndPoolTX(t)\n\tif err == nil {\n\t\ts.broadcastTX(t, nil)\n\t}\n\treturn err\n}", "func (_Bindings *BindingsSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.Contract.Approve(&_Bindings.TransactOpts, spender, amount)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowTransactor) Redelegate(opts *bind.TransactOpts, previousOperator common.Address, amount *big.Int, extraData []byte) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.contract.Transact(opts, \"redelegate\", previousOperator, amount, extraData)\n}", "func UnsafeWithdrawImpersonateValidators(\n\tprivKeys []string,\n\treceiverAddress string,\n\tethereumAssetID string,\n\tbridgeAddress string,\n\tamountStr string,\n) error {\n\t// validate amount\n\tamount, ok := big.NewInt(0).SetString(amountStr, 10)\n\tif !ok {\n\t\treturn errors.New(\"invalid amount, make sure you specified a base 10 price without decimals\")\n\t}\n\n\t// the keystore where we will temporay load our private keys\n\twstore := NewStore()\n\t// the final signed payload\n\tsigs := \"0x\"\n\tmsgs := map[string]struct{}{}\n\n\tvar finalmsg string\n\tnow := time.Now()\n\texpiry := now.Add(2 * time.Hour).Unix()\n\tnonce := big.NewInt(expiry + 42)\n\n\tfor _, priv := range privKeys {\n\t\taddress, err := wstore.Import(priv, passphrase)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to import key: %w, (you may want to delete the %s folder)\", err, keystoreDir)\n\t\t}\n\t\tfmt.Printf(\"generating signature for address: %v\\n\", address)\n\n\t\tmsg, sig, err := signWithdrawal(\n\t\t\tamount, expiry, nonce, wstore, passphrase, address, bridgeAddress, ethereumAssetID, receiverAddress)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to create signature: %w\", err)\n\t\t}\n\n\t\tfmt.Printf(\"0x%v\\n\", hex.EncodeToString(sig))\n\n\t\tmsgs[string(msg)] = struct{}{}\n\t\tfinalmsg = \"0x\" + hex.EncodeToString(msg)\n\t\tsigs = sigs + hex.EncodeToString(sig)\n\t}\n\tif len(msgs) != 1 {\n\t\tfmt.Printf(\"Incorrect message count: %v\\n\", len(msgs))\n\t\tos.Exit(1)\n\t}\n\tfmt.Printf(\"Message: %v\\n\\n\", finalmsg)\n\n\tfmt.Printf(\"Asset source (address) : %v\\n\", ethereumAssetID)\n\tfmt.Printf(\"Amount (uint256) : %v\\n\", amount)\n\tfmt.Printf(\"Expiry (uint256) : %v\\n\", expiry)\n\tfmt.Printf(\"Target (address) : %v\\n\", receiverAddress)\n\tfmt.Printf(\"Nonce (uint256) : %v\\n\", nonce)\n\tfmt.Printf(\"Signature (bytes) : %v\\n\", sigs)\n\tfmt.Printf(\"Value in ETH: 0\\n\")\n\n\treturn nil\n}", "func (_DelegatableDai *DelegatableDaiSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func GetDelegationsFor(w http.ResponseWriter, r *http.Request) {\n\n\t// Add header so that received knows they're receiving JSON\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// Retrieving name of node from query request\n\tnodeName := r.URL.Query().Get(\"name\")\n\tconfirmation, socket := checkNodeName(nodeName)\n\tif confirmation == false {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Node name requested doesn't exist\"})\n\t\treturn\n\t}\n\n\t// Retrieving height from query request\n\trecvHeight := r.URL.Query().Get(\"height\")\n\theight := checkHeight(recvHeight)\n\tif height == -1 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Unexpected value found, height needs to be a string representing an int!\"})\n\t\treturn\n\t}\n\n\t// Note Make sure that public key that is being sent is coded properly\n\t// Example A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU+h+blS9pto= should be\n\t// A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU%2Bh%2BblS9pto=\n\t//var pubKey common_signature.PublicKey\n\townerKey := r.URL.Query().Get(\"ownerKey\")\n\tif len(ownerKey) == 0 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tlgr.Warning.Println(\n\t\t\t\"Request at /api/staking/delegationsfor failed, address can't be \" +\n\t\t\t\t\"empty!\")\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"address can't be empty!\"})\n\t\treturn\n\t}\n\n\t// Unmarshal text into public key object\n\t//err := pubKey.UnmarshalText([]byte(ownerKey))\n\t//if err != nil {\n\t//\tlgr.Error.Println(\"Failed to UnmarshalText into Public Key\", err)\n\t//\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t//\t\tError: \"Failed to UnmarshalText into Public Key.\"})\n\t//\treturn\n\t//}\n\n\tvar address staking.Address\n\terr := address.UnmarshalText([]byte(ownerKey))\n\tif err != nil {\n\t\tlgr.Error.Println(\"Failed to UnmarshalText into Address\", err)\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to UnmarshalText into Address.\"})\n\t\treturn\n\t}\n\n\t// Attempt to load connection with staking client\n\tconnection, so := loadStakingClient(socket)\n\n\t// Close connection once code underneath executes\n\tdefer connection.Close()\n\n\t// If null object was retrieved send response\n\tif so == nil {\n\n\t\t// Stop code here faild to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to establish connection using socket : \" + socket})\n\t\treturn\n\t}\n\n\t// Create an owner query to be able to retrieve data with regards to account\n\tquery := staking.OwnerQuery{Height: height, Owner: address}\n\n\t// Return delegations for given account query\n\tdelegationsFor, err := so.DelegationsFor(context.Background(), &query)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to get Delegations!\"})\n\n\t\tlgr.Error.Println(\n\t\t\t\"Request at /api/staking/delegationsfor failed to retrieve \"+\n\t\t\t\t\"Delegations : \", err)\n\t\treturn\n\t}\n\n\t// Respond with delegations for given account query\n\tlgr.Info.Println(\"Request at /api/staking/delegations responding with \" +\n\t\t\"delegations!\")\n\tjson.NewEncoder(w).Encode(responses.DelegationsResponse{Delegations:\n\tdelegationsFor})\n}", "func (_Bindings *BindingsTransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.Contract.Approve(&_Bindings.TransactOpts, spender, amount)\n}", "func SetupContractsT(t *testing.T, chainURL string, onChainTxTimeout time.Duration) (\n\tadjudicator, asset pwallet.Address) {\n\tvar err error\n\tadjudicator, asset, err = SetupContracts(chainURL, onChainTxTimeout)\n\trequire.NoError(t, err)\n\treturn adjudicator, asset\n}", "func AddContract(\n\tctx context.Context,\n\tfc *client.Client,\n\tkm keys.Manager,\n\taccountAddress string,\n\tcontract flow_templates.Contract,\n\ttransactionTimeout time.Duration) error {\n\n\t// Get admin account authorizer\n\tpayer, err := km.AdminAuthorizer(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get user account authorizer\n\tproposer, err := km.UserAuthorizer(ctx, flow.HexToAddress(accountAddress))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get latest blocks id as reference id\n\treferenceBlockID, err := flow_helpers.LatestBlockId(ctx, fc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tflowTx := flow.NewTransaction().\n\t\tSetReferenceBlockID(*referenceBlockID).\n\t\tSetProposalKey(proposer.Address, proposer.Key.Index, proposer.Key.SequenceNumber).\n\t\tSetPayer(payer.Address).\n\t\tSetGasLimit(maxGasLimit).\n\t\tSetScript([]byte(template_strings.AddAccountContractWithAdmin)).\n\t\tAddAuthorizer(payer.Address)\n\n\tif err := flowTx.AddArgument(cadence.String(contract.Name)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := flowTx.AddArgument(cadence.String(contract.SourceHex())); err != nil {\n\t\treturn err\n\t}\n\n\t// Proposer signs the payload\n\tif proposer.Address.Hex() != payer.Address.Hex() {\n\t\tif err := flowTx.SignPayload(proposer.Address, proposer.Key.Index, proposer.Signer); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Payer signs the envelope\n\tif err := flowTx.SignEnvelope(payer.Address, payer.Key.Index, payer.Signer); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = flow_helpers.SendAndWait(ctx, fc, *flowTx, transactionTimeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) Deposit(token common.Address, participant common.Address, partner common.Address, amount *big.Int, settle_timeout uint64) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.Deposit(&_TokensNetwork.TransactOpts, token, participant, partner, amount, settle_timeout)\n}", "func (_Dospayment *DospaymentRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {\n\treturn _Dospayment.Contract.DospaymentTransactor.contract.Transact(opts, method, params...)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowFilterer) WatchDepositRedelegated(opts *bind.WatchOpts, sink chan<- *TokenStakingEscrowDepositRedelegated, previousOperator []common.Address, newOperator []common.Address, grantId []*big.Int) (event.Subscription, error) {\n\n\tvar previousOperatorRule []interface{}\n\tfor _, previousOperatorItem := range previousOperator {\n\t\tpreviousOperatorRule = append(previousOperatorRule, previousOperatorItem)\n\t}\n\tvar newOperatorRule []interface{}\n\tfor _, newOperatorItem := range newOperator {\n\t\tnewOperatorRule = append(newOperatorRule, newOperatorItem)\n\t}\n\tvar grantIdRule []interface{}\n\tfor _, grantIdItem := range grantId {\n\t\tgrantIdRule = append(grantIdRule, grantIdItem)\n\t}\n\n\tlogs, sub, err := _TokenStakingEscrow.contract.WatchLogs(opts, \"DepositRedelegated\", previousOperatorRule, newOperatorRule, grantIdRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(TokenStakingEscrowDepositRedelegated)\n\t\t\t\tif err := _TokenStakingEscrow.contract.UnpackLog(event, \"DepositRedelegated\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (wt *Wallet) SendOutputs(outputs []*types.TxOutput, account int64, satPerKb types.Amount) (*string, error) {\n\n\t// Ensure the outputs to be created adhere to the network's consensus\n\t// rules.\n\tsyncSendOutputs.Lock()\n\tdefer syncSendOutputs.Unlock()\n\ttx := types.NewTransaction()\n\tpayAmout := types.Amount(0)\n\tfeeAmout := int64(0)\n\tfor _, output := range outputs {\n\t\tif err := txrules.CheckOutput(output, satPerKb); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayAmout = payAmout + types.Amount(output.Amount)\n\t\ttx.AddTxOut(output)\n\t}\n\taaars, err := wt.GetAccountAndAddress(waddrmgr.KeyScopeBIP0044)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar sendAddrTxOutput []wtxmgr.AddrTxOutput\n\t//var prk string\nb:\n\tfor _, aaar := range aaars {\n\n\t\tif int64(aaar.AccountNumber) != account && account != waddrmgr.AccountMergePayNum {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, addroutput := range aaar.AddrsOutput {\n\t\t\tlog.Trace(fmt.Sprintf(\"addr:%s,unspend:%v\", addroutput.Addr, addroutput.balance.UnspendAmount))\n\t\t\tif addroutput.balance.UnspendAmount > 0 {\n\t\t\t\taddr, err := address.DecodeAddress(addroutput.Addr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tfrompkscipt, err := txscript.PayToAddrScript(addr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\taddrByte := []byte(addroutput.Addr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tfor _, output := range addroutput.Txoutput {\n\t\t\t\t\toutput.Address = addroutput.Addr\n\t\t\t\t\tif output.Spend == wtxmgr.SpendStatusUnspent {\n\t\t\t\t\t\tif payAmout > 0 && feeAmout == 0 {\n\t\t\t\t\t\t\tif output.Amount > payAmout {\n\t\t\t\t\t\t\t\tinput := types.NewOutPoint(&output.TxId, output.Index)\n\t\t\t\t\t\t\t\ttx.AddTxIn(types.NewTxInput(input, addrByte))\n\t\t\t\t\t\t\t\tselfTxOut := types.NewTxOutput(uint64(output.Amount-payAmout), frompkscipt)\n\t\t\t\t\t\t\t\tfeeAmout = util.CalcMinRequiredTxRelayFee(int64(tx.SerializeSize()+selfTxOut.SerializeSize()), types.Amount(config.Cfg.MinTxFee))\n\t\t\t\t\t\t\t\tsendAddrTxOutput = append(sendAddrTxOutput, output)\n\t\t\t\t\t\t\t\tif (output.Amount - payAmout - types.Amount(feeAmout)) >= 0 {\n\t\t\t\t\t\t\t\t\tselfTxOut.Amount = uint64(output.Amount - payAmout - types.Amount(feeAmout))\n\t\t\t\t\t\t\t\t\tif selfTxOut.Amount > 0 {\n\t\t\t\t\t\t\t\t\t\ttx.AddTxOut(selfTxOut)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tpayAmout = 0\n\t\t\t\t\t\t\t\t\tfeeAmout = 0\n\t\t\t\t\t\t\t\t\tbreak b\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselfTxOut.Amount = uint64(output.Amount - payAmout)\n\t\t\t\t\t\t\t\t\tpayAmout = 0\n\t\t\t\t\t\t\t\t\ttx.AddTxOut(selfTxOut)\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tinput := types.NewOutPoint(&output.TxId, output.Index)\n\t\t\t\t\t\t\t\ttx.AddTxIn(types.NewTxInput(input, addrByte))\n\t\t\t\t\t\t\t\tsendAddrTxOutput = append(sendAddrTxOutput, output)\n\t\t\t\t\t\t\t\tpayAmout = payAmout - output.Amount\n\t\t\t\t\t\t\t\tif payAmout == 0 {\n\t\t\t\t\t\t\t\t\tfeeAmout = util.CalcMinRequiredTxRelayFee(int64(tx.SerializeSize()), types.Amount(config.Cfg.MinTxFee))\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 if payAmout == 0 && feeAmout > 0 {\n\t\t\t\t\t\t\tif output.Amount >= types.Amount(feeAmout) {\n\t\t\t\t\t\t\t\tinput := types.NewOutPoint(&output.TxId, output.Index)\n\t\t\t\t\t\t\t\ttx.AddTxIn(types.NewTxInput(input, addrByte))\n\t\t\t\t\t\t\t\tselfTxOut := types.NewTxOutput(uint64(output.Amount-types.Amount(feeAmout)), frompkscipt)\n\t\t\t\t\t\t\t\tif selfTxOut.Amount > 0 {\n\t\t\t\t\t\t\t\t\ttx.AddTxOut(selfTxOut)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tsendAddrTxOutput = append(sendAddrTxOutput, output)\n\t\t\t\t\t\t\t\tfeeAmout = 0\n\t\t\t\t\t\t\t\tbreak b\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tlog.Trace(\"utxo < feeAmout\")\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.Trace(fmt.Sprintf(\"system err payAmout :%v ,feeAmout :%v\\n\", payAmout, feeAmout))\n\t\t\t\t\t\t\treturn nil, fmt.Errorf(\"system err payAmout :%v ,feeAmout :%v\\n\", payAmout, feeAmout)\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}\n\t}\n\tif payAmout.ToCoin() != types.Amount(0).ToCoin() || feeAmout != 0 {\n\t\tlog.Trace(\"payAmout\", \"payAmout\", payAmout)\n\t\tlog.Trace(\"feeAmout\", \"feeAmout\", feeAmout)\n\t\treturn nil, fmt.Errorf(\"balance is not enough,please deduct the service charge:%v\", types.Amount(feeAmout).ToCoin())\n\t}\n\n\tsignTx, err := wt.multiAddressMergeSign(*tx, wt.chainParams.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Trace(fmt.Sprintf(\"signTx size:%v\", len(signTx)), \"signTx\", signTx)\n\tmsg, err := wt.HttpClient.SendRawTransaction(signTx, false)\n\tif err != nil {\n\t\tlog.Trace(\"SendRawTransaction txSign err \", \"err\", err.Error())\n\t\treturn nil, err\n\t} else {\n\t\tmsg = strings.ReplaceAll(msg, \"\\\"\", \"\")\n\t\tlog.Trace(\"SendRawTransaction txSign response msg\", \"msg\", msg)\n\t}\n\n\terr = walletdb.Update(wt.db, func(tx walletdb.ReadWriteTx) error {\n\t\tns := tx.ReadWriteBucket(wtxmgrNamespaceKey)\n\t\toutns := ns.NestedReadWriteBucket(wtxmgr.BucketAddrtxout)\n\t\tfor _, txoutput := range sendAddrTxOutput {\n\t\t\ttxoutput.Spend = wtxmgr.SpendStatusSpend\n\t\t\terr = wt.TxStore.UpdateAddrTxOut(outns, &txoutput)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"UpdateAddrTxOut to spend err\", \"err\", err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tlog.Trace(\"UpdateAddrTxOut to spend succ \")\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Error(\"UpdateAddrTxOut to spend err\", \"err\", err.Error())\n\t\treturn nil, err\n\t}\n\n\treturn &msg, nil\n}", "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (wallet *Wallet) SendFunds(options ...SendFundsOption) (tx *ledgerstate.Transaction, err error) {\n\t// build options from the parameters\n\tsendFundsOptions, err := buildSendFundsOptions(options...)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// determine which outputs to use for our transfer\n\tconsumedOutputs, err := wallet.determineOutputsToConsume(sendFundsOptions)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// determine pledge IDs\n\tallowedPledgeNodeIDs, err := wallet.connector.GetAllowedPledgeIDs()\n\tif err != nil {\n\t\treturn\n\t}\n\tvar accessPledgeNodeID identity.ID\n\tif sendFundsOptions.AccessManaPledgeID == \"\" {\n\t\taccessPledgeNodeID, err = mana.IDFromStr(allowedPledgeNodeIDs[mana.AccessMana][0])\n\t} else {\n\t\taccessPledgeNodeID, err = mana.IDFromStr(sendFundsOptions.AccessManaPledgeID)\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar consensusPledgeNodeID identity.ID\n\tif sendFundsOptions.ConsensusManaPledgeID == \"\" {\n\t\tconsensusPledgeNodeID, err = mana.IDFromStr(allowedPledgeNodeIDs[mana.AccessMana][0])\n\t} else {\n\t\tconsensusPledgeNodeID, err = mana.IDFromStr(sendFundsOptions.ConsensusManaPledgeID)\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build transaction\n\tinputs, consumedFunds := wallet.buildInputs(consumedOutputs)\n\toutputs := wallet.buildOutputs(sendFundsOptions, consumedFunds)\n\ttxEssence := ledgerstate.NewTransactionEssence(0, time.Now(), accessPledgeNodeID, consensusPledgeNodeID, inputs, outputs)\n\toutputsByID := consumedOutputs.OutputsByID()\n\n\tunlockBlocks := make([]ledgerstate.UnlockBlock, len(inputs))\n\texistingUnlockBlocks := make(map[address.Address]uint16)\n\tfor outputIndex, input := range inputs {\n\t\toutput := outputsByID[input.(*ledgerstate.UTXOInput).ReferencedOutputID()]\n\t\tif unlockBlockIndex, unlockBlockExists := existingUnlockBlocks[output.Address]; unlockBlockExists {\n\t\t\tunlockBlocks[outputIndex] = ledgerstate.NewReferenceUnlockBlock(unlockBlockIndex)\n\t\t\tcontinue\n\t\t}\n\n\t\tkeyPair := wallet.Seed().KeyPair(output.Address.Index)\n\t\tunlockBlock := ledgerstate.NewSignatureUnlockBlock(ledgerstate.NewED25519Signature(keyPair.PublicKey, keyPair.PrivateKey.Sign(txEssence.Bytes())))\n\t\tunlockBlocks[outputIndex] = unlockBlock\n\t\texistingUnlockBlocks[output.Address] = uint16(len(existingUnlockBlocks))\n\t}\n\n\ttx = ledgerstate.NewTransaction(txEssence, unlockBlocks)\n\n\t// mark outputs as spent\n\tfor addr, outputs := range consumedOutputs {\n\t\tfor transactionID := range outputs {\n\t\t\twallet.unspentOutputManager.MarkOutputSpent(addr, transactionID)\n\t\t}\n\t}\n\n\t// mark addresses as spent\n\tif !wallet.reusableAddress {\n\t\tfor addr := range consumedOutputs {\n\t\t\twallet.addressManager.MarkAddressSpent(addr.Index)\n\t\t}\n\t}\n\n\t// send transaction\n\terr = wallet.connector.SendTransaction(tx)\n\n\treturn\n}", "func (_TokensNetwork *TokensNetworkSession) Deposit(token common.Address, participant common.Address, partner common.Address, amount *big.Int, settle_timeout uint64) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.Deposit(&_TokensNetwork.TransactOpts, token, participant, partner, amount, settle_timeout)\n}", "func (_Votes *VotesCallerSession) ContractManager() (common.Address, error) {\n\treturn _Votes.Contract.ContractManager(&_Votes.CallOpts)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) Redelegate(previousOperator common.Address, amount *big.Int, extraData []byte) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.Contract.Redelegate(&_TokenStakingEscrow.TransactOpts, previousOperator, amount, extraData)\n}" ]
[ "0.6664051", "0.6610577", "0.6550637", "0.6250649", "0.561776", "0.5591287", "0.55830765", "0.55713487", "0.5567391", "0.5544448", "0.5430178", "0.53975296", "0.5380001", "0.53193086", "0.5317567", "0.52527523", "0.52345926", "0.52203125", "0.51660734", "0.5135369", "0.5123468", "0.5112093", "0.5110234", "0.5104703", "0.5096922", "0.5087165", "0.5060594", "0.50585765", "0.505513", "0.5032539", "0.5023158", "0.49970987", "0.49827644", "0.49782062", "0.4978104", "0.4976769", "0.49623564", "0.49485525", "0.4926179", "0.488452", "0.48838174", "0.48655486", "0.48540866", "0.48528317", "0.48497456", "0.4834355", "0.48235813", "0.48154163", "0.48094627", "0.4804658", "0.4799114", "0.47941113", "0.47938108", "0.47695673", "0.47476873", "0.47381544", "0.47263327", "0.47226802", "0.47065976", "0.47034085", "0.47023913", "0.47006482", "0.469931", "0.46901113", "0.46801832", "0.4677905", "0.46758124", "0.46754345", "0.46589032", "0.46477118", "0.4638036", "0.4632094", "0.46301225", "0.46247664", "0.46228516", "0.46213007", "0.4615191", "0.4611508", "0.459295", "0.45880273", "0.45874944", "0.45603743", "0.4553003", "0.45509696", "0.4549332", "0.45490536", "0.45483992", "0.45455432", "0.45296228", "0.45286295", "0.45239007", "0.45217147", "0.4516847", "0.45141724", "0.4512139", "0.45061153", "0.44999298", "0.4466143", "0.44581333", "0.4457709" ]
0.81933373
0
/ Description: Calculates the total payout in all commitments for a delegated contract Param delegatedContracts (DelegatedClient): the delegated contract to calulate over Returns (DelegatedClient): return the contract with the Total Payout
func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{ for _, contract := range delegatedContract.Contracts{ delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout } return delegatedContract }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{\n for _, delegatedContract := range delegatedContracts {\n err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias)\n if (err != nil){\n return errors.New(\"Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: \" + err.Error())\n }\n }\n return nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func CalculateAllContractsForCycles(delegatedContracts []DelegatedContract, cycleStart int, cycleEnd int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var err error\n\n for cycleStart <= cycleEnd {\n //fmt.Println(cycleStart)\n delegatedContracts, err = CalculateAllContractsForCycle(delegatedContracts, cycleStart, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycles \" + strconv.Itoa(cycleStart) + \"-\" + strconv.Itoa(cycleEnd) + \":CalculateAllCommitmentsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64) failed: \" + err.Error())\n }\n cycleStart = cycleStart + 1\n }\n return delegatedContracts, nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) DepositRedelegatedAmount(opts *bind.CallOpts, operator common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"depositRedelegatedAmount\", operator)\n\treturn *ret0, err\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (c *ClaimPayment) TotalDue() decimal.Decimal {\n\ttotalDue := decimal.Zero\n\tfor _, sc := range c.ClaimsPayed {\n\t\ttotalDue = totalDue.Add(sc.EventSlot.Cost)\n\t}\n\treturn totalDue\n}", "func (_Cakevault *CakevaultCallerSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (_DayLimitMock *DayLimitMockCallerSession) TotalSpending() (*big.Int, error) {\n\treturn _DayLimitMock.Contract.TotalSpending(&_DayLimitMock.CallOpts)\n}", "func GenerateGetTotalCommitmentBalanceWithoutDelegatorsScript(env Environment) []byte {\n\tcode := assets.MustAssetString(getTotalCommitmentWithoutDelegatorsFilename)\n\n\treturn []byte(replaceAddresses(code, env))\n}", "func GetAllDelegatedContracts(delegateAddr string) ([]string, error){\n var rtnString []string\n delegatedContractsCmd := \"/chains/main/blocks/head/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n s, err := TezosRPCGet(delegatedContractsCmd)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts: TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1) //TODO Error checking\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get all delegated contracts: Regex failed\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func (_Cakevault *CakevaultCaller) TotalShares(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"totalShares\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_DayLimitMock *DayLimitMockSession) TotalSpending() (*big.Int, error) {\n\treturn _DayLimitMock.Contract.TotalSpending(&_DayLimitMock.CallOpts)\n}", "func (_Cakevault *CakevaultSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (_ConsortiumManagement *ConsortiumManagementCaller) Delegates(opts *bind.CallOpts) ([]common.Address, error) {\n\tvar out []interface{}\n\terr := _ConsortiumManagement.contract.Call(opts, &out, \"delegates\")\n\n\tif err != nil {\n\t\treturn *new([]common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address)\n\n\treturn out0, err\n\n}", "func (d *DonationController) GetTotalDonations(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\tif !d.enabled {\n\t\td.base.Response(\"\", \"Donations have not been enabled.\", http.StatusBadRequest, w)\n\t\treturn\n\t}\n\n\tamount, err := d.d.GetTotalDonations()\n\tif err != nil {\n\t\td.base.Response(\"\", \"An error occurred getting donations\", 500, w)\n\t\treturn\n\t}\n\n\tres := struct {\n\t\tTotalDonations int `json:\"totalDonations\"`\n\t}{amount}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(res)\n}", "func (d *DonationController) GetTotal(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\tif !d.enabled {\n\t\td.base.Response(\"\", \"Donations have not been enabled.\", http.StatusBadRequest, w)\n\t\treturn\n\t}\n\n\tamount, err := d.d.GetTotalAmount()\n\tif err != nil {\n\t\td.base.Response(\"\", \"An error occurred getting total donation amount\", 500, w)\n\t\treturn\n\t}\n\n\tres := struct {\n\t\tDonationAmount float64 `json:\"donationAmount\"`\n\t}{amount}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(res)\n}", "func (c Contract) CalculateSalary() int {\n return c.basicPay\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func (c Checkout) Total() int {\n\ttotal := 0\n\tfor code, quantity := range c.basket {\n\t\toffer, exists := offers[code]\n\t\tif exists {\n\t\t\ttotal += calculateOfferPrice(code, quantity, offer)\n\t\t} else {\n\t\t\ttotal += calculatePrice(code, quantity)\n\t\t}\n\t}\n\treturn total\n}", "func GetDelegatedContractsForCycle(cycle int, delegateAddr string) ([]string, error){\n var rtnString []string\n snapShot, err := GetSnapShot(cycle)\n // fmt.Println(snapShot)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetSnapShot(cycle int) failed: \" + err.Error())\n }\n hash, err:= GetBlockLevelHash(snapShot.AssociatedBlock)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetBlockLevelHash(level int) failed: \" + err.Error())\n }\n // fmt.Println(hash)\n getDelegatedContracts := \"/chains/main/blocks/\" + hash + \"/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n\n s, err := TezosRPCGet(getDelegatedContracts)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1)\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": You have no contracts.\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalReserves\")\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func (_ConsortiumManagement *ConsortiumManagementCallerSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (c Contract) CalculateSalary() int {\n return c.basicpay\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (s SwapCost) Total() btcutil.Amount {\n\treturn s.Server + s.Onchain + s.Offchain\n}", "func (r *postCommentResolver) PaymentsTotal(ctx context.Context, comment *posts.Comment, currencyCode string) (float64, error) {\n\treturn r.paymentService.TotalPayments(comment.ID, currencyCode)\n}", "func (_Cakevault *CakevaultCaller) CalculateTotalPendingCakeRewards(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"calculateTotalPendingCakeRewards\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_ConsortiumManagement *ConsortiumManagementSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func (a *Account) TotalReceived(confirms int) (btcutil.Amount, error) {\n\trpcc, err := accessClient()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tbs, err := rpcc.BlockStamp()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar amount btcutil.Amount\n\tfor _, r := range a.TxStore.Records() {\n\t\tfor _, c := range r.Credits() {\n\t\t\t// Ignore change.\n\t\t\tif c.Change() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Tally if the appropiate number of block confirmations have passed.\n\t\t\tif c.Confirmed(confirms, bs.Height) {\n\t\t\t\tamount += c.Amount()\n\t\t\t}\n\t\t}\n\t}\n\treturn amount, nil\n}", "func (_DayLimitMock *DayLimitMockCaller) TotalSpending(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DayLimitMock.contract.Call(opts, out, \"totalSpending\")\n\treturn *ret0, err\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (mp MassPayment) Total() float64 {\n\ttotal := 0.0\n\tfor _, item := range mp.Items {\n\t\ttotal += item.Amount\n\t}\n\n\treturn total\n}", "func (_Bindings *BindingsCaller) TotalBorrows(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalBorrows\")\n\treturn *ret0, err\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (_CrToken *CrTokenCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"totalReserves\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (i *Item) ReduceContracts(amount decimal.Decimal) error {\n\tif !i.asset.IsFutures() {\n\t\treturn fmt.Errorf(\"%v %v %v %w\", i.exchange, i.asset, i.currency, errNotFutures)\n\t}\n\tif i.isCollateral {\n\t\treturn fmt.Errorf(\"%v %v %v %w cannot add contracts to collateral\", i.exchange, i.asset, i.currency, ErrIsCollateral)\n\t}\n\tif amount.LessThanOrEqual(decimal.Zero) {\n\t\treturn errZeroAmountReceived\n\t}\n\tif amount.GreaterThan(i.available) {\n\t\treturn fmt.Errorf(\"%w for %v %v %v. Requested %v Reserved: %v\",\n\t\t\terrCannotAllocate,\n\t\t\ti.exchange,\n\t\t\ti.asset,\n\t\t\ti.currency,\n\t\t\tamount,\n\t\t\ti.reserved)\n\t}\n\ti.available = i.available.Sub(amount)\n\treturn nil\n}", "func Total(amount int, currency string) (totalSum int) {\r\n\r\n\tbonus := PercentFor(currency)\r\n\ttotalSum = amount + (amount * bonus / 1000)\r\n\treturn totalSum\r\n}", "func (o *CreditPayStubEarnings) GetTotal() PayStubEarningsTotal {\n\tif o == nil {\n\t\tvar ret PayStubEarningsTotal\n\t\treturn ret\n\t}\n\n\treturn o.Total\n}", "func (_DelegatableDai *DelegatableDaiCaller) Balances(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegatableDai.contract.Call(opts, out, \"balances\", arg0)\n\treturn *ret0, err\n}", "func Total(cards []types.Card) types.Money {\n\tsum := types.Money(0)\n\tfor _, operation := range cards {\n\t\t\n\t\tif !operation.Active {\n\t\t\tcontinue\n\t\t}\n\t\tif operation.Balance < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tsum += operation.Balance\n\t}\n\t\n\treturn sum\n}", "func (_DelegatableDai *DelegatableDaiSession) TotalSupply() (*big.Int, error) {\n\treturn _DelegatableDai.Contract.TotalSupply(&_DelegatableDai.CallOpts)\n}", "func (_DelegationController *DelegationControllerSession) ContractManager() (common.Address, error) {\n\treturn _DelegationController.Contract.ContractManager(&_DelegationController.CallOpts)\n}", "func (del Delegation) pendingWithdrawalsValue() (*big.Int, error) {\n\t// call for it only once\n\tval, err, _ := del.cg.Do(\"withdraw-total\", func() (interface{}, error) {\n\t\treturn repository.R().WithdrawRequestsPendingTotal(&del.Address, del.Delegation.ToStakerId)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn val.(*big.Int), nil\n}", "func (m *GraphBaseServiceClient) Contracts()(*ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.ContractsRequestBuilder) {\n return ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.NewContractsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Contracts()(*ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.ContractsRequestBuilder) {\n return ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.NewContractsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (_DelegationController *DelegationControllerCallerSession) ContractManager() (common.Address, error) {\n\treturn _DelegationController.Contract.ContractManager(&_DelegationController.CallOpts)\n}", "func (s *ArkClient) CalculateVotersProfit(params DelegateQueryParams, shareRatio float64, blocklist string, whitelist string, capBalance bool, balanceCapAmount float64, blockBalanceCap bool) []DelegateDataProfit {\n\tdelegateRes, _, _ := s.GetDelegate(params)\n\tvoters, _, _ := s.GetDelegateVoters(params)\n\taccountRes, _, _ := s.GetAccount(AccountQueryParams{Address: delegateRes.SingleDelegate.Address})\n\n\tdelegateBalance, _ := strconv.ParseFloat(accountRes.Account.Balance, 64)\n\tdelegateBalance = float64(delegateBalance) / SATOSHI\n\n\t//calculating vote weight\n\tvotersProfit := []DelegateDataProfit{}\n\tdelelgateVoteWeight := 0\n\n\t//computing summ of all votes\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tintBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tintBalance = int(balanceCapAmount)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelelgateVoteWeight += intBalance\n\t}\n\n\t//calculating\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tcurrentVoterBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcurrentVoterBalance = balanceCapAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdeleProfit := DelegateDataProfit{\n\t\t\tAddress: element.Address,\n\t\t}\n\t\tdeleProfit.VoteWeight = currentVoterBalance / SATOSHI\n\t\tdeleProfit.VoteWeightShare = float64(currentVoterBalance) / float64(delelgateVoteWeight)\n\t\tdeleProfit.EarnedAmount100 = float64(delegateBalance) * deleProfit.VoteWeightShare\n\t\tdeleProfit.EarnedAmountXX = float64(delegateBalance) * deleProfit.VoteWeightShare * shareRatio\n\t\tdeleProfit.VoteDuration = s.GetVoteDuration(element.Address)\n\t\tvotersProfit = append(votersProfit, deleProfit)\n\t}\n\n\treturn votersProfit\n}", "func (_CrToken *CrTokenCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (bc *Blockchain) TotalAmount(blockchainAddress string) float32 {\n\tvar amount float32 = 0.0\n\tfor _, b := range bc.chain {\n\t\tfor _, t := range b.transactions {\n\t\t\tif blockchainAddress == t.recipientAddress {\n\t\t\t\tamount += t.value\n\t\t\t}\n\t\t\tif blockchainAddress == t.senderAddress {\n\t\t\t\tamount -= t.value\n\t\t\t}\n\t\t}\n\t}\n\treturn amount\n}", "func (_DelegatableDai *DelegatableDaiSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) TotalSupply() (*big.Int, error) {\n\treturn _DelegatableDai.Contract.TotalSupply(&_DelegatableDai.CallOpts)\n}", "func (this *Event) GetTotal(PaymentType bson.ObjectId, quantity int, ticketCost float32) (BookingCost, error) {\n\n\t//Find the commision\n\teventComission := this.Comission\n\textraCost := eventComission.Value\n\n\tif eventComission.IsPercent == true {\n\t\textraCost = (eventComission.Value / 100) * ticketCost\n\t}\n\n\t// Calculate the cost from total tickets\n\tsubtotal := float32(quantity) * ticketCost\n\tcomissionTotal := float32(quantity) * extraCost\n\tcost := subtotal + comissionTotal\n\n\ttotal := BookingCost{quantity, subtotal, comissionTotal, cost}\n\n\treturn total, nil\n\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func TotalStaked(ctx contract.StaticContext, bootstrapNodes map[string]bool) (*types.BigUInt, error) {\n\tvalidatorStats, err := getValidatorStatistics(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstatistics := map[string]*ValidatorStatistic{}\n\tfor _, statistic := range validatorStats {\n\t\tnodeAddr := loom.UnmarshalAddressPB(statistic.Address)\n\t\tif _, ok := bootstrapNodes[strings.ToLower(nodeAddr.String())]; !ok {\n\t\t\tstatistics[statistic.Address.String()] = statistic\n\t\t}\n\t}\n\n\tcandidateList := map[string]bool{}\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, candidate := range candidates {\n\t\tcandidateAddr := loom.UnmarshalAddressPB(candidate.Address)\n\t\tif _, ok := bootstrapNodes[strings.ToLower(candidateAddr.String())]; !ok {\n\t\t\tcandidateList[candidate.Address.String()] = true\n\t\t}\n\t}\n\n\tdelegationList, err := loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttotalStaked := &types.BigUInt{Value: *loom.NewBigUIntFromInt(0)}\n\t// Sum all delegations\n\tfor _, d := range delegationList {\n\t\tif _, ok := candidateList[d.Validator.String()]; ok {\n\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\tif err == contract.ErrNotFound {\n\t\t\t\tcontinue\n\t\t\t} else if err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ttotalStaked.Value.Add(&totalStaked.Value, &delegation.Amount.Value)\n\t\t}\n\t}\n\t// Sum all whitelist amounts of validators except bootstrap validators\n\tfor _, candidate := range candidates {\n\t\tif statistic, ok := statistics[candidate.Address.String()]; ok {\n\t\t\tif statistic.WhitelistAmount != nil {\n\t\t\t\ttotalStaked.Value.Add(&totalStaked.Value, &statistic.WhitelistAmount.Value)\n\t\t\t}\n\t\t}\n\t}\n\treturn totalStaked, nil\n}", "func (c Contract) CalculateSalary() int {\n\treturn c.basicpay\n}", "func (c Contract) CalculateSalary() int {\n\treturn c.basicpay\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (o *NetPay) GetTotal() Total {\n\tif o == nil || o.Total == nil {\n\t\tvar ret Total\n\t\treturn ret\n\t}\n\treturn *o.Total\n}", "func (_Cakevault *CakevaultCallerSession) CalculateTotalPendingCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateTotalPendingCakeRewards(&_Cakevault.CallOpts)\n}", "func (_Bindings *BindingsCallerSession) TotalBorrows() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalBorrows(&_Bindings.CallOpts)\n}", "func (_Cakevault *CakevaultSession) CalculateTotalPendingCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateTotalPendingCakeRewards(&_Cakevault.CallOpts)\n}", "func (r *postBoostResolver) PaymentsTotal(ctx context.Context, boost *posts.Boost, currencyCode string) (float64, error) {\n\treturn r.paymentService.TotalPayments(boost.ID, currencyCode)\n}", "func (a API) GetNetTotals(cmd *None) (e error) {\n\tRPCHandlers[\"getnettotals\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (ftm *FtmBridge) PendingWithdrawalsAmount(addr *common.Address, staker *big.Int) (*big.Int, error) {\n\t// get withdraw requests list\n\tlist, err := ftm.withdrawRequestsList(addr, staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// start with an empty value\n\tvalue := big.NewInt(0)\n\n\t// loop over the list of requests and add non-finished\n\tfor _, req := range list {\n\t\t// is this request doesn't have a finalization block number\n\t\t// it's still pending and it's amount will be added\n\t\t// to the pending total\n\t\tif req.WithdrawBlockNumber == nil {\n\t\t\tvalue = new(big.Int).Add(value, req.Amount.ToInt())\n\t\t}\n\t}\n\n\treturn value, nil\n}", "func (r Receipt) Total() float64 {\n\tvar total float64\n\tfor _, li := range r.LineItems {\n\t\ttotal += li.Subtotal()\n\t\tfmt.Println(li)\n\t}\n\treturn total\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (_Votes *VotesCallerSession) ContractManager() (common.Address, error) {\n\treturn _Votes.Contract.ContractManager(&_Votes.CallOpts)\n}", "func (cm *RPCConnManager) NetTotals() (uint64, uint64) {\n\treturn cm.server.NetTotals()\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_Votes *VotesCaller) ContractManager(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _Votes.contract.Call(opts, out, \"contractManager\")\n\treturn *ret0, err\n}", "func (a *Account) TotalReceived(confirms int) (float64, error) {\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar totalSatoshis int64\n\tfor _, record := range a.TxStore.SortedRecords() {\n\t\ttxout, ok := record.(*tx.RecvTxOut)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ignore change.\n\t\tif txout.Change() {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Tally if the appropiate number of block confirmations have passed.\n\t\tif confirmed(confirms, txout.Height(), bs.Height) {\n\t\t\ttotalSatoshis += txout.Value()\n\t\t}\n\t}\n\n\treturn float64(totalSatoshis) / float64(btcutil.SatoshiPerBitcoin), nil\n}", "func (_DelegatableDai *DelegatableDaiCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegatableDai.contract.Call(opts, out, \"totalSupply\")\n\treturn *ret0, err\n}", "func (_Votes *VotesSession) ContractManager() (common.Address, error) {\n\treturn _Votes.Contract.ContractManager(&_Votes.CallOpts)\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_DelegationController *DelegationControllerCaller) ContractManager(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"contractManager\")\n\treturn *ret0, err\n}", "func (_CrToken *CrTokenCaller) TotalBorrows(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"totalBorrows\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (p *Player) CashSpentTotal() int {\n\treturn p.AdditionalPlayerInformation.TotalCashSpent\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) Contracts(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"contracts\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func getBalanceTotal(recordCollection []record) (totalBalance time.Duration) {\n\tfor _, r := range recordCollection {\n\t\t_, balance := getWorkedHours(&r)\n\t\ttotalBalance += balance\n\t}\n\treturn totalBalance\n}", "func (_Bindings *BindingsSession) TotalBorrows() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalBorrows(&_Bindings.CallOpts)\n}", "func (_Distributor *DistributorCallerSession) ContractManager() (common.Address, error) {\n\treturn _Distributor.Contract.ContractManager(&_Distributor.CallOpts)\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}" ]
[ "0.7310195", "0.71182424", "0.6583033", "0.64505965", "0.6234857", "0.61979526", "0.5745349", "0.56663364", "0.5451578", "0.5441809", "0.543796", "0.53392106", "0.5260928", "0.5253004", "0.51619387", "0.5142344", "0.5124914", "0.51214784", "0.51185465", "0.51028943", "0.50880456", "0.50781345", "0.50440526", "0.50151396", "0.49819094", "0.4977098", "0.49692678", "0.49680835", "0.49509108", "0.49473852", "0.49325857", "0.4926077", "0.49251658", "0.488542", "0.48608667", "0.48605913", "0.485452", "0.48424473", "0.4837296", "0.48359403", "0.483447", "0.4815592", "0.48081625", "0.48041153", "0.48040164", "0.48004994", "0.47940877", "0.47932857", "0.4744212", "0.47367007", "0.4735273", "0.47313654", "0.4713596", "0.47110364", "0.4708703", "0.46865094", "0.46767384", "0.4675965", "0.467134", "0.467134", "0.4670467", "0.4659723", "0.46440345", "0.46370023", "0.46369413", "0.46366206", "0.46324664", "0.46289447", "0.4622422", "0.46201396", "0.4616964", "0.4610867", "0.46070445", "0.46070445", "0.4605936", "0.46034718", "0.45856503", "0.4573725", "0.45691535", "0.45578393", "0.45543328", "0.4552102", "0.4551888", "0.45347872", "0.4531565", "0.45292768", "0.45288417", "0.45096624", "0.44964203", "0.44963545", "0.4469134", "0.44629246", "0.446139", "0.44607127", "0.4453801", "0.4448952", "0.44467187", "0.44399688", "0.44379842", "0.4435878" ]
0.7865262
0
/ Description: payout in all commitments for a delegated contract for all contracts Param delegatedContracts (DelegatedClient): the delegated contracts to calulate over Returns (DelegatedClient): return the contract with the Total Payout for all contracts
func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{ for index, delegatedContract := range delegatedContracts{ delegatedContracts[index] = CalculateTotalPayout(delegatedContract) } return delegatedContracts }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{\n for _, delegatedContract := range delegatedContracts {\n err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias)\n if (err != nil){\n return errors.New(\"Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: \" + err.Error())\n }\n }\n return nil\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func CalculateAllContractsForCycles(delegatedContracts []DelegatedContract, cycleStart int, cycleEnd int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var err error\n\n for cycleStart <= cycleEnd {\n //fmt.Println(cycleStart)\n delegatedContracts, err = CalculateAllContractsForCycle(delegatedContracts, cycleStart, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycles \" + strconv.Itoa(cycleStart) + \"-\" + strconv.Itoa(cycleEnd) + \":CalculateAllCommitmentsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64) failed: \" + err.Error())\n }\n cycleStart = cycleStart + 1\n }\n return delegatedContracts, nil\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func GetAllDelegatedContracts(delegateAddr string) ([]string, error){\n var rtnString []string\n delegatedContractsCmd := \"/chains/main/blocks/head/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n s, err := TezosRPCGet(delegatedContractsCmd)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts: TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1) //TODO Error checking\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get all delegated contracts: Regex failed\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func (_ConsortiumManagement *ConsortiumManagementCaller) Delegates(opts *bind.CallOpts) ([]common.Address, error) {\n\tvar out []interface{}\n\terr := _ConsortiumManagement.contract.Call(opts, &out, \"delegates\")\n\n\tif err != nil {\n\t\treturn *new([]common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address)\n\n\treturn out0, err\n\n}", "func (_ConsortiumManagement *ConsortiumManagementCallerSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func GetDelegatedContractsForCycle(cycle int, delegateAddr string) ([]string, error){\n var rtnString []string\n snapShot, err := GetSnapShot(cycle)\n // fmt.Println(snapShot)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetSnapShot(cycle int) failed: \" + err.Error())\n }\n hash, err:= GetBlockLevelHash(snapShot.AssociatedBlock)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetBlockLevelHash(level int) failed: \" + err.Error())\n }\n // fmt.Println(hash)\n getDelegatedContracts := \"/chains/main/blocks/\" + hash + \"/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n\n s, err := TezosRPCGet(getDelegatedContracts)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1)\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": You have no contracts.\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func (_ConsortiumManagement *ConsortiumManagementSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}", "func (m *GraphBaseServiceClient) Contracts()(*ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.ContractsRequestBuilder) {\n return ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.NewContractsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Contracts()(*ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.ContractsRequestBuilder) {\n return ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.NewContractsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) DepositRedelegatedAmount(opts *bind.CallOpts, operator common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"depositRedelegatedAmount\", operator)\n\treturn *ret0, err\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (k Keeper) AwardCoinsForRelays(ctx sdk.Ctx, relays int64, toAddr sdk.Address) sdk.BigInt {\n\treturn k.posKeeper.RewardForRelays(ctx, sdk.NewInt(relays), toAddr)\n}", "func (_DelegatableDai *DelegatableDaiSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func (_DelegatableDai *DelegatableDaiCaller) Balances(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegatableDai.contract.Call(opts, out, \"balances\", arg0)\n\treturn *ret0, err\n}", "func (i *Item) ReduceContracts(amount decimal.Decimal) error {\n\tif !i.asset.IsFutures() {\n\t\treturn fmt.Errorf(\"%v %v %v %w\", i.exchange, i.asset, i.currency, errNotFutures)\n\t}\n\tif i.isCollateral {\n\t\treturn fmt.Errorf(\"%v %v %v %w cannot add contracts to collateral\", i.exchange, i.asset, i.currency, ErrIsCollateral)\n\t}\n\tif amount.LessThanOrEqual(decimal.Zero) {\n\t\treturn errZeroAmountReceived\n\t}\n\tif amount.GreaterThan(i.available) {\n\t\treturn fmt.Errorf(\"%w for %v %v %v. Requested %v Reserved: %v\",\n\t\t\terrCannotAllocate,\n\t\t\ti.exchange,\n\t\t\ti.asset,\n\t\t\ti.currency,\n\t\t\tamount,\n\t\t\ti.reserved)\n\t}\n\ti.available = i.available.Sub(amount)\n\treturn nil\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) Contracts(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"contracts\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func SortDelegateContracts(delegatedContracts []DelegatedContract) []DelegatedContract{\n for i, j := 0, len(delegatedContracts)-1; i < j; i, j = i+1, j-1 {\n delegatedContracts[i], delegatedContracts[j] = delegatedContracts[j], delegatedContracts[i]\n }\n return delegatedContracts\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_Cakevault *CakevaultCallerSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) Contracts(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"contracts\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (s *RoundsService) Delegates(ctx context.Context, id int64) (*GetDelegates, *http.Response, error) {\n\turi := fmt.Sprintf(\"rounds/%v/delegates\", id)\n\n\tvar responseStruct *GetDelegates\n\tresp, err := s.client.SendRequest(ctx, \"GET\", uri, nil, nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_Cakevault *CakevaultCaller) TotalShares(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"totalShares\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Cakevault *CakevaultSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (_DelegationController *DelegationControllerSession) ContractManager() (common.Address, error) {\n\treturn _DelegationController.Contract.ContractManager(&_DelegationController.CallOpts)\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func (s *State) applyContractMaintenance(td *TransactionDiff) (diffs []OutputDiff) {\n\t// Scan all open contracts and perform any required maintenance on each.\n\tvar contractsToDelete []ContractID\n\tfor _, openContract := range s.openContracts {\n\t\t// Check if the window index is changing.\n\t\tcontract := openContract.FileContract\n\t\tcontractProgress := s.height() - contract.Start\n\t\tif s.height() > contract.Start && contractProgress%contract.ChallengeWindow == 0 {\n\t\t\t// If the proof was missed for this window, add an output.\n\t\t\tcd := ContractDiff{\n\t\t\t\tContract: openContract.FileContract,\n\t\t\t\tContractID: openContract.ContractID,\n\t\t\t\tNew: false,\n\t\t\t\tTerminated: false,\n\t\t\t\tPreviousOpenContract: *openContract,\n\t\t\t}\n\t\t\tif openContract.WindowSatisfied == false {\n\t\t\t\tdiff := s.applyMissedProof(openContract)\n\t\t\t\tdiffs = append(diffs, diff)\n\t\t\t} else {\n\t\t\t\ts.currentBlockNode().SuccessfulWindows = append(s.currentBlockNode().SuccessfulWindows, openContract.ContractID)\n\t\t\t}\n\t\t\topenContract.WindowSatisfied = false\n\t\t\tcd.NewOpenContract = *openContract\n\t\t\ttd.ContractDiffs = append(td.ContractDiffs, cd)\n\t\t}\n\n\t\t// Check for a terminated contract.\n\t\tif openContract.FundsRemaining == 0 || contract.End == s.height() || contract.Tolerance == openContract.Failures {\n\t\t\tif openContract.FundsRemaining != 0 {\n\t\t\t\t// Create a new output that terminates the contract.\n\t\t\t\toutput := Output{\n\t\t\t\t\tValue: openContract.FundsRemaining,\n\t\t\t\t}\n\n\t\t\t\t// Get the output address.\n\t\t\t\tcontractSuccess := openContract.Failures != openContract.FileContract.Tolerance\n\t\t\t\tif contractSuccess {\n\t\t\t\t\toutput.SpendHash = contract.ValidProofAddress\n\t\t\t\t} else {\n\t\t\t\t\toutput.SpendHash = contract.MissedProofAddress\n\t\t\t\t}\n\n\t\t\t\t// Create the output.\n\t\t\t\toutputID := ContractTerminationOutputID(openContract.ContractID, contractSuccess)\n\t\t\t\ts.unspentOutputs[outputID] = output\n\t\t\t\tdiff := OutputDiff{New: true, ID: outputID, Output: output}\n\t\t\t\tdiffs = append(diffs, diff)\n\t\t\t}\n\n\t\t\t// Add the contract to contract terminations.\n\t\t\ts.currentBlockNode().ContractTerminations = append(s.currentBlockNode().ContractTerminations, openContract)\n\n\t\t\t// Mark contract for deletion (can't delete from a map while\n\t\t\t// iterating through it - results in undefined behavior of the\n\t\t\t// iterator.\n\t\t\tcontractsToDelete = append(contractsToDelete, openContract.ContractID)\n\t\t}\n\t}\n\n\t// Delete all of the contracts that terminated.\n\tfor _, contractID := range contractsToDelete {\n\t\tdelete(s.openContracts, contractID)\n\t}\n\treturn\n}", "func GenerateGetTotalCommitmentBalanceWithoutDelegatorsScript(env Environment) []byte {\n\tcode := assets.MustAssetString(getTotalCommitmentWithoutDelegatorsFilename)\n\n\treturn []byte(replaceAddresses(code, env))\n}", "func (_DelegationController *DelegationControllerCallerSession) ContractManager() (common.Address, error) {\n\treturn _DelegationController.Contract.ContractManager(&_DelegationController.CallOpts)\n}", "func (c *ClaimPayment) TotalDue() decimal.Decimal {\n\ttotalDue := decimal.Zero\n\tfor _, sc := range c.ClaimsPayed {\n\t\ttotalDue = totalDue.Add(sc.EventSlot.Cost)\n\t}\n\treturn totalDue\n}", "func (s *ArkClient) CalculateVotersProfit(params DelegateQueryParams, shareRatio float64, blocklist string, whitelist string, capBalance bool, balanceCapAmount float64, blockBalanceCap bool) []DelegateDataProfit {\n\tdelegateRes, _, _ := s.GetDelegate(params)\n\tvoters, _, _ := s.GetDelegateVoters(params)\n\taccountRes, _, _ := s.GetAccount(AccountQueryParams{Address: delegateRes.SingleDelegate.Address})\n\n\tdelegateBalance, _ := strconv.ParseFloat(accountRes.Account.Balance, 64)\n\tdelegateBalance = float64(delegateBalance) / SATOSHI\n\n\t//calculating vote weight\n\tvotersProfit := []DelegateDataProfit{}\n\tdelelgateVoteWeight := 0\n\n\t//computing summ of all votes\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tintBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tintBalance = int(balanceCapAmount)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelelgateVoteWeight += intBalance\n\t}\n\n\t//calculating\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tcurrentVoterBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcurrentVoterBalance = balanceCapAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdeleProfit := DelegateDataProfit{\n\t\t\tAddress: element.Address,\n\t\t}\n\t\tdeleProfit.VoteWeight = currentVoterBalance / SATOSHI\n\t\tdeleProfit.VoteWeightShare = float64(currentVoterBalance) / float64(delelgateVoteWeight)\n\t\tdeleProfit.EarnedAmount100 = float64(delegateBalance) * deleProfit.VoteWeightShare\n\t\tdeleProfit.EarnedAmountXX = float64(delegateBalance) * deleProfit.VoteWeightShare * shareRatio\n\t\tdeleProfit.VoteDuration = s.GetVoteDuration(element.Address)\n\t\tvotersProfit = append(votersProfit, deleProfit)\n\t}\n\n\treturn votersProfit\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (_Bep20 *Bep20CallerSession) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func (_DayLimitMock *DayLimitMockCallerSession) TotalSpending() (*big.Int, error) {\n\treturn _DayLimitMock.Contract.TotalSpending(&_DayLimitMock.CallOpts)\n}", "func payout(delegate string, operator string) string {\n\t// get operator's address\n\toperator_addr, err := alias.Address(operator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// get delegate's name to 12-byte array\n\tdelegate_name := delegateName(delegate)\n\n\trs := calculateRewardShares(operator_addr, delegate_name, epochToQuery)\n\n\t// prepare input for multisend\n\t// https://member.iotex.io/multi-send\n\tvar voters []string\n\tvar rewards []string\n\n\tstradd := func(a string, b string, c string) string {\n\t\taa, _ := new(big.Int).SetString(a, 10)\n\t\tbb, _ := new(big.Int).SetString(b, 10)\n\t\tcc, _ := new(big.Int).SetString(c, 10)\n\t\treturn cc.Add(aa.Add(aa, bb), cc).Text(10)\n\t}\n\n\tfor _, share := range rs.Shares {\n\t\tvoters = append(voters, \"0x\" + share.ETHAddr)\n\t\trewards = append(rewards, stradd(\n\t\t\t\t\t\tshare.Reward.Block,\n\t\t\t\t\t\tshare.Reward.FoundationBonus,\n\t\t\t\t\t\tshare.Reward.EpochBonus))\n\t}\n\n\tvar sent []MultisendReward\n\tfor i, a := range rewards {\n\t\tamount, _ := new(big.Int).SetString(a, 10)\n\t\tsent = append(sent, MultisendReward{voters[i],\n\t\t\t\t\tutil.RauToString(amount, util.IotxDecimalNum)})\n\t}\n\ts, _ := json.Marshal(sent)\n\tfmt.Println(string(s))\n\n\treturn rs.String()\n}", "func (_Bep20 *Bep20Caller) Delegates(opts *bind.CallOpts, delegator common.Address) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"delegates\", delegator)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (c *DPOS) ClaimRewardsFromAllValidators(ctx contract.Context, req *ClaimDelegatorRewardsRequest) (*ClaimDelegatorRewardsResponse, error) {\n\tif ctx.FeatureEnabled(features.DPOSVersion3_6, false) {\n\t\treturn c.claimRewardsFromAllValidators2(ctx, req)\n\t}\n\n\tdelegator := ctx.Message().Sender\n\tvalidators, err := ValidatorList(ctx)\n\tif err != nil {\n\t\treturn nil, logStaticDposError(ctx, err, req.String())\n\t}\n\n\ttotal := big.NewInt(0)\n\tchainID := ctx.Block().ChainID\n\tvar claimedFromValidators []*types.Address\n\tvar amounts []*types.BigUInt\n\tfor _, v := range validators {\n\t\tvalAddress := loom.Address{ChainID: chainID, Local: loom.LocalAddressFromPublicKey(v.PubKey)}\n\t\tdelegation, err := GetDelegation(ctx, REWARD_DELEGATION_INDEX, *valAddress.MarshalPB(), *delegator.MarshalPB())\n\t\tif err == contract.ErrNotFound {\n\t\t\t// Skip reward delegations that were not found.\n\t\t\tctx.Logger().Error(\"DPOS ClaimRewardsFromAllValidators\", \"error\", err, \"delegator\", delegator)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to load delegation\")\n\t\t}\n\n\t\tclaimedFromValidators = append(claimedFromValidators, valAddress.MarshalPB())\n\t\tamounts = append(amounts, delegation.Amount)\n\n\t\t// Set to UNBONDING and UpdateAmount == Amount, to fully unbond it.\n\t\tdelegation.State = UNBONDING\n\t\tdelegation.UpdateAmount = delegation.Amount\n\n\t\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to update delegation\")\n\t\t}\n\n\t\terr = c.emitDelegatorUnbondsEvent(ctx, delegation)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Add to the sum\n\t\ttotal.Add(total, delegation.Amount.Value.Int)\n\t}\n\n\tamount := &types.BigUInt{Value: *loom.NewBigUInt(total)}\n\n\terr = c.emitDelegatorClaimsRewardsEvent(ctx, delegator.MarshalPB(), claimedFromValidators, amounts, amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ClaimDelegatorRewardsResponse{\n\t\tAmount: amount,\n\t}, nil\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (d *DonationController) GetTotalDonations(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\tif !d.enabled {\n\t\td.base.Response(\"\", \"Donations have not been enabled.\", http.StatusBadRequest, w)\n\t\treturn\n\t}\n\n\tamount, err := d.d.GetTotalDonations()\n\tif err != nil {\n\t\td.base.Response(\"\", \"An error occurred getting donations\", 500, w)\n\t\treturn\n\t}\n\n\tres := struct {\n\t\tTotalDonations int `json:\"totalDonations\"`\n\t}{amount}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(res)\n}", "func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalReserves\")\n\treturn *ret0, err\n}", "func (_DayLimitMock *DayLimitMockSession) TotalSpending() (*big.Int, error) {\n\treturn _DayLimitMock.Contract.TotalSpending(&_DayLimitMock.CallOpts)\n}", "func (_BREMICO *BREMICOCaller) Balances(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"balances\", arg0)\n\treturn *ret0, err\n}", "func (c *Client) RenterContractsGet() (rc api.RenterContracts, err error) {\n\terr = c.get(\"/renter/contracts\", &rc)\n\treturn\n}", "func (_Votes *VotesCallerSession) ContractManager() (common.Address, error) {\n\treturn _Votes.Contract.ContractManager(&_Votes.CallOpts)\n}", "func (c Checkout) Total() int {\n\ttotal := 0\n\tfor code, quantity := range c.basket {\n\t\toffer, exists := offers[code]\n\t\tif exists {\n\t\t\ttotal += calculateOfferPrice(code, quantity, offer)\n\t\t} else {\n\t\t\ttotal += calculatePrice(code, quantity)\n\t\t}\n\t}\n\treturn total\n}", "func (_Bep20 *Bep20Session) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func (c Contract) CalculateSalary() int {\n return c.basicPay\n}", "func (_Votes *VotesSession) ContractManager() (common.Address, error) {\n\treturn _Votes.Contract.ContractManager(&_Votes.CallOpts)\n}", "func (_AccessIndexor *AccessIndexorCaller) Contracts(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _AccessIndexor.contract.Call(opts, &out, \"contracts\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func (_Cakevault *CakevaultCaller) CalculateTotalPendingCakeRewards(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"calculateTotalPendingCakeRewards\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Votes *VotesCaller) ContractManager(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _Votes.contract.Call(opts, out, \"contractManager\")\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (_Bindings *BindingsCaller) TotalBorrows(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalBorrows\")\n\treturn *ret0, err\n}", "func (f *VRFTest) deployContracts() error {\n\tif err := f.deployCommonContracts(); err != nil {\n\t\treturn err\n\t}\n\n\tcontractChan := make(chan ConsumerCoordinatorPair, f.TestOptions.NumberOfContracts)\n\tg := errgroup.Group{}\n\n\tfor i := 0; i < f.TestOptions.NumberOfContracts; i++ {\n\t\tg.Go(func() error {\n\t\t\treturn f.deployConsumerCoordinatorPair(contractChan)\n\t\t})\n\t}\n\tif err := g.Wait(); err != nil {\n\t\treturn err\n\t}\n\tclose(contractChan)\n\tfor contract := range contractChan {\n\t\tf.contractInstances = append(f.contractInstances, contract)\n\t}\n\treturn f.Blockchain.WaitForEvents()\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (_DelegationController *DelegationControllerCaller) GetLockedInPendingDelegations(opts *bind.CallOpts, holder common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"getLockedInPendingDelegations\", holder)\n\treturn *ret0, err\n}", "func AddContract(\n\tctx context.Context,\n\tfc *client.Client,\n\tkm keys.Manager,\n\taccountAddress string,\n\tcontract flow_templates.Contract,\n\ttransactionTimeout time.Duration) error {\n\n\t// Get admin account authorizer\n\tpayer, err := km.AdminAuthorizer(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get user account authorizer\n\tproposer, err := km.UserAuthorizer(ctx, flow.HexToAddress(accountAddress))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get latest blocks id as reference id\n\treferenceBlockID, err := flow_helpers.LatestBlockId(ctx, fc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tflowTx := flow.NewTransaction().\n\t\tSetReferenceBlockID(*referenceBlockID).\n\t\tSetProposalKey(proposer.Address, proposer.Key.Index, proposer.Key.SequenceNumber).\n\t\tSetPayer(payer.Address).\n\t\tSetGasLimit(maxGasLimit).\n\t\tSetScript([]byte(template_strings.AddAccountContractWithAdmin)).\n\t\tAddAuthorizer(payer.Address)\n\n\tif err := flowTx.AddArgument(cadence.String(contract.Name)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := flowTx.AddArgument(cadence.String(contract.SourceHex())); err != nil {\n\t\treturn err\n\t}\n\n\t// Proposer signs the payload\n\tif proposer.Address.Hex() != payer.Address.Hex() {\n\t\tif err := flowTx.SignPayload(proposer.Address, proposer.Key.Index, proposer.Signer); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Payer signs the envelope\n\tif err := flowTx.SignEnvelope(payer.Address, payer.Key.Index, payer.Signer); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = flow_helpers.SendAndWait(ctx, fc, *flowTx, transactionTimeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (tb *transactionBuilder) FundContract(amount types.Currency) ([]types.SiacoinOutput, error) {\n\t// dustThreshold has to be obtained separate from the lock\n\tdustThreshold, err := tb.wallet.DustThreshold()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tconsensusHeight, err := dbGetConsensusHeight(tb.wallet.dbTx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tso, err := tb.wallet.getSortedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tvar spentScoids []types.SiacoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that the output can be spent.\n\t\tif err := tb.wallet.checkOutput(tb.wallet.dbTx, consensusHeight, scoid, sco, dustThreshold); err != nil {\n\t\t\tif err == errSpendHeightTooHigh {\n\t\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tkey, ok := tb.wallet.keys[sco.UnlockHash]\n\t\tif !ok {\n\t\t\treturn nil, errMissingOutputKey\n\t\t}\n\n\t\t// Add a siacoin input for this output.\n\t\tsci := types.SiacoinInput{\n\t\t\tParentID: scoid,\n\t\t\tUnlockConditions: key.UnlockConditions,\n\t\t}\n\t\ttb.siacoinInputs = append(tb.siacoinInputs, len(tb.transaction.SiacoinInputs))\n\t\ttb.transaction.SiacoinInputs = append(tb.transaction.SiacoinInputs, sci)\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn nil, modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn nil, modules.ErrLowBalance\n\t}\n\tvar refundOutput types.SiacoinOutput\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\trefundUnlockConditions, err := tb.wallet.nextPrimarySeedAddress(tb.wallet.dbTx)\n\t\tif err != nil {\n\t\t\trefundUnlockConditions, err = tb.wallet.GetAddress() // try get address if generate address failed when funding contracts\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\trefundOutput = types.SiacoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tUnlockHash: refundUnlockConditions.UnlockHash(),\n\t\t}\n\t\ttb.transaction.SiacoinOutputs = append(tb.transaction.SiacoinOutputs, refundOutput)\n\t}\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\terr = dbPutSpentOutput(tb.wallet.dbTx, types.OutputID(scoid), consensusHeight)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn []types.SiacoinOutput{refundOutput}, nil\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) Delegations(opts *bind.CallOpts, arg0 [32]byte) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (ftm *FtmBridge) PendingWithdrawalsAmount(addr *common.Address, staker *big.Int) (*big.Int, error) {\n\t// get withdraw requests list\n\tlist, err := ftm.withdrawRequestsList(addr, staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// start with an empty value\n\tvalue := big.NewInt(0)\n\n\t// loop over the list of requests and add non-finished\n\tfor _, req := range list {\n\t\t// is this request doesn't have a finalization block number\n\t\t// it's still pending and it's amount will be added\n\t\t// to the pending total\n\t\tif req.WithdrawBlockNumber == nil {\n\t\t\tvalue = new(big.Int).Add(value, req.Amount.ToInt())\n\t\t}\n\t}\n\n\treturn value, nil\n}", "func (del Delegation) pendingWithdrawalsValue() (*big.Int, error) {\n\t// call for it only once\n\tval, err, _ := del.cg.Do(\"withdraw-total\", func() (interface{}, error) {\n\t\treturn repository.R().WithdrawRequestsPendingTotal(&del.Address, del.Delegation.ToStakerId)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn val.(*big.Int), nil\n}", "func SetupContracts(chainURL string, onChainTxTimeout time.Duration) (\n\tadjudicator, asset pwallet.Address, _ error) {\n\tprng := rand.New(rand.NewSource(RandSeedForTestAccs))\n\tws, err := NewWalletSetup(prng, 2)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tonChainCred := perun.Credential{\n\t\tAddr: ws.Accs[0].Address(),\n\t\tWallet: ws.Wallet,\n\t\tKeystore: ws.KeystorePath,\n\t\tPassword: \"\",\n\t}\n\tif !isBlockchainRunning(chainURL) {\n\t\treturn nil, nil, errors.New(\"cannot connect to ganache-cli node at \" + chainURL)\n\t}\n\n\tif adjudicatorAddr == nil && assetAddr == nil {\n\t\tadjudicator = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(onChainCred.Addr), 0))\n\t\tasset = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(onChainCred.Addr), 1))\n\t\tadjudicatorAddr = adjudicator\n\t\tassetAddr = asset\n\t} else {\n\t\tadjudicator = adjudicatorAddr\n\t\tasset = assetAddr\n\t}\n\n\tchain, err := ethereum.NewChainBackend(chainURL, ChainConnTimeout, onChainTxTimeout, onChainCred)\n\tif err != nil {\n\t\treturn nil, nil, errors.WithMessage(err, \"initializaing chain backend\")\n\t}\n\n\terr = chain.ValidateContracts(adjudicator, asset)\n\tif err != nil {\n\t\t// Contracts not yet deployed for this ganache-cli instance.\n\t\tadjudicator, asset, err = deployContracts(chain, onChainCred)\n\t}\n\treturn adjudicator, asset, errors.WithMessage(err, \"initializaing chain backend\")\n}", "func (msg MsgWithdrawalFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (c Contract) CalculateSalary() int {\n return c.basicpay\n}", "func (_DelegationController *DelegationControllerCaller) ContractManager(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"contractManager\")\n\treturn *ret0, err\n}", "func (_Distributor *DistributorCallerSession) ContractManager() (common.Address, error) {\n\treturn _Distributor.Contract.ContractManager(&_Distributor.CallOpts)\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) Delegations(arg0 [32]byte) (common.Address, error) {\n\treturn _PlasmaFramework.Contract.Delegations(&_PlasmaFramework.CallOpts, arg0)\n}", "func (r *postCommentResolver) PaymentsTotal(ctx context.Context, comment *posts.Comment, currencyCode string) (float64, error) {\n\treturn r.paymentService.TotalPayments(comment.ID, currencyCode)\n}", "func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func DelegatorSharesInvariant(k Keeper) sdk.Invariant {\n\treturn func(ctx sdk.Context) (string, bool) {\n\t\tvar (\n\t\t\tmsg string\n\t\t\tbroken bool\n\t\t)\n\n\t\tdefis := k.GetAllDefis(ctx)\n\t\tfor _, defi := range defis {\n\t\t\tdefiTotalDelShares := defi.GetDelegatorShares()\n\t\t\ttotalDelShares := sdk.ZeroDec()\n\n\t\t\tdelegations := k.GetDefiDelegations(ctx, defi.GetOperator())\n\t\t\tfor _, delegation := range delegations {\n\t\t\t\ttotalDelShares = totalDelShares.Add(delegation.Shares)\n\t\t\t}\n\n\t\t\tif !defiTotalDelShares.Equal(totalDelShares) {\n\t\t\t\tbroken = true\n\t\t\t\tmsg += fmt.Sprintf(\"broken delegator shares invariance:\\n\"+\n\t\t\t\t\t\"\\tdefi.DelegatorShares: %v\\n\"+\n\t\t\t\t\t\"\\tsum of Delegator.Shares: %v\\n\", defiTotalDelShares, totalDelShares)\n\t\t\t}\n\t\t}\n\n\t\treturn sdk.FormatInvariant(types.ModuleName, \"delegator shares\", msg), broken\n\t}\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (_CrToken *CrTokenCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"totalReserves\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Distributor *DistributorSession) ContractManager() (common.Address, error) {\n\treturn _Distributor.Contract.ContractManager(&_Distributor.CallOpts)\n}", "func (gc *GovernanceContract) DelegationsBy(args struct{ From common.Address }) ([]common.Address, error) {\n\t// decide by the contract type\n\tswitch gc.Type {\n\tcase \"sfc\":\n\t\treturn gc.sfcDelegationsBy(args.From)\n\t}\n\n\t// no delegations by default\n\tgc.repo.Log().Debugf(\"unknown governance type of %s\", gc.Address.Hex())\n\treturn []common.Address{}, nil\n}", "func sendToNextSettlementContract(ctx context.Context,\r\n\tw *node.ResponseWriter,\r\n\trk *wallet.Key,\r\n\titx *inspector.Transaction,\r\n\ttransferTx *inspector.Transaction,\r\n\ttransfer *actions.Transfer,\r\n\tsettleTx *txbuilder.TxBuilder,\r\n\tsettlement *actions.Settlement,\r\n\tsettlementRequest *messages.SettlementRequest,\r\n\ttracer *filters.Tracer) error {\r\n\tctx, span := trace.StartSpan(ctx, \"handlers.Transfer.sendToNextSettlementContract\")\r\n\tdefer span.End()\r\n\r\n\tboomerangIndex := uint32(0xffffffff)\r\n\tif !bytes.Equal(itx.Hash[:], transferTx.Hash[:]) {\r\n\t\t// If already an M1, use only output\r\n\t\tboomerangIndex = 0\r\n\t} else {\r\n\t\tboomerangIndex = findBoomerangIndex(transferTx, transfer, rk.Address)\r\n\t}\r\n\r\n\tif boomerangIndex == 0xffffffff {\r\n\t\treturn fmt.Errorf(\"Multi-Contract Transfer missing boomerang output\")\r\n\t}\r\n\tnode.LogVerbose(ctx, \"Boomerang output index : %d\", boomerangIndex)\r\n\r\n\t// Find next contract\r\n\tnextContractIndex := uint32(0x0000ffff)\r\n\tcurrentFound := false\r\n\tcompletedContracts := make(map[bitcoin.Hash20]bool)\r\n\tfor _, asset := range transfer.Assets {\r\n\t\tif asset.ContractIndex == uint32(0x0000ffff) {\r\n\t\t\tcontinue // Asset transfer doesn't have a contract (probably BSV transfer).\r\n\t\t}\r\n\r\n\t\tif int(asset.ContractIndex) >= len(transferTx.Outputs) {\r\n\t\t\treturn errors.New(\"Transfer contract index out of range\")\r\n\t\t}\r\n\r\n\t\thash, err := transferTx.Outputs[asset.ContractIndex].Address.Hash()\r\n\t\tif err != nil {\r\n\t\t\treturn errors.Wrap(err, \"Transfer contract address invalid\")\r\n\t\t}\r\n\r\n\t\tif !currentFound {\r\n\t\t\tcompletedContracts[*hash] = true\r\n\t\t\tif transferTx.Outputs[asset.ContractIndex].Address.Equal(rk.Address) {\r\n\t\t\t\tcurrentFound = true\r\n\t\t\t}\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\t// Contracts can be used more than once, so ensure this contract wasn't referenced before\r\n\t\t// the current contract.\r\n\t\t_, complete := completedContracts[*hash]\r\n\t\tif !complete {\r\n\t\t\tnextContractIndex = asset.ContractIndex\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\r\n\tif nextContractIndex == 0xffff {\r\n\t\treturn fmt.Errorf(\"Next contract not found in multi-contract transfer\")\r\n\t}\r\n\r\n\tnode.Log(ctx, \"Sending settlement offer to %s\",\r\n\t\tbitcoin.NewAddressFromRawAddress(transferTx.Outputs[nextContractIndex].Address,\r\n\t\t\tw.Config.Net))\r\n\r\n\t// Setup M1 response\r\n\tvar err error\r\n\terr = w.SetUTXOs(ctx, []bitcoin.UTXO{itx.Outputs[boomerangIndex].UTXO})\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\t// Add output to next contract.\r\n\t// Mark as change so it gets everything except the tx fee.\r\n\terr = w.AddChangeOutput(ctx, transferTx.Outputs[nextContractIndex].Address)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\t// Serialize settlement tx for Message payload.\r\n\tsettlementRequest.Settlement, err = protocol.Serialize(settlement, w.Config.IsTest)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\t// Setup Message\r\n\tvar payBuf bytes.Buffer\r\n\terr = settlementRequest.Serialize(&payBuf)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tmessage := actions.Message{\r\n\t\tReceiverIndexes: []uint32{0}, // First output is receiver of message\r\n\t\tMessageCode: settlementRequest.Code(),\r\n\t\tMessagePayload: payBuf.Bytes(),\r\n\t}\r\n\r\n\tif err := node.RespondSuccess(ctx, w, itx, rk, &message); err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tif bytes.Equal(itx.Hash[:], transferTx.Hash[:]) {\r\n\t\toutpoint := wire.OutPoint{Hash: *itx.Hash, Index: boomerangIndex}\r\n\t\ttracer.Add(ctx, &outpoint)\r\n\t}\r\n\treturn nil\r\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func Redeem(contract []byte, contractTx wire.MsgTx, secret []byte, currency string, autopublish bool) (api.RedeemResponse, error) {\n\tnetwork := RetrieveNetwork(currency)\n\tclient := GetRPCClient(currency)\n\n\tdefer func() {\n\t\tclient.Shutdown()\n\t\tclient.WaitForShutdown()\n\t}()\n\n\tpushes, err := txscript.ExtractAtomicSwapDataPushes(0, contract)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tif pushes == nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, errors.New(\"contract is not an atomic swap script recognized by this tool\")\n\t}\n\n\trecipientAddr, err := diviutil.NewAddressPubKeyHash(pushes.RecipientHash160[:], network)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tcontractHash := diviutil.Hash160(contract)\n\tcontractOut := -1\n\tfor i, out := range contractTx.TxOut {\n\t\tsc, addrs, _, _ := txscript.ExtractPkScriptAddrs(out.PkScript, network)\n\t\tif sc == txscript.ScriptHashTy &&\n\t\t\tbytes.Equal(addrs[0].(*diviutil.AddressScriptHash).Hash160()[:], contractHash) {\n\t\t\tcontractOut = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif contractOut == -1 {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, errors.New(\"transaction does not contain a contract output\")\n\t}\n\n\taddr, err := RawChangeAddress(client, currency)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\toutScript, err := txscript.PayToAddrScript(addr)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\n\tcontractTxHash := contractTx.TxHash()\n\tcontractOutPoint := wire.OutPoint{\n\t\tHash: contractTxHash,\n\t\tIndex: uint32(contractOut),\n\t}\n\n\tfeePerKb, minFeePerKb, err := GetFees(client, currency)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\n\tredeemTx := wire.NewMsgTx(util.TXVersion)\n\tredeemTx.LockTime = uint32(pushes.LockTime)\n\tredeemTx.AddTxIn(wire.NewTxIn(&contractOutPoint, nil, nil))\n\tredeemTx.AddTxOut(wire.NewTxOut(0, outScript)) // amount set below\n\tredeemSize := util.EstimateRedeemSerializeSize(contract, redeemTx.TxOut)\n\tfee := txrules.FeeForSerializeSize(feePerKb, redeemSize)\n\tredeemTx.TxOut[0].Value = contractTx.TxOut[contractOut].Value - int64(fee)\n\tif txrules.IsDustOutput(redeemTx.TxOut[0], minFeePerKb) {\n\t\tpanic(fmt.Errorf(\"redeem output value of %v is dust\", diviutil.Amount(redeemTx.TxOut[0].Value)))\n\t}\n\n\tredeemSig, redeemPubKey, err := CreateSig(redeemTx, 0, contract, recipientAddr, client)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tredeemSigScript, err := RedeemP2SHContract(contract, redeemSig, redeemPubKey, secret)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tredeemTx.TxIn[0].SignatureScript = redeemSigScript\n\n\tredeemTxHash := redeemTx.TxHash()\n\tredeemFeePerKb := CalcFeePerKb(fee, redeemTx.SerializeSize())\n\n\tvar buf bytes.Buffer\n\tbuf.Grow(redeemTx.SerializeSize())\n\tredeemTx.Serialize(&buf)\n\n\tif autopublish == false {\n\t\tfmt.Printf(\"Redeem fee: %v (%0.8f BTC/kB)\\n\\n\", fee, redeemFeePerKb)\n\t\tfmt.Printf(\"Redeem transaction (%v):\\n\", &redeemTxHash)\n\t\tfmt.Printf(\"%x\\n\\n\", buf.Bytes())\n\t}\n\n\tif util.Verify {\n\t\te, err := txscript.NewEngine(contractTx.TxOut[contractOutPoint.Index].PkScript,\n\t\t\tredeemTx, 0, txscript.StandardVerifyFlags, txscript.NewSigCache(10),\n\t\t\ttxscript.NewTxSigHashes(redeemTx), contractTx.TxOut[contractOut].Value)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = e.Execute()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tPromptPublishTx(client, redeemTx, \"redeem\", autopublish)\n\n\treturn api.RedeemResponse{\n\t\tfee.String(),\n\t\tredeemTxHash.String(),\n\t\tstruct{}{},\n\t\tnil,\n\t\t51200,\n\t}, nil\n}", "func DeployKeeperContracts(\n\tt *testing.T,\n\tregistryVersion ethereum.KeeperRegistryVersion,\n\tregistrySettings contracts.KeeperRegistrySettings,\n\tnumberOfUpkeeps int,\n\tupkeepGasLimit uint32,\n\tlinkToken contracts.LinkToken,\n\tcontractDeployer contracts.ContractDeployer,\n\tclient blockchain.EVMClient,\n\tlinkFundsForEachUpkeep *big.Int,\n) (contracts.KeeperRegistry, contracts.KeeperRegistrar, []contracts.KeeperConsumer, []*big.Int) {\n\tef, err := contractDeployer.DeployMockETHLINKFeed(big.NewInt(2e18))\n\trequire.NoError(t, err, \"Deploying mock ETH-Link feed shouldn't fail\")\n\tgf, err := contractDeployer.DeployMockGasFeed(big.NewInt(2e11))\n\trequire.NoError(t, err, \"Deploying mock gas feed shouldn't fail\")\n\terr = client.WaitForEvents()\n\trequire.NoError(t, err, \"Failed waiting for mock feeds to deploy\")\n\n\t// Deploy the transcoder here, and then set it to the registry\n\ttranscoder := DeployUpkeepTranscoder(t, contractDeployer, client)\n\tregistry := DeployKeeperRegistry(t, contractDeployer, client,\n\t\t&contracts.KeeperRegistryOpts{\n\t\t\tRegistryVersion: registryVersion,\n\t\t\tLinkAddr: linkToken.Address(),\n\t\t\tETHFeedAddr: ef.Address(),\n\t\t\tGasFeedAddr: gf.Address(),\n\t\t\tTranscoderAddr: transcoder.Address(),\n\t\t\tRegistrarAddr: ZeroAddress.Hex(),\n\t\t\tSettings: registrySettings,\n\t\t},\n\t)\n\n\t// Fund the registry with 1 LINK * amount of KeeperConsumerPerformance contracts\n\terr = linkToken.Transfer(registry.Address(), big.NewInt(0).Mul(big.NewInt(1e18), big.NewInt(int64(numberOfUpkeeps))))\n\trequire.NoError(t, err, \"Funding keeper registry contract shouldn't fail\")\n\n\tregistrarSettings := contracts.KeeperRegistrarSettings{\n\t\tAutoApproveConfigType: 2,\n\t\tAutoApproveMaxAllowed: math.MaxUint16,\n\t\tRegistryAddr: registry.Address(),\n\t\tMinLinkJuels: big.NewInt(0),\n\t}\n\tregistrar := DeployKeeperRegistrar(t, registryVersion, linkToken, registrarSettings, contractDeployer, client, registry)\n\n\tupkeeps := DeployKeeperConsumers(t, contractDeployer, client, numberOfUpkeeps)\n\tvar upkeepsAddresses []string\n\tfor _, upkeep := range upkeeps {\n\t\tupkeepsAddresses = append(upkeepsAddresses, upkeep.Address())\n\t}\n\tupkeepIds := RegisterUpkeepContracts(\n\t\tt, linkToken, linkFundsForEachUpkeep, client, upkeepGasLimit, registry, registrar, numberOfUpkeeps, upkeepsAddresses,\n\t)\n\terr = client.WaitForEvents()\n\trequire.NoError(t, err, \"Error waiting for events\")\n\n\treturn registry, registrar, upkeeps, upkeepIds\n}", "func (msg MsgWithdrawalSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}" ]
[ "0.77173555", "0.71786165", "0.7143318", "0.63859755", "0.62173766", "0.584412", "0.5712975", "0.5710026", "0.5636962", "0.5519932", "0.55071235", "0.53510237", "0.5233354", "0.51962984", "0.5183588", "0.5167286", "0.51359797", "0.5119506", "0.5119506", "0.49317974", "0.48478612", "0.48376688", "0.48370078", "0.4821532", "0.4818905", "0.48136672", "0.48125428", "0.48018065", "0.47919926", "0.47395125", "0.4725664", "0.47082776", "0.4704227", "0.46945006", "0.46606815", "0.4659702", "0.46396858", "0.4624956", "0.46216446", "0.46208408", "0.46140832", "0.4594035", "0.45887184", "0.45805523", "0.4563693", "0.45086816", "0.45053276", "0.45028803", "0.45014226", "0.44945392", "0.4489923", "0.44893593", "0.4481766", "0.44745204", "0.44640902", "0.44514152", "0.44502926", "0.4440616", "0.44404227", "0.44369495", "0.4424993", "0.44178328", "0.44152415", "0.441162", "0.44037202", "0.439127", "0.4381312", "0.4378714", "0.43696353", "0.43687445", "0.43607825", "0.43522134", "0.43462133", "0.43430594", "0.43409315", "0.43392265", "0.43340874", "0.43307957", "0.43300754", "0.43292966", "0.4322812", "0.43164954", "0.43020523", "0.4290425", "0.42884028", "0.42832476", "0.4282383", "0.42800656", "0.4259708", "0.425963", "0.4258394", "0.4256288", "0.42551926", "0.42490813", "0.42471814", "0.42407855", "0.42374155", "0.4232982", "0.42329016", "0.42321596" ]
0.7504203
1
/ Description: A test function that loops through the commitments of each delegated contract for a specific cycle, then it computes the share value of each one. The output should be = 1. With my tests it was, so you can really just ignore this. Param cycle (int): The cycle number to be queryed Param delegatedContracts ([]DelegatedClient): the group of delegated DelegatedContracts Returns (float64): The sum of all shares
func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{ var sum float64 sum = 0 for x := 0; x < len(delegatedContracts); x++{ counter := 0 for y := 0; y < len(delegatedContracts[x].Contracts); y++{ if (delegatedContracts[x].Contracts[y].Cycle == cycle){ break } counter = counter + 1 } sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage } return sum }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func CalculateAllContractsForCycles(delegatedContracts []DelegatedContract, cycleStart int, cycleEnd int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var err error\n\n for cycleStart <= cycleEnd {\n //fmt.Println(cycleStart)\n delegatedContracts, err = CalculateAllContractsForCycle(delegatedContracts, cycleStart, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycles \" + strconv.Itoa(cycleStart) + \"-\" + strconv.Itoa(cycleEnd) + \":CalculateAllCommitmentsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64) failed: \" + err.Error())\n }\n cycleStart = cycleStart + 1\n }\n return delegatedContracts, nil\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func GetDelegatedContractsForCycle(cycle int, delegateAddr string) ([]string, error){\n var rtnString []string\n snapShot, err := GetSnapShot(cycle)\n // fmt.Println(snapShot)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetSnapShot(cycle int) failed: \" + err.Error())\n }\n hash, err:= GetBlockLevelHash(snapShot.AssociatedBlock)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetBlockLevelHash(level int) failed: \" + err.Error())\n }\n // fmt.Println(hash)\n getDelegatedContracts := \"/chains/main/blocks/\" + hash + \"/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n\n s, err := TezosRPCGet(getDelegatedContracts)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1)\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": You have no contracts.\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{\n for _, delegatedContract := range delegatedContracts {\n err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias)\n if (err != nil){\n return errors.New(\"Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: \" + err.Error())\n }\n }\n return nil\n}", "func calculateRewardShares(operator string, delegate []byte, epochs string) *RewardShares {\n\tif epochs == \"\" {\n\t\treturn calculateEpochRewardShares(\n\t\t\toperator, delegate, currentEpochNum())\n\t}\n\n\t// parse a range of epochs\n\tresult := NewRewardShares()\n\tresult.SetEpochNum(epochs)\n\tfor epoch := range epochRangeGen(epochs) {\n\t\tfmt.Printf(\"epoch: %v\\n\", epoch)\n\t\treward := calculateEpochRewardShares(operator, delegate, epoch)\n\t\tresult = result.Combine(reward)\n\t}\n\treturn result\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func DelegatorSharesInvariant(k Keeper) sdk.Invariant {\n\treturn func(ctx sdk.Context) (string, bool) {\n\t\tvar (\n\t\t\tmsg string\n\t\t\tbroken bool\n\t\t)\n\n\t\tdefis := k.GetAllDefis(ctx)\n\t\tfor _, defi := range defis {\n\t\t\tdefiTotalDelShares := defi.GetDelegatorShares()\n\t\t\ttotalDelShares := sdk.ZeroDec()\n\n\t\t\tdelegations := k.GetDefiDelegations(ctx, defi.GetOperator())\n\t\t\tfor _, delegation := range delegations {\n\t\t\t\ttotalDelShares = totalDelShares.Add(delegation.Shares)\n\t\t\t}\n\n\t\t\tif !defiTotalDelShares.Equal(totalDelShares) {\n\t\t\t\tbroken = true\n\t\t\t\tmsg += fmt.Sprintf(\"broken delegator shares invariance:\\n\"+\n\t\t\t\t\t\"\\tdefi.DelegatorShares: %v\\n\"+\n\t\t\t\t\t\"\\tsum of Delegator.Shares: %v\\n\", defiTotalDelShares, totalDelShares)\n\t\t\t}\n\t\t}\n\n\t\treturn sdk.FormatInvariant(types.ModuleName, \"delegator shares\", msg), broken\n\t}\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func calcTransmissionRisks(cycle Cycle) {\n\tfor i := 0; i < len(Inputs.People); i++ {\n\n\t\t//check people's ids line up\n\t\tthisPerson := Inputs.People[i]\n\t\tif uint(i) != thisPerson.Id {\n\t\t\tfmt.Println(\"Person Id doesn't make position in array\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\t// if uninfected\n\t\tunif_TB_state_id := Query.getStateByName(\"Uninfected TB\").Id\n\t\t// active_TB_state_id := Query.getStateByName(\"Active - untreated\").Id\n\t\t// active_treat_1_state_id := Query.getStateByName(\"Active Treated Month 1\").Id\n\t\t// active_treat_2_state_id := Query.getStateByName(\"Active Treated Month 2\").Id\n\t\ttb_chain := Query.getChainByName(\"TB disease and treatment\")\n\n\t\tthis_person_state_id := thisPerson.get_state_by_chain(tb_chain, cycle).Id\n\n\t\tisUsb := 0\n\t\tif thisPerson.get_state_by_chain(Inputs.Chains[BIRTHPLACE_CHAIN_ID], cycle).Name == \"United States\" {\n\t\t\tisUsb = 1\n\t\t}\n\n\t\trace_state_id := thisPerson.get_state_by_chain(Inputs.Chains[RACE_CHAIN_ID], cycle).Id\n\n\t\tif this_person_state_id == unif_TB_state_id {\n\t\t\tQuery.Num_susceptible_by_cycle_isUsb_and_race[cycle.Id][isUsb][race_state_id] += 1\n\t\t\tQuery.Total_susceptible_by_cycle[cycle.Id] += 1\n\t\t}\n\n\t\t// originally, all people in active + active treat m 1 + active treat m 2 were here\n\t\t// but it's 6 per CASE, not 6 per person. this is a more accurate way, since (almost) everyone\n\t\t// will eventually be treated, and this is only one month of contributing risk\n\t\t// if this_person_state_id == active_treat_1_state_id { //this_person_state_id == active_TB_state_id || || this_person_state_id == active_treat_2_state_id {\n\t\tQuery.Total_active_by_cycle[cycle.Id] += thisPerson.RiskOfProgression\n\n\t\tQuery.Num_active_cases_by_cycle_isUsb_and_race[cycle.Id][isUsb][race_state_id] += thisPerson.RiskOfProgression\n\n\t\t// }\n\n\t}\n\n\t//// -------------------------- NOTE I'VE TAKE OUT TRANSMISSION BY RACE AND BIRTHPLACE FOR NOW\n\n\tgeneralPopulationRisk := float64(Query.Total_active_by_cycle[cycle.Id]) / float64(Query.Total_susceptible_by_cycle[cycle.Id]) * 0.2\n\n\t// fmt.Println(\"In cycle \", cycle.Id, \" we have general population risk of: \", generalPopulationRisk)\n\n\t// calculate risk\n\tfor isUsb := 0; isUsb < 2; isUsb++ {\n\t\tfor r := 0; r < len(Inputs.States); r++ {\n\t\t\tnumSus := Query.Num_susceptible_by_cycle_isUsb_and_race[cycle.Id][isUsb][r]\n\t\t\tif numSus > 0 {\n\t\t\t\tnumActive := Query.Num_active_cases_by_cycle_isUsb_and_race[cycle.Id][isUsb][r]\n\t\t\t\t// todo make real\n\n\t\t\t\t//xyx\n\n\t\t\t\ttrans_adjustment := 0.0\n\t\t\t\tif cycle.Id <= 12 {\n\t\t\t\t\ttrans_adjustment = 1 //2.1\n\t\t\t\t} else if cycle.Id > 12 && cycle.Id <= 24 {\n\t\t\t\t\ttrans_adjustment = 1 //1.1\n\t\t\t\t} else if cycle.Id > 24 && cycle.Id <= 36 {\n\t\t\t\t\ttrans_adjustment = 1 //1.1\n\t\t\t\t} else {\n\t\t\t\t\ttrans_adjustment = 1.0\n\t\t\t\t}\n\n\t\t\t\trisk := ((float64(numActive)/float64(numSus))*0.8 + generalPopulationRisk) * trans_adjustment * NumberOfLtbiCasesCausedByOneActiveCase.Value\n\n\t\t\t\t// if float64(numActive)/float64(numSus) > 0 {\n\t\t\t\t// \tfmt.Println(\"risk in \", Inputs.States[b].Name, Inputs.States[r].Name, \" is \", float64(numActive)/float64(numSus))\n\t\t\t\t// }\n\n\t\t\t\tif risk > 1 {\n\t\t\t\t\trisk = 1\n\t\t\t\t}\n\t\t\t\tQuery.LTBI_risk_by_cycle_isUsb_and_race[cycle.Id][isUsb][r] = risk\n\t\t\t\t// fmt.Println(\"usb \", isUsb, \" race \", Inputs.States[r].Name, \" risk is \", numActive, \" / \", numSus, \" = \", risk)\n\n\t\t\t}\n\t\t}\n\t}\n\n}", "func GenerateShares(transportPrivateKey *big.Int, transportPublicKey [2]*big.Int, participants ParticipantList, threshold int) ([]*big.Int, []*big.Int, [][2]*big.Int, error) {\n\n\t// create coefficients (private/public)\n\tprivateCoefficients, err := cloudflare.ConstructPrivatePolyCoefs(rand.Reader, threshold)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tpublicCoefficients := cloudflare.GeneratePublicCoefs(privateCoefficients)\n\n\t// create commitments\n\tcommitments := make([][2]*big.Int, len(publicCoefficients))\n\tfor idx, publicCoefficient := range publicCoefficients {\n\t\tcommitments[idx] = bn256.G1ToBigIntArray(publicCoefficient)\n\t}\n\n\t// secret shares\n\ttransportPublicKeyG1, err := bn256.BigIntArrayToG1(transportPublicKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// convert public keys into G1 structs\n\tpublicKeyG1s := []*cloudflare.G1{}\n\tfor idx := 0; idx < len(participants); idx++ {\n\t\tparticipant := participants[idx]\n\t\tlogger.Infof(\"participants[%v]: %v\", idx, participant)\n\t\tif participant != nil && participant.PublicKey[0] != nil && participant.PublicKey[1] != nil {\n\t\t\tpublicKeyG1, err := bn256.BigIntArrayToG1(participant.PublicKey)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\tpublicKeyG1s = append(publicKeyG1s, publicKeyG1)\n\t\t}\n\t}\n\n\t// check for missing data\n\tif len(publicKeyG1s) != len(participants) {\n\t\treturn nil, nil, nil, fmt.Errorf(\"only have %v of %v public keys\", len(publicKeyG1s), len(participants))\n\t}\n\n\tif len(privateCoefficients) != threshold+1 {\n\t\treturn nil, nil, nil, fmt.Errorf(\"only have %v of %v private coefficients\", len(privateCoefficients), threshold+1)\n\t}\n\n\t//\n\tsecretsArray, err := cloudflare.GenerateSecretShares(transportPublicKeyG1, privateCoefficients, publicKeyG1s)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to generate secret shares: %v\", err)\n\t}\n\n\t// final encrypted shares\n\tencryptedShares, err := cloudflare.GenerateEncryptedShares(secretsArray, transportPrivateKey, publicKeyG1s)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to generate encrypted shares: %v\", err)\n\t}\n\n\treturn encryptedShares, privateCoefficients, commitments, nil\n}", "func DeployPerformanceKeeperContracts(\n\tt *testing.T,\n\tregistryVersion ethereum.KeeperRegistryVersion,\n\tnumberOfContracts int,\n\tupkeepGasLimit uint32,\n\tlinkToken contracts.LinkToken,\n\tcontractDeployer contracts.ContractDeployer,\n\tclient blockchain.EVMClient,\n\tregistrySettings *contracts.KeeperRegistrySettings,\n\tlinkFundsForEachUpkeep *big.Int,\n\tblockRange, // How many blocks to run the test for\n\tblockInterval, // Interval of blocks that upkeeps are expected to be performed\n\tcheckGasToBurn, // How much gas should be burned on checkUpkeep() calls\n\tperformGasToBurn int64, // How much gas should be burned on performUpkeep() calls\n) (contracts.KeeperRegistry, contracts.KeeperRegistrar, []contracts.KeeperConsumerPerformance, []*big.Int) {\n\tef, err := contractDeployer.DeployMockETHLINKFeed(big.NewInt(2e18))\n\trequire.NoError(t, err, \"Deploying mock ETH-Link feed shouldn't fail\")\n\tgf, err := contractDeployer.DeployMockGasFeed(big.NewInt(2e11))\n\trequire.NoError(t, err, \"Deploying mock gas feed shouldn't fail\")\n\terr = client.WaitForEvents()\n\trequire.NoError(t, err, \"Failed waiting for mock feeds to deploy\")\n\n\tregistry := DeployKeeperRegistry(t, contractDeployer, client,\n\t\t&contracts.KeeperRegistryOpts{\n\t\t\tRegistryVersion: registryVersion,\n\t\t\tLinkAddr: linkToken.Address(),\n\t\t\tETHFeedAddr: ef.Address(),\n\t\t\tGasFeedAddr: gf.Address(),\n\t\t\tTranscoderAddr: ZeroAddress.Hex(),\n\t\t\tRegistrarAddr: ZeroAddress.Hex(),\n\t\t\tSettings: *registrySettings,\n\t\t},\n\t)\n\n\t// Fund the registry with 1 LINK * amount of KeeperConsumerPerformance contracts\n\terr = linkToken.Transfer(registry.Address(), big.NewInt(0).Mul(big.NewInt(1e18), big.NewInt(int64(numberOfContracts))))\n\trequire.NoError(t, err, \"Funding keeper registry contract shouldn't fail\")\n\n\tregistrarSettings := contracts.KeeperRegistrarSettings{\n\t\tAutoApproveConfigType: 2,\n\t\tAutoApproveMaxAllowed: math.MaxUint16,\n\t\tRegistryAddr: registry.Address(),\n\t\tMinLinkJuels: big.NewInt(0),\n\t}\n\tregistrar := DeployKeeperRegistrar(t, registryVersion, linkToken, registrarSettings, contractDeployer, client, registry)\n\n\tupkeeps := DeployKeeperConsumersPerformance(\n\t\tt, contractDeployer, client, numberOfContracts, blockRange, blockInterval, checkGasToBurn, performGasToBurn,\n\t)\n\n\tvar upkeepsAddresses []string\n\tfor _, upkeep := range upkeeps {\n\t\tupkeepsAddresses = append(upkeepsAddresses, upkeep.Address())\n\t}\n\n\tupkeepIds := RegisterUpkeepContracts(\n\t\tt, linkToken, linkFundsForEachUpkeep, client, upkeepGasLimit, registry, registrar, numberOfContracts, upkeepsAddresses,\n\t)\n\n\treturn registry, registrar, upkeeps, upkeepIds\n}", "func TestContractSet(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\t// create contract set\n\ttestDir := build.TempDir(t.Name())\n\trl := ratelimit.NewRateLimit(0, 0, 0)\n\tcs, err := NewContractSet(testDir, rl, modules.ProdDependencies)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\theader1 := contractHeader{Transaction: types.Transaction{\n\t\tFileContractRevisions: []types.FileContractRevision{{\n\t\t\tParentID: types.FileContractID{1},\n\t\t\tNewValidProofOutputs: []types.SiacoinOutput{{}, {}},\n\t\t\tUnlockConditions: types.UnlockConditions{\n\t\t\t\tPublicKeys: []types.SiaPublicKey{{}, {}},\n\t\t\t},\n\t\t}},\n\t}}\n\theader2 := contractHeader{Transaction: types.Transaction{\n\t\tFileContractRevisions: []types.FileContractRevision{{\n\t\t\tParentID: types.FileContractID{2},\n\t\t\tNewValidProofOutputs: []types.SiacoinOutput{{}, {}},\n\t\t\tUnlockConditions: types.UnlockConditions{\n\t\t\t\tPublicKeys: []types.SiaPublicKey{{}, {}},\n\t\t\t},\n\t\t}},\n\t}}\n\tid1 := header1.ID()\n\tid2 := header2.ID()\n\n\t_, err = cs.managedInsertContract(header1, []crypto.Hash{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = cs.managedInsertContract(header2, []crypto.Hash{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// uncontested acquire/release\n\tc1 := cs.managedMustAcquire(t, id1)\n\tcs.Return(c1)\n\n\t// 100 concurrent serialized mutations\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < 100; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tc1 := cs.managedMustAcquire(t, id1)\n\t\t\tc1.header.Transaction.FileContractRevisions[0].NewRevisionNumber++\n\t\t\ttime.Sleep(time.Duration(fastrand.Intn(100)))\n\t\t\tcs.Return(c1)\n\t\t}()\n\t}\n\twg.Wait()\n\tc1 = cs.managedMustAcquire(t, id1)\n\tcs.Return(c1)\n\tif c1.header.LastRevision().NewRevisionNumber != 100 {\n\t\tt.Fatal(\"expected exactly 100 increments, got\", c1.header.LastRevision().NewRevisionNumber)\n\t}\n\n\t// a blocked acquire shouldn't prevent a return\n\tc1 = cs.managedMustAcquire(t, id1)\n\tgo func() {\n\t\ttime.Sleep(time.Millisecond)\n\t\tcs.Return(c1)\n\t}()\n\tc1 = cs.managedMustAcquire(t, id1)\n\tcs.Return(c1)\n\n\t// delete and reinsert id2\n\tc2 := cs.managedMustAcquire(t, id2)\n\tcs.Delete(c2)\n\troots, err := c2.merkleRoots.merkleRoots()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcs.managedInsertContract(c2.header, roots)\n\n\t// call all the methods in parallel haphazardly\n\tfuncs := []func(){\n\t\tfunc() { cs.Len() },\n\t\tfunc() { cs.IDs() },\n\t\tfunc() { cs.View(id1); cs.View(id2) },\n\t\tfunc() { cs.ViewAll() },\n\t\tfunc() { cs.Return(cs.managedMustAcquire(t, id1)) },\n\t\tfunc() { cs.Return(cs.managedMustAcquire(t, id2)) },\n\t\tfunc() {\n\t\t\theader3 := contractHeader{\n\t\t\t\tTransaction: types.Transaction{\n\t\t\t\t\tFileContractRevisions: []types.FileContractRevision{{\n\t\t\t\t\t\tParentID: types.FileContractID{3},\n\t\t\t\t\t\tNewValidProofOutputs: []types.SiacoinOutput{{}, {}},\n\t\t\t\t\t\tUnlockConditions: types.UnlockConditions{\n\t\t\t\t\t\t\tPublicKeys: []types.SiaPublicKey{{}, {}},\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\tid3 := header3.ID()\n\t\t\t_, err := cs.managedInsertContract(header3, []crypto.Hash{})\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tc3 := cs.managedMustAcquire(t, id3)\n\t\t\tcs.Delete(c3)\n\t\t},\n\t}\n\twg = sync.WaitGroup{}\n\tfor _, fn := range funcs {\n\t\twg.Add(1)\n\t\tgo func(fn func()) {\n\t\t\tdefer wg.Done()\n\t\t\tfor i := 0; i < 100; i++ {\n\t\t\t\ttime.Sleep(time.Duration(fastrand.Intn(100)))\n\t\t\t\tfn()\n\t\t\t}\n\t\t}(fn)\n\t}\n\twg.Wait()\n}", "func calculateRewards(delegationTotal loom.BigUInt, params *Params, totalValidatorDelegations loom.BigUInt) loom.BigUInt {\n\tcycleSeconds := params.ElectionCycleLength\n\treward := CalculateFraction(blockRewardPercentage, delegationTotal)\n\n\t// If totalValidator Delegations are high enough to make simple reward\n\t// calculations result in more rewards given out than the value of `MaxYearlyReward`,\n\t// scale the rewards appropriately\n\tyearlyRewardTotal := CalculateFraction(blockRewardPercentage, totalValidatorDelegations)\n\tif yearlyRewardTotal.Cmp(&params.MaxYearlyReward.Value) > 0 {\n\t\treward.Mul(&reward, &params.MaxYearlyReward.Value)\n\t\treward.Div(&reward, &yearlyRewardTotal)\n\t}\n\n\t// When election cycle = 0, estimate block time at 2 sec\n\tif cycleSeconds == 0 {\n\t\tcycleSeconds = 2\n\t}\n\treward.Mul(&reward, &loom.BigUInt{big.NewInt(cycleSeconds)})\n\treward.Div(&reward, &secondsInYear)\n\n\treturn reward\n}", "func DeployPerformDataCheckerContracts(\n\tt *testing.T,\n\tregistryVersion ethereum.KeeperRegistryVersion,\n\tnumberOfContracts int,\n\tupkeepGasLimit uint32,\n\tlinkToken contracts.LinkToken,\n\tcontractDeployer contracts.ContractDeployer,\n\tclient blockchain.EVMClient,\n\tregistrySettings *contracts.KeeperRegistrySettings,\n\tlinkFundsForEachUpkeep *big.Int,\n\texpectedData []byte,\n) (contracts.KeeperRegistry, contracts.KeeperRegistrar, []contracts.KeeperPerformDataChecker, []*big.Int) {\n\tef, err := contractDeployer.DeployMockETHLINKFeed(big.NewInt(2e18))\n\trequire.NoError(t, err, \"Deploying mock ETH-Link feed shouldn't fail\")\n\tgf, err := contractDeployer.DeployMockGasFeed(big.NewInt(2e11))\n\trequire.NoError(t, err, \"Deploying mock gas feed shouldn't fail\")\n\terr = client.WaitForEvents()\n\trequire.NoError(t, err, \"Failed waiting for mock feeds to deploy\")\n\n\tregistry := DeployKeeperRegistry(t, contractDeployer, client,\n\t\t&contracts.KeeperRegistryOpts{\n\t\t\tRegistryVersion: registryVersion,\n\t\t\tLinkAddr: linkToken.Address(),\n\t\t\tETHFeedAddr: ef.Address(),\n\t\t\tGasFeedAddr: gf.Address(),\n\t\t\tTranscoderAddr: ZeroAddress.Hex(),\n\t\t\tRegistrarAddr: ZeroAddress.Hex(),\n\t\t\tSettings: *registrySettings,\n\t\t},\n\t)\n\n\t// Fund the registry with 1 LINK * amount of KeeperConsumerPerformance contracts\n\terr = linkToken.Transfer(registry.Address(), big.NewInt(0).Mul(big.NewInt(1e18), big.NewInt(int64(numberOfContracts))))\n\trequire.NoError(t, err, \"Funding keeper registry contract shouldn't fail\")\n\n\tregistrarSettings := contracts.KeeperRegistrarSettings{\n\t\tAutoApproveConfigType: 2,\n\t\tAutoApproveMaxAllowed: math.MaxUint16,\n\t\tRegistryAddr: registry.Address(),\n\t\tMinLinkJuels: big.NewInt(0),\n\t}\n\tregistrar := DeployKeeperRegistrar(t, registryVersion, linkToken, registrarSettings, contractDeployer, client, registry)\n\n\tupkeeps := DeployPerformDataChecker(t, contractDeployer, client, numberOfContracts, expectedData)\n\n\tvar upkeepsAddresses []string\n\tfor _, upkeep := range upkeeps {\n\t\tupkeepsAddresses = append(upkeepsAddresses, upkeep.Address())\n\t}\n\n\tupkeepIds := RegisterUpkeepContracts(\n\t\tt, linkToken, linkFundsForEachUpkeep, client, upkeepGasLimit, registry, registrar, numberOfContracts, upkeepsAddresses,\n\t)\n\n\treturn registry, registrar, upkeeps, upkeepIds\n}", "func GetAllDelegatedContracts(delegateAddr string) ([]string, error){\n var rtnString []string\n delegatedContractsCmd := \"/chains/main/blocks/head/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n s, err := TezosRPCGet(delegatedContractsCmd)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts: TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1) //TODO Error checking\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get all delegated contracts: Regex failed\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func TestContractSet(t *testing.T) {\n\t// create contract set\n\tc1 := &SafeContract{header: contractHeader{Transaction: types.Transaction{\n\t\tFileContractRevisions: []types.FileContractRevision{{\n\t\t\tParentID: types.FileContractID{1},\n\t\t\tNewValidProofOutputs: []types.SiacoinOutput{{}, {}},\n\t\t\tUnlockConditions: types.UnlockConditions{\n\t\t\t\tPublicKeys: []types.SiaPublicKey{{}, {}},\n\t\t\t},\n\t\t}},\n\t}}}\n\tid1 := c1.header.ID()\n\tc2 := &SafeContract{header: contractHeader{Transaction: types.Transaction{\n\t\tFileContractRevisions: []types.FileContractRevision{{\n\t\t\tParentID: types.FileContractID{2},\n\t\t\tNewValidProofOutputs: []types.SiacoinOutput{{}, {}},\n\t\t\tUnlockConditions: types.UnlockConditions{\n\t\t\t\tPublicKeys: []types.SiaPublicKey{{}, {}},\n\t\t\t},\n\t\t}},\n\t}}}\n\tid2 := c2.header.ID()\n\tcs := &ContractSet{\n\t\tcontracts: map[types.FileContractID]*SafeContract{\n\t\t\tid1: c1,\n\t\t\tid2: c2,\n\t\t},\n\t}\n\n\t// uncontested acquire/release\n\tc1 = cs.mustAcquire(t, id1)\n\tcs.Return(c1)\n\n\t// 100 concurrent serialized mutations\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < 100; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tc1 := cs.mustAcquire(t, id1)\n\t\t\tc1.header.Transaction.FileContractRevisions[0].NewRevisionNumber++\n\t\t\ttime.Sleep(time.Duration(fastrand.Intn(100)))\n\t\t\tcs.Return(c1)\n\t\t}()\n\t}\n\twg.Wait()\n\tc1 = cs.mustAcquire(t, id1)\n\tcs.Return(c1)\n\tif c1.header.LastRevision().NewRevisionNumber != 100 {\n\t\tt.Fatal(\"expected exactly 100 increments, got\", c1.header.LastRevision().NewRevisionNumber)\n\t}\n\n\t// a blocked acquire shouldn't prevent a return\n\tc1 = cs.mustAcquire(t, id1)\n\tgo func() {\n\t\ttime.Sleep(time.Millisecond)\n\t\tcs.Return(c1)\n\t}()\n\tc1 = cs.mustAcquire(t, id1)\n\tcs.Return(c1)\n\n\t// delete and reinsert id2\n\tc2 = cs.mustAcquire(t, id2)\n\tcs.Delete(c2)\n\tcs.mu.Lock()\n\tcs.contracts[id2] = c2\n\tcs.mu.Unlock()\n\n\t// call all the methods in parallel haphazardly\n\tfuncs := []func(){\n\t\tfunc() { cs.Len() },\n\t\tfunc() { cs.IDs() },\n\t\tfunc() { cs.View(id1); cs.View(id2) },\n\t\tfunc() { cs.ViewAll() },\n\t\tfunc() { cs.Return(cs.mustAcquire(t, id1)) },\n\t\tfunc() { cs.Return(cs.mustAcquire(t, id2)) },\n\t\tfunc() {\n\t\t\tc3 := &SafeContract{header: contractHeader{\n\t\t\t\tTransaction: types.Transaction{\n\t\t\t\t\tFileContractRevisions: []types.FileContractRevision{{\n\t\t\t\t\t\tParentID: types.FileContractID{3},\n\t\t\t\t\t\tNewValidProofOutputs: []types.SiacoinOutput{{}, {}},\n\t\t\t\t\t\tUnlockConditions: types.UnlockConditions{\n\t\t\t\t\t\t\tPublicKeys: []types.SiaPublicKey{{}, {}},\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\tid3 := c3.header.ID()\n\t\t\tcs.mu.Lock()\n\t\t\tcs.contracts[id3] = c3\n\t\t\tcs.mu.Unlock()\n\t\t\tcs.mustAcquire(t, id3)\n\t\t\tcs.Delete(c3)\n\t\t},\n\t}\n\twg = sync.WaitGroup{}\n\tfor _, fn := range funcs {\n\t\twg.Add(1)\n\t\tgo func(fn func()) {\n\t\t\tdefer wg.Done()\n\t\t\tfor i := 0; i < 100; i++ {\n\t\t\t\ttime.Sleep(time.Duration(fastrand.Intn(100)))\n\t\t\t\tfn()\n\t\t\t}\n\t\t}(fn)\n\t}\n\twg.Wait()\n}", "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (w *Worker) IncrementShares(sessionDifficulty float64, reward float64) {\n\tp := w.s.Client.pool\n\tcbid := p.cs.CurrentBlock().ID()\n\tblockTarget, _ := p.cs.ChildTarget(cbid)\n\tblockDifficulty, _ := blockTarget.Difficulty().Uint64()\n\n\tsessionTarget, _ := difficultyToTarget(sessionDifficulty)\n\tsiaSessionDifficulty, _ := sessionTarget.Difficulty().Uint64()\n\tshareRatio := caculateRewardRatio(sessionTarget.Difficulty().Big(), blockTarget.Difficulty().Big())\n\tshareReward := shareRatio * reward\n\t// w.log.Printf(\"shareRatio: %f, shareReward: %f\", shareRatio, shareReward)\n\n\tshare := &Share{\n\t\tuserid: w.Parent().cr.clientID,\n\t\tworkerid: w.wr.workerID,\n\t\theight: int64(p.cs.Height()) + 1,\n\t\tvalid: true,\n\t\tdifficulty: sessionDifficulty,\n\t\tshareDifficulty: float64(siaSessionDifficulty),\n\t\treward: reward,\n\t\tblockDifficulty: blockDifficulty,\n\t\tshareReward: shareReward,\n\t\ttime: time.Now(),\n\t}\n\n\tw.s.Shift().IncrementShares(share)\n}", "func (k *Keeper) GetAllDecryptionShares(ctx sdk.Context, round uint64) ([]*types.DecryptionShare, sdk.Error) {\n\tstage := k.GetStage(ctx, round)\n\tif stage != stageDSCollecting && stage != stageCompleted {\n\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"wrong round stage: %v. round: %v\", stage, round))\n\t}\n\n\tdsStore := ctx.KVStore(k.storeDecryptionSharesKey)\n\n\tkeyAllShares := []byte(fmt.Sprintf(\"rd_%d\", round))\n\n\tif !dsStore.Has(keyAllShares) {\n\t\treturn []*types.DecryptionShare{}, nil\n\t}\n\n\taddrListBytes := dsStore.Get(keyAllShares)\n\tvar addrList []string\n\terr := k.cdc.UnmarshalJSON(addrListBytes, &addrList)\n\tif err != nil {\n\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"can't unmarshal list of all adderesses from store: %v\", err))\n\t}\n\tdsList := make([]*types.DecryptionShare, 0, len(addrList))\n\tfor _, addrStr := range addrList {\n\t\taddr, err := sdk.AccAddressFromBech32(addrStr)\n\t\tif err != nil {\n\t\t\treturn nil, sdk.ErrUnknownAddress(fmt.Sprintf(\"can't get address from bench32: %v\", err))\n\t\t}\n\t\tkey := createKeyBytesByAddr(round, addr)\n\t\tif !dsStore.Has(key) {\n\t\t\treturn nil, sdk.ErrUnknownRequest(\"addresses list and real decryption share sender doesn't meet\")\n\t\t}\n\t\tdsBytes := dsStore.Get(key)\n\t\tvar dsJSON types.DecryptionShareJSON\n\t\terr = k.cdc.UnmarshalJSON(dsBytes, &dsJSON)\n\t\tif err != nil {\n\t\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"can't unmarthsal decryption share: %v\", err))\n\t\t}\n\t\tds, err1 := dsJSON.Deserialize()\n\t\tif err1 != nil {\n\t\t\treturn nil, err1\n\t\t}\n\t\tdsList = append(dsList, ds)\n\t}\n\treturn dsList, nil\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func mockReduction(hash []byte, round uint64, step uint8, keys []key.ConsensusKeys, iterativeIdx ...int) consensus.Event {\n\tidx := 0\n\tif len(iterativeIdx) != 0 {\n\t\tidx = iterativeIdx[0]\n\t}\n\n\tif idx > len(keys) {\n\t\tpanic(\"wrong iterative index: cannot iterate more than there are keys\")\n\t}\n\n\thdr := header.Header{Round: round, Step: step, BlockHash: hash, PubKeyBLS: keys[idx].BLSPubKeyBytes}\n\n\tr := new(bytes.Buffer)\n\t_ = header.MarshalSignableVote(r, hdr)\n\tsigma, _ := bls.Sign(keys[idx].BLSSecretKey, keys[idx].BLSPubKey, r.Bytes())\n\tsignedHash := sigma.Compress()\n\treturn consensus.Event{hdr, *bytes.NewBuffer(signedHash)}\n}", "func ProportionalShare(config *pb.Algorithm) Algorithm {\n\tlength, interval := getAlgorithmParams(config)\n\n\treturn func(r Request) Lease {\n\t\tvar (\n\t\t\tcount = r.Store.Count()\n\t\t\told = r.Store.Get(r.Client)\n\t\t\tgets = 0.0\n\t\t)\n\n\t\t// If this is a new client, we adjust the count.\n\t\tif !r.Store.HasClient(r.Client) {\n\t\t\tcount += r.Subclients\n\t\t}\n\n\t\t// This is the equal share that every subclient has an absolute\n\t\t// claim on.\n\t\tequalShare := r.Capacity / float64(count)\n\n\t\t// This is the equal share that should be assigned to the current client\n\t\t// based on the number of its subclients.\n\t\tequalSharePerClient := equalShare * float64(r.Subclients)\n\n\t\t// This is the capacity which is currently unused (assuming that\n\t\t// the requesting client has no capacity). It is the maximum\n\t\t// capacity that this run of the algorithm can assign to the\n\t\t// requesting client.\n\t\tunusedCapacity := r.Capacity - r.Store.SumHas() + old.Has\n\n\t\t// If the client wants less than it equal share or\n\t\t// if the sum of what all clients want together is less\n\t\t// than the available capacity we can give this client what\n\t\t// it wants.\n\t\tif r.Store.SumWants() <= r.Capacity || r.Wants <= equalSharePerClient {\n\t\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\t\tminF(r.Wants, unusedCapacity), r.Wants, r.Subclients)\n\t\t}\n\n\t\t// We now need to determine if we can give a top-up on\n\t\t// the equal share. The capacity for this top up comes\n\t\t// from clients who want less than their equal share,\n\t\t// so we calculate how much capacity this is. We also\n\t\t// calculate the excess need of all the clients, which\n\t\t// is the sum of all the wants over the equal share.\n\t\textraCapacity := 0.0\n\t\textraNeed := 0.0\n\n\t\tr.Store.Map(func(id string, lease Lease) {\n\t\t\tvar wants float64\n\t\t\tvar subclients int64\n\n\t\t\tif id == r.Client {\n\t\t\t\twants = r.Wants\n\t\t\t\tsubclients = r.Subclients\n\t\t\t} else {\n\t\t\t\twants = lease.Wants\n\t\t\t\tsubclients = lease.Subclients\n\t\t\t}\n\n\t\t\t// Every client should receive the resource capacity based on the number\n\t\t\t// of subclients it has.\n\t\t\tequalSharePerClient := equalShare * float64(subclients)\n\t\t\tif wants < equalSharePerClient {\n\t\t\t\textraCapacity += equalSharePerClient - wants\n\t\t\t} else {\n\t\t\t\textraNeed += wants - equalSharePerClient\n\t\t\t}\n\t\t})\n\n\t\t// Every client with a need over the equal share will get\n\t\t// a proportional top-up.\n\t\tgets = equalSharePerClient + (r.Wants-equalSharePerClient)*(extraCapacity/extraNeed)\n\n\t\t// Insert the capacity grant into the lease store. We cannot\n\t\t// give out more than the currently unused capacity. If that\n\t\t// is less than what the algorithm calculated we will\n\t\t// adjust this in the next capacity refreshes.\n\n\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\tminF(gets, unusedCapacity), r.Wants, r.Subclients)\n\t}\n}", "func totalExpense(s []SalaryCalculator) int {\n expense := 0\n for _, v := range s {\n expense += v.CalculateSalary()\n }\n\n return expense\n}", "func (s *ArkClient) CalculateVotersProfit(params DelegateQueryParams, shareRatio float64, blocklist string, whitelist string, capBalance bool, balanceCapAmount float64, blockBalanceCap bool) []DelegateDataProfit {\n\tdelegateRes, _, _ := s.GetDelegate(params)\n\tvoters, _, _ := s.GetDelegateVoters(params)\n\taccountRes, _, _ := s.GetAccount(AccountQueryParams{Address: delegateRes.SingleDelegate.Address})\n\n\tdelegateBalance, _ := strconv.ParseFloat(accountRes.Account.Balance, 64)\n\tdelegateBalance = float64(delegateBalance) / SATOSHI\n\n\t//calculating vote weight\n\tvotersProfit := []DelegateDataProfit{}\n\tdelelgateVoteWeight := 0\n\n\t//computing summ of all votes\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tintBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tintBalance = int(balanceCapAmount)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelelgateVoteWeight += intBalance\n\t}\n\n\t//calculating\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tcurrentVoterBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcurrentVoterBalance = balanceCapAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdeleProfit := DelegateDataProfit{\n\t\t\tAddress: element.Address,\n\t\t}\n\t\tdeleProfit.VoteWeight = currentVoterBalance / SATOSHI\n\t\tdeleProfit.VoteWeightShare = float64(currentVoterBalance) / float64(delelgateVoteWeight)\n\t\tdeleProfit.EarnedAmount100 = float64(delegateBalance) * deleProfit.VoteWeightShare\n\t\tdeleProfit.EarnedAmountXX = float64(delegateBalance) * deleProfit.VoteWeightShare * shareRatio\n\t\tdeleProfit.VoteDuration = s.GetVoteDuration(element.Address)\n\t\tvotersProfit = append(votersProfit, deleProfit)\n\t}\n\n\treturn votersProfit\n}", "func totalExpense(s []SalaryCalculator) {\n expense := 0\n for _, v := range s {\n expense = expense + v.CalculateSalary()\n }\n fmt.Printf(\"Total Expense Per Month $%d\", expense)\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func DeployKeeperContracts(\n\tt *testing.T,\n\tregistryVersion ethereum.KeeperRegistryVersion,\n\tregistrySettings contracts.KeeperRegistrySettings,\n\tnumberOfUpkeeps int,\n\tupkeepGasLimit uint32,\n\tlinkToken contracts.LinkToken,\n\tcontractDeployer contracts.ContractDeployer,\n\tclient blockchain.EVMClient,\n\tlinkFundsForEachUpkeep *big.Int,\n) (contracts.KeeperRegistry, contracts.KeeperRegistrar, []contracts.KeeperConsumer, []*big.Int) {\n\tef, err := contractDeployer.DeployMockETHLINKFeed(big.NewInt(2e18))\n\trequire.NoError(t, err, \"Deploying mock ETH-Link feed shouldn't fail\")\n\tgf, err := contractDeployer.DeployMockGasFeed(big.NewInt(2e11))\n\trequire.NoError(t, err, \"Deploying mock gas feed shouldn't fail\")\n\terr = client.WaitForEvents()\n\trequire.NoError(t, err, \"Failed waiting for mock feeds to deploy\")\n\n\t// Deploy the transcoder here, and then set it to the registry\n\ttranscoder := DeployUpkeepTranscoder(t, contractDeployer, client)\n\tregistry := DeployKeeperRegistry(t, contractDeployer, client,\n\t\t&contracts.KeeperRegistryOpts{\n\t\t\tRegistryVersion: registryVersion,\n\t\t\tLinkAddr: linkToken.Address(),\n\t\t\tETHFeedAddr: ef.Address(),\n\t\t\tGasFeedAddr: gf.Address(),\n\t\t\tTranscoderAddr: transcoder.Address(),\n\t\t\tRegistrarAddr: ZeroAddress.Hex(),\n\t\t\tSettings: registrySettings,\n\t\t},\n\t)\n\n\t// Fund the registry with 1 LINK * amount of KeeperConsumerPerformance contracts\n\terr = linkToken.Transfer(registry.Address(), big.NewInt(0).Mul(big.NewInt(1e18), big.NewInt(int64(numberOfUpkeeps))))\n\trequire.NoError(t, err, \"Funding keeper registry contract shouldn't fail\")\n\n\tregistrarSettings := contracts.KeeperRegistrarSettings{\n\t\tAutoApproveConfigType: 2,\n\t\tAutoApproveMaxAllowed: math.MaxUint16,\n\t\tRegistryAddr: registry.Address(),\n\t\tMinLinkJuels: big.NewInt(0),\n\t}\n\tregistrar := DeployKeeperRegistrar(t, registryVersion, linkToken, registrarSettings, contractDeployer, client, registry)\n\n\tupkeeps := DeployKeeperConsumers(t, contractDeployer, client, numberOfUpkeeps)\n\tvar upkeepsAddresses []string\n\tfor _, upkeep := range upkeeps {\n\t\tupkeepsAddresses = append(upkeepsAddresses, upkeep.Address())\n\t}\n\tupkeepIds := RegisterUpkeepContracts(\n\t\tt, linkToken, linkFundsForEachUpkeep, client, upkeepGasLimit, registry, registrar, numberOfUpkeeps, upkeepsAddresses,\n\t)\n\terr = client.WaitForEvents()\n\trequire.NoError(t, err, \"Error waiting for events\")\n\n\treturn registry, registrar, upkeeps, upkeepIds\n}", "func calcdutyCycleFromNeutralCenter(iC *InterfaceConfig, channel int, side string, degreeVal int) int {\n degreeValf := float64(degreeVal)\n var dutyCycle float64 = 0\n if side == \"left\" {\n if iC.StickDir[channel]==\"rev\" {\n if iC.NeutralStickPos[channel]>iC.LeftStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.LeftStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n } else if iC.LeftStickMaxPos[channel]>iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.LeftStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n }\n } else if iC.StickDir[channel]==\"norm\" {\n if iC.NeutralStickPos[channel]<iC.LeftStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.LeftStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n } else if iC.LeftStickMaxPos[channel]<iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.LeftStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=dutyCycle+float64(iC.NeutralStickPos[channel])\n }\n }\n } else if side == \"right\" {\n if iC.StickDir[channel]==\"rev\" {\n if(iC.NeutralStickPos[channel]>iC.RightStickMaxPos[channel]) {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.RightStickMaxPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n } else if(iC.RightStickMaxPos[channel]>iC.NeutralStickPos[channel]) {\n dutyCycle=float64(iC.RightStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100.0\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n }\n } else if iC.StickDir[channel]==\"norm\" {\n\n if iC.NeutralStickPos[channel]<iC.RightStickMaxPos[channel] {\n dutyCycle=float64(iC.NeutralStickPos[channel]-iC.RightStickMaxPos[channel])\n dutyCycle=dutyCycle/100\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n } else if iC.RightStickMaxPos[channel]<iC.NeutralStickPos[channel] {\n dutyCycle=float64(iC.RightStickMaxPos[channel]-iC.NeutralStickPos[channel])\n dutyCycle=dutyCycle/100\n dutyCycle=dutyCycle*degreeValf\n dutyCycle=float64(iC.NeutralStickPos[channel])-dutyCycle\n }\n }\n }\n println(\"calc Duty cycle: \" + strconv.Itoa(int(dutyCycle)))\n return int(dutyCycle)\n}", "func calculateEpochRewardShares(operator string, delegate []byte, epoch_num uint64) *RewardShares {\n\t// get epoch response\n\tgetEpochResponse(epoch_num)\n\n\t// get gravity height\n\tgravity_height := epochGravityHeight()\n\n\t// get number of produced blocks\n\tblocks := delegateProductivity(operator)\n\n\t// get delegate's votes\n\tvotes_distribution, elected, delegate_votes, total_votes := getVotes(delegate, gravity_height)\n\n\t// calculate reward\n\treward := calculateReward(blocks, elected, delegate_votes, total_votes)\n\n\t// populate rewardshare structure\n\treturn NewRewardShares().\n\t\tSetEpochNum(strconv.FormatUint(epoch_num, 10)).\n\t\tSetProductivity(blocks).\n\t\tSetTotalVotes(delegate_votes).\n\t\tSetReward(reward).\n\t\tCalculateShares(votes_distribution, delegate_votes, epoch_num)\n}", "func (_DelegatableDai *DelegatableDaiSession) Balances(arg0 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Balances(&_DelegatableDai.CallOpts, arg0)\n}", "func (suite *InterestTestSuite) TestSynchronizeInterest() {\n\ttype args struct {\n\t\tctype string\n\t\tinitialTime time.Time\n\t\tinitialCollateral sdk.Coin\n\t\tinitialPrincipal sdk.Coin\n\t\ttimeElapsed int\n\t\texpectedFees sdk.Coin\n\t\texpectedFeesUpdatedTime time.Time\n\t}\n\n\ttype test struct {\n\t\tname string\n\t\targs args\n\t}\n\n\toneYearInSeconds := 31536000\n\ttestCases := []test{\n\t\t{\n\t\t\t\"1 year\",\n\t\t\targs{\n\t\t\t\tctype: \"bnb-a\",\n\t\t\t\tinitialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),\n\t\t\t\tinitialCollateral: c(\"bnb\", 1000000000000),\n\t\t\t\tinitialPrincipal: c(\"usdx\", 100000000000),\n\t\t\t\ttimeElapsed: oneYearInSeconds,\n\t\t\t\texpectedFees: c(\"usdx\", 5000000000),\n\t\t\t\texpectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * oneYearInSeconds)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"1 month\",\n\t\t\targs{\n\t\t\t\tctype: \"bnb-a\",\n\t\t\t\tinitialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),\n\t\t\t\tinitialCollateral: c(\"bnb\", 1000000000000),\n\t\t\t\tinitialPrincipal: c(\"usdx\", 100000000000),\n\t\t\t\ttimeElapsed: 86400 * 30,\n\t\t\t\texpectedFees: c(\"usdx\", 401820189),\n\t\t\t\texpectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 86400 * 30)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"7 seconds\",\n\t\t\targs{\n\t\t\t\tctype: \"bnb-a\",\n\t\t\t\tinitialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),\n\t\t\t\tinitialCollateral: c(\"bnb\", 1000000000000),\n\t\t\t\tinitialPrincipal: c(\"usdx\", 100000000000),\n\t\t\t\ttimeElapsed: 7,\n\t\t\t\texpectedFees: c(\"usdx\", 1083),\n\t\t\t\texpectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"7 seconds - zero apy\",\n\t\t\targs{\n\t\t\t\tctype: \"busd-a\",\n\t\t\t\tinitialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),\n\t\t\t\tinitialCollateral: c(\"busd\", 10000000000000),\n\t\t\t\tinitialPrincipal: c(\"usdx\", 10000000000),\n\t\t\t\ttimeElapsed: 7,\n\t\t\t\texpectedFees: c(\"usdx\", 0),\n\t\t\t\texpectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"7 seconds - fees round to zero\",\n\t\t\targs{\n\t\t\t\tctype: \"bnb-a\",\n\t\t\t\tinitialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),\n\t\t\t\tinitialCollateral: c(\"bnb\", 1000000000),\n\t\t\t\tinitialPrincipal: c(\"usdx\", 10000000),\n\t\t\t\ttimeElapsed: 7,\n\t\t\t\texpectedFees: c(\"usdx\", 0),\n\t\t\t\texpectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tsuite.Run(tc.name, func() {\n\t\t\tsuite.SetupTest()\n\t\t\tsuite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime)\n\n\t\t\t// setup account state\n\t\t\t_, addrs := app.GeneratePrivKeyAddressPairs(1)\n\t\t\tak := suite.app.GetAccountKeeper()\n\t\t\t// setup the first account\n\t\t\tacc := ak.NewAccountWithAddress(suite.ctx, addrs[0])\n\t\t\tak.SetAccount(suite.ctx, acc)\n\t\t\tbk := suite.app.GetBankKeeper()\n\n\t\t\terr := bk.MintCoins(suite.ctx, types.ModuleName, cs(tc.args.initialCollateral))\n\t\t\tsuite.Require().NoError(err)\n\t\t\terr = bk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleName, addrs[0], cs(tc.args.initialCollateral))\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// setup pricefeed\n\t\t\tpk := suite.app.GetPriceFeedKeeper()\n\t\t\t_, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, \"bnb:usd\", d(\"17.25\"), tc.args.expectedFeesUpdatedTime.Add(time.Second))\n\t\t\tsuite.NoError(err)\n\t\t\t_, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, \"busd:usd\", d(\"1\"), tc.args.expectedFeesUpdatedTime.Add(time.Second))\n\t\t\tsuite.NoError(err)\n\n\t\t\t// setup cdp state\n\t\t\tsuite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime())\n\t\t\tsuite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec())\n\t\t\terr = suite.keeper.AddCdp(suite.ctx, addrs[0], tc.args.initialCollateral, tc.args.initialPrincipal, tc.args.ctype)\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tupdatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed))\n\t\t\tsuite.ctx = suite.ctx.WithBlockTime(updatedBlockTime)\n\t\t\terr = suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype)\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tcdp, found := suite.keeper.GetCDP(suite.ctx, tc.args.ctype, 1)\n\t\t\tsuite.Require().True(found)\n\n\t\t\tcdp = suite.keeper.SynchronizeInterest(suite.ctx, cdp)\n\n\t\t\tsuite.Require().Equal(tc.args.expectedFees, cdp.AccumulatedFees)\n\t\t\tsuite.Require().Equal(tc.args.expectedFeesUpdatedTime, cdp.FeesUpdated)\n\t\t})\n\t}\n}", "func (_DelegatableDai *DelegatableDaiCaller) Balances(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegatableDai.contract.Call(opts, out, \"balances\", arg0)\n\treturn *ret0, err\n}", "func (suite *InterestTestSuite) TestCalculateCDPInterest() {\n\ttype args struct {\n\t\tctype string\n\t\tinitialTime time.Time\n\t\tinitialCollateral sdk.Coin\n\t\tinitialPrincipal sdk.Coin\n\t\ttimeElapsed int\n\t\texpectedFees sdk.Coin\n\t}\n\n\ttype test struct {\n\t\tname string\n\t\targs args\n\t}\n\n\toneYearInSeconds := 31536000\n\ttestCases := []test{\n\t\t{\n\t\t\t\"1 year\",\n\t\t\targs{\n\t\t\t\tctype: \"bnb-a\",\n\t\t\t\tinitialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),\n\t\t\t\tinitialCollateral: c(\"bnb\", 1000000000000),\n\t\t\t\tinitialPrincipal: c(\"usdx\", 100000000000),\n\t\t\t\ttimeElapsed: oneYearInSeconds,\n\t\t\t\texpectedFees: c(\"usdx\", 5000000000),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"1 month\",\n\t\t\targs{\n\t\t\t\tctype: \"bnb-a\",\n\t\t\t\tinitialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),\n\t\t\t\tinitialCollateral: c(\"bnb\", 1000000000000),\n\t\t\t\tinitialPrincipal: c(\"usdx\", 100000000000),\n\t\t\t\ttimeElapsed: 86400 * 30,\n\t\t\t\texpectedFees: c(\"usdx\", 401820189),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"7 seconds\",\n\t\t\targs{\n\t\t\t\tctype: \"bnb-a\",\n\t\t\t\tinitialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),\n\t\t\t\tinitialCollateral: c(\"bnb\", 1000000000000),\n\t\t\t\tinitialPrincipal: c(\"usdx\", 100000000000),\n\t\t\t\ttimeElapsed: 7,\n\t\t\t\texpectedFees: c(\"usdx\", 1083),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"7 seconds - fees round to zero\",\n\t\t\targs{\n\t\t\t\tctype: \"bnb-a\",\n\t\t\t\tinitialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),\n\t\t\t\tinitialCollateral: c(\"bnb\", 1000000000),\n\t\t\t\tinitialPrincipal: c(\"usdx\", 10000000),\n\t\t\t\ttimeElapsed: 7,\n\t\t\t\texpectedFees: c(\"usdx\", 0),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tsuite.Run(tc.name, func() {\n\t\t\tsuite.SetupTest()\n\t\t\tsuite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime)\n\n\t\t\t// setup account state\n\t\t\t_, addrs := app.GeneratePrivKeyAddressPairs(1)\n\t\t\tak := suite.app.GetAccountKeeper()\n\t\t\t// setup the first account\n\t\t\tacc := ak.NewAccountWithAddress(suite.ctx, addrs[0])\n\t\t\tak.SetAccount(suite.ctx, acc)\n\t\t\tbk := suite.app.GetBankKeeper()\n\t\t\terr := bk.MintCoins(suite.ctx, types.ModuleName, cs(tc.args.initialCollateral))\n\t\t\tsuite.Require().NoError(err)\n\t\t\terr = bk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleName, addrs[0], cs(tc.args.initialCollateral))\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// setup pricefeed\n\t\t\tpk := suite.app.GetPriceFeedKeeper()\n\t\t\t_, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, \"bnb:usd\", d(\"17.25\"), tc.args.initialTime.Add(time.Duration(int(time.Second)*tc.args.timeElapsed)))\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// setup cdp state\n\t\t\tsuite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime())\n\t\t\tsuite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec())\n\t\t\terr = suite.keeper.AddCdp(suite.ctx, addrs[0], tc.args.initialCollateral, tc.args.initialPrincipal, tc.args.ctype)\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tupdatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed))\n\t\t\tsuite.ctx = suite.ctx.WithBlockTime(updatedBlockTime)\n\t\t\terr = suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype)\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tcdp, found := suite.keeper.GetCDP(suite.ctx, tc.args.ctype, 1)\n\t\t\tsuite.Require().True(found)\n\n\t\t\tnewInterest := suite.keeper.CalculateNewInterest(suite.ctx, cdp)\n\n\t\t\tsuite.Require().Equal(tc.args.expectedFees, newInterest)\n\t\t})\n\t}\n}", "func TestCalcTicketReturnAmounts(t *testing.T) {\n\tt.Parallel()\n\n\t// Default header bytes for tests.\n\tprevHeaderBytes, _ := hex.DecodeString(\"07000000dc02335daa073d293e1b15064\" +\n\t\t\"8f0444a60b9c97604abd01e00000000000000003c449b2321c4bd0d1fa76ed59f80e\" +\n\t\t\"baf46f16cfb2d17ba46948f09f21861095566482410a463ed49473c27278cd7a2a37\" +\n\t\t\"12a3b19ff1f6225717d3eb71cc2b5590100012c7312a3c30500050095a100000cf42\" +\n\t\t\"418f1820a870300000020a10700091600005b32a55f5bcce31078832100007469943\" +\n\t\t\"958002e000000000000000000000000000000000000000007000000\")\n\n\t// Default ticket commitment script hex for tests.\n\tp2pkhCommitScriptHex := \"ba76a914097e847d49c6806f6933e806a350f43b97ac70d088ac\"\n\n\t// createTestTicketOuts is a helper function that creates mock minimal outputs\n\t// for a ticket with the given contribution amounts. Note that this only\n\t// populates the ticket commitment outputs since those are the only outputs\n\t// used to calculate ticket return amounts.\n\tcreateTestTicketOuts := func(contribAmounts []int64) []*stake.MinimalOutput {\n\t\tticketOuts := make([]*stake.MinimalOutput, len(contribAmounts)*2+1)\n\t\tfor i := 0; i < len(contribAmounts); i++ {\n\t\t\tcommitScript := hexToBytes(p2pkhCommitScriptHex)\n\t\t\tamtBytes := commitScript[commitAmountStartIdx:commitAmountEndIdx]\n\t\t\tbinary.LittleEndian.PutUint64(amtBytes, uint64(contribAmounts[i]))\n\t\t\tticketOuts[i*2+1] = &stake.MinimalOutput{PkScript: commitScript}\n\t\t}\n\t\treturn ticketOuts\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tcontribAmounts []int64\n\t\tticketPurchaseAmount int64\n\t\tvoteSubsidy int64\n\t\tprevHeaderBytes []byte\n\t\tisVote bool\n\t\tisAutoRevocationsEnabled bool\n\t\twant []int64\n\t}{{\n\t\tname: \"vote rewards - evenly divisible over all outputs (auto \" +\n\t\t\t\"revocations disabled)\",\n\t\tcontribAmounts: []int64{\n\t\t\t2500000000,\n\t\t\t2500000000,\n\t\t\t5000000000,\n\t\t\t10000000000,\n\t\t},\n\t\tticketPurchaseAmount: 20000000000,\n\t\tvoteSubsidy: 100000000,\n\t\tisVote: true,\n\t\twant: []int64{\n\t\t\t2512500000,\n\t\t\t2512500000,\n\t\t\t5025000000,\n\t\t\t10050000000,\n\t\t},\n\t}, {\n\t\tname: \"revocation rewards - evenly divisible over all outputs (auto \" +\n\t\t\t\"revocations disabled)\",\n\t\tcontribAmounts: []int64{\n\t\t\t2500000000,\n\t\t\t2500000000,\n\t\t\t5000000000,\n\t\t\t10000000000,\n\t\t},\n\t\tticketPurchaseAmount: 20000000000,\n\t\tvoteSubsidy: 0,\n\t\twant: []int64{\n\t\t\t2500000000,\n\t\t\t2500000000,\n\t\t\t5000000000,\n\t\t\t10000000000,\n\t\t},\n\t}, {\n\t\tname: \"vote rewards - remainder of 2 (auto revocations disabled)\",\n\t\tcontribAmounts: []int64{\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t},\n\t\tticketPurchaseAmount: 300000000,\n\t\tvoteSubsidy: 300002,\n\t\tisVote: true,\n\t\twant: []int64{\n\t\t\t100100000,\n\t\t\t100100000,\n\t\t\t100100000,\n\t\t},\n\t}, {\n\t\tname: \"revocation rewards - remainder of 4 (auto revocations disabled)\",\n\t\tcontribAmounts: []int64{\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t},\n\t\tticketPurchaseAmount: 799999996,\n\t\tvoteSubsidy: 0,\n\t\twant: []int64{\n\t\t\t99999999,\n\t\t\t99999999,\n\t\t\t99999999,\n\t\t\t99999999,\n\t\t\t99999999,\n\t\t\t99999999,\n\t\t\t99999999,\n\t\t\t99999999,\n\t\t},\n\t}, {\n\t\tname: \"vote rewards - evenly divisible over all outputs (auto \" +\n\t\t\t\"revocations enabled)\",\n\t\tcontribAmounts: []int64{\n\t\t\t2500000000,\n\t\t\t2500000000,\n\t\t\t5000000000,\n\t\t\t10000000000,\n\t\t},\n\t\tticketPurchaseAmount: 20000000000,\n\t\tvoteSubsidy: 100000000,\n\t\tprevHeaderBytes: prevHeaderBytes,\n\t\tisVote: true,\n\t\tisAutoRevocationsEnabled: true,\n\t\twant: []int64{\n\t\t\t2512500000,\n\t\t\t2512500000,\n\t\t\t5025000000,\n\t\t\t10050000000,\n\t\t},\n\t}, {\n\t\tname: \"revocation rewards - evenly divisible over all outputs (auto \" +\n\t\t\t\"revocations enabled)\",\n\t\tcontribAmounts: []int64{\n\t\t\t2500000000,\n\t\t\t2500000000,\n\t\t\t5000000000,\n\t\t\t10000000000,\n\t\t},\n\t\tticketPurchaseAmount: 20000000000,\n\t\tvoteSubsidy: 0,\n\t\tprevHeaderBytes: prevHeaderBytes,\n\t\tisAutoRevocationsEnabled: true,\n\t\twant: []int64{\n\t\t\t2500000000,\n\t\t\t2500000000,\n\t\t\t5000000000,\n\t\t\t10000000000,\n\t\t},\n\t}, {\n\t\tname: \"vote rewards - remainder of 2 (auto revocations enabled)\",\n\t\tcontribAmounts: []int64{\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t},\n\t\tticketPurchaseAmount: 400000000,\n\t\tvoteSubsidy: 400002,\n\t\tprevHeaderBytes: prevHeaderBytes,\n\t\tisVote: true,\n\t\tisAutoRevocationsEnabled: true,\n\t\twant: []int64{\n\t\t\t100100000,\n\t\t\t100100000,\n\t\t\t100100000,\n\t\t\t100100000,\n\t\t},\n\t}, {\n\t\tname: \"revocation rewards - remainder of 4 (auto revocations enabled)\",\n\t\tcontribAmounts: []int64{\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t\t100000000,\n\t\t},\n\t\tticketPurchaseAmount: 799999996,\n\t\tvoteSubsidy: 0,\n\t\tprevHeaderBytes: prevHeaderBytes,\n\t\tisAutoRevocationsEnabled: true,\n\t\twant: []int64{\n\t\t\t99999999,\n\t\t\t100000000,\n\t\t\t99999999,\n\t\t\t99999999,\n\t\t\t99999999,\n\t\t\t99999999,\n\t\t\t100000001,\n\t\t\t100000000,\n\t\t},\n\t}}\n\n\tfor _, test := range tests {\n\t\tgot := calcTicketReturnAmounts(createTestTicketOuts(test.contribAmounts),\n\t\t\ttest.ticketPurchaseAmount, test.voteSubsidy, test.prevHeaderBytes,\n\t\t\ttest.isVote, test.isAutoRevocationsEnabled)\n\t\tif !reflect.DeepEqual(got, test.want) {\n\t\t\tt.Errorf(\"%q: unexpected result -- got %v, want %v\", test.name, got,\n\t\t\t\ttest.want)\n\t\t}\n\t}\n}", "func (f *VRFTest) deployContracts() error {\n\tif err := f.deployCommonContracts(); err != nil {\n\t\treturn err\n\t}\n\n\tcontractChan := make(chan ConsumerCoordinatorPair, f.TestOptions.NumberOfContracts)\n\tg := errgroup.Group{}\n\n\tfor i := 0; i < f.TestOptions.NumberOfContracts; i++ {\n\t\tg.Go(func() error {\n\t\t\treturn f.deployConsumerCoordinatorPair(contractChan)\n\t\t})\n\t}\n\tif err := g.Wait(); err != nil {\n\t\treturn err\n\t}\n\tclose(contractChan)\n\tfor contract := range contractChan {\n\t\tf.contractInstances = append(f.contractInstances, contract)\n\t}\n\treturn f.Blockchain.WaitForEvents()\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCallerSession) Digests(arg0 [32]byte) (*big.Int, error) {\n\treturn _BondedECDSAKeep.Contract.Digests(&_BondedECDSAKeep.CallOpts, arg0)\n}", "func Verify_shares(encrypted_shares []ed25519.Point, proof ShareCorrectnessProof, public_keys []ed25519.Point, recovery_threshold int) bool {\n\tnum_nodes := len(public_keys)\n\tcommitments, challenge, responses := proof.commitments, proof.challenge, proof.responses\n\n\tvar G_bytestring []ed25519.Point\n\tfor j := 0; j < num_nodes; j++ {\n\t\tG_bytestring = append(G_bytestring, G)\n\t}\n\t// 1. verify the DLEQ NIZK proof\n\tif !DLEQ_verify(G_bytestring, public_keys, commitments, encrypted_shares, challenge, responses) {\n\t\treturn false\n\t}\n\n\t// 2. verify the validity of the shares by sampling and testing with a random codeword\n\n\tcodeword := Random_codeword(num_nodes, recovery_threshold)\n\t// codeword := Cdword()\n\tproduct := commitments[0].Mul(codeword[0])\n\t// fmt.Println(len(codeword))\n\t// fmt.Println(len(commitments))\n\tfor i := 1; i < num_nodes; i++ {\n\t\tproduct = product.Add(commitments[i].Mul(codeword[i]))\n\t}\n\t// fmt.Println(product)\n\t// fmt.Println(ed25519.ONE)\n\treturn product.Equal(ed25519.ONE)\n\n}", "func (suite *KeeperTestSuite) TestGetAllPacketCommitmentsAtChannel() {\n\tpath := ibctesting.NewPath(suite.chainA, suite.chainB)\n\tsuite.coordinator.Setup(path)\n\n\t// create second channel\n\tpath1 := ibctesting.NewPath(suite.chainA, suite.chainB)\n\tpath1.SetChannelOrdered()\n\tpath1.EndpointA.ClientID = path.EndpointA.ClientID\n\tpath1.EndpointB.ClientID = path.EndpointB.ClientID\n\tpath1.EndpointA.ConnectionID = path.EndpointA.ConnectionID\n\tpath1.EndpointB.ConnectionID = path.EndpointB.ConnectionID\n\n\tsuite.coordinator.CreateMockChannels(path1)\n\n\tctxA := suite.chainA.GetContext()\n\texpectedSeqs := make(map[uint64]bool)\n\thash := []byte(\"commitment\")\n\n\tseq := uint64(15)\n\tmaxSeq := uint64(25)\n\tsuite.Require().Greater(maxSeq, seq)\n\n\t// create consecutive commitments\n\tfor i := uint64(1); i < seq; i++ {\n\t\tsuite.chainA.App.GetIBCKeeper().ChannelKeeper.SetPacketCommitment(ctxA, path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, i, hash)\n\t\texpectedSeqs[i] = true\n\t}\n\n\t// add non-consecutive commitments\n\tfor i := seq; i < maxSeq; i += 2 {\n\t\tsuite.chainA.App.GetIBCKeeper().ChannelKeeper.SetPacketCommitment(ctxA, path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, i, hash)\n\t\texpectedSeqs[i] = true\n\t}\n\n\t// add sequence on different channel/port\n\tsuite.chainA.App.GetIBCKeeper().ChannelKeeper.SetPacketCommitment(ctxA, path1.EndpointA.ChannelConfig.PortID, path1.EndpointA.ChannelID, maxSeq+1, hash)\n\n\tcommitments := suite.chainA.App.GetIBCKeeper().ChannelKeeper.GetAllPacketCommitmentsAtChannel(ctxA, path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\n\tsuite.Equal(len(expectedSeqs), len(commitments))\n\t// ensure above for loops occurred\n\tsuite.NotEqual(0, len(commitments))\n\n\t// verify that all the packet commitments were stored\n\tfor _, packet := range commitments {\n\t\tsuite.True(expectedSeqs[packet.Sequence])\n\t\tsuite.Equal(path.EndpointA.ChannelConfig.PortID, packet.PortId)\n\t\tsuite.Equal(path.EndpointA.ChannelID, packet.ChannelId)\n\t\tsuite.Equal(hash, packet.Data)\n\n\t\t// prevent duplicates from passing checks\n\t\texpectedSeqs[packet.Sequence] = false\n\t}\n}", "func FairShare(config *pb.Algorithm) Algorithm {\n\tlength, interval := getAlgorithmParams(config)\n\n\treturn func(r Request) Lease {\n\t\tvar (\n\t\t\tcount = r.Store.Count()\n\t\t\told = r.Store.Get(r.Client)\n\t\t)\n\n\t\t// If this is a new client, we adjust the count.\n\t\tif !r.Store.HasClient(r.Client) {\n\t\t\tcount += r.Subclients\n\t\t}\n\n\t\t// This is the equal share that every subclient should get.\n\t\tequalShare := r.Capacity / float64(count)\n\n\t\t// This is the equal share that should be assigned to the current client\n\t\t// based on the number of its subclients.\n\t\tequalSharePerClient := equalShare * float64(r.Subclients)\n\n\t\t// This is the capacity which is currently unused (assuming that\n\t\t// the requesting client has no capacity). It is the maximum\n\t\t// capacity that this run of the algorithm can assign to the\n\t\t// requesting client.\n\t\tunusedCapacity := r.Capacity - r.Store.SumHas() + old.Has\n\n\t\t// If the client wants less than its equal share or\n\t\t// if the sum of what all clients want together is less\n\t\t// than the available capacity we can give this client what\n\t\t// it wants.\n\t\tif r.Wants <= equalSharePerClient || r.Store.SumWants() <= r.Capacity {\n\t\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\t\tminF(r.Wants, unusedCapacity), r.Wants, r.Subclients)\n\t\t}\n\n\t\t// Map of what each client will get from this algorithm run.\n\t\t// Ultimately we need only determine what this client gets,\n\t\t// but for the algorithm we need to keep track of what\n\t\t// other clients would be getting as well.\n\t\tgets := make(map[string]float64)\n\n\t\t// This list contains all the clients which are still in\n\t\t// the race to get some capacity.\n\t\tclients := list.New()\n\t\tclientsNext := list.New()\n\n\t\t// Puts every client in the list to signify that they all\n\t\t// still need capacity.\n\t\tr.Store.Map(func(id string, lease Lease) {\n\t\t\tclients.PushBack(id)\n\t\t})\n\n\t\t// This is the capacity that can still be divided.\n\t\tavailableCapacity := r.Capacity\n\n\t\t// The clients list now contains all the clients who still need/want\n\t\t// capacity. We are going to divide the capacity in availableCapacity\n\t\t// in iterations until there is nothing more to divide or until we\n\t\t// completely satisfied the client who is making the request.\n\t\tfor availableCapacity > epsilon && gets[r.Client] < r.Wants-epsilon {\n\t\t\t// Calculate number of subclients for the given clients list.\n\t\t\tclientsCopy := *clients\n\t\t\tvar subclients int64\n\t\t\tfor e := clientsCopy.Front(); e != nil; e = e.Next() {\n\t\t\t\tsubclients += r.Store.Subclients(e.Value.(string))\n\t\t\t}\n\n\t\t\t// This is the fair share that is available to all subclients\n\t\t\t// who are still in the race to get capacity.\n\t\t\tfairShare := availableCapacity / float64(subclients)\n\n\t\t\t// Not enough capacity to actually worry about. Prevents\n\t\t\t// an infinite loop.\n\t\t\tif fairShare < epsilon {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// We now process the list of clients and give a topup to\n\t\t\t// every client's capacity. That topup is either the fair\n\t\t\t// share or the capacity still needed to be completely\n\t\t\t// satisfied (in case the client needs less than the\n\t\t\t// fair share to reach its need/wants).\n\t\t\tfor e := clients.Front(); e != nil; e = e.Next() {\n\t\t\t\tid := e.Value.(string)\n\n\t\t\t\t// Determines the wants for this client, which comes\n\t\t\t\t// either from the store, or from the request info if it\n\t\t\t\t// is the client making the request,\n\t\t\t\tvar wants float64\n\t\t\t\tvar subclients int64\n\n\t\t\t\tif id == r.Client {\n\t\t\t\t\twants = r.Wants\n\t\t\t\t\tsubclients = r.Subclients\n\t\t\t\t} else {\n\t\t\t\t\twants = r.Store.Get(id).Wants\n\t\t\t\t\tsubclients = r.Store.Subclients(id)\n\t\t\t\t}\n\n\t\t\t\t// stillNeeds is the capacity this client still needs to\n\t\t\t\t// be completely satisfied.\n\t\t\t\tstillNeeds := wants - gets[id]\n\n\t\t\t\t// Tops up the client's capacity.\n\t\t\t\t// Every client should receive the resource capacity based on\n\t\t\t\t// the number of its subclients.\n\t\t\t\tfairSharePerClient := fairShare * float64(subclients)\n\t\t\t\tif stillNeeds <= fairSharePerClient {\n\t\t\t\t\tgets[id] += stillNeeds\n\t\t\t\t\tavailableCapacity -= stillNeeds\n\t\t\t\t} else {\n\t\t\t\t\tgets[id] += fairSharePerClient\n\t\t\t\t\tavailableCapacity -= fairSharePerClient\n\t\t\t\t}\n\n\t\t\t\t// If the client is not yet satisfied we include it in the next\n\t\t\t\t// generation of the list. If it is completely satisfied we\n\t\t\t\t// don't.\n\t\t\t\tif gets[id] < wants {\n\t\t\t\t\tclientsNext.PushBack(id)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Ready for the next iteration of the loop. Swap the clients with the\n\t\t\t// clientsNext list.\n\t\t\tclients, clientsNext = clientsNext, clients\n\n\t\t\t// Cleans the clientsNext list so that it can be used again.\n\t\t\tclientsNext.Init()\n\t\t}\n\n\t\t// Insert the capacity grant into the lease store. We cannot\n\t\t// give out more than the currently unused capacity. If that\n\t\t// is less than what the algorithm calculated this will get\n\t\t// fixed in the next capacity refreshes.\n\t\treturn r.Store.Assign(r.Client, length, interval,\n\t\t\tminF(gets[r.Client], unusedCapacity), r.Wants, r.Subclients)\n\t}\n}", "func (suite *KeeperTestSuite) TestGetAllPacketCommitmentsAtChannel() {\n\tpath := tibctesting.NewPath(suite.chainA, suite.chainB)\n\tsuite.coordinator.SetupClients(path)\n\n\tctxA := suite.chainA.GetContext()\n\texpectedSeqs := make(map[uint64]bool)\n\thash := []byte(\"commitment\")\n\n\tseq := uint64(15)\n\tmaxSeq := uint64(25)\n\tsuite.Require().Greater(maxSeq, seq)\n\n\t// create consecutive commitments\n\tfor i := uint64(1); i < seq; i++ {\n\t\tsuite.chainA.App.TIBCKeeper.PacketKeeper.SetPacketCommitment(ctxA, path.EndpointA.ChainName, path.EndpointB.ChainName, i, hash)\n\t\texpectedSeqs[i] = true\n\t}\n\n\t// add non-consecutive commitments\n\tfor i := seq; i < maxSeq; i += 2 {\n\t\tsuite.chainA.App.TIBCKeeper.PacketKeeper.SetPacketCommitment(ctxA, path.EndpointA.ChainName, path.EndpointB.ChainName, i, hash)\n\t\texpectedSeqs[i] = true\n\t}\n\n\t// add sequence on different channel/port\n\tsuite.chainA.App.TIBCKeeper.PacketKeeper.SetPacketCommitment(ctxA, path.EndpointA.ChainName, \"EndpointBChainName\", maxSeq+1, hash)\n\n\tcommitments := suite.chainA.App.TIBCKeeper.PacketKeeper.GetAllPacketCommitmentsAtChannel(ctxA, path.EndpointA.ChainName, path.EndpointB.ChainName)\n\n\tsuite.Equal(len(expectedSeqs), len(commitments))\n\t// ensure above for loops occurred\n\tsuite.NotEqual(0, len(commitments))\n\n\t// verify that all the packet commitments were stored\n\tfor _, packet := range commitments {\n\t\tsuite.True(expectedSeqs[packet.Sequence])\n\t\tsuite.Equal(path.EndpointA.ChainName, packet.SourceChain)\n\t\tsuite.Equal(path.EndpointB.ChainName, packet.DestinationChain)\n\t\tsuite.Equal(hash, packet.Data)\n\n\t\t// prevent duplicates from passing checks\n\t\texpectedSeqs[packet.Sequence] = false\n\t}\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func Test_consensusIterations(t *testing.T) {\n\ttest := newConsensusTest()\n\n\ttotalNodes := 15\n\tcfg := config.Config{N: totalNodes, F: totalNodes/2 - 1, RoundDuration: 1, ExpectedLeaders: 5, LimitIterations: 1000, LimitConcurrent: 100}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tmesh, err := mocknet.FullMeshLinked(ctx, totalNodes)\n\trequire.NoError(t, err)\n\n\ttest.initialSets = make([]*Set, totalNodes)\n\tset1 := NewSetFromValues(value1)\n\ttest.fill(set1, 0, totalNodes-1)\n\ttest.honestSets = []*Set{set1}\n\toracle := eligibility.New(logtest.New(t))\n\ti := 0\n\tcreationFunc := func() {\n\t\thost := mesh.Hosts()[i]\n\t\tps, err := pubsub.New(ctx, logtest.New(t), host, pubsub.DefaultConfig())\n\t\trequire.NoError(t, err)\n\t\tp2pm := &p2pManipulator{nd: ps, stalledLayer: types.NewLayerID(1), err: errors.New(\"fake err\")}\n\t\tproc, broker := createConsensusProcess(t, true, cfg, oracle, p2pm, test.initialSets[i], types.NewLayerID(1), t.Name())\n\t\ttest.procs = append(test.procs, proc)\n\t\ttest.brokers = append(test.brokers, broker)\n\t\ti++\n\t}\n\ttest.Create(totalNodes, creationFunc)\n\trequire.NoError(t, mesh.ConnectAllButSelf())\n\ttest.Start()\n\ttest.WaitForTimedTermination(t, 40*time.Second)\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func calcIters(neurons []network.Neuron, synapses []network.Synapse) int {\n\ta := make(map[float64]bool, 10)\n\tb := make(map[float64]bool, 10)\n\tfor _, s := range synapses {\n\t\tsrc := neurons[s.Source]\n\t\ttgt := neurons[s.Target]\n\t\ta[tgt.Y] = true\n\t\tif tgt.Y <= src.Y {\n\t\t\tb[src.Y] = true\n\t\t}\n\t}\n\treturn len(a) + len(b)\n}", "func SortDelegateContracts(delegatedContracts []DelegatedContract) []DelegatedContract{\n for i, j := 0, len(delegatedContracts)-1; i < j; i, j = i+1, j-1 {\n delegatedContracts[i], delegatedContracts[j] = delegatedContracts[j], delegatedContracts[i]\n }\n return delegatedContracts\n}", "func (_Cakevault *CakevaultCaller) TotalShares(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"totalShares\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCaller) Digests(opts *bind.CallOpts, arg0 [32]byte) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BondedECDSAKeep.contract.Call(opts, out, \"digests\", arg0)\n\treturn *ret0, err\n}", "func AnalyseChurn(channel chan tor.ObjectSet, params *CmdLineParams, group *sync.WaitGroup) {\n\n\tdefer group.Done()\n\n\tvar newConsensus, prevConsensus *tor.Consensus\n\n\tif params.WindowSize <= 0 {\n\t\tlog.Printf(\"Window size set to %d, but cannot be smaller than 1. Setting it to 1.\", params.WindowSize)\n\t\tparams.WindowSize = 1\n\t}\n\n\tlog.Printf(\"Threshold for churn analysis is %.5f.\\n\", params.Threshold)\n\n\t// Print CSV header, either in long or wide format.\n\tfmt.Print(\"Date\")\n\tfor _, flag := range RelayFlags {\n\t\tif params.CSVFormat == longCSVFormat {\n\t\t\tfmt.Printf(\",%s\", flag)\n\t\t} else {\n\t\t\tfmt.Printf(\",New%s,Gone%s\", flag, flag)\n\t\t}\n\t}\n\tif params.CSVFormat == longCSVFormat {\n\t\tfmt.Print(\",NewChurn,GoneChurn\")\n\t}\n\tfmt.Println()\n\n\tmovAvg := make(PerFlagMovAvg)\n\tfor _, flag := range RelayFlags {\n\t\tmovAvg[flag] = NewMovingAverage(params.WindowSize)\n\t}\n\n\t// Every loop iteration processes one consensus. We compare consensus t\n\t// to consensus t - 1.\n\tfor objects := range channel {\n\n\t\tswitch obj := objects.(type) {\n\t\tcase *tor.Consensus:\n\t\t\tnewConsensus = obj\n\t\tdefault:\n\t\t\tlog.Fatalln(\"Only router status files are supported for churn analysis.\")\n\t\t}\n\n\t\tif prevConsensus == nil {\n\t\t\tprevConsensus = newConsensus\n\t\t\tcontinue\n\t\t}\n\n\t\t// Are we missing consensuses?\n\t\tif prevConsensus.ValidAfter.Add(time.Hour) != newConsensus.ValidAfter {\n\t\t\tlog.Printf(\"Missing consensuses between %s and %s.\\n\",\n\t\t\t\tprevConsensus.ValidAfter.Format(time.RFC3339),\n\t\t\t\tnewConsensus.ValidAfter.Format(time.RFC3339))\n\t\t\tprevConsensus = newConsensus\n\t\t\tcontinue\n\t\t}\n\n\t\tDeterminePerFlagChurn(prevConsensus, newConsensus, movAvg, params)\n\n\t\tprevConsensus = newConsensus\n\t}\n}", "func getAccumulatedRewards(ctx sdk.Context, distKeeper types.DistributionKeeper, delegation stakingtypes.Delegation) ([]wasmvmtypes.Coin, error) {\n\t// Try to get *delegator* reward info!\n\tparams := distributiontypes.QueryDelegationRewardsRequest{\n\t\tDelegatorAddress: delegation.DelegatorAddress,\n\t\tValidatorAddress: delegation.ValidatorAddress,\n\t}\n\tcache, _ := ctx.CacheContext()\n\tqres, err := distKeeper.DelegationRewards(sdk.WrapSDKContext(cache), &params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// now we have it, convert it into wasmvm types\n\trewards := make([]wasmvmtypes.Coin, len(qres.Rewards))\n\tfor i, r := range qres.Rewards {\n\t\trewards[i] = wasmvmtypes.Coin{\n\t\t\tDenom: r.Denom,\n\t\t\tAmount: r.Amount.TruncateInt().String(),\n\t\t}\n\t}\n\treturn rewards, nil\n}", "func (t *TaskChaincode) getBalance(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\t// 0\n\t// \"$account\"\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tfmt.Println(\"cacluate begins!\");\n\tif len(args[0]) <= 0 {\n\t\treturn shim.Error(\"1st argument must be a non-empty string\")\n\t}\n\n\taccount := args[0]\n\n\tqueryString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"objectType\\\":\\\"PayTX\\\",\\\"payer\\\":\\\"%s\\\"}}\", account)\n\tqueryResults, err := getResultForQueryString(stub, queryString)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tvar payerTXs []payTX\n\terr = json.Unmarshal(queryResults, &payerTXs)\n\tif err != nil {\n\t\tshim.Error(err.Error())\n\t}\n\n\t//fmt.Println(len(payTXs))\n\tvar i int\n\toutcomeVal := 0.0\n for i=0;i<len(payerTXs);i=i+1 {\n\t\tpayerTX := payerTXs[i]\n\t\toutcomeVal = outcomeVal + payerTX.Value\n\t}\n //fmt.Println(outcomeVal)\n\n\tqueryString = fmt.Sprintf(\"{\\\"selector\\\":{\\\"objectType\\\":\\\"PayTX\\\",\\\"payee\\\":\\\"%s\\\"}}\", account)\n\tqueryResults, err = getResultForQueryString(stub, queryString)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tvar payeeTXs []payTX\n\terr = json.Unmarshal(queryResults, &payeeTXs)\n\tif err != nil {\n\t\tshim.Error(err.Error())\n\t}\n\n\tincomeVal := 0.0\n for i=0;i<len(payeeTXs);i=i+1 {\n\t\tpayeeTX := payeeTXs[i]\n\t\tincomeVal = incomeVal + payeeTX.Value\n\t}\n //fmt.Println(incomeVal)\n\n\tbalance := incomeVal - outcomeVal\n\t//fmt.Println(balance)\n balanceStr := strconv.FormatFloat(balance, 'f', 6, 64)\n\n return shim.Success([]byte(balanceStr))\n}", "func (_Ethdkg *EthdkgTransactor) DistributeShares(opts *bind.TransactOpts, encrypted_shares []*big.Int, commitments [][2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.contract.Transact(opts, \"distribute_shares\", encrypted_shares, commitments)\n}", "func (_Ethdkg *EthdkgSession) DistributeShares(encrypted_shares []*big.Int, commitments [][2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.Contract.DistributeShares(&_Ethdkg.TransactOpts, encrypted_shares, commitments)\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func GenerateShares(secret int64, n int, M *big.Int) []*big.Int {\n\ts := new(big.Int).SetInt64(secret)\n\tsum := new(big.Int)\n\tshares := make([]*big.Int, n)\n\tj := mr.Intn(n)\n\tfor i := 0; i < n; i++ {\n\t\tif i != j {\n\t\t\tshares[i] = getRandom(M)\n\t\t\tsum.Add(sum, shares[i])\n\t\t}\n\t}\n\tshares[j] = s.Sub(s, sum).Mod(s, M)\n\treturn shares\n}", "func (_DelegationController *DelegationControllerCaller) DelegationsByHolder(opts *bind.CallOpts, arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"delegationsByHolder\", arg0, arg1)\n\treturn *ret0, err\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) Digests(arg0 [32]byte) (*big.Int, error) {\n\treturn _BondedECDSAKeep.Contract.Digests(&_BondedECDSAKeep.CallOpts, arg0)\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_Ethdkg *EthdkgTransactorSession) DistributeShares(encrypted_shares []*big.Int, commitments [][2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.Contract.DistributeShares(&_Ethdkg.TransactOpts, encrypted_shares, commitments)\n}", "func runTest1(n int) []int64 {\n\tcreateBlockchain()\n\tt := []int64{}\n\tif verbose {\n\t\tbalance1, _ := utxos.FindSpendableOutputs(HashPubKey(wallet1.PublicKey), 9999999)\n\t\tbalance2, _ := utxos.FindSpendableOutputs(HashPubKey(wallet2.PublicKey), 9999999)\n\t\tfmt.Printf(\"%d %d %d\\n\", len(chain.blocks), balance1, balance2)\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tnewTransaction(10) // Send 10\n\t\ttxs := prepareTXs()\n\t\tt0 := time.Now()\n\t\t_, err := chain.MineBlock(txs)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\treturn nil\n\t\t}\n\t\tt = append(t, time.Now().Sub(t0).Milliseconds())\n\t\tutxos.Update(txs)\n\t\tif verbose {\n\t\t\tbalance1, _ := utxos.FindSpendableOutputs(HashPubKey(wallet1.PublicKey), 9999999)\n\t\t\tbalance2, _ := utxos.FindSpendableOutputs(HashPubKey(wallet2.PublicKey), 9999999)\n\t\t\tfmt.Printf(\"%d %d %d\\n\", len(chain.blocks), balance1, balance2)\n\t\t}\n\t\ttxBuffer = []*Transaction{}\n\t}\n\n\treturn t\n}", "func TestFeeBudget(t *testing.T) {\n\tquote := &loop.LoopOutQuote{\n\t\tSwapFee: btcutil.Amount(1),\n\t\tPrepayAmount: btcutil.Amount(500),\n\t\tMinerFee: btcutil.Amount(50),\n\t}\n\n\tchan1 := applyFeeCategoryQuote(\n\t\tchan1Rec, 5000, defaultPrepayRoutingFeePPM,\n\t\tdefaultRoutingFeePPM, *quote,\n\t)\n\tchan2 := applyFeeCategoryQuote(\n\t\tchan2Rec, 5000, defaultPrepayRoutingFeePPM,\n\t\tdefaultRoutingFeePPM, *quote,\n\t)\n\n\ttests := []struct {\n\t\tname string\n\n\t\t// budget is our autoloop budget.\n\t\tbudget btcutil.Amount\n\n\t\t// maxMinerFee is the maximum miner fee we will pay for swaps.\n\t\tmaxMinerFee btcutil.Amount\n\n\t\t// existingSwaps represents our existing swaps, mapping their\n\t\t// last update time to their total cost.\n\t\texistingSwaps map[time.Time]btcutil.Amount\n\n\t\t// suggestions is the set of swaps we expect to be suggested.\n\t\tsuggestions *Suggestions\n\t}{\n\t\t{\n\t\t\t// Two swaps will cost (78+5000)*2, set exactly 10156\n\t\t\t// budget.\n\t\t\tname: \"budget for 2 swaps, no existing\",\n\t\t\tbudget: 10156,\n\t\t\tmaxMinerFee: 5000,\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1, chan2,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Two swaps will cost (78+5000)*2, set 10155 so we can\n\t\t\t// only afford one swap.\n\t\t\tname: \"budget for 1 swaps, no existing\",\n\t\t\tbudget: 10155,\n\t\t\tmaxMinerFee: 5000,\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID2: ReasonBudgetInsufficient,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Set an existing swap which would limit us to a single\n\t\t\t// swap if it were in our period.\n\t\t\tname: \"existing swaps, before budget period\",\n\t\t\tbudget: 10156,\n\t\t\tmaxMinerFee: 5000,\n\t\t\texistingSwaps: map[time.Time]btcutil.Amount{\n\t\t\t\ttestBudgetStart.Add(time.Hour * -1): 200,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1, chan2,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Add an existing swap in our budget period such that\n\t\t\t// we only have budget left for one more swap.\n\t\t\tname: \"existing swaps, in budget period\",\n\t\t\tbudget: 10156,\n\t\t\tmaxMinerFee: 5000,\n\t\t\texistingSwaps: map[time.Time]btcutil.Amount{\n\t\t\t\ttestBudgetStart.Add(time.Hour): 500,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID2: ReasonBudgetInsufficient,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"existing swaps, budget used\",\n\t\t\tbudget: 500,\n\t\t\tmaxMinerFee: 1000,\n\t\t\texistingSwaps: map[time.Time]btcutil.Amount{\n\t\t\t\ttestBudgetStart.Add(time.Hour): 500,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonBudgetElapsed,\n\t\t\t\t\tchanID2: ReasonBudgetElapsed,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, testCase := range tests {\n\t\ttestCase := testCase\n\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\tcfg, lnd := newTestConfig()\n\n\t\t\t// Create a swap set of existing swaps with our set of\n\t\t\t// existing swap timestamps.\n\t\t\tswaps := make(\n\t\t\t\t[]*loopdb.LoopOut, 0,\n\t\t\t\tlen(testCase.existingSwaps),\n\t\t\t)\n\n\t\t\t// Add an event with the timestamp and budget set by\n\t\t\t// our test case.\n\t\t\tfor ts, amt := range testCase.existingSwaps {\n\t\t\t\tevent := &loopdb.LoopEvent{\n\t\t\t\t\tSwapStateData: loopdb.SwapStateData{\n\t\t\t\t\t\tCost: loopdb.SwapCost{\n\t\t\t\t\t\t\tServer: amt,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tState: loopdb.StateSuccess,\n\t\t\t\t\t},\n\t\t\t\t\tTime: ts,\n\t\t\t\t}\n\n\t\t\t\tswaps = append(swaps, &loopdb.LoopOut{\n\t\t\t\t\tLoop: loopdb.Loop{\n\t\t\t\t\t\tEvents: []*loopdb.LoopEvent{\n\t\t\t\t\t\t\tevent,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tContract: autoOutContract,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tcfg.ListLoopOut = func(context.Context) ([]*loopdb.LoopOut, error) {\n\t\t\t\treturn swaps, nil\n\t\t\t}\n\n\t\t\tcfg.LoopOutQuote = func(_ context.Context,\n\t\t\t\t_ *loop.LoopOutQuoteRequest) (*loop.LoopOutQuote,\n\t\t\t\terror) {\n\n\t\t\t\treturn quote, nil\n\t\t\t}\n\n\t\t\t// Set two channels that need swaps.\n\t\t\tlnd.Channels = []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t\tchannel2,\n\t\t\t}\n\n\t\t\tparams := defaultParameters\n\t\t\tparams.ChannelRules = map[lnwire.ShortChannelID]*SwapRule{\n\t\t\t\tchanID1: chanRule,\n\t\t\t\tchanID2: chanRule,\n\t\t\t}\n\t\t\tparams.AutoFeeBudget = testCase.budget\n\t\t\tparams.AutoFeeRefreshPeriod = testBudgetRefresh\n\t\t\tparams.AutoloopBudgetLastRefresh = testBudgetStart\n\t\t\tparams.MaxAutoInFlight = 2\n\t\t\tparams.FeeLimit = NewFeeCategoryLimit(\n\t\t\t\tdefaultSwapFeePPM, defaultRoutingFeePPM,\n\t\t\t\tdefaultPrepayRoutingFeePPM,\n\t\t\t\ttestCase.maxMinerFee, defaultMaximumPrepay,\n\t\t\t\tdefaultSweepFeeRateLimit,\n\t\t\t)\n\n\t\t\t// Set our custom max miner fee on each expected swap,\n\t\t\t// rather than having to create multiple vars for\n\t\t\t// different rates.\n\t\t\tfor i := range testCase.suggestions.OutSwaps {\n\t\t\t\ttestCase.suggestions.OutSwaps[i].MaxMinerFee =\n\t\t\t\t\ttestCase.maxMinerFee\n\t\t\t}\n\n\t\t\ttestSuggestSwaps(\n\t\t\t\tt, newSuggestSwapsSetup(cfg, lnd, params),\n\t\t\t\ttestCase.suggestions, nil,\n\t\t\t)\n\t\t})\n\t}\n}", "func sum(numbers chan int) int {\n\tacc := 0\n\tfor v := range numbers {\n\t\tfmt.Printf(\"Got doubled value %d \\n\", v)\n\t\tacc += v\n\t}\n\treturn acc\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func TestCommitmentSpendValidation(t *testing.T) {\n\tt.Parallel()\n\n\t// In the modern network, all channels use the new tweakless format,\n\t// but we also need to support older nodes that want to open channels\n\t// with the legacy format, so we'll test spending in both scenarios.\n\tfor _, tweakless := range []bool{true, false} {\n\t\ttweakless := tweakless\n\t\tt.Run(fmt.Sprintf(\"tweak=%v\", tweakless), func(t *testing.T) {\n\t\t\ttestSpendValidation(t, tweakless)\n\t\t})\n\t}\n}", "func TestAllShares(t *testing.T) {\n\tshares := []m.Share{\n\t\t{\n\t\t\tID: uuid.MustParse(\"f43b0e48-13cc-4c6c-8a23-3a18a670effd\"),\n\t\t\tIsPublic: true,\n\t\t},\n\t\t{\n\t\t\tID: uuid.MustParse(\"a558aca3-fb40-400b-8dc6-ae49c705c791\"),\n\t\t\tIsPublic: false,\n\t\t},\n\t}\n\tdb.Create(&shares[0])\n\tdb.Create(&shares[1])\n\tdefer db.Delete(&shares[0])\n\tdefer db.Delete(&shares[1])\n\n\tt.Run(\"happy path\", func(t *testing.T) {\n\t\t// request\n\t\tres, _ := http.Get(url + \"/shares\")\n\t\t// parse\n\t\tbody, _ := ioutil.ReadAll(res.Body)\n\t\tvar actual []m.Share\n\t\tvar expected = []m.Share{parseShare(shares[0])}\n\t\t_ = json.Unmarshal(body, &actual)\n\t\t// assertions\n\t\tassert.Equal(t, http.StatusOK, res.StatusCode)\n\t\tassert.Len(t, actual, len(expected))\n\t\tassert.Equal(t, expected, actual)\n\t})\n\n\tt.Run(\"with admin key\", func(t *testing.T) {\n\t\t// do request\n\t\treq, _ := http.NewRequest(\"GET\", fmt.Sprint(url, \"/shares\"), nil)\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+base64.StdEncoding.EncodeToString([]byte(os.Getenv(\"ADMIN_KEY\"))))\n\t\tres, _ := http.DefaultClient.Do(req)\n\t\t// parse\n\t\tbody, _ := ioutil.ReadAll(res.Body)\n\t\tvar actual []m.Share\n\t\tvar expected = []m.Share{parseShare(shares[0]), parseShare(shares[1])}\n\t\t_ = json.Unmarshal(body, &actual)\n\t\t// assertions\n\t\tassert.Equal(t, http.StatusOK, res.StatusCode)\n\t\tassert.Len(t, actual, len(expected))\n\t\tassert.Equal(t, expected, actual)\n\t})\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func trackMockBalances(bankKeeper *govtestutil.MockBankKeeper, distributionKeeper *govtestutil.MockDistributionKeeper) {\n\tbalances := make(map[string]sdk.Coins)\n\tbalances[distAcct.String()] = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)))\n\n\t// We don't track module account balances.\n\tbankKeeper.EXPECT().MintCoins(gomock.Any(), mintModuleName, gomock.Any()).AnyTimes()\n\tbankKeeper.EXPECT().BurnCoins(gomock.Any(), types.ModuleName, gomock.Any()).AnyTimes()\n\tbankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), mintModuleName, types.ModuleName, gomock.Any()).AnyTimes()\n\n\t// But we do track normal account balances.\n\tbankKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), gomock.Any(), types.ModuleName, gomock.Any()).DoAndReturn(func(_ sdk.Context, sender sdk.AccAddress, _ string, coins sdk.Coins) error {\n\t\tnewBalance, negative := balances[sender.String()].SafeSub(coins...)\n\t\tif negative {\n\t\t\treturn fmt.Errorf(\"not enough balance\")\n\t\t}\n\t\tbalances[sender.String()] = newBalance\n\t\treturn nil\n\t}).AnyTimes()\n\tbankKeeper.EXPECT().SendCoinsFromModuleToAccount(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ sdk.Context, module string, rcpt sdk.AccAddress, coins sdk.Coins) error {\n\t\tbalances[rcpt.String()] = balances[rcpt.String()].Add(coins...)\n\t\treturn nil\n\t}).AnyTimes()\n\tbankKeeper.EXPECT().GetAllBalances(gomock.Any(), gomock.Any()).DoAndReturn(func(_ sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\t\treturn balances[addr.String()]\n\t}).AnyTimes()\n\tbankKeeper.EXPECT().GetBalance(gomock.Any(), gomock.Any(), sdk.DefaultBondDenom).DoAndReturn(func(_ sdk.Context, addr sdk.AccAddress, _ string) sdk.Coin {\n\t\tbalances := balances[addr.String()]\n\t\tfor _, balance := range balances {\n\t\t\tif balance.Denom == sdk.DefaultBondDenom {\n\t\t\t\treturn balance\n\t\t\t}\n\t\t}\n\t\treturn sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0))\n\t}).AnyTimes()\n\n\tdistributionKeeper.EXPECT().FundCommunityPool(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ sdk.Context, coins sdk.Coins, sender sdk.AccAddress) error {\n\t\t// sender balance\n\t\tnewBalance, negative := balances[sender.String()].SafeSub(coins...)\n\t\tif negative {\n\t\t\treturn fmt.Errorf(\"not enough balance\")\n\t\t}\n\t\tbalances[sender.String()] = newBalance\n\t\t// receiver balance\n\t\tbalances[distAcct.String()] = balances[distAcct.String()].Add(coins...)\n\t\treturn nil\n\t}).AnyTimes()\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (k *Keeper) GetAllCiphertexts(ctx sdk.Context, round uint64) ([]*types.CiphertextShare, sdk.Error) {\n\tctStore := ctx.KVStore(k.storeCiphertextSharesKey)\n\tstage := k.GetStage(ctx, round)\n\n\tif stage == stageUnstarted {\n\t\treturn nil, sdk.ErrUnknownRequest(\"round hasn't started yet\")\n\t}\n\n\tkeyBytesAllCt := []byte(fmt.Sprintf(\"rd_%d\", round))\n\n\t//if store doesn't have such key -> no cts was added\n\tif !ctStore.Has(keyBytesAllCt) {\n\t\treturn []*types.CiphertextShare{}, nil\n\t}\n\n\taddrListBytes := ctStore.Get(keyBytesAllCt)\n\tvar addrList []string\n\terr := k.cdc.UnmarshalJSON(addrListBytes, &addrList)\n\tif err != nil {\n\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"can't unmarshal list of all adderesses from store: %v\", err))\n\t}\n\tctList := make([]*types.CiphertextShare, 0, len(addrList))\n\tfor _, addrStr := range addrList {\n\t\taddr, err := sdk.AccAddressFromBech32(addrStr)\n\t\tif err != nil {\n\t\t\treturn nil, sdk.ErrUnknownAddress(fmt.Sprintf(\"can't get address from bench32: %v\", err))\n\t\t}\n\t\tkey := createKeyBytesByAddr(round, addr)\n\t\tif !ctStore.Has(key) {\n\t\t\treturn nil, sdk.ErrUnknownRequest(\"addresses list and real ciphertext providers doesn't meet\")\n\t\t}\n\t\tctBytes := ctStore.Get(key)\n\t\tvar ctJSON types.CiphertextShareJSON\n\t\terr = k.cdc.UnmarshalJSON(ctBytes, &ctJSON)\n\t\tif err != nil {\n\t\t\treturn nil, sdk.ErrUnknownRequest(fmt.Sprintf(\"can't unmarthsal ciphertext: %v\", err))\n\t\t}\n\t\tct, err1 := ctJSON.Deserialize()\n\t\tif err1 != nil {\n\t\t\treturn nil, err1\n\t\t}\n\t\tctList = append(ctList, ct)\n\t}\n\treturn ctList, nil\n}", "func totalExpense(s []SalaryCalculator) {\n\texpense := 0\n\tfor _, v := range s {\n\t\texpense = expense + v.CalculateSalary()\n\t}\n\tfmt.Printf(\"Total Expense Per Month $%d\", expense)\n}", "func (m *GraphBaseServiceClient) Contracts()(*ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.ContractsRequestBuilder) {\n return ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.NewContractsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Contracts()(*ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.ContractsRequestBuilder) {\n return ie3631868038c44f490dbc03525ac7249d0523c29cc45cbb25b2aebcf470d6c0c.NewContractsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (mixerService *MixerService) CyclePool() {\n\tfmt.Println(\"\\nCycling Pool\")\n\t// check pathway deposit addresses for new deposits\n\t// move empty deposit addresses to pool && update pathway debt amount (with 1% cut)\n\tfmt.Println(\"\\n\\nChecking deposit addresses for new deposits\")\n\tmixerService.checkAndEmptyDepositAddresses()\n\n\tfmt.Println(\"\\n\\nPruning Pool (moving funds to members)\")\n\t// go through all pathways with outstanding debt, and \"prune\" each pathway\n\tmixerService.prunePathwayDebt()\n}", "func FindNoOfRedistributionCycles(bank []int) int {\n\thashList := []uint64{hash(bank)}\n\tfor {\n\t\tcurrentElement := getMaxIndex(bank)\n\t\tvalue := bank[currentElement]\n\t\tbank[currentElement] = 0\n\n\t\tfor i := 0; i < value; i++ {\n\t\t\tcurrentElement++\n\t\t\tif currentElement > len(bank)-1 {\n\t\t\t\tcurrentElement = 0\n\t\t\t}\n\t\t\tbank[currentElement]++\n\t\t}\n\n\t\thash := hash(bank)\n\t\tfor _, h := range hashList {\n\t\t\tif h == hash {\n\t\t\t\treturn len(hashList)\n\t\t\t}\n\t\t}\n\t\thashList = append(hashList, hash)\n\t}\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) Contracts(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"contracts\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func runTest1(n int) []int64 {\n\tcreateBlockchain()\n\tt := []int64{}\n\tif verbose {\n\t\tbalance1, _ := utxos.FindSpendableOutputs(HashPubKey(wallet1.PublicKey), 9999999)\n\t\tbalance2, _ := utxos.FindSpendableOutputs(HashPubKey(wallet2.PublicKey), 9999999)\n\t\tfmt.Printf(\"%d %d %d\\n\", len(chain.blocks), balance1, balance2)\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tnewTransaction(10) // Send 10\n\t\ttxs := prepareTXs()\n\t\tt0 := time.Now()\n\n\t\tblock := mine(txs, chain.CurrentBlock().Hash)\n\t\tchain.blocks = append(chain.blocks, &block)\n\n\t\tt = append(t, time.Now().Sub(t0).Milliseconds())\n\t\tutxos.Update(txs)\n\t\tif verbose {\n\t\t\tbalance1, _ := utxos.FindSpendableOutputs(HashPubKey(wallet1.PublicKey), 9999999)\n\t\t\tbalance2, _ := utxos.FindSpendableOutputs(HashPubKey(wallet2.PublicKey), 9999999)\n\t\t\tfmt.Printf(\"%d %d %d\\n\", len(chain.blocks), balance1, balance2)\n\t\t}\n\t\ttxBuffer = []*Transaction{}\n\n\t\tif block.Nonce%2 == 1 {\n\t\t\tslave1Score++\n\t\t} else {\n\t\t\tslave2Score++\n\t\t}\n\t\tif len(chain.blocks)%100 == 0 {\n\t\t\tfmt.Println(\"Length of chain:\", len(chain.blocks))\n\t\t}\n\t}\n\n\treturn t\n}", "func TestValidatorSMMultiVoting(t *testing.T) {\n\n\tctx, _, mk := CreateTestInput(t, false, SufficientInitPower)\n\tclearNotBondedPool(t, ctx, mk.SupplyKeeper)\n\n\tparams := DefaultParams()\n\n\toriginVaSet := addrVals[1:]\n\tparams.MaxValidators = uint16(len(originVaSet))\n\tparams.Epoch = 2\n\tparams.UnbondingTime = time.Millisecond * 300\n\n\tstartUpValidator := NewValidator(StartUpValidatorAddr, StartUpValidatorPubkey, Description{}, types.DefaultMinSelfDelegation)\n\n\tstartUpStatus := baseValidatorStatus{startUpValidator}\n\n\tbAction := baseAction{mk}\n\n\torgValsLen := len(originVaSet)\n\tfullVaSet := make([]sdk.ValAddress, orgValsLen+1)\n\tcopy(fullVaSet, originVaSet)\n\tcopy(fullVaSet[orgValsLen:], []sdk.ValAddress{startUpStatus.getValidator().GetOperator()})\n\n\texpZeroDec := sdk.ZeroDec()\n\texpValsBondedToken := DefaultMSD.MulInt64(int64(len(fullVaSet)))\n\texpDlgGrpBondedToken := DelegatedToken1.Add(DelegatedToken2)\n\texpAllBondedToken := expValsBondedToken.Add(expDlgGrpBondedToken)\n\tstartUpCheck := andChecker{[]actResChecker{\n\t\tqueryPoolCheck(&expAllBondedToken, &expZeroDec),\n\t\tnoErrorInHandlerResult(true),\n\t}}\n\n\t// after delegator in group finish adding shares, do following check\n\taddSharesChecker := andChecker{[]actResChecker{\n\t\tvalidatorDelegatorShareIncreased(true),\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t\tqueryDelegatorCheck(ValidDelegator2, true, fullVaSet, nil, &DelegatedToken2, &expZeroDec),\n\t\tqueryAllValidatorCheck([]sdk.BondStatus{sdk.Unbonded, sdk.Bonded, sdk.Unbonding}, []int{1, 4, 0}),\n\t\tquerySharesToCheck(startUpStatus.getValidator().OperatorAddress, 1, []sdk.AccAddress{ValidDelegator2}),\n\t\tqueryPoolCheck(&expAllBondedToken, &expZeroDec),\n\t\tnoErrorInHandlerResult(true),\n\t}}\n\n\t// All Deleagtor Unbond half of the delegation\n\texpDlgBondedTokens1 := DelegatedToken1.QuoInt64(2)\n\texpDlgUnbondedToken1 := expDlgBondedTokens1\n\texpDlgBondedTokens2 := DelegatedToken2.QuoInt64(2)\n\texpDlgUnbondedToken2 := expDlgBondedTokens2\n\texpAllUnBondedToken1 := expDlgUnbondedToken1.Add(expDlgUnbondedToken2)\n\texpAllBondedToken1 := DefaultMSD.MulInt64(int64(len(fullVaSet))).Add(expDlgBondedTokens1).Add(expDlgBondedTokens2)\n\twithdrawChecker1 := andChecker{[]actResChecker{\n\t\tvalidatorDelegatorShareIncreased(false),\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t\tqueryDelegatorCheck(ValidDelegator1, true, originVaSet, nil, &expDlgBondedTokens1, &expDlgUnbondedToken1),\n\t\tqueryDelegatorCheck(ValidDelegator2, true, fullVaSet, nil, &expDlgBondedTokens2, &expDlgUnbondedToken2),\n\t\tqueryAllValidatorCheck([]sdk.BondStatus{sdk.Unbonded, sdk.Bonded, sdk.Unbonding}, []int{1, 4, 0}),\n\t\tquerySharesToCheck(startUpStatus.getValidator().OperatorAddress, 1, []sdk.AccAddress{ValidDelegator2}),\n\t\tqueryPoolCheck(&expAllBondedToken1, &expAllUnBondedToken1),\n\t\tqueryValidatorCheck(sdk.Unbonded, false, nil, nil, nil),\n\t}}\n\n\t// All Deleagtor Unbond the delegation left\n\texpDlgGrpUnbonded2 := expZeroDec\n\texpAllBondedToken2 := DefaultMSD.MulInt64(int64(len(fullVaSet)))\n\twithdrawChecker2 := andChecker{[]actResChecker{\n\t\t// cannot find unbonding token in GetUnbonding info\n\t\tqueryDelegatorCheck(ValidDelegator1, false, []sdk.ValAddress{}, nil, &expZeroDec, nil),\n\t\tqueryDelegatorCheck(ValidDelegator2, false, []sdk.ValAddress{}, nil, &expZeroDec, nil),\n\t\tqueryAllValidatorCheck([]sdk.BondStatus{sdk.Unbonded, sdk.Bonded, sdk.Unbonding}, []int{1, 4, 0}),\n\t\tquerySharesToCheck(startUpStatus.getValidator().OperatorAddress, 0, []sdk.AccAddress{}),\n\t\tqueryPoolCheck(&expAllBondedToken2, &expDlgGrpUnbonded2),\n\t\tqueryValidatorCheck(sdk.Unbonded, false, nil, nil, nil),\n\t}}\n\n\tinputActions := []IAction{\n\t\tcreateValidatorAction{bAction, nil},\n\t\tendBlockAction{bAction},\n\t\tdelegatorsAddSharesAction{bAction, true, false, 0, []sdk.AccAddress{ValidDelegator1}},\n\t\tendBlockAction{bAction},\n\t\tdelegatorsAddSharesAction{bAction, true, true, 0, []sdk.AccAddress{ValidDelegator2}},\n\t\tendBlockAction{bAction},\n\t\tendBlockAction{bAction},\n\t\tdelegatorsWithdrawAction{bAction, true, false},\n\t\tendBlockAction{bAction},\n\t\tendBlockAction{bAction},\n\t\tdelegatorsWithdrawAction{bAction, true, true},\n\t\twaitUntilUnbondingTimeExpired{bAction},\n\t\tendBlockAction{bAction},\n\t}\n\n\tactionsAndChecker := []actResChecker{\n\t\tstartUpCheck.GetChecker(),\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t\tvalidatorDelegatorShareIncreased(false),\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t\taddSharesChecker.GetChecker(),\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t\tnil,\n\t\twithdrawChecker1.GetChecker(),\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t\tnil,\n\t\twithdrawChecker2.GetChecker(),\n\t}\n\n\tsmTestCase := newValidatorSMTestCase(mk, params, startUpStatus, inputActions, actionsAndChecker, t)\n\tsmTestCase.SetupValidatorSetAndDelegatorSet(int(params.MaxValidators))\n\tsmTestCase.printParticipantSnapshot(t)\n\tsmTestCase.Run(t)\n\n}", "func Share(mod *big.Int, nPieces int, secret *big.Int) []*big.Int {\n\tif nPieces == 0 {\n\t\tpanic(\"Number of shares must be at least 1\")\n\t} else if nPieces == 1 {\n\t\treturn []*big.Int{secret}\n\t}\n\n\tout := make([]*big.Int, nPieces)\n\n\tacc := new(big.Int)\n\tfor i := 0; i < nPieces-1; i++ {\n\t\tout[i] = utils.RandInt(mod)\n\n\t\tacc.Add(acc, out[i])\n\t}\n\n\tacc.Sub(secret, acc)\n\tacc.Mod(acc, mod)\n\tout[nPieces-1] = acc\n\n\treturn out\n}", "func (k Keeper) AwardCoinsForRelays(ctx sdk.Ctx, relays int64, toAddr sdk.Address) sdk.BigInt {\n\treturn k.posKeeper.RewardForRelays(ctx, sdk.NewInt(relays), toAddr)\n}", "func TestDonationCase1(t *testing.T) {\n\tassert := assert.New(t)\n\tstore := newReputationStoreOnMock()\n\trep := NewTestReputationImpl(store)\n\tt1 := time.Date(1995, time.February, 5, 11, 11, 0, 0, time.UTC)\n\tt3 := time.Date(1995, time.February, 6, 12, 11, 0, 0, time.UTC)\n\tt4 := time.Date(1995, time.February, 7, 13, 11, 1, 0, time.UTC)\n\tuser1 := \"user1\"\n\tpost1 := \"post1\"\n\tpost2 := \"post2\"\n\n\t// round 2\n\trep.Update(t1.Unix())\n\trep.DonateAt(user1, post1, big.NewInt(100*OneLinoCoin))\n\tassert.Equal(big.NewInt(100*OneLinoCoin), rep.store.GetRoundPostSumStake(2, post1))\n\tassert.Equal(rep.GetReputation(user1), big.NewInt(InitialCustomerScore))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.store.GetRoundSumDp(2)) // bounded by this user's dp\n\n\t// round 3\n\trep.Update(t3.Unix())\n\t// (1 * 9 + 100) / 10\n\tassert.Equal(big.NewInt(1090000), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.GetSumRep(post1))\n\trep.DonateAt(user1, post1, big.NewInt(1*OneLinoCoin)) // does not count\n\trep.DonateAt(user1, post2, big.NewInt(900*OneLinoCoin))\n\trep.Update(t4.Unix())\n\t// (10.9 * 9 + 900) / 10\n\tassert.Equal(big.NewInt(9981000), rep.GetReputation(user1))\n\tassert.Equal([]Pid{post2}, rep.store.GetRoundResult(3))\n\t// round 4\n}", "func (s *MarketWatch) getContractItems(contract *Contract) error {\n\twg := sync.WaitGroup{}\n\n\t// Return Channels\n\trchan := make(chan []esi.GetContractsPublicItemsContractId200Ok, 100000)\n\techan := make(chan error, 100000)\n\n\titems, res, err := s.esi.ESI.ContractsApi.GetContractsPublicItemsContractId(\n\t\tcontext.Background(), contract.Contract.Contract.ContractId, nil,\n\t)\n\t// No items on the order\n\tif res != nil && (res.StatusCode == 204 || res.StatusCode == 403 || res.StatusCode == 404) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\trchan <- items\n\n\t// Figure out if there are more pages\n\tpages, err := getPages(res)\n\tif err != nil {\n\t\tlog.Printf(\"%d %v\\n\", contract.Contract.Contract.ContractId, err)\n\t\treturn err\n\t}\n\n\t// Get the other pages concurrently\n\tfor pages > 1 {\n\t\twg.Add(1) // count whats running\n\t\tgo func(page int32) {\n\t\t\tdefer wg.Done() // release when done\n\n\t\t\titems, _, err := s.esi.ESI.ContractsApi.GetContractsPublicItemsContractId(\n\t\t\t\tcontext.Background(),\n\t\t\t\tcontract.Contract.Contract.ContractId,\n\t\t\t\t&esi.GetContractsPublicItemsContractIdOpts{Page: optional.NewInt32(page)},\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\techan <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Add the contracts to the channel\n\t\t\trchan <- items\n\t\t}(pages)\n\t\tpages--\n\t}\n\n\twg.Wait()\n\n\t// Close the channels\n\tclose(rchan)\n\tclose(echan)\n\n\tfor err := range echan {\n\t\t// Fail all if one fails\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\t// Add all the contracts together\n\tfor o := range rchan {\n\t\tcontract.Contract.Items = append(contract.Contract.Items, o...)\n\t}\n\n\treturn nil\n}", "func totalExpense(s []SalaryCalculator) {\n\texpense := 0\n\tfor _, v := range s {\n\t\texpense = expense + v.CalculateSalary()\n\t}\n\tfmt.Printf(\"\\n Total Expense Per Month $%d\", expense)\n}", "func CalculatePayValue(lineCh chan *line_name_schedule.Line, doneCh chan *bool) {\n\n\t// loop for create a goroutine for each line\n\tfor {\n\t\tline, more := <- lineCh\n\t\tif more {\n\t\t\tgo calculateTotalPayValue(line)\n\t\t\tcontinue\n\t\t}\n\t\tclose(doneCh)\n\t\treturn\n\t}\n}", "func (ms mainnetSchedule) ConsensusRatio() float64 {\n\treturn mainnetConsensusRatio\n}", "func (pp *PermuteProtocol) GenShares(sk *ring.Poly, ciphertext *bfv.Ciphertext, crs *ring.Poly, permutation []uint64, share RefreshShare) {\n\n\tlevel := len(ciphertext.Value()[1].Coeffs) - 1\n\n\tringQ := pp.context.ringQ\n\tringT := pp.context.ringT\n\tringQP := pp.context.ringQP\n\n\t// h0 = s*ct[1]\n\tringQ.NTTLazy(ciphertext.Value()[1], pp.tmp1)\n\tringQ.MulCoeffsMontgomeryConstant(sk, pp.tmp1, share.RefreshShareDecrypt)\n\tringQ.InvNTTLazy(share.RefreshShareDecrypt, share.RefreshShareDecrypt)\n\n\t// h0 = s*ct[1]*P\n\tringQ.MulScalarBigint(share.RefreshShareDecrypt, pp.context.ringP.ModulusBigint, share.RefreshShareDecrypt)\n\n\t// h0 = s*ct[1]*P + e\n\tpp.gaussianSampler.ReadLvl(len(ringQP.Modulus)-1, pp.tmp1, ringQP, pp.sigma, int(6*pp.sigma))\n\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\n\n\tfor x, i := 0, len(ringQ.Modulus); i < len(pp.context.ringQP.Modulus); x, i = x+1, i+1 {\n\t\ttmphP := pp.hP.Coeffs[x]\n\t\ttmp1 := pp.tmp1.Coeffs[i]\n\t\tfor j := 0; j < ringQ.N; j++ {\n\t\t\ttmphP[j] += tmp1[j]\n\t\t}\n\t}\n\n\t// h0 = (s*ct[1]*P + e)/P\n\tpp.baseconverter.ModDownSplitPQ(level, share.RefreshShareDecrypt, pp.hP, share.RefreshShareDecrypt)\n\n\t// h1 = -s*a\n\tringQP.Neg(crs, pp.tmp1)\n\tringQP.NTTLazy(pp.tmp1, pp.tmp1)\n\tringQP.MulCoeffsMontgomeryConstant(sk, pp.tmp1, pp.tmp2)\n\tringQP.InvNTTLazy(pp.tmp2, pp.tmp2)\n\n\t// h1 = s*a + e'\n\tpp.gaussianSampler.ReadAndAdd(pp.tmp2, ringQP, pp.sigma, int(6*pp.sigma))\n\n\t// h1 = (-s*a + e')/P\n\tpp.baseconverter.ModDownPQ(level, pp.tmp2, share.RefreshShareRecrypt)\n\n\t// mask = (uniform plaintext in [0, T-1]) * floor(Q/T)\n\n\t// Mask in the time domain\n\tcoeffs := pp.uniformSampler.ReadNew()\n\n\t// Multiply by Q/t\n\tlift(coeffs, pp.tmp1, pp.context)\n\n\t// h0 = (s*ct[1]*P + e)/P + mask\n\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\n\n\t// Mask in the spectral domain\n\tringT.NTT(coeffs, coeffs)\n\n\t// Permutation over the mask\n\tpp.permuteWithIndex(coeffs, permutation, pp.tmp1)\n\n\t// Switch back the mask in the time domain\n\tringT.InvNTTLazy(pp.tmp1, coeffs)\n\n\t// Multiply by Q/t\n\tlift(coeffs, pp.tmp1, pp.context)\n\n\t// h1 = (-s*a + e')/P - permute(mask)\n\tringQ.Sub(share.RefreshShareRecrypt, pp.tmp1, share.RefreshShareRecrypt)\n}", "func distributeLockedAmount(ctx coretypes.Sandbox, bets []*BetInfo, totalLockedAmount int64) bool {\n\tsumsByPlayers := make(map[coretypes.AgentID]int64)\n\ttotalWinningAmount := int64(0)\n\tfor _, bet := range bets {\n\t\tif _, ok := sumsByPlayers[bet.Player]; !ok {\n\t\t\tsumsByPlayers[bet.Player] = 0\n\t\t}\n\t\tsumsByPlayers[bet.Player] += bet.Sum\n\t\ttotalWinningAmount += bet.Sum\n\t}\n\n\t// NOTE 1: float64 was avoided for determinism reasons\n\t// NOTE 2: beware overflows\n\n\tfor player, sum := range sumsByPlayers {\n\t\tsumsByPlayers[player] = (totalLockedAmount * sum) / totalWinningAmount\n\t}\n\n\t// make deterministic sequence by sorting. Eliminate possible rounding effects\n\tseqPlayers := make([]coretypes.AgentID, 0, len(sumsByPlayers))\n\tresultSum := int64(0)\n\tfor player, sum := range sumsByPlayers {\n\t\tseqPlayers = append(seqPlayers, player)\n\t\tresultSum += sum\n\t}\n\tsort.Slice(seqPlayers, func(i, j int) bool {\n\t\treturn bytes.Compare(seqPlayers[i][:], seqPlayers[j][:]) < 0\n\t})\n\n\t// ensure we distribute not more than totalLockedAmount iotas\n\tif resultSum > totalLockedAmount {\n\t\tsumsByPlayers[seqPlayers[0]] -= resultSum - totalLockedAmount\n\t}\n\n\t// filter out those who proportionally got 0\n\tfinalWinners := seqPlayers[:0]\n\tfor _, player := range seqPlayers {\n\t\tif sumsByPlayers[player] <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfinalWinners = append(finalWinners, player)\n\t}\n\t// distribute iotas\n\tfor i := range finalWinners {\n\n\t\tavailable := ctx.Balance(balance.ColorIOTA)\n\t\tctx.Event(fmt.Sprintf(\"sending reward iotas %d to the winner %s. Available iotas: %d\",\n\t\t\tsumsByPlayers[finalWinners[i]], finalWinners[i].String(), available))\n\n\t\t//if !ctx.MoveTokens(finalWinners[i], balance.ColorIOTA, sumsByPlayers[finalWinners[i]]) {\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}", "func sum(s []int, c chan int) {\n\tsum := 0\n\tfor _, v := range s {\n\t\tsum += v\n\t}\n\tc <- sum // send sum to c\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) Contracts(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"contracts\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (_DelegationController *DelegationControllerCallerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (_Cakevault *CakevaultCallerSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (_DelegationController *DelegationControllerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func testLeaderCycle(t *testing.T, preVote bool) {\n\tvar cfg func(*Config)\n\tif preVote {\n\t\tcfg = preVoteConfig\n\t}\n\tn := newNetworkWithConfig(cfg, nil, nil, nil)\n\tdefer n.closeAll()\n\tfor campaignerID := uint64(1); campaignerID <= 3; campaignerID++ {\n\t\tn.send(pb.Message{From: campaignerID, To: campaignerID, Type: pb.MsgHup})\n\n\t\tfor _, peer := range n.peers {\n\t\t\tsm := peer.(*raft)\n\t\t\tif sm.id == campaignerID && sm.state != StateLeader {\n\t\t\t\tt.Errorf(\"preVote=%v: campaigning node %d state = %v, want StateLeader\",\n\t\t\t\t\tpreVote, sm.id, sm.state)\n\t\t\t} else if sm.id != campaignerID && sm.state != StateFollower {\n\t\t\t\tt.Errorf(\"preVote=%v: after campaign of node %d, \"+\n\t\t\t\t\t\"node %d had state = %v, want StateFollower\",\n\t\t\t\t\tpreVote, campaignerID, sm.id, sm.state)\n\t\t\t}\n\t\t}\n\t}\n}", "func SetupContracts(chainURL string, onChainTxTimeout time.Duration) (\n\tadjudicator, asset pwallet.Address, _ error) {\n\tprng := rand.New(rand.NewSource(RandSeedForTestAccs))\n\tws, err := NewWalletSetup(prng, 2)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tonChainCred := perun.Credential{\n\t\tAddr: ws.Accs[0].Address(),\n\t\tWallet: ws.Wallet,\n\t\tKeystore: ws.KeystorePath,\n\t\tPassword: \"\",\n\t}\n\tif !isBlockchainRunning(chainURL) {\n\t\treturn nil, nil, errors.New(\"cannot connect to ganache-cli node at \" + chainURL)\n\t}\n\n\tif adjudicatorAddr == nil && assetAddr == nil {\n\t\tadjudicator = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(onChainCred.Addr), 0))\n\t\tasset = pethwallet.AsWalletAddr(crypto.CreateAddress(pethwallet.AsEthAddr(onChainCred.Addr), 1))\n\t\tadjudicatorAddr = adjudicator\n\t\tassetAddr = asset\n\t} else {\n\t\tadjudicator = adjudicatorAddr\n\t\tasset = assetAddr\n\t}\n\n\tchain, err := ethereum.NewChainBackend(chainURL, ChainConnTimeout, onChainTxTimeout, onChainCred)\n\tif err != nil {\n\t\treturn nil, nil, errors.WithMessage(err, \"initializaing chain backend\")\n\t}\n\n\terr = chain.ValidateContracts(adjudicator, asset)\n\tif err != nil {\n\t\t// Contracts not yet deployed for this ganache-cli instance.\n\t\tadjudicator, asset, err = deployContracts(chain, onChainCred)\n\t}\n\treturn adjudicator, asset, errors.WithMessage(err, \"initializaing chain backend\")\n}", "func TestDonationCase2(t *testing.T) {\n\tassert := assert.New(t)\n\tstore := newReputationStoreOnMock()\n\trep := NewTestReputationImpl(store)\n\tt1 := time.Date(1995, time.February, 5, 11, 11, 0, 0, time.UTC)\n\tt3 := time.Date(1995, time.February, 6, 12, 11, 0, 0, time.UTC)\n\tt4 := time.Date(1995, time.February, 7, 13, 11, 1, 0, time.UTC)\n\tuser1 := \"user1\"\n\tuser2 := \"user2\"\n\tuser3 := \"user3\"\n\tpost1 := \"post1\"\n\tpost2 := \"post2\"\n\n\t// round 2\n\trep.Update(t1.Unix())\n\tdp1 := rep.DonateAt(user1, post1, big.NewInt(100*OneLinoCoin))\n\tdp2 := rep.DonateAt(user2, post2, big.NewInt(1000*OneLinoCoin))\n\tdp3 := rep.DonateAt(user3, post2, big.NewInt(1000*OneLinoCoin))\n\tassert.Equal(big.NewInt(OneLinoCoin), dp1)\n\tassert.Equal(big.NewInt(OneLinoCoin), dp2)\n\tassert.Equal(big.NewInt(OneLinoCoin), dp3)\n\tassert.Equal(big.NewInt(100*OneLinoCoin), rep.store.GetRoundPostSumStake(2, post1))\n\tassert.Equal(rep.GetReputation(user1), big.NewInt(InitialCustomerScore))\n\tassert.Equal(big.NewInt(3*OneLinoCoin), rep.store.GetRoundSumDp(2)) // bounded by this user's dp\n\n\t// post1, dp, 1\n\t// post2, dp, 2\n\t// round 3\n\trep.Update(t3.Unix())\n\tassert.Equal([]Pid{post2, post1}, rep.store.GetRoundResult(2))\n\tassert.Equal(big.NewInt(1090000), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(13943027), rep.GetReputation(user2))\n\tassert.Equal(big.NewInt(6236972), rep.GetReputation(user3))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.GetSumRep(post1))\n\tassert.Equal(big.NewInt(2*OneLinoCoin), rep.GetSumRep(post2))\n\n\t// user1: 10.9\n\t// user2: 139.43027\n\t// user3: 62.36972\n\tdp1 = rep.DonateAt(user2, post2, big.NewInt(200*OneLinoCoin))\n\tdp2 = rep.DonateAt(user1, post1, big.NewInt(400*OneLinoCoin))\n\t// does not count because rep used up.\n\tdp3 = rep.DonateAt(user1, post1, big.NewInt(900*OneLinoCoin))\n\tdp4 := rep.DonateAt(user3, post1, big.NewInt(500*OneLinoCoin))\n\tassert.Equal(big.NewInt(13943027-OneLinoCoin), dp1)\n\tassert.Equal(big.NewInt(1090000-OneLinoCoin), dp2)\n\tassert.Equal(BigIntZero, dp3)\n\tassert.Equal(big.NewInt(6236972), dp4)\n\n\t// round 4\n\trep.Update(t4.Unix())\n\tassert.Equal([]Pid{post2, post1}, rep.store.GetRoundResult(3))\n\tassert.Equal(big.NewInt(16136841), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(14548724), rep.GetReputation(user2))\n\tassert.Equal(big.NewInt(8457432), rep.GetReputation(user3))\n}" ]
[ "0.7617152", "0.7309428", "0.72370875", "0.68309754", "0.6308223", "0.61517656", "0.60849655", "0.5973892", "0.59176695", "0.5554153", "0.5120732", "0.5011268", "0.49605462", "0.49056253", "0.4874525", "0.48609063", "0.48357624", "0.48321053", "0.48303255", "0.48050258", "0.47735748", "0.47197926", "0.47174463", "0.47156247", "0.47046614", "0.4635779", "0.46280932", "0.45870832", "0.4555822", "0.45556647", "0.4553067", "0.45518237", "0.45353988", "0.45330775", "0.4532603", "0.4514857", "0.45143226", "0.44984138", "0.4489991", "0.4479593", "0.4476542", "0.4454902", "0.44379687", "0.4428233", "0.4415868", "0.4412239", "0.4400673", "0.43956044", "0.43807057", "0.43646106", "0.4355781", "0.4351919", "0.43502742", "0.43441474", "0.43402097", "0.43351007", "0.4333106", "0.43279257", "0.43235296", "0.4323371", "0.43207857", "0.43165874", "0.43159467", "0.43154135", "0.43147263", "0.43124002", "0.430879", "0.43067995", "0.430646", "0.4292392", "0.42812568", "0.42770913", "0.42725456", "0.42717326", "0.42404893", "0.4218741", "0.42058355", "0.42058355", "0.4187219", "0.41856405", "0.41847926", "0.4181087", "0.41767076", "0.41725764", "0.4168574", "0.41653484", "0.41605163", "0.4159988", "0.41501185", "0.4146732", "0.41457835", "0.4139794", "0.4136418", "0.4136152", "0.4133652", "0.41281477", "0.41232142", "0.4123117", "0.41123554", "0.40939748" ]
0.7727162
0
/ Description: A function to account for incomplete rolls, and the payouts associated with that TODO: In Progress
func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) { stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle) if (err != nil){ return delegatedContracts, errors.New("func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: " + err.Error()) } mod := math.Mod(stakingBalance, 10000) sum := mod * 10000 for index, delegatedContract := range delegatedContracts{ for i, contract := range delegatedContract.Contracts{ if (contract.Cycle == cycle){ stakingBalance = stakingBalance - contract.Amount if (stakingBalance < 0){ delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum } } } } return delegatedContracts, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func journalAssessment(ctx context.Context, xbiz *XBusiness, d time.Time, a *Assessment, d1, d2 *time.Time) (Journal, error) {\n\tfuncname := \"journalAssessment\"\n\t// Console(\"*** Entered %s\\n\", funcname)\n\t// Console(\"%s: d = %s, d1 = %s, d2 = %s\\n\", funcname, d.Format(RRDATEREPORTFMT), d1.Format(RRDATEREPORTFMT), d2.Format(RRDATEREPORTFMT))\n\t// Console(\"%s: Assessment: PASMID = %d, RentCycle = %d, ProrationCycle = %d, Start = %s, Stop = %s\\n\", funcname, a.PASMID, a.RentCycle, a.ProrationCycle, a.Start.Format(RRDATETIMEW2UIFMT), a.Stop.Format(RRDATETIMEW2UIFMT))\n\tvar j Journal\n\n\t// pf, num, den, start, stop, err := ProrateAssessment(ctx, xbiz, a, &d, d1, d2)\n\tpf, _, _, _, _, err := ProrateAssessment(ctx, xbiz, a, &d, d1, d2)\n\tif err != nil {\n\t\t// Console(\"%s: exiting. err = %s\\n\", funcname, err.Error())\n\t\treturn j, err\n\t}\n\n\t// Console(\"%s: A:: **** AFTER PRORATION CHECK **** pf = %6.4f, num = %d, den = %d, start = %s, stop = %s\\n\", funcname, pf, num, den, start.Format(RRDATEFMT3), stop.Format(RRDATEFMT3))\n\t// Console(\"%s: B:: After ProrateAssessment: start = %s, stop = %s\\n\", funcname, start.Format(RRDATETIMEW2UIFMT), stop.Format(RRDATETIMEW2UIFMT))\n\n\t//--------------------------------------------------------------------------------------\n\t// This is a safeguard against issues encountered in Feb 2018 where rent assessments\n\t// continued after the RentalAgreement RentStop date.\n\t//--------------------------------------------------------------------------------------\n\tif pf < float64(0) {\n\t\tpf = float64(0)\n\t}\n\n\t// Console(\"%s: a.ASMTID = %d, d = %s, d1 = %s, d2 = %s\\n\", funcname, a.ASMID, d.Format(RRDATEFMT4), d1.Format(RRDATEFMT4), d2.Format(RRDATEFMT4))\n\t// Console(\"%s: pf = %f, num = %d, den = %d, start = %s, stop = %s\\n\", funcname, pf, num, den, start.Format(RRDATEFMT4), stop.Format(RRDATEFMT4))\n\n\tj = Journal{BID: a.BID, Dt: d, Type: JNLTYPEASMT, ID: a.ASMID}\n\n\tasmRules, err := GetAssessmentAccountRule(ctx, a)\n\tif err != nil {\n\t\t// Console(\"%s: exiting. err = %s\\n\", funcname, err.Error())\n\t\treturn j, err\n\t}\n\n\t// Console(\"%s: C:: Parsing account rule: %s Amount = %8.2f\\n\", funcname, asmRules, a.Amount)\n\tm, err := ParseAcctRule(ctx, xbiz, a.RID, d1, d2, asmRules, a.Amount, pf) // a rule such as \"d 11001 1000.0, c 40001 1100.0, d 41004 100.00\"\n\tif err != nil {\n\t\t// Console(\"%s: C1:: exiting. err = %s\\n\", funcname, err.Error())\n\t\treturn j, err\n\t}\n\n\t// Console(\"%s: m = %#v\\n\", funcname, m)\n\t// for i := 0; i < len(m); i++ {\n\t// \tConsole(\"D:: m[%d].Amount = %f, .Action = %s .Expr = %s\\n\", i, m[i].Amount, m[i].Action, m[i].Expr)\n\t// }\n\n\t_, j.Amount = sumAllocations(&m)\n\tj.Amount = RoundToCent(j.Amount)\n\n\t// Console(\"%s: E:: j.Amount = %8.2f, pf = %8.5f\\n\", funcname, j.Amount, pf)\n\n\t//------------------------------------------------------------------------------------------------------\n\t// THIS BLOCK OF CODE SHOULD BE DELETED. IT SHOULD BE HANDLED IN ASSESSMENT CODE, NOT JOURNAL CODE.\n\t//=====================================================================================================\n\t// the assessment amount may have\n\t// been prorated as it was a newly created recurring assessment for a RentalAgreement that was either\n\t// just beginning or just ending. If so, we'll update the assessment amount here the calculated\n\t// j.Amount != a.Amount\n\t//------------------------------------------------------------------------------------------------------\n\t// if pf < 1.0 {\n\t// \tConsole(\"%s: F:: will update assessment\\n\", funcname)\n\t// \ta.Amount = j.Amount // update to the prorated amount\n\t// \ta.Start = start // adjust to the dates used in the proration\n\t// \ta.Stop = stop // adjust to the dates used in the proration\n\t// \ta.Comment = fmt.Sprintf(\"Prorated for %d of %d %s\", num, den, ProrationUnits(a.ProrationCycle))\n\t// \tConsole(\"%s: G:: a.Amount = %8.2f\\n\", funcname, a.Amount)\n\t// \tif err := UpdateAssessment(ctx, a); err != nil {\n\t// \t\terr = fmt.Errorf(\"Error updating prorated assessment amount: %s\", err.Error())\n\t// \t\tConsole(\"%s: H:: exiting. err = %s\\n\", funcname, err.Error())\n\t// \t\treturn j, err\n\t// \t}\n\t// \tConsole(\"%s: I:: Updating ASMID = %d, Amount = %8.2f\\n\", funcname, a.ASMID, a.Amount)\n\t// }\n\t// Console(\"%s: J:: ASMID = %d, Amount = %8.2f\\n\", funcname, a.ASMID, a.Amount)\n\n\t//-------------------------------------------------------------------------------------------\n\t// In the event that we need to prorate, pull together the pieces and determine the\n\t// fractional amounts so that all the entries can net to 0.00. Essentially, this means\n\t// handling the $0.01 off problem when dealing with fractional numbers. The way we'll\n\t// handle this is to apply the extra cent to the largest number\n\t//-------------------------------------------------------------------------------------------\n\tif pf < 1.0 {\n\t\t// new method using ProcessSum\n\t\tvar asum []SumFloat\n\t\tfor i := 0; i < len(m); i++ {\n\t\t\tvar b SumFloat\n\t\t\tif m[i].Action == \"c\" {\n\t\t\t\tb.Val = -m[i].Amount\n\t\t\t} else {\n\t\t\t\tb.Val = m[i].Amount\n\t\t\t}\n\t\t\tb.Amount = RoundToCent(b.Val)\n\t\t\tb.Remainder = b.Amount - b.Val\n\t\t\tasum = append(asum, b)\n\t\t}\n\t\tProcessSumFloats(asum)\n\t\tfor i := 0; i < len(asum); i++ {\n\t\t\tif m[i].Action == \"c\" {\n\t\t\t\tm[i].Amount = -asum[i].Amount // the adjusted value after ProcessSumFloats\n\t\t\t} else {\n\t\t\t\tm[i].Amount = asum[i].Amount // the adjusted value after ProcessSumFloats\n\t\t\t}\n\t\t}\n\n\t}\n\n\t// Console(\"INSERTING JOURNAL: Date = %s, Type = %d, amount = %f\\n\", j.Dt, j.Type, j.Amount)\n\n\tjid, err := InsertJournal(ctx, &j)\n\tif err != nil {\n\t\tLogAndPrintError(funcname, err)\n\t\t// Console(\"%s: exiting. err = %s\\n\", funcname, err.Error())\n\t\treturn j, err\n\t}\n\n\ts := \"\"\n\tfor i := 0; i < len(m); i++ {\n\t\ts += fmt.Sprintf(\"%s %s %.2f\", m[i].Action, m[i].AcctExpr, RoundToCent(m[i].Amount))\n\t\tif i+1 < len(m) {\n\t\t\ts += \", \"\n\t\t}\n\t}\n\tif jid > 0 {\n\t\tvar ja JournalAllocation\n\t\tja.JID = jid\n\t\tja.RID = a.RID\n\t\tja.ASMID = a.ASMID\n\t\tja.Amount = RoundToCent(j.Amount)\n\t\tja.AcctRule = s\n\t\tja.BID = a.BID\n\t\tja.RAID = a.RAID\n\n\t\t// Console(\"INSERTING JOURNAL-ALLOCATION: ja.JID = %d, ja.ASMID = %d, ja.RAID = %d\\n\", ja.JID, ja.ASMID, ja.RAID)\n\t\tif _, err = InsertJournalAllocationEntry(ctx, &ja); err != nil {\n\t\t\tLogAndPrintError(funcname, err)\n\t\t\t// Console(\"%s: exiting. err = %s\\n\", funcname, err.Error())\n\t\t\treturn j, err\n\t\t}\n\t\tj.JA = append(j.JA, ja)\n\t}\n\n\t// Console(\"%s: exiting\\n\", funcname)\n\treturn j, err\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (r *AutoRoller) rollFinished(ctx context.Context, justFinished codereview.RollImpl) error {\n\trecent := r.recent.GetRecentRolls()\n\t// Sanity check: pop any rolls which occurred after the one which just\n\t// finished.\n\tidx := -1\n\tvar currentRoll *autoroll.AutoRollIssue\n\tfor i, roll := range recent {\n\t\tissue := fmt.Sprintf(\"%d\", roll.Issue)\n\t\tif issue == justFinished.IssueID() {\n\t\t\tidx = i\n\t\t\tcurrentRoll = roll\n\t\t\tbreak\n\t\t}\n\t}\n\tif currentRoll == nil {\n\t\treturn skerr.Fmt(\"Unable to find just-finished roll %q in recent list!\", justFinished.IssueID())\n\t}\n\n\t// Feed AutoRoll stats into metrics.\n\tv := int64(0)\n\tif currentRoll.Closed && currentRoll.Committed {\n\t\tv = int64(1)\n\t}\n\tmetrics2.GetInt64Metric(\"autoroll_last_roll_result\", map[string]string{\"roller\": r.cfg.RollerName}).Update(v)\n\n\trecent = recent[idx:]\n\tvar lastRoll *autoroll.AutoRollIssue\n\tif len(recent) > 1 {\n\t\tlastRoll = recent[1]\n\t} else {\n\t\t// If there are no other rolls, then the below alerts do not apply.\n\t\treturn nil\n\t}\n\n\tissueURL := fmt.Sprintf(\"%s%d\", r.codereview.GetIssueUrlBase(), currentRoll.Issue)\n\n\t// Send notifications if this roll had a different result from the last\n\t// roll, ie. success -> failure or failure -> success.\n\tcurrentSuccess := util.In(currentRoll.Result, autoroll.SUCCESS_RESULTS)\n\tlastSuccess := util.In(lastRoll.Result, autoroll.SUCCESS_RESULTS)\n\tif lastRoll != nil {\n\t\tif currentSuccess && !lastSuccess {\n\t\t\tr.notifier.SendNewSuccess(ctx, fmt.Sprintf(\"%d\", currentRoll.Issue), issueURL)\n\t\t} else if !currentSuccess && lastSuccess {\n\t\t\tr.notifier.SendNewFailure(ctx, fmt.Sprintf(\"%d\", currentRoll.Issue), issueURL)\n\t\t}\n\t}\n\n\t// Send a notification if the last N rolls failed in a row.\n\tnFailed := 0\n\t// recent is in reverse chronological order.\n\tfor _, roll := range recent {\n\t\tif util.In(roll.Result, autoroll.SUCCESS_RESULTS) {\n\t\t\tbreak\n\t\t} else {\n\t\t\tnFailed++\n\t\t}\n\t}\n\tif nFailed == notifyIfLastNFailed {\n\t\tr.notifier.SendLastNFailed(ctx, notifyIfLastNFailed, issueURL)\n\t}\n\n\treturn nil\n}", "func DummyRoll(dieType int) int {\n\treturn dieType / 2\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func (db *DB) Roll() {\n\tr := rand.Intn(50)\n\n\tif db.ActiveReq.Requests[r].Shown == 0 {\n\t\treturn\n\t}\n\n\tdb.InactiveReq.Requests = append(db.InactiveReq.Requests, db.ActiveReq.Requests[r])\n\n\tdb.ActiveReq.Requests[r] = &Request{\n\t\tData: strRand.String(2),\n\t\tShown: 0,\n\t}\n}", "func (m *WebsocketRoutineManager) printAccountHoldingsChangeSummary(o account.Change) {\n\tif m == nil || atomic.LoadInt32(&m.state) == stoppedState {\n\t\treturn\n\t}\n\tlog.Debugf(log.WebsocketMgr,\n\t\t\"Account Holdings Balance Changed: %s %s %s has changed balance by %f for account: %s\",\n\t\to.Exchange,\n\t\to.Asset,\n\t\to.Currency,\n\t\to.Amount,\n\t\to.Account)\n}", "func TestRoll(t *testing.T) {\n\ttype response struct {\n\t\tCode int\n\t\tBody string\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs string\n\t\twant response\n\t}{\n\t\t{\"Default roll\", \"\", response{http.StatusOK, ``}},\n\t\t{\"Valid query for sides\", \"?sides=4\", response{http.StatusOK, `\"sides\":4`}},\n\t\t{\"Invalid query for sides\", \"?sides=5\", response{http.StatusNotAcceptable, `\"invalid sides\"`}},\n\t\t{\"Valid query for count\", \"?count=2\", response{http.StatusOK, `\"count\":2`}},\n\t\t{\"Invalid query for count\", \"?count=0\", response{http.StatusNotAcceptable, `\"invalid count\"`}},\n\t\t{\"Valid query for sides, invalid for count\", \"?sides=4&count=0\", response{http.StatusNotAcceptable, `\"invalid count\"`}},\n\t\t{\"Valid query for count, invalid for sides\", \"?count=2&sides=1\", response{http.StatusNotAcceptable, `\"invalid sides\"`}},\n\t\t{\"Valid query for sides and count\", \"?sides=4&count=2\", response{http.StatusOK, `\"count\":2,\"sides\":4`}},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tr := gofight.New()\n\n\t\t\tr.GET(\"/api/v1/roll\"+tt.args).\n\t\t\t\tRun(router, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {\n\t\t\t\t\tif r.Code != tt.want.Code {\n\t\t\t\t\t\tt.Errorf(\"Handler returned wrong status code: got %v want %v\", r.Code, tt.want.Code)\n\t\t\t\t\t}\n\n\t\t\t\t\tif !bytes.Contains(r.Body.Bytes(), []byte(tt.want.Body)) {\n\t\t\t\t\t\tt.Errorf(\"Unexpected body returned.\\ngot %v\\nwant %v\", r.Body, tt.want.Body)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t})\n\t}\n}", "func (p PgDb) CheckAndTriggerPayout(referrer User, payoutType PayoutType) (Payout, bool, error) {\n\tvar lastCheckpoint int\n\tvar payout Payout\n\n\tcheckpointQ := \"SELECT checkpoint_id FROM payouts WHERE user_id=$1 AND activity_type=$2 ORDER BY id DESC LIMIT 1\"\n\terr := p.Conn.QueryRow(checkpointQ, referrer.ID, payoutType).Scan(&lastCheckpoint)\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn payout, false, err\n\t}\n\n\tif payoutType == Signups {\n\t\tfriends := make([]User, MinReferrals)\n\t\terr = p.copyFriendsForSignups(friends, referrer, lastCheckpoint)\n\t\tif err != nil {\n\t\t\treturn payout, false, err\n\t\t}\n\n\t\tp.Logger.Info().Msgf(\"processing signup payouts because %+v\", friends)\n\n\t\t// pick the last user in the list to use as checkpoint\n\t\tnewCheckpoint := friends[MinReferrals-1]\n\t\tif newCheckpoint.ID == 0 {\n\t\t\treturn payout, false, nil\n\t\t}\n\n\t\tvar amount string\n\t\tnewPayoutQ := \"INSERT INTO payouts(user_id, activity_type, checkpoint_id, amount, status) VALUES($1, $2, $3, $4, $5) RETURNING id, user_id, activity_type, checkpoint_id, amount, status\"\n\t\terr = p.Conn.QueryRow(newPayoutQ, referrer.ID, Signups, newCheckpoint.ID, ReferralBonus, Pending).Scan(\n\t\t\t&payout.ID, &payout.UserID, &payout.Type, &payout.CheckpointID, &amount, &payout.Status,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn payout, false, err\n\t\t} else {\n\t\t\tpayout.Amount, _ = decimal.NewFromString(amount)\n\t\t\tpayout.Username = referrer.Username\n\t\t}\n\t} else if payoutType == Transactions {\n\t\ttxns := make([]Transaction, MinReferrals)\n\t\terr = p.copyFriendsForTransactions(txns, referrer, lastCheckpoint)\n\t\tif err != nil {\n\t\t\treturn payout, false, err\n\t\t}\n\n\t\tp.Logger.Info().Msgf(\"processing txn payouts because %+v\", txns)\n\t\t// pick the last user in the list to use as checkpoint\n\t\tnewCheckpoint := txns[MinReferrals-1]\n\t\tif newCheckpoint.ID == 0 {\n\t\t\treturn payout, false, nil\n\t\t}\n\n\t\tvar amount string\n\t\tnewPayoutQ := \"INSERT INTO payouts(user_id, activity_type, checkpoint_id, amount, status) VALUES($1, $2, $3, $4, $5) RETURNING id, user_id, activity_type, checkpoint_id, amount, status\"\n\t\terr = p.Conn.QueryRow(newPayoutQ, referrer.ID, Transactions, newCheckpoint.ID, ReferralBonus, Pending).Scan(\n\t\t\t&payout.ID, &payout.UserID, &payout.Type, &payout.CheckpointID, &amount, &payout.Status,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn payout, false, err\n\t\t} else {\n\t\t\tpayout.Amount, _ = decimal.NewFromString(amount)\n\t\t\tpayout.Username = referrer.Username\n\t\t}\n\t}\n\treturn payout, true, nil\n}", "func TestRollN(t *testing.T) {\n\ttype response struct {\n\t\tCode int\n\t\tBody string\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs string\n\t\twant response\n\t}{\n\t\t{\"Valid roll\", \"/d4\", response{http.StatusOK, `\"sides\":4`}},\n\t\t{\"Valid roll\", \"/D4\", response{http.StatusOK, `\"sides\":4`}},\n\t\t{\"Invalid variable\", \"/d5\", response{http.StatusNotAcceptable, `\"error\"`}},\n\t\t{\"Invalid variable\", \"/D5\", response{http.StatusNotAcceptable, `\"error\"`}},\n\t\t{\"Valid query for count\", \"/d4?count=2\", response{http.StatusOK, `\"count\":2,\"sides\":4`}},\n\t\t{\"Valid query for count\", \"/D4?count=2\", response{http.StatusOK, `\"count\":2,\"sides\":4`}},\n\t\t{\"Invalid query for count\", \"/d4?count=0\", response{http.StatusNotAcceptable, `\"error\"`}},\n\t\t{\"Invalid query for count\", \"/D4?count=0\", response{http.StatusNotAcceptable, `\"error\"`}},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tr := gofight.New()\n\n\t\t\tr.GET(\"/api/v1/roll\"+tt.args).\n\t\t\t\tRun(router, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {\n\t\t\t\t\tif r.Code != tt.want.Code {\n\t\t\t\t\t\tt.Errorf(\"Handler returned wrong status code: got %v want %v\", r.Code, tt.want.Code)\n\t\t\t\t\t}\n\n\t\t\t\t\tif !bytes.Contains(r.Body.Bytes(), []byte(tt.want.Body)) {\n\t\t\t\t\t\tt.Errorf(\"Unexpected body returned.\\ngot %v\\nwant %v\", r.Body, tt.want.Body)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t})\n\t}\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func Roll(w http.ResponseWriter, r *http.Request) {\n\tsides := r.FormValue(\"sides\")\n\tcount := r.FormValue(\"count\")\n\n\ts := getSides(sides)\n\tif s == 0 {\n\t\tsidesErrResponse(w)\n\t\treturn\n\t}\n\n\tc := getCount(count)\n\tif c == 0 {\n\t\tcountErrResponse(w)\n\t\treturn\n\t}\n\n\tresponse(w, s, c)\n}", "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func (game *Game) Roll(pinsDown int) {\n\tgame.currentFrame.Roll(pinsDown)\n\n\tif game.currentFrame.IsComplete() {\n\t\tgame.score += game.beforePreviousFrame.Bonus(\n\t\t\tgame.previousFrame,\n\t\t\tgame.currentFrame,\n\t\t)\n\t\tgame.score += game.currentFrame.Score()\n\t\tgame.beforePreviousFrame = game.previousFrame\n\t\tgame.previousFrame = game.currentFrame\n\t\tgame.currentFrame = *new(Frame)\n\t}\n}", "func (g *testGenerator) oldestCoinbaseOuts() []spendableOut {\n\touts := g.spendableOuts[0]\n\tg.spendableOuts = g.spendableOuts[1:]\n\treturn outs\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{\n for _, delegatedContract := range delegatedContracts {\n err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias)\n if (err != nil){\n return errors.New(\"Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: \" + err.Error())\n }\n }\n return nil\n}", "func ProrateAssessment(ctx context.Context, xbiz *XBusiness, a *Assessment, d, d1, d2 *time.Time) (float64, int64, int64, time.Time, time.Time, error) {\n\tconst funcname = \"ProrateAssessment\"\n\n\tvar pf float64\n\tvar num, den int64\n\tvar start, stop time.Time\n\tvar r Rentable\n\tvar err error\n\n\t// Console(\"ProrateAssessment: A\\n\")\n\tuseStatus := int64(USESTATUSinService) // if RID==0, then it's for an application fee or similar. Assume rentable is online.\n\tuseType := int64(USETYPEstandard)\n\n\tif a.RID > 0 {\n\t\t// Console(\"ProrateAssessment: B\\n\")\n\t\tr, err = GetRentable(ctx, a.RID)\n\t\tif err != nil {\n\t\t\treturn pf, num, den, start, stop, err\n\t\t}\n\n\t\tuseStatus, err = GetRentableStateForDate(ctx, r.RID, d)\n\t\tif err != nil {\n\t\t\treturn pf, num, den, start, stop, err\n\t\t}\n\t\tuseType, err = GetRentableUseTypeForDate(ctx, r.RID, d)\n\t\tif err != nil {\n\t\t\treturn pf, num, den, start, stop, err\n\t\t}\n\t}\n\n\t// Console(\"ProrateAssessment: C\\n\")\n\t// Console(\"GetRentableStateForDate( %d, %s ) = %d\\n\", r.RID, d.Format(RRDATEINPFMT), useStatus)\n\tif useType == USETYPEstandard || useType == USETYPEemployee { /*useStatus == USESTATUSready || useStatus == USETYPEemployee || useStatus == USESTATUSinService &&*/\n\t\t// Console(\"ProrateAssessment: D\\n\")\n\t\t// Console(\"%s: at case USESTATUSinService.\\n\", funcname)\n\t\tra, err := GetRentalAgreement(ctx, a.RAID)\n\t\tif err != nil {\n\t\t\tUlog(\"ProrateAssessment: error getting rental agreement RAID=%d, err = %s\\n\", a.RAID, err.Error())\n\t\t} else {\n\t\t\t// Console(\"ProrateAssessment: E\\n\")\n\t\t\tswitch a.RentCycle {\n\t\t\tcase RECURDAILY:\n\t\t\t\t// Console(\"%s: RECURDAILY: ra.RAID = %d, ra.RentStart = %s, ra.RentStop = %s\\n\", funcname, ra.RAID, ra.RentStart.Format(RRDATEFMT4), ra.RentStop.Format(RRDATEFMT4))\n\t\t\t\tpf, num, den, start, stop = CalcProrationInfo(&ra.RentStart, &ra.RentStop, d, d, a.RentCycle, a.ProrationCycle)\n\t\t\tcase RECURNONE:\n\t\t\t\tfallthrough\n\t\t\tcase RECURMONTHLY:\n\t\t\t\t// Console(\"%s: RECURMONTHLY: ra.RAID = %d, ra.RentStart = %s, ra.RentStop = %s\\n\", funcname, ra.RAID, ra.RentStart.Format(RRDATEFMT4), ra.RentStop.Format(RRDATEFMT4))\n\t\t\t\tpf, num, den, start, stop = CalcProrationInfo(&ra.RentStart, &ra.RentStop, d1, d2, a.RentCycle, a.ProrationCycle)\n\t\t\tdefault:\n\t\t\t\tLogAndPrint(\"Accrual rate %d not implemented\\n\", a.RentCycle)\n\t\t\t}\n\t\t}\n\t\t// Console(\"Assessment = %d, Rentable = %d, RA = %d, pf = %3.2f\\n\", a.ASMID, r.RID, ra.RAID, pf)\n\t} else if useType == USETYPEadministrative || useType == USETYPEownerOccupied { //useStatus == USETYPEadministrative || useStatus == USETYPEownerOccupied\n\t\t// Console(\"ProrateAssessment: F\\n\")\n\t\tta, err := GetASMInstancesByRIDandDateRange(ctx, r.RID, d1, d2)\n\t\tif err != nil {\n\t\t\treturn pf, num, den, start, stop, nil\n\t\t}\n\n\t\tif len(ta) > 0 {\n\t\t\trentcycle, proration, _, err := GetRentCycleAndProration(ctx, &r, d1, xbiz)\n\t\t\tif err != nil {\n\t\t\t\tUlog(\"%s: error getting rent cycle for rentable %d. err = %s\\n\", funcname, r.RID, err.Error())\n\t\t\t\treturn pf, num, den, start, stop, err\n\t\t\t}\n\n\t\t\tpf, num, den, start, stop = CalcProrationInfo(&(ta[0].Start), &(ta[0].Stop), d1, d2, rentcycle, proration)\n\t\t\tif len(ta) > 1 {\n\t\t\t\tUlog(\"%s: %d Assessments affect Rentable %d (%s) with OFFLINE useStatus during %s - %s\\n\",\n\t\t\t\t\tfuncname, len(ta), r.RID, r.RentableName, d1.Format(RRDATEINPFMT), d2.Format(RRDATEINPFMT))\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Console(\"ProrateAssessment: G\\n\")\n\t\tUlog(\"%s: Rentable %d on %s has unknown useStatus: %d and useType %d\\n\", funcname, r.RID, d.Format(RRDATEINPFMT), useStatus, useType)\n\t}\n\n\treturn pf, num, den, start, stop, err\n}", "func endRound(g *Game, ai AI) {\n\tdScore := Score(g.dealer...)\n\tdBlackjack := Blackjack(g.dealer...)\n\tallHands := make([][]deck.Card, len(g.player))\n\n\tfor hi, hand := range g.player {\n\t\tallHands[hi] = hand.cards\n\t\tcards := hand.cards\n\t\tpScore, pBlackjack := Score(cards...), Blackjack(cards...)\n\t\twinnings := hand.bet\n\t\tswitch {\n\t\t// if dealer is a blackjack, but you also have a blackjack, it's a draw\n\t\tcase dBlackjack && pBlackjack:\n\t\t\twinnings = 0\n\t\t// no matter what, if dealer has a blackjack, player lose\n\t\tcase dBlackjack:\n\t\t\twinnings *= -1\n\t\tcase pBlackjack:\n\t\t\twinnings *= int(float64(winnings) * g.blackjackPayout)\n\t\t\t// not sure if there is other way than typecasting\n\t\tcase pScore > 21:\n\t\t\twinnings *= -1\n\t\tcase dScore > 21:\n\t\t\t// win\n\t\tcase pScore > dScore:\n\t\t\t// win\n\t\tcase dScore > pScore:\n\t\t\twinnings *= -1\n\t\tcase pScore == dScore:\n\t\t\twinnings = 0\n\t\t}\n\t\tg.balance += winnings\n\t}\n\tai.Summary(allHands, g.dealer)\n\tg.player = nil\n\tg.dealer = nil\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}", "func test_claimPRLInsufficientFunds(t *testing.T) {\n\n\tt.Skip(nil)\n\n\t// Receiver\n\treceiverAddress := prlAddress03\n\n\t// Treasure Wallet\n\tprlWallet := getWallet(prl2File)\n\ttreasureAddress := prlWallet.Address\n\ttreasurePrivateKey := prlWallet.PrivateKey\n\n\t// Claim PRL\n\tclaimed := eth_gateway.EthWrapper.ClaimPRL(receiverAddress, treasureAddress, treasurePrivateKey)\n\tif !claimed {\n\t\tt.Log(\"Failed to claim PRLs\") // expected result\n\t} else {\n\t\tt.Log(\"PRLs have been successfully claimed\") // not expected\n\t}\n\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 NewOutcomeNotCompleted() Outcome { return Outcome{Winner: Transparent, Reason: notCompleted} }", "func (btc *ExchangeWallet) lockedSats() (uint64, error) {\n\tlockedOutpoints, err := btc.wallet.ListLockUnspent()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, outPoint := range lockedOutpoints {\n\t\topID := outpointID(outPoint.TxID, outPoint.Vout)\n\t\tutxo, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tsum += utxo.amount\n\t\t\tcontinue\n\t\t}\n\t\ttxHash, err := chainhash.NewHashFromStr(outPoint.TxID)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttxOut, err := btc.node.GetTxOut(txHash, outPoint.Vout, true)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif txOut == nil {\n\t\t\t// Must be spent now?\n\t\t\tbtc.log.Debugf(\"ignoring output from listlockunspent that wasn't found with gettxout. %s\", opID)\n\t\t\tcontinue\n\t\t}\n\t\tsum += toSatoshi(txOut.Value)\n\t}\n\treturn sum, nil\n}", "func accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {\n\t// TODO: implement mining rewards\n}", "func deductTransactions(p int) ([]Balance, error) {\n\t//First go through transactions newest -> oldest, in order to set how many points are available\n\t// at each transaction (if a future transaction is negative, then the current transaction\n\t// cannot have more points available than the future transaction amount)\n\treturnList := []Balance{}\n\tvar deductions map[string]Balance = make(map[string]Balance)\n\tvar futureDeductions map[string]int = make(map[string]int)\n\tvar availableHere []int = make([]int, len(sortedTransactions))\n\tfor i := len(sortedTransactions) - 1; i >= 0; i-- {\n\t\tcur := sortedTransactions[i]\n\t\t_, prs := futureDeductions[cur.Payer]\n\t\t//if the payer has a pending future deduction\n\t\tif prs {\n\t\t\tif cur.Points < 0 { //if this transaction is also a deduction\n\t\t\t\tfutureDeductions[cur.Payer] += cur.Points\n\t\t\t\tavailableHere[i] = 0\n\t\t\t\tcontinue\n\t\t\t} else { //if this transaction can reduce the future deduction amount\n\t\t\t\tfutureDeductions[cur.Payer] += cur.Points\n\t\t\t\tif futureDeductions[cur.Payer] >= 0 { //this transaction is more positive than future deductions\n\t\t\t\t\tavailableHere[i] = futureDeductions[cur.Payer]\n\t\t\t\t\tdelete(futureDeductions, cur.Payer)\n\t\t\t\t} else { //this transaction is not enough to offset future deductions\n\t\t\t\t\tavailableHere[i] = 0\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t} else { //if the payer currently has no pending future deductions\n\t\t\tif cur.Points < 0 { //if this is a deduction\n\t\t\t\tfutureDeductions[cur.Payer] = cur.Points\n\t\t\t\tavailableHere[i] = 0\n\t\t\t\tcontinue\n\t\t\t} else { //this is a positive amount and the player has no current deductions pending\n\t\t\t\tavailableHere[i] = cur.Points\n\t\t\t}\n\t\t}\n\t}\n\n\t//Next iterate through transactions oldest -> newest, keeping track of how much to deduct from each payer\n\t// with a *positive* \"availableHere\" value. Update the current payer's temporary deduction balance's points\n\t// with the negative of min(remaining balance, availableHere value)\n\t//Continue this for each transaction until the remaining balance is 0. if we go through all the transactions\n\t// and we are still > 0, return an error and say that there are not enough points.\n\t// Otherwise, the remaining balance hit 0 and we can add each deduction transaction and return the balances to the user\n\tremainingBalance := p\n\tfor b := range sortedTransactions {\n\t\t//skip deductions\n\t\tif sortedTransactions[b].Points <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\t//establish current payer\n\t\tcurPayer := sortedTransactions[b].Payer\n\t\t//exit to return output\n\t\tif remainingBalance == 0 {\n\t\t\tbreak\n\t\t} else if availableHere[b] > 0 { //this payer has points available\n\t\t\tdeductions[curPayer] = Balance{curPayer, -1 * int(math.Min(float64(availableHere[b]), float64(remainingBalance)))}\n\t\t\tremainingBalance += deductions[curPayer].Points\n\t\t}\n\n\t}\n\tif remainingBalance == 0 {\n\t\t//create transactions for every payer's deductions and populate balances return list\n\t\tfor pyr, pnts := range deductions {\n\t\t\tadd(Transaction{pyr, pnts.Points, time.Now().Format(time.RFC3339)})\n\t\t\treturnList = append(returnList, pnts)\n\t\t}\n\t\tsort.Sort(sortedTransactions)\n\t\treturn returnList, nil\n\n\t} else {\n\t\treturn returnList, errors.New(\"Insufficent points to spend\")\n\t}\n\n}", "func (k Keeper) AccrueInterest(ctx sdk.Context, denom string) error {\n\tpreviousAccrualTime, found := k.GetPreviousAccrualTime(ctx, denom)\n\tif !found {\n\t\tk.SetPreviousAccrualTime(ctx, denom, ctx.BlockTime())\n\t\treturn nil\n\t}\n\n\ttimeElapsed := int64(math.RoundToEven(\n\t\tctx.BlockTime().Sub(previousAccrualTime).Seconds(),\n\t))\n\tif timeElapsed == 0 {\n\t\treturn nil\n\t}\n\n\t// Get current protocol state and hold in memory as 'prior'\n\tmacc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleName)\n\tcashPrior := k.bankKeeper.GetBalance(ctx, macc.GetAddress(), denom).Amount\n\n\tborrowedPrior := sdk.NewCoin(denom, sdk.ZeroInt())\n\tborrowedCoinsPrior, foundBorrowedCoinsPrior := k.GetBorrowedCoins(ctx)\n\tif foundBorrowedCoinsPrior {\n\t\tborrowedPrior = sdk.NewCoin(denom, borrowedCoinsPrior.AmountOf(denom))\n\t}\n\tif borrowedPrior.IsZero() {\n\t\tk.SetPreviousAccrualTime(ctx, denom, ctx.BlockTime())\n\t\treturn nil\n\t}\n\n\treservesPrior, foundReservesPrior := k.GetTotalReserves(ctx)\n\tif !foundReservesPrior {\n\t\tnewReservesPrior := sdk.NewCoins()\n\t\tk.SetTotalReserves(ctx, newReservesPrior)\n\t\treservesPrior = newReservesPrior\n\t}\n\n\tborrowInterestFactorPrior, foundBorrowInterestFactorPrior := k.GetBorrowInterestFactor(ctx, denom)\n\tif !foundBorrowInterestFactorPrior {\n\t\tnewBorrowInterestFactorPrior := sdk.MustNewDecFromStr(\"1.0\")\n\t\tk.SetBorrowInterestFactor(ctx, denom, newBorrowInterestFactorPrior)\n\t\tborrowInterestFactorPrior = newBorrowInterestFactorPrior\n\t}\n\n\tsupplyInterestFactorPrior, foundSupplyInterestFactorPrior := k.GetSupplyInterestFactor(ctx, denom)\n\tif !foundSupplyInterestFactorPrior {\n\t\tnewSupplyInterestFactorPrior := sdk.MustNewDecFromStr(\"1.0\")\n\t\tk.SetSupplyInterestFactor(ctx, denom, newSupplyInterestFactorPrior)\n\t\tsupplyInterestFactorPrior = newSupplyInterestFactorPrior\n\t}\n\n\t// Fetch money market from the store\n\tmm, found := k.GetMoneyMarket(ctx, denom)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrMoneyMarketNotFound, \"%s\", denom)\n\t}\n\n\t// GetBorrowRate calculates the current interest rate based on utilization (the fraction of supply that has been borrowed)\n\tborrowRateApy, err := CalculateBorrowRate(mm.InterestRateModel, sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowedPrior.Amount), sdk.NewDecFromInt(reservesPrior.AmountOf(denom)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Convert from APY to SPY, expressed as (1 + borrow rate)\n\tborrowRateSpy, err := APYToSPY(sdk.OneDec().Add(borrowRateApy))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Calculate borrow interest factor and update\n\tborrowInterestFactor := CalculateBorrowInterestFactor(borrowRateSpy, sdkmath.NewInt(timeElapsed))\n\tinterestBorrowAccumulated := (borrowInterestFactor.Mul(sdk.NewDecFromInt(borrowedPrior.Amount)).TruncateInt()).Sub(borrowedPrior.Amount)\n\n\tif interestBorrowAccumulated.IsZero() && borrowRateApy.IsPositive() {\n\t\t// don't accumulate if borrow interest is rounding to zero\n\t\treturn nil\n\t}\n\n\ttotalBorrowInterestAccumulated := sdk.NewCoins(sdk.NewCoin(denom, interestBorrowAccumulated))\n\treservesNew := sdk.NewDecFromInt(interestBorrowAccumulated).Mul(mm.ReserveFactor).TruncateInt()\n\tborrowInterestFactorNew := borrowInterestFactorPrior.Mul(borrowInterestFactor)\n\tk.SetBorrowInterestFactor(ctx, denom, borrowInterestFactorNew)\n\n\t// Calculate supply interest factor and update\n\tsupplyInterestNew := interestBorrowAccumulated.Sub(reservesNew)\n\tsupplyInterestFactor := CalculateSupplyInterestFactor(sdk.NewDecFromInt(supplyInterestNew), sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowedPrior.Amount), sdk.NewDecFromInt(reservesPrior.AmountOf(denom)))\n\tsupplyInterestFactorNew := supplyInterestFactorPrior.Mul(supplyInterestFactor)\n\tk.SetSupplyInterestFactor(ctx, denom, supplyInterestFactorNew)\n\n\t// Update accural keys in store\n\tk.IncrementBorrowedCoins(ctx, totalBorrowInterestAccumulated)\n\tk.IncrementSuppliedCoins(ctx, sdk.NewCoins(sdk.NewCoin(denom, supplyInterestNew)))\n\tk.SetTotalReserves(ctx, reservesPrior.Add(sdk.NewCoin(denom, reservesNew)))\n\tk.SetPreviousAccrualTime(ctx, denom, ctx.BlockTime())\n\n\treturn nil\n}", "func (s *PayoutService) ListPayouts(req *PayoutListRequest) (*PayoutList, error) {\n\treqd, err := http.NewRequest(\"GET\", \"/payouts\", nil)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tos.Exit(1)\n\t}\n\tparams := reqd.URL.Query()\n\tif req.After != \"\" { params.Add(\"after\", req.After) }\n\tif req.Before != \"\" { params.Add(\"before\", req.Before) }\n\tif req.CreatedAt.Gt != \"\" { params.Add(\"created_at[gt]\", req.CreatedAt.Gt) }\n\tif req.CreatedAt.Gte != \"\" { params.Add(\"created_at[gte]\", req.CreatedAt.Gte) }\n\tif req.CreatedAt.Lt != \"\" { params.Add(\"created_at[lt]\", req.CreatedAt.Lt) }\n\tif req.CreatedAt.Lte != \"\" { params.Add(\"created_at[lte]\", req.CreatedAt.Lte) }\n\tif req.Limit > 0 { params.Add(\"limit\", string(req.Limit)) }\n\tif req.Status != \"\" { params.Add(\"status\", req.Status) }\n\tif req.Currency != \"\" {params.Add(\"currency\", req.Currency)}\n\tif req.CreditorBankAccount != \"\" {params.Add(\"creditor_bank_account\", req.CreditorBankAccount)}\n\tif req.Creditor != \"\" {params.Add(\"creditor\", req.Creditor)}\n\tif req.PayoutType != \"\" {params.Add(\"payout_type\", req.PayoutType)}\n\n\treqd.URL.RawQuery = params.Encode()\n\tpath := reqd.URL.String()\n\tpayoutList := &PayoutList{}\n\terr = s.client.Call(\"GET\", path, nil, payoutList)\n\n\treturn payoutList, err\n}", "func getTotals(snapshots []Snapshot) TotalResponse {\n reports := len(snapshots)\n days := make(map[string]int)\n people := make(map[string]int)\n locations := make(map[string]int)\n activities:= make(map[string]int)\n coffees := 0\n\n for _, snapshot := range snapshots {\n // Count people\n date := snapshot.Date[:10]\n days[date]++\n\n for _, response := range snapshot.Responses {\n question := response.QuestionPrompt\n // Count people\n if question == \"Who are you with?\" {\n for _, token := range response.Tokens {\n people[token.Text]++\n }\n } else if question == \"Where are you?\" {\n // count locations\n locations[response.LocationResponse.Text]++\n } else if question == \"How many coffees did you have today?\" {\n // count coffees\n amount, err := strconv.Atoi(response.NumericResponse)\n if err == nil {\n coffees += amount\n }\n } else if question == \"What are you doing?\" {\n for _, token := range response.Tokens {\n activities[token.Text]++\n }\n }\n }\n }\n\n return TotalResponse{\n TotalDays: len(days),\n TotalReports: reports,\n TotalPeople: len(people),\n TotalLocations: len(locations),\n AvgPerDay: float32(reports)/float32(len(days)),\n TotalCoffees: coffees,\n CoffeesPerDay: float32(coffees)/float32(len(days)),\n PeopleList: people,\n LocationList: locations,\n ActivityList: activities,\n }\n}", "func TestFundsStateChangeRollback(t *testing.T) {\n\tcleanAndPrepare()\n\n\trandVar := rand.New(rand.NewSource(time.Now().Unix()))\n\n\taccAHash := protocol.SerializeHashContent(accA.Address)\n\taccBHash := protocol.SerializeHashContent(accB.Address)\n\tminerAccHash := protocol.SerializeHashContent(validatorAcc.Address)\n\n\tvar testSize uint32\n\ttestSize = 1000\n\n\tb := newBlock([32]byte{}, [crypto.COMM_PROOF_LENGTH]byte{}, 1)\n\tvar funds []*protocol.FundsTx\n\n\tvar feeA, feeB uint64\n\n\t//State snapshot\n\trollBackA := accA.Balance\n\trollBackB := accB.Balance\n\n\t//Record transaction amounts in this variables\n\tbalanceA := accA.Balance\n\tbalanceB := accB.Balance\n\n\tloopMax := int(randVar.Uint32()%testSize + 1)\n\tfor i := 0; i < loopMax+1; i++ {\n\t\tftx, _ := protocol.ConstrFundsTx(0x01, randVar.Uint64()%1000000+1, randVar.Uint64()%100+1, uint32(i), accAHash, accBHash, PrivKeyAccA, PrivKeyMultiSig, nil)\n\t\tif addTx(b, ftx) == nil {\n\t\t\tfunds = append(funds, ftx)\n\t\t\tbalanceA -= ftx.Amount\n\t\t\tfeeA += ftx.Fee\n\n\t\t\tbalanceB += ftx.Amount\n\t\t} else {\n\t\t\tt.Errorf(\"Block rejected a valid transaction: %v\\n\", ftx)\n\t\t}\n\n\t\tftx2, _ := protocol.ConstrFundsTx(0x01, randVar.Uint64()%1000+1, randVar.Uint64()%100+1, uint32(i), accBHash, accAHash, PrivKeyAccB, PrivKeyMultiSig, nil)\n\t\tif addTx(b, ftx2) == nil {\n\t\t\tfunds = append(funds, ftx2)\n\t\t\tbalanceB -= ftx2.Amount\n\t\t\tfeeB += ftx2.Fee\n\n\t\t\tbalanceA += ftx2.Amount\n\t\t} else {\n\t\t\tt.Errorf(\"Block rejected a valid transaction: %v\\n\", ftx2)\n\t\t}\n\t}\n\tfundsStateChange(funds)\n\tif accA.Balance != balanceA || accB.Balance != balanceB {\n\t\tt.Error(\"State update failed!\")\n\t}\n\tfundsStateChangeRollback(funds)\n\tif accA.Balance != rollBackA || accB.Balance != rollBackB {\n\t\tt.Error(\"Rollback failed!\")\n\t}\n\n\t//collectTxFees is checked below in its own test (to additionally cover overflow scenario)\n\tbalBeforeRew := validatorAcc.Balance\n\treward := 5\n\tcollectBlockReward(uint64(reward), minerAccHash)\n\tif validatorAcc.Balance != balBeforeRew+uint64(reward) {\n\t\tt.Error(\"Block reward collection failed!\")\n\t}\n\tcollectBlockRewardRollback(uint64(reward), minerAccHash)\n\tif validatorAcc.Balance != balBeforeRew {\n\t\tt.Error(\"Block reward collection rollback failed!\")\n\t}\n}", "func TestRecoverAlertsPostOutage(t *testing.T) {\n\t// Test Setup\n\t// alert FOR 30m, already ran for 10m, outage down at 15m prior to now(), outage tolerance set to 1hr\n\t// EXPECTATION: for state for alert restores to 10m+(now-15m)\n\n\t// FIRST set up 1 Alert rule with 30m FOR duration\n\talertForDuration, _ := time.ParseDuration(\"30m\")\n\tmockRules := map[string]rulespb.RuleGroupList{\n\t\t\"user1\": {\n\t\t\t&rulespb.RuleGroupDesc{\n\t\t\t\tName: \"group1\",\n\t\t\t\tNamespace: \"namespace1\",\n\t\t\t\tUser: \"user1\",\n\t\t\t\tRules: []*rulespb.RuleDesc{\n\t\t\t\t\t{\n\t\t\t\t\t\tAlert: \"UP_ALERT\",\n\t\t\t\t\t\tExpr: \"1\", // always fire for this test\n\t\t\t\t\t\tFor: alertForDuration,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tInterval: interval,\n\t\t\t},\n\t\t},\n\t}\n\n\t// NEXT, set up ruler config with outage tolerance = 1hr\n\tstore := newMockRuleStore(mockRules)\n\trulerCfg := defaultRulerConfig(t)\n\trulerCfg.OutageTolerance, _ = time.ParseDuration(\"1h\")\n\n\t// NEXT, set up mock distributor containing sample,\n\t// metric: ALERTS_FOR_STATE{alertname=\"UP_ALERT\"}, ts: time.now()-15m, value: time.now()-25m\n\tcurrentTime := time.Now().UTC()\n\tdownAtTime := currentTime.Add(time.Minute * -15)\n\tdownAtTimeMs := downAtTime.UnixNano() / int64(time.Millisecond)\n\tdownAtActiveAtTime := currentTime.Add(time.Minute * -25)\n\tdownAtActiveSec := downAtActiveAtTime.Unix()\n\td := &querier.MockDistributor{}\n\td.On(\"Query\", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(\n\t\tmodel.Matrix{\n\t\t\t&model.SampleStream{\n\t\t\t\tMetric: model.Metric{\n\t\t\t\t\tlabels.MetricName: \"ALERTS_FOR_STATE\",\n\t\t\t\t\t// user1's only alert rule\n\t\t\t\t\tlabels.AlertName: model.LabelValue(mockRules[\"user1\"][0].GetRules()[0].Alert),\n\t\t\t\t},\n\t\t\t\tValues: []model.SamplePair{{Timestamp: model.Time(downAtTimeMs), Value: model.SampleValue(downAtActiveSec)}},\n\t\t\t},\n\t\t},\n\t\tnil)\n\td.On(\"MetricsForLabelMatchers\", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Panic(\"This should not be called for the ruler use-cases.\")\n\tquerierConfig := querier.DefaultQuerierConfig()\n\tquerierConfig.IngesterStreaming = false\n\n\t// set up an empty store\n\tqueryables := []querier.QueryableWithFilter{\n\t\tquerier.UseAlwaysQueryable(newEmptyQueryable()),\n\t}\n\n\t// create a ruler but don't start it. instead, we'll evaluate the rule groups manually.\n\tr := buildRuler(t, rulerCfg, &querier.TestConfig{Cfg: querierConfig, Distributor: d, Stores: queryables}, store, nil)\n\tr.syncRules(context.Background(), rulerSyncReasonInitial)\n\n\t// assert initial state of rule group\n\truleGroup := r.manager.GetRules(\"user1\")[0]\n\trequire.Equal(t, time.Time{}, ruleGroup.GetLastEvaluation())\n\trequire.Equal(t, \"group1\", ruleGroup.Name())\n\trequire.Equal(t, 1, len(ruleGroup.Rules()))\n\n\t// assert initial state of rule within rule group\n\talertRule := ruleGroup.Rules()[0]\n\trequire.Equal(t, time.Time{}, alertRule.GetEvaluationTimestamp())\n\trequire.Equal(t, \"UP_ALERT\", alertRule.Name())\n\trequire.Equal(t, promRules.HealthUnknown, alertRule.Health())\n\n\t// NEXT, evaluate the rule group the first time and assert\n\tctx := user.InjectOrgID(context.Background(), \"user1\")\n\truleGroup.Eval(ctx, currentTime)\n\n\t// since the eval is done at the current timestamp, the activeAt timestamp of alert should equal current timestamp\n\trequire.Equal(t, \"UP_ALERT\", alertRule.Name())\n\trequire.Equal(t, promRules.HealthGood, alertRule.Health())\n\n\tactiveMapRaw := reflect.ValueOf(alertRule).Elem().FieldByName(\"active\")\n\tactiveMapKeys := activeMapRaw.MapKeys()\n\trequire.True(t, len(activeMapKeys) == 1)\n\n\tactiveAlertRuleRaw := activeMapRaw.MapIndex(activeMapKeys[0]).Elem()\n\tactiveAtTimeRaw := activeAlertRuleRaw.FieldByName(\"ActiveAt\")\n\n\trequire.Equal(t, promRules.StatePending, promRules.AlertState(activeAlertRuleRaw.FieldByName(\"State\").Int()))\n\trequire.Equal(t, reflect.NewAt(activeAtTimeRaw.Type(), unsafe.Pointer(activeAtTimeRaw.UnsafeAddr())).Elem().Interface().(time.Time), currentTime)\n\n\t// NEXT, restore the FOR state and assert\n\truleGroup.RestoreForState(currentTime)\n\n\trequire.Equal(t, \"UP_ALERT\", alertRule.Name())\n\trequire.Equal(t, promRules.HealthGood, alertRule.Health())\n\trequire.Equal(t, promRules.StatePending, promRules.AlertState(activeAlertRuleRaw.FieldByName(\"State\").Int()))\n\trequire.Equal(t, reflect.NewAt(activeAtTimeRaw.Type(), unsafe.Pointer(activeAtTimeRaw.UnsafeAddr())).Elem().Interface().(time.Time), downAtActiveAtTime.Add(currentTime.Sub(downAtTime)))\n\n\t// NEXT, 20 minutes is expected to be left, eval timestamp at currentTimestamp +20m\n\tcurrentTime = currentTime.Add(time.Minute * 20)\n\truleGroup.Eval(ctx, currentTime)\n\n\t// assert alert state after alert is firing\n\tfiredAtRaw := activeAlertRuleRaw.FieldByName(\"FiredAt\")\n\tfiredAtTime := reflect.NewAt(firedAtRaw.Type(), unsafe.Pointer(firedAtRaw.UnsafeAddr())).Elem().Interface().(time.Time)\n\trequire.Equal(t, firedAtTime, currentTime)\n\n\trequire.Equal(t, promRules.StateFiring, promRules.AlertState(activeAlertRuleRaw.FieldByName(\"State\").Int()))\n}", "func checkInvoicesRaised(stub shim.ChaincodeStubInterface, ufaNumber string, billingPeriod string) bool {\r\n\r\n\tvar isAvailable = false\r\n\tlogger.Info(\"checkInvoicesRaised started for :\" + ufaNumber + \" : Billing month \" + billingPeriod)\r\n\tallInvoices := getInvoicesForUFA(stub, ufaNumber)\r\n\tif len(allInvoices) > 0 {\r\n\t\tfor _, invoiceDetails := range allInvoices {\r\n\t\t\tlogger.Info(\"checkInvoicesRaised checking for invoice number :\" + invoiceDetails[\"invoiceNumber\"])\r\n\t\t\tif invoiceDetails[\"billingPeriod\"] == billingPeriod {\r\n\t\t\t\tisAvailable = true\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn isAvailable\r\n}", "func (s2 *S2BlockGrader) Payout(index int) int64 {\n\treturn S1Payout(index)\n}", "func Roll(n, d, b int, s *discordgo.Session, m *discordgo.MessageCreate) {\n\tresult := \"Rolled: [\"\n\ttotal := b\n\tfor i := 0; i < n-1; i++ {\n\t\tval := rand.Intn(d) + 1\n\t\tresult += strconv.Itoa(val) + \", \"\n\t\ttotal += val\n\t}\n\tval := rand.Intn(d) + 1\n\tresult += strconv.Itoa(val)\n\ttotal += val\n\tif b > 0 {\n\t\tresult += \"] +\" + strconv.Itoa(b)\n\t} else if b == 0 {\n\t\tresult += \"]\"\n\t} else {\n\t\tresult += \"] \" + strconv.Itoa(b)\n\t}\n\n\tresult += \" = \" + strconv.Itoa(total)\n\ts.ChannelMessageSend(m.ChannelID, result)\n}", "func (g *Game) Roll(pins int) {\n\tg.rolls[g.rollCnt] = pins\n\tg.rollCnt++\n}", "func getBalanceTotal(recordCollection []record) (totalBalance time.Duration) {\n\tfor _, r := range recordCollection {\n\t\t_, balance := getWorkedHours(&r)\n\t\ttotalBalance += balance\n\t}\n\treturn totalBalance\n}", "func (s *state) nextRound(heads bool) {\n\tif s.ruined {\n\t\treturn\n\t}\n\ts.lastRoundNo += 1\n\tif heads {\n\t\ts.capital += 1\n\t} else {\n\t\ts.capital -= 1\n\t}\n\tif s.capital == 0 {\n\t\ts.ruined = true\n\t}\n}", "func (r *AutoRoller) handleManualRolls(ctx context.Context) error {\n\tr.runningMtx.Lock()\n\tdefer r.runningMtx.Unlock()\n\n\tif r.GetMode() == modes.ModeOffline {\n\t\treturn nil\n\t}\n\n\tsklog.Infof(\"Searching manual roll requests for %s\", r.cfg.RollerName)\n\treqs, err := r.manualRollDB.GetIncomplete(r.cfg.RollerName)\n\tif err != nil {\n\t\treturn skerr.Wrapf(err, \"Failed to get incomplete rolls\")\n\t}\n\tsklog.Infof(\"Found %d requests.\", len(reqs))\n\tfor _, req := range reqs {\n\t\tvar issue *autoroll.AutoRollIssue\n\t\tvar to *revision.Revision\n\t\tif req.NoResolveRevision {\n\t\t\tto = &revision.Revision{Id: req.Revision}\n\t\t} else {\n\t\t\tto, err = r.getRevision(ctx, req.Revision)\n\t\t\tif err != nil {\n\t\t\t\terr := skerr.Wrapf(err, \"failed to resolve revision %q\", req.Revision)\n\t\t\t\treq.Status = manual.STATUS_COMPLETE\n\t\t\t\treq.Result = manual.RESULT_FAILURE\n\t\t\t\treq.ResultDetails = err.Error()\n\t\t\t\tsklog.Errorf(\"Failed to create manual roll: %s\", req.ResultDetails)\n\t\t\t\tr.notifier.SendManualRollCreationFailed(ctx, req.Requester, req.Revision, err)\n\t\t\t\tif err := r.manualRollDB.Put(req); err != nil {\n\t\t\t\t\treturn skerr.Wrapf(err, \"Failed to update manual roll request\")\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif req.ExternalChangeId != \"\" {\n\t\t\tto.ExternalChangeId = req.ExternalChangeId\n\t\t}\n\t\tif req.Status == manual.STATUS_PENDING {\n\t\t\t// Avoid creating rolls to the current revision.\n\t\t\tfrom := r.GetCurrentRev()\n\t\t\tif to.Id == from.Id {\n\t\t\t\terr := skerr.Fmt(\"Already at revision %q\", from.Id)\n\t\t\t\treq.Status = manual.STATUS_COMPLETE\n\t\t\t\treq.Result = manual.RESULT_FAILURE\n\t\t\t\treq.ResultDetails = err.Error()\n\t\t\t\tsklog.Errorf(\"Failed to create manual roll: %s\", req.ResultDetails)\n\t\t\t\tr.notifier.SendManualRollCreationFailed(ctx, req.Requester, req.Revision, err)\n\t\t\t\tif err := r.manualRollDB.Put(req); err != nil {\n\t\t\t\t\treturn skerr.Wrapf(err, \"Failed to update manual roll request\")\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\temails := []string{}\n\t\t\tif !req.NoEmail {\n\t\t\t\temails = r.GetEmails()\n\t\t\t\tif !util.In(req.Requester, emails) {\n\t\t\t\t\temails = append(emails, req.Requester)\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar err error\n\t\t\tsklog.Infof(\"Creating manual roll to %s as requested by %s...\", req.Revision, req.Requester)\n\n\t\t\tissue, err = r.createNewRoll(ctx, from, to, emails, req.DryRun, req.Canary, req.Requester)\n\t\t\tif err != nil {\n\t\t\t\terr := skerr.Wrapf(err, \"failed to create manual roll for %s\", req.Id)\n\t\t\t\treq.Status = manual.STATUS_COMPLETE\n\t\t\t\treq.Result = manual.RESULT_FAILURE\n\t\t\t\treq.ResultDetails = err.Error()\n\t\t\t\tsklog.Errorf(\"Failed to create manual roll: %s\", req.ResultDetails)\n\t\t\t\tr.notifier.SendManualRollCreationFailed(ctx, req.Requester, req.Revision, err)\n\t\t\t\tif err := r.manualRollDB.Put(req); err != nil {\n\t\t\t\t\treturn skerr.Wrapf(err, \"Failed to update manual roll request\")\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else if req.Status == manual.STATUS_STARTED {\n\t\t\tsplit := strings.Split(req.Url, \"/\")\n\t\t\ti, err := strconv.Atoi(split[len(split)-1])\n\t\t\tif err != nil {\n\t\t\t\treturn skerr.Wrapf(err, \"Failed to parse issue number from %s for %s: %s\", req.Url, req.Id, err)\n\t\t\t}\n\t\t\tissue = &autoroll.AutoRollIssue{\n\t\t\t\tRollingTo: req.Revision,\n\t\t\t\tIsDryRun: req.DryRun,\n\t\t\t\tIssue: int64(i),\n\t\t\t}\n\t\t} else {\n\t\t\tsklog.Errorf(\"Found manual roll request %s in unknown status %q\", req.Id, req.Status)\n\t\t\tcontinue\n\t\t}\n\t\tsklog.Infof(\"Getting status for manual roll # %d\", issue.Issue)\n\t\troll, err := r.retrieveRoll(ctx, issue, to)\n\t\tif err != nil {\n\t\t\treturn skerr.Wrapf(err, \"Failed to retrieve manual roll %s: %s\", req.Id, err)\n\t\t}\n\t\treq.Status = manual.STATUS_STARTED\n\t\treq.Url = roll.IssueURL()\n\n\t\tif req.DryRun {\n\t\t\tif roll.IsDryRunFinished() {\n\t\t\t\treq.Status = manual.STATUS_COMPLETE\n\t\t\t\tif roll.IsDryRunSuccess() {\n\t\t\t\t\treq.Result = manual.RESULT_SUCCESS\n\t\t\t\t} else {\n\t\t\t\t\treq.Result = manual.RESULT_FAILURE\n\t\t\t\t}\n\t\t\t}\n\t\t} else if roll.IsFinished() {\n\t\t\treq.Status = manual.STATUS_COMPLETE\n\t\t\tif roll.IsSuccess() {\n\t\t\t\treq.Result = manual.RESULT_SUCCESS\n\t\t\t} else {\n\t\t\t\treq.Result = manual.RESULT_FAILURE\n\t\t\t}\n\t\t}\n\t\tif err := r.manualRollDB.Put(req); err != nil {\n\t\t\treturn skerr.Wrapf(err, \"Failed to update manual roll request\")\n\t\t}\n\t}\n\treturn nil\n}", "func RollN(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tsides := vars[\"sides\"]\n\tcount := r.FormValue(\"count\")\n\n\ts := getSides(sides[1:])\n\tif s == 0 {\n\t\tsidesErrResponse(w)\n\t\treturn\n\t}\n\n\tc := getCount(count)\n\tif c == 0 {\n\t\tcountErrResponse(w)\n\t\treturn\n\t}\n\n\tresponse(w, s, c)\n}", "func StatefulSetRolloutStatus(sts *appsv1.StatefulSet) (string, bool, error) {\n\tif sts.Spec.UpdateStrategy.Type != appsv1.RollingUpdateStatefulSetStrategyType {\n\t\treturn \"\", true, fmt.Errorf(\"rollout status is only available for %s strategy type\", appsv1.RollingUpdateStatefulSetStrategyType)\n\t}\n\tif sts.Status.ObservedGeneration == 0 || sts.Generation > sts.Status.ObservedGeneration {\n\t\treturn \"Waiting for statefulset spec update to be observed...\\n\", false, nil\n\t}\n\tif sts.Spec.Replicas != nil && sts.Status.ReadyReplicas < *sts.Spec.Replicas {\n\t\treturn fmt.Sprintf(\"Waiting for %d pods to be ready...\\n\", *sts.Spec.Replicas-sts.Status.ReadyReplicas), false, nil\n\t}\n\tif sts.Spec.UpdateStrategy.Type == appsv1.RollingUpdateStatefulSetStrategyType && sts.Spec.UpdateStrategy.RollingUpdate != nil {\n\t\tif sts.Spec.Replicas != nil && sts.Spec.UpdateStrategy.RollingUpdate.Partition != nil {\n\t\t\tif sts.Status.UpdatedReplicas < (*sts.Spec.Replicas - *sts.Spec.UpdateStrategy.RollingUpdate.Partition) {\n\t\t\t\treturn fmt.Sprintf(\"Waiting for partitioned roll out to finish: %d out of %d new pods have been updated...\\n\",\n\t\t\t\t\tsts.Status.UpdatedReplicas, *sts.Spec.Replicas-*sts.Spec.UpdateStrategy.RollingUpdate.Partition), false, nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Sprintf(\"partitioned roll out complete: %d new pods have been updated...\\n\",\n\t\t\tsts.Status.UpdatedReplicas), true, nil\n\t}\n\tif sts.Status.UpdateRevision != sts.Status.CurrentRevision {\n\t\treturn fmt.Sprintf(\"waiting for statefulset rolling update to complete %d pods at revision %s...\\n\",\n\t\t\tsts.Status.UpdatedReplicas, sts.Status.UpdateRevision), false, nil\n\t}\n\treturn fmt.Sprintf(\"statefulset rolling update complete %d pods at revision %s...\\n\", sts.Status.CurrentReplicas, sts.Status.CurrentRevision), true, nil\n}", "func (p *Person) Owed() AmountFigure {\n\tvar total AmountFigure\n\tfor _, d := range p.Debits {\n\t\ttotal = total.Add(d.Amount)\n\t}\n\treturn total\n}", "func LedgerBalanceReport(ri *ReporterInfo) rlib.Table {\n\tbid := ri.Xbiz.P.BID\n\tvar tbl rlib.Table\n\tri.RptHeaderD2 = true\n\tri.BlankLineAfterRptName = true\n\ttbl.SetTitle(ReportHeaderBlock(\"Trial Balance\", \"RRreportRentalAgreements\", ri))\n\ttbl.Init()\n\ttbl.AddColumn(\"LID\", 9, rlib.CELLSTRING, rlib.COLJUSTIFYLEFT)\n\ttbl.AddColumn(\"GLNumber\", 8, rlib.CELLSTRING, rlib.COLJUSTIFYLEFT)\n\ttbl.AddColumn(\"Name\", 35, rlib.CELLSTRING, rlib.COLJUSTIFYLEFT)\n\ttbl.AddColumn(\"Summary Balance\", 12, rlib.CELLFLOAT, rlib.COLJUSTIFYRIGHT)\n\ttbl.AddColumn(\"Balance\", 12, rlib.CELLFLOAT, rlib.COLJUSTIFYRIGHT)\n\n\tfor i := int64(0); i < int64(len(rlib.RRdb.BizTypes[bid].GLAccounts)); i++ {\n\t\tacct, ok := rlib.RRdb.BizTypes[bid].GLAccounts[i]\n\t\tif ok {\n\t\t\ttbl.AddRow()\n\t\t\ttbl.Puts(-1, 0, acct.IDtoString())\n\t\t\ttbl.Puts(-1, 1, acct.GLNumber)\n\t\t\ttbl.Puts(-1, 2, acct.Name)\n\t\t\tif rlib.RRdb.BizTypes[bid].GLAccounts[i].AllowPost != 0 {\n\t\t\t\ttbl.Putf(-1, 4, rlib.GetAccountBalance(bid, acct.LID, &ri.D2))\n\t\t\t} else {\n\t\t\t\ttbl.Putf(-1, 3, rlib.GetAccountBalance(bid, acct.LID, &ri.D2))\n\t\t\t}\n\t\t}\n\t}\n\ttbl.Sort(0, len(tbl.Row)-1, 1)\n\ttbl.AddLineAfter(len(tbl.Row) - 1) // a line after the last row in the table\n\ttbl.InsertSumRow(len(tbl.Row), 0, len(tbl.Row)-1, []int{4}) // insert @ len essentially adds a row. Only want to sum column 4\n\treturn tbl\n}", "func GetBookingsRangeSummary(s *mgo.Session) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// Copy and launch a Mongo session\n\t\tsession := s.Copy()\n\t\tdefer session.Close()\n\n\t\t// Open bookings collections\n\t\tdbc := session.DB(\"tickets\").C(\"bookings\")\n\n\t\tvars := mux.Vars(r)\n\t\tstartdate := strings.Split(vars[\"date\"], \":\")[0]\n\t\tenddate := strings.Split(vars[\"date\"], \":\")[1]\n\n\t\tvar bookings []Booking\n\n\t\t// Find all bookings matching the date\n\t\terr := dbc.Find(bson.M{\"date\": bson.M{\"$gte\": startdate, \"$lte\": enddate}}).All(&bookings)\n\t\tif err != nil {\n\t\t\tErrorWithJSON(w, \"Database error, failed to find booking with date!\", http.StatusInternalServerError)\n\t\t\tlog.Println(\"Failed to find booking with the specified date: \", err)\n\t\t\treturn\n\t\t}\n\n\t\tvar summary Booking\n\t\tvar guides []string\n\t\tfor _, booking := range bookings {\n\t\t\tsummary.Total += booking.Total\n\t\t\tsummary.Ntickets += booking.Ntickets\n\t\t\tsummary.NAdults += booking.NAdults\n\t\t\tsummary.Nchild += booking.Nchild\n\t\t\tsummary.Nconcession += booking.Nconcession\n\t\t\tsummary.Nguides += booking.Nguides\n\t\t\tfor _, book := range booking.Guidebooks {\n\t\t\t\tguides = append(guides, book)\n\t\t\t}\n\t\t}\n\t\tsummary.Name = \"Total # of booking: \" + strconv.Itoa(len(bookings))\n\n\t\t// Count number of guide books in each category\n\t\tguidescounter := make(map[string]int)\n\t\tfor _, row := range guides {\n\t\t\tguidescounter[row]++\n\t\t}\n\n\t\t// Add counter to Guidebooks as a string\n\t\tvar guidescount []string\n\t\tguidescount = append(guidescount, StringifyKeyValuePairs(guidescounter))\n\t\tsummary.Guidebooks = guidescount\n\n\t\t// Marshall booking\n\t\trespBody, err := json.MarshalIndent(summary, \"\", \" \")\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tResponseWithJSON(w, respBody, http.StatusOK)\n\t}\n}", "func (c *Checkout) CreateNewRoll(ctx context.Context, from, to *revision.Revision, rolling []*revision.Revision, emails []string, dryRun bool, commitMsg string, createRoll CreateRollFunc, uploadRoll UploadRollFunc) (int64, error) {\n\t// Create the roll branch.\n\t_, upstreamBranch, err := c.Update(ctx)\n\tif err != nil {\n\t\treturn 0, skerr.Wrap(err)\n\t}\n\t_, _ = c.Git(ctx, \"branch\", \"-D\", RollBranch) // Fails if the branch does not exist.\n\tif _, err := c.Git(ctx, \"checkout\", \"-b\", RollBranch, \"-t\", fmt.Sprintf(\"origin/%s\", upstreamBranch)); err != nil {\n\t\treturn 0, skerr.Wrap(err)\n\t}\n\tif _, err := c.Git(ctx, \"reset\", \"--hard\", upstreamBranch); err != nil {\n\t\treturn 0, skerr.Wrap(err)\n\t}\n\n\t// Run the provided function to create the changes for the roll.\n\thash, err := createRoll(ctx, c.Checkout, from, to, rolling, commitMsg)\n\tif err != nil {\n\t\treturn 0, skerr.Wrap(err)\n\t}\n\n\t// Ensure that createRoll generated at least one commit downstream of\n\t// p.baseCommit, and that it did not leave uncommitted changes.\n\tcommits, err := c.RevList(ctx, \"--ancestry-path\", \"--first-parent\", fmt.Sprintf(\"%s..%s\", upstreamBranch, hash))\n\tif err != nil {\n\t\treturn 0, skerr.Wrap(err)\n\t}\n\tif len(commits) == 0 {\n\t\treturn 0, skerr.Fmt(\"createRoll generated no commits!\")\n\t}\n\tif _, err := c.Git(ctx, \"diff\", \"--quiet\"); err != nil {\n\t\treturn 0, skerr.Wrapf(err, \"createRoll left uncommitted changes\")\n\t}\n\tout, err := c.Git(ctx, \"ls-files\", \"--others\", \"--exclude-standard\")\n\tif err != nil {\n\t\treturn 0, skerr.Wrap(err)\n\t}\n\tif len(strings.Fields(out)) > 0 {\n\t\treturn 0, skerr.Fmt(\"createRoll left untracked files:\\n%s\", out)\n\t}\n\n\t// Upload the CL.\n\treturn uploadRoll(ctx, c.Checkout, upstreamBranch, hash, emails, dryRun, commitMsg)\n}", "func (player *Athelete) Pay() {\n\tPayAmount := player.Salary / 12\n\tplayer.AccountBalance += PayAmount\n\n}", "func (c *Client) InvoicePayouts(lip *cms.InvoicePayouts) (*cms.InvoicePayoutsReply, error) {\n\tresponseBody, err := c.makeRequest(http.MethodPost,\n\t\tcms.APIRoute, cms.RouteInvoicePayouts, lip)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar lipr cms.InvoicePayoutsReply\n\terr = json.Unmarshal(responseBody, &lipr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshal InvoicePayouts: %v\", err)\n\t}\n\n\tif c.cfg.Verbose {\n\t\terr := prettyPrintJSON(lipr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &lipr, nil\n}", "func (h *Holding) total() int {\n\ttotal := 0\n\tfor _, l := range h.Lots {\n\t\ttotal += l.Quantity\n\t}\n\treturn total\n}", "func (room *GameRoom) RequestPayment() *ReqPenance {\n\troom.applyCards()\n\treq := &ReqPenance{\n\t\tPublicList: make(map[string]int),\n\t\tSlaves: []*Slave{},\n\t\tBlackList: []string{},\n\t}\n\n\tfor _, user := range room.turnPlayers {\n\t\tfmt.Println(user.Email, user.Job)\n\t\tvar bnk *User\n\t\tif user.Treat != nil && user.Treat.Name == \"altf4\" {\n\t\t\tbnk = room.findBnk()\n\t\t\tuser.Owners = append(user.Owners, bnk.Email)\n\t\t} else {\n\t\t\tif user.Job == nil {\n\t\t\t\treq.PublicList[user.Email] = user.PaySize\n\t\t\t\tfmt.Println(\"Job nil : \", user.PaySize)\n\t\t\t} else if user.PaySize == 1 {\n\t\t\t\treq.PublicList[user.Email] = user.Job.Economy[1]\n\t\t\t\tfmt.Println(\"User PaySize == 1\", user.Job.Economy[1])\n\t\t\t} else {\n\t\t\t\treq.PublicList[user.Email] = user.Job.Economy[1] + user.PaySize\n\t\t\t\tfmt.Println(\"User PaySize > 1\", user.Job.Economy[1]+user.PaySize)\n\t\t\t}\n\t\t}\n\n\t\tfor _, owner := range user.Owners {\n\t\t\tslave := &Slave{\n\t\t\t\tName: user.Email,\n\t\t\t\tOwner: owner,\n\t\t\t}\n\n\t\t\tif owner == bnk.Email {\n\t\t\t\tslave.Quote = user.Treat.Economy[0]\n\t\t\t} else {\n\t\t\t\tslave.Quote = user.PaySize\n\t\t\t}\n\t\t\treq.Slaves = append(req.Slaves, slave)\n\t\t}\n\t}\n\n\tfor key := range room.blackList {\n\t\treq.BlackList = append(req.BlackList, key)\n\t}\n\n\treturn req\n}", "func (this *FamilyAccount) pay() {\n\tfmt.Println(\"Amount of Expenditure: \")\n\tAmountEx:fmt.Scanln(&this.money)\n\tif this.money > this.balance {\n\t\tfmt.Println(\"Sorry! You don't have enough money!!!\\nPlease enter another amount: \")\n\t\tgoto AmountEx\n\t} else {\n\t\tthis.balance -= this.money\n\t\tfmt.Println(\"Note of Expenditure: \")\n\t\tfmt.Scanln(&this.note)\n\t\t//Splicing revenue into “details”\n\t\tthis.details += fmt.Sprintf(\"\\nExpenditure\\t\\t%v\\t\\t%v\\t%v\", this.balance, this.money, this.note)\n\t\tfmt.Println(\"Successfully added new details!\")\n\t\tthis.flag = true\n\t}\n}", "func payInvoice(w http.ResponseWriter, r *http.Request) {\n\tinvoiceID, err := strconv.Atoi(mux.Vars(r)[\"id\"])\n\tif err == nil {\n\t\tvar payInvoice PayInvoice\n\n\t\treqBody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(w, \"Kindly enter data of the invoice to pay\")\n\t\t}\n\t\tjson.Unmarshal(reqBody, &payInvoice)\n\n\t\tfor i, singleInvoice := range invoices {\n\n\t\t\tlog.Println(singleInvoice.Balance)\n\t\t\tif singleInvoice.Id == invoiceID && singleInvoice.Balance < 0 {\n\t\t\t\tvar newBalance = singleInvoice.Balance + payInvoice.Amount\n\n\t\t\t\tif newBalance <= 0 {\n\t\t\t\t\tvar newPay Payments\n\t\t\t\t\tmaxIdPay = maxIdPay + 1\n\t\t\t\t\tnewPay.Id = maxIdPay\n\t\t\t\t\tnewPay.Total = payInvoice.Amount\n\t\t\t\t\tsingleInvoice.Payments = append(singleInvoice.Payments, newPay)\n\t\t\t\t\tsingleInvoice.Balance = singleInvoice.Balance + newPay.Total\n\t\t\t\t}\n\n\t\t\t\tinvoices = append(invoices[:i], singleInvoice)\n\t\t\t\tjson.NewEncoder(w).Encode(invoices)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfmt.Fprintf(w, \"Invalid InvoiceID\")\n\t} else {\n\t\tfmt.Fprintf(w, \"Incorrect format InvoiceID\")\n\t}\n}", "func distributeLockedAmount(ctx coretypes.Sandbox, bets []*BetInfo, totalLockedAmount int64) bool {\n\tsumsByPlayers := make(map[coretypes.AgentID]int64)\n\ttotalWinningAmount := int64(0)\n\tfor _, bet := range bets {\n\t\tif _, ok := sumsByPlayers[bet.Player]; !ok {\n\t\t\tsumsByPlayers[bet.Player] = 0\n\t\t}\n\t\tsumsByPlayers[bet.Player] += bet.Sum\n\t\ttotalWinningAmount += bet.Sum\n\t}\n\n\t// NOTE 1: float64 was avoided for determinism reasons\n\t// NOTE 2: beware overflows\n\n\tfor player, sum := range sumsByPlayers {\n\t\tsumsByPlayers[player] = (totalLockedAmount * sum) / totalWinningAmount\n\t}\n\n\t// make deterministic sequence by sorting. Eliminate possible rounding effects\n\tseqPlayers := make([]coretypes.AgentID, 0, len(sumsByPlayers))\n\tresultSum := int64(0)\n\tfor player, sum := range sumsByPlayers {\n\t\tseqPlayers = append(seqPlayers, player)\n\t\tresultSum += sum\n\t}\n\tsort.Slice(seqPlayers, func(i, j int) bool {\n\t\treturn bytes.Compare(seqPlayers[i][:], seqPlayers[j][:]) < 0\n\t})\n\n\t// ensure we distribute not more than totalLockedAmount iotas\n\tif resultSum > totalLockedAmount {\n\t\tsumsByPlayers[seqPlayers[0]] -= resultSum - totalLockedAmount\n\t}\n\n\t// filter out those who proportionally got 0\n\tfinalWinners := seqPlayers[:0]\n\tfor _, player := range seqPlayers {\n\t\tif sumsByPlayers[player] <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfinalWinners = append(finalWinners, player)\n\t}\n\t// distribute iotas\n\tfor i := range finalWinners {\n\n\t\tavailable := ctx.Balance(balance.ColorIOTA)\n\t\tctx.Event(fmt.Sprintf(\"sending reward iotas %d to the winner %s. Available iotas: %d\",\n\t\t\tsumsByPlayers[finalWinners[i]], finalWinners[i].String(), available))\n\n\t\t//if !ctx.MoveTokens(finalWinners[i], balance.ColorIOTA, sumsByPlayers[finalWinners[i]]) {\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}", "func TestDRollN(t *testing.T) {\n\ttype response struct {\n\t\tCode int\n\t\tBody string\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs string\n\t\twant response\n\t}{\n\t\t{\"Valid request\", \"/d4/1\", response{http.StatusOK, `\"count\":1,\"sides\":4`}},\n\t\t{\"Valid request\", \"/D4/1\", response{http.StatusOK, `\"count\":1,\"sides\":4`}},\n\t\t{\"Invalid dice variable\", \"/d5/1\", response{http.StatusNotAcceptable, `\"error\"`}},\n\t\t{\"Invalid dice variable\", \"/D5/1\", response{http.StatusNotAcceptable, `\"error\"`}},\n\t\t{\"Invalid count variable\", \"/d4/0\", response{http.StatusNotAcceptable, `\"error\"`}},\n\t\t{\"Invalid count variable\", \"/D4/0\", response{http.StatusNotAcceptable, `\"error\"`}},\n\t\t// Not sure why count ocmes up first here, since the sides get parsed first in the code.\n\t\t// Moreover, not sure if I should be looking specifically for it or just for an error.\n\t\t{\"Invalid dice and count variable\", \"/d5/0\", response{http.StatusNotAcceptable, `\"error\":\"invalid count\"`}},\n\t\t{\"Invalid dice and count variable\", \"/D5/0\", response{http.StatusNotAcceptable, `\"error\":\"invalid count\"`}},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tr := gofight.New()\n\n\t\t\tr.GET(\"/api/v1/roll\"+tt.args).\n\t\t\t\tRun(router, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {\n\t\t\t\t\tif r.Code != tt.want.Code {\n\t\t\t\t\t\tt.Errorf(\"Handler returned wrong status code: got %v want %v\", r.Code, tt.want.Code)\n\t\t\t\t\t}\n\n\t\t\t\t\tif !bytes.Contains(r.Body.Bytes(), []byte(tt.want.Body)) {\n\t\t\t\t\t\tt.Errorf(\"Unexpected body returned.\\ngot %v\\nwant %v\", r.Body, tt.want.Body)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t})\n\t}\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (dcr *ExchangeWallet) tryFund(utxos []*compositeUTXO, enough func(sum uint64, size uint32, unspent *compositeUTXO) bool) (\n\tsum uint64, size uint32, coins asset.Coins, spents []*fundingCoin, redeemScripts []dex.Bytes, err error) {\n\n\taddUTXO := func(unspent *compositeUTXO) error {\n\t\ttxHash, err := chainhash.NewHashFromStr(unspent.rpc.TxID)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error decoding txid: %w\", err)\n\t\t}\n\t\tv := toAtoms(unspent.rpc.Amount)\n\t\tredeemScript, err := hex.DecodeString(unspent.rpc.RedeemScript)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error decoding redeem script for %s, script = %s: %w\",\n\t\t\t\tunspent.rpc.TxID, unspent.rpc.RedeemScript, err)\n\t\t}\n\t\top := newOutput(txHash, unspent.rpc.Vout, v, unspent.rpc.Tree)\n\t\tcoins = append(coins, op)\n\t\tspents = append(spents, &fundingCoin{\n\t\t\top: op,\n\t\t\taddr: unspent.rpc.Address,\n\t\t})\n\t\tredeemScripts = append(redeemScripts, redeemScript)\n\t\tsize += unspent.input.Size()\n\t\tsum += v\n\t\treturn nil\n\t}\n\n\tisEnoughWith := func(utxo *compositeUTXO) bool {\n\t\treturn enough(sum, size, utxo)\n\t}\n\n\ttryUTXOs := func(minconf int64) (ok bool, err error) {\n\t\tsum, size = 0, 0 // size is only sum of inputs size, not including tx overhead or outputs\n\t\tcoins, spents, redeemScripts = nil, nil, nil\n\n\t\tokUTXOs := make([]*compositeUTXO, 0, len(utxos)) // over-allocate\n\t\tfor _, cu := range utxos {\n\t\t\tif cu.confs >= minconf && cu.rpc.Spendable {\n\t\t\t\tokUTXOs = append(okUTXOs, cu)\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\t// If there are none left, we don't have enough.\n\t\t\tif len(okUTXOs) == 0 {\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\t// Check if the largest output is too small.\n\t\t\tlastUTXO := okUTXOs[len(okUTXOs)-1]\n\t\t\tif !isEnoughWith(lastUTXO) {\n\t\t\t\tif err = addUTXO(lastUTXO); err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tokUTXOs = okUTXOs[0 : len(okUTXOs)-1]\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// We only need one then. Find it.\n\t\t\tidx := sort.Search(len(okUTXOs), func(i int) bool {\n\t\t\t\treturn isEnoughWith(okUTXOs[i])\n\t\t\t})\n\t\t\t// No need to check idx == -1. We already verified that the last\n\t\t\t// utxo passes above.\n\t\t\tif err = addUTXO(okUTXOs[idx]); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\t// First try with confs>0.\n\tok, err := tryUTXOs(1)\n\tif err != nil {\n\t\treturn 0, 0, nil, nil, nil, err\n\t}\n\n\t// Fallback to allowing 0-conf outputs.\n\tif !ok {\n\t\tok, err = tryUTXOs(0)\n\t\tif err != nil {\n\t\t\treturn 0, 0, nil, nil, nil, err\n\t\t}\n\t\tif !ok {\n\t\t\treturn 0, 0, nil, nil, nil, fmt.Errorf(\"not enough to cover requested funds. \"+\n\t\t\t\t\"%s DCR available in %d UTXOs\", amount(sum), len(coins))\n\t\t}\n\t}\n\n\treturn\n}", "func payout(delegate string, operator string) string {\n\t// get operator's address\n\toperator_addr, err := alias.Address(operator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// get delegate's name to 12-byte array\n\tdelegate_name := delegateName(delegate)\n\n\trs := calculateRewardShares(operator_addr, delegate_name, epochToQuery)\n\n\t// prepare input for multisend\n\t// https://member.iotex.io/multi-send\n\tvar voters []string\n\tvar rewards []string\n\n\tstradd := func(a string, b string, c string) string {\n\t\taa, _ := new(big.Int).SetString(a, 10)\n\t\tbb, _ := new(big.Int).SetString(b, 10)\n\t\tcc, _ := new(big.Int).SetString(c, 10)\n\t\treturn cc.Add(aa.Add(aa, bb), cc).Text(10)\n\t}\n\n\tfor _, share := range rs.Shares {\n\t\tvoters = append(voters, \"0x\" + share.ETHAddr)\n\t\trewards = append(rewards, stradd(\n\t\t\t\t\t\tshare.Reward.Block,\n\t\t\t\t\t\tshare.Reward.FoundationBonus,\n\t\t\t\t\t\tshare.Reward.EpochBonus))\n\t}\n\n\tvar sent []MultisendReward\n\tfor i, a := range rewards {\n\t\tamount, _ := new(big.Int).SetString(a, 10)\n\t\tsent = append(sent, MultisendReward{voters[i],\n\t\t\t\t\tutil.RauToString(amount, util.IotxDecimalNum)})\n\t}\n\ts, _ := json.Marshal(sent)\n\tfmt.Println(string(s))\n\n\treturn rs.String()\n}", "func (obj *expense) Remaining() *hash.Hash {\n\treturn obj.remaining\n}", "func (dcr *ExchangeWallet) tryFund(utxos []*compositeUTXO, enough func(sum uint64, size uint32, unspent *compositeUTXO) bool) (\n\tsum uint64, size uint32, coins asset.Coins, spents []*fundingCoin, redeemScripts []dex.Bytes, err error) {\n\n\taddUTXO := func(unspent *compositeUTXO) error {\n\t\ttxHash, err := chainhash.NewHashFromStr(unspent.rpc.TxID)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error decoding txid: %w\", err)\n\t\t}\n\t\tv := toAtoms(unspent.rpc.Amount)\n\t\tredeemScript, err := hex.DecodeString(unspent.rpc.RedeemScript)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error decoding redeem script for %s, script = %s: %w\",\n\t\t\t\tunspent.rpc.TxID, unspent.rpc.RedeemScript, err)\n\t\t}\n\t\top := newOutput(txHash, unspent.rpc.Vout, v, unspent.rpc.Tree)\n\t\tcoins = append(coins, op)\n\t\tspents = append(spents, &fundingCoin{\n\t\t\top: op,\n\t\t\taddr: unspent.rpc.Address,\n\t\t})\n\t\tredeemScripts = append(redeemScripts, redeemScript)\n\t\tsize += unspent.input.Size()\n\t\tsum += v\n\t\treturn nil\n\t}\n\n\ttryUTXOs := func(minconf int64) (ok bool, err error) {\n\t\tsum, size = 0, 0\n\t\tcoins, spents = nil, nil\n\n\t\tokUTXOs := make([]*compositeUTXO, 0, len(utxos)) // over-allocate\n\t\tfor _, cu := range utxos {\n\t\t\tif cu.confs >= minconf {\n\t\t\t\tokUTXOs = append(okUTXOs, cu)\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\t// If there are none left, we don't have enough.\n\t\t\tif len(okUTXOs) == 0 {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\t// On each loop, find the smallest UTXO that is enough.\n\t\t\tfor _, txout := range okUTXOs {\n\t\t\t\tif enough(sum, size, txout) {\n\t\t\t\t\tif err = addUTXO(txout); err != nil {\n\t\t\t\t\t\treturn false, err\n\t\t\t\t\t}\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\t// No single UTXO was large enough. Add the largest (the last\n\t\t\t// output) and continue.\n\t\t\tif err = addUTXO(okUTXOs[len(okUTXOs)-1]); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\t// Pop the utxo.\n\t\t\tokUTXOs = okUTXOs[:len(okUTXOs)-1]\n\t\t}\n\t}\n\n\t// First try with confs>0.\n\tok, err := tryUTXOs(1)\n\tif err != nil {\n\t\treturn 0, 0, nil, nil, nil, err\n\t}\n\t// Fallback to allowing 0-conf outputs.\n\tif !ok {\n\t\tok, err = tryUTXOs(0)\n\t\tif err != nil {\n\t\t\treturn 0, 0, nil, nil, nil, err\n\t\t}\n\t\tif !ok {\n\t\t\treturn 0, 0, nil, nil, nil, fmt.Errorf(\"not enough to cover requested funds. %.8f available\", toDCR(sum))\n\t\t}\n\t}\n\n\treturn\n}", "func CalculateAllContractsForCycles(delegatedContracts []DelegatedContract, cycleStart int, cycleEnd int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var err error\n\n for cycleStart <= cycleEnd {\n //fmt.Println(cycleStart)\n delegatedContracts, err = CalculateAllContractsForCycle(delegatedContracts, cycleStart, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycles \" + strconv.Itoa(cycleStart) + \"-\" + strconv.Itoa(cycleEnd) + \":CalculateAllCommitmentsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64) failed: \" + err.Error())\n }\n cycleStart = cycleStart + 1\n }\n return delegatedContracts, nil\n}", "func (s *Slot) IncrPhaseDecrRound() {\n\ts.Phase++\n\ts.Round--\n}", "func (a *FundsApiService) GetUserWalletFundsHolding(ctx context.Context, limit int32, offset int32) (InlineResponse20020, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20020\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/users/wallets/funds/holdings/{limit}/{offset}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"limit\"+\"}\", fmt.Sprintf(\"%v\", limit), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"offset\"+\"}\", fmt.Sprintf(\"%v\", offset), -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{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\tif err == nil { \n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20020\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 401 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 502 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 503 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 504 {\n\t\t\tvar v ErrorV1\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func printCheckoutStats(checkouts []*Checkout, totalProcessedProducts int64) {\n\tvar highest int64 = 0\n\tvar totalUtilization float64\n\tfor i := range checkouts {\n\t\tif checkouts[i].getFirstCustomerArrivalTime()+checkouts[i].getProcessedProductsTime() > highest {\n\t\t\thighest = checkouts[i].getFirstCustomerArrivalTime() + checkouts[i].getProcessedProductsTime()\n\t\t}\n\t}\n\n\tfor i := range checkouts {\n\t\tcheckout := checkouts[i]\n\t\tfmt.Printf(\"Checkout: #%d\\n\", checkout.Number)\n\n\t\t// Utilization based on time checkout was open compared to time shop was open.\n\t\tfigure := float64(checkout.getProcessedProductsTime()) / float64(highest) * 100\n\t\ttotalUtilization += figure\n\t\tif checkout.hasScanner {\n\t\t\tfmt.Printf(\"Has Scanner: %t\\nSaved Time: %d seconds\\n\", checkout.hasScanner, int(checkout.processedProductsTime/1000))\n\t\t}\n\t\tfmt.Printf(\"Utilisation: %.2f%s\\n\", figure, \"%\")\n\t\tproductsProcessed := checkout.ProcessedProducts\n\t\tfmt.Printf(\"Products Processed: %d\\n\", productsProcessed)\n\t\tpercentProducts := float64(productsProcessed) / float64(totalProcessedProducts) * 100\n\t\tfmt.Printf(\"Total Products Processed (%%): %.2f%s\\n\\n\", percentProducts, \"%\")\n\t}\n\n\ttotal := getTotalNumberOfCustomersToday()\n\tfmt.Printf(\"Average Products Per Trolley: %d\\n\", int(float64(totalProcessedProducts)/float64(total)))\n\n\tavgWait, avgProcess := getCustomerTimesInSeconds()\n\tfmt.Printf(\"Average Customer Wait Time: %s, \\nAverage Customer Process Time: %s\\n\", avgWait, avgProcess)\n\n\tfmt.Printf(\"Average Checkout Utilisation: %.2f%s\\n\", totalUtilization/float64(getNumCheckouts()), \"%\")\n\tfmt.Printf(\"Customers Lost: %d\\n\", numCustomersLost)\n\tfmt.Printf(\"Customers Banned: %d\\n\", numCustomersBanned)\n}", "func ROLL(ci, mr operand.Op) { ctx.ROLL(ci, mr) }", "func MakePendingBooking(c *gin.Context) {\n\tconst (\n\t\tERROR_STRING = \"MakePendingBooking\"\n\t)\n\tvar input []models.BookingInput\n\tif err := c.ShouldBindJSON(&input); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Check input fields\"})\n\t\tfmt.Sprintln(\"Error in getting all inputs for function %s. \"+err.Error()+\"\\n\", ERROR_STRING)\n\t\treturn\n\t}\n\n\t// get pending booking status\n\tstatusCode, err := GetBookingStatusCode(DB, \"In the midst of booking\")\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for status code.\"})\n\t\tfmt.Println(\"Check statusQuery. \" + err.Error() + \"\\n\")\n\t}\n\n\tstatusIDArr, err := GetAllBookingStatusCodes(DB)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for booking statusID.\"})\n\t\tfmt.Println(\"Check bookingstatus query \" + err.Error() + \"\\n\")\n\t}\n\n\tcounter := 0\n\tfor _, s := range input {\n\t\tvenue, err := GetVenueFromBuildingAndUnit(DB, s)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for venueID.\"})\n\t\t\tfmt.Printf(\"Error in querying for venueID for function %s. \"+err.Error()+\"\\n\", ERROR_STRING)\n\t\t}\n\t\ts.Venueid = venue.ID\n\n\t\toverLimitAndTime, err := CheckIfOverLimitAndTime(DB, s, venue, statusIDArr)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for unavailable timings.\"})\n\t\t\tfmt.Println(\"Check timingsQuery \" + err.Error() + \"\\n\")\n\t\t}\n\n\t\tID, added, err := InsertBooking(DB, overLimitAndTime, s, venue, statusCode)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"success\": false, \"message\": err.Error()})\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\tif added {\n\t\t\tcounter++\n\t\t}\n\t\t// after 15 min, pending booking should be deleted\n\t\ttime.AfterFunc(time.Minute*15, func() {\n\t\t\t// do not execute if booking becomes confirmed/already deleted\n\t\t\tcheckBooking, exists, err := RetrieveBooking(DB, models.URLBooking{BookingID: ID.String()})\n\t\t\tif err != nil {\n\t\t\t\terrorMessage := fmt.Sprintf(\"Unable to check on status of booking %s after 15 minutes\", ID.String())\n\t\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": errorMessage})\n\t\t\t} else if exists && checkBooking.Bookingstatusdescription == \"In the midst of booking\" {\n\t\t\t\tvar temp models.MakeDeleteBookings\n\t\t\t\ttemp.BookingID = []string{ID.String()}\n\t\t\t\tif _, err := DeletePendingBookingFromTable(DB, temp); err != nil {\n\t\t\t\t\terrorMessage := fmt.Sprintf(\"Unable to remove pending booking %s after 15 minutes.\", ID.String())\n\t\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error(), \"message\": errorMessage})\n\t\t\t\t} else {\n\t\t\t\t\tdeletedMessage := fmt.Sprintf(\"Deleted pending booking %s as it has been 15 minutes.\", ID.String())\n\t\t\t\t\tfmt.Println(deletedMessage)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tsuccessMsg := fmt.Sprintf(\"Successfully recorded %d booking(s)!\", counter)\n\tc.JSON(http.StatusOK, gin.H{\"message\": successMsg})\n\tfmt.Println(successMsg)\n}", "func (c *Channel) Outstanding() *big.Int {\n\treturn c.PartnerState.amountLocked()\n}", "func (c *Channel) Outstanding() *big.Int {\n\treturn c.PartnerState.AmountLocked()\n}", "func calcFinalLotteryState(winners []*stakeTicket, prngStateHash chainhash.Hash) [6]byte {\n\tdata := make([]byte, (len(winners)+1)*chainhash.HashSize)\n\tfor i := 0; i < len(winners); i++ {\n\t\th := winners[i].tx.TxHash()\n\t\tcopy(data[chainhash.HashSize*i:], h[:])\n\t}\n\tcopy(data[chainhash.HashSize*len(winners):], prngStateHash[:])\n\tdataHash := chainhash.HashH(data)\n\n\tvar finalState [6]byte\n\tcopy(finalState[:], dataHash[0:6])\n\treturn finalState\n}", "func (r *MockRepoManager) mockRolledPast(hash string, rolled bool) {\n\tr.mtx.Lock()\n\tdefer r.mtx.Unlock()\n\tr.rolledPast[hash] = rolled\n}", "func (s *State) applyMissedProof(openContract *OpenContract) (diff OutputDiff) {\n\tcontract := openContract.FileContract\n\tpayout := contract.MissedProofPayout\n\tif openContract.FundsRemaining < contract.MissedProofPayout {\n\t\tpayout = openContract.FundsRemaining\n\t}\n\n\t// Create the output for the missed proof.\n\tnewOutputID, err := contract.StorageProofOutputID(openContract.ContractID, s.height(), false)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\toutput := Output{\n\t\tValue: payout,\n\t\tSpendHash: contract.MissedProofAddress,\n\t}\n\ts.unspentOutputs[newOutputID] = output\n\tmsp := MissedStorageProof{\n\t\tOutputID: newOutputID,\n\t\tContractID: openContract.ContractID,\n\t}\n\tdiff = OutputDiff{New: true, ID: newOutputID, Output: output}\n\n\t// Update the open contract to reflect the missed payment.\n\ts.currentBlockNode().MissedStorageProofs = append(s.currentBlockNode().MissedStorageProofs, msp)\n\topenContract.FundsRemaining -= payout\n\topenContract.Failures += 1\n\treturn\n}", "func (account *Account) Withdraw(amount int) error {\r\n\tif account.balance < amount {\r\n\t\t// return errors.New(\"Can't widthdraw amount is more than yout balance\")\r\n\t\treturn errNoMoney\r\n\t}\r\n\taccount.balance -= amount\r\n\treturn nil\r\n\t// nill is null or None\r\n\r\n}", "func (s *Server) handleDashboardBookings() http.HandlerFunc {\n\tvar o sync.Once\n\tvar tpl *template.Template\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx, logger := GetLogger(s.getCtx(r))\n\t\to.Do(func() {\n\t\t\ttpl = s.loadWebTemplateDashboard(ctx, \"orders.html\")\n\t\t})\n\t\tctx, provider, data, errs, ok := s.createTemplateDataDashboard(w, r.WithContext(ctx), tpl, false)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tuser := provider.GetProviderUser()\n\n\t\t//setup the breadcrumbs\n\t\tbreadcrumbs := []breadcrumb{\n\t\t\t{\"Orders\", \"\"},\n\t\t}\n\t\tdata[TplParamBreadcrumbs] = breadcrumbs\n\t\tdata[TplParamActiveNav] = provider.GetURLBookings()\n\t\tdata[TplParamFormAction] = provider.GetURLBookings()\n\n\t\t//url for the calendar\n\t\turl := createDashboardAPIURL(URIOrdersCalendar)\n\t\tdata[TplParamURL] = url\n\n\t\t//load the counts\n\t\tnow := data[TplParamCurrentTime].(time.Time)\n\t\tctx, countNew, err := CountBookingsByProviderIDAndFilter(ctx, s.getDB(), provider.ID, user, BookingFilterNew, \"\", now)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"count bookings new\", \"error\", err, \"id\", provider.ID)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamCountNew] = countNew\n\t\tctx, countUnPaid, err := CountBookingsByProviderIDAndFilter(ctx, s.getDB(), provider.ID, user, BookingFilterUnPaid, \"\", now)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"count bookings unpaid\", \"error\", err, \"id\", provider.ID)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamCountUnPaid] = countUnPaid\n\t\tctx, countUpcoming, err := CountBookingsByProviderIDAndFilter(ctx, s.getDB(), provider.ID, user, BookingFilterUpcoming, BookingFilterAll, now)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"count bookings upcoming\", \"error\", err, \"id\", provider.ID)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamCountUpcoming] = countUpcoming\n\n\t\t//read the form\n\t\ttimeStr := r.FormValue(URLParams.Time)\n\t\tfilterStr := r.FormValue(URLParams.Filter)\n\t\tfilterSubStr := r.FormValue(URLParams.FilterSub)\n\t\tif filterSubStr == \"\" {\n\t\t\t//default to the new filter if possible\n\t\t\tif countNew > 0 {\n\t\t\t\tfilterSubStr = string(BookingFilterNew)\n\t\t\t} else {\n\t\t\t\tfilterSubStr = string(BookingFilterAll)\n\t\t\t}\n\t\t}\n\n\t\t//prepare the data\n\t\tdata[TplParamFilter] = filterStr\n\t\tdata[TplParamFilterSub] = filterSubStr\n\t\tdata[TplParamTime] = timeStr\n\n\t\t//validate the filter\n\t\tif filterStr != \"\" {\n\t\t\tfilter, err := ParseBookingFilter(filterStr)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"parse filter\", \"error\", err, \"filter\", filterStr)\n\t\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t}\n\t\t\tfilterSub, err := ParseBookingFilter(filterSubStr)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"parse filter\", \"error\", err, \"filter\", filterSubStr)\n\t\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t}\n\n\t\t\t//check permissions\n\t\t\tswitch filter {\n\t\t\tcase BookingFilterUpcoming:\n\t\t\tdefault:\n\t\t\t\tok := s.checkPermission(w, r.WithContext(ctx), provider, true)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//validate the time\n\t\t\tvar timeCurrent time.Time\n\t\t\tif timeStr != \"\" {\n\t\t\t\tform := TimeUnixForm{\n\t\t\t\t\tTime: timeStr,\n\t\t\t\t}\n\t\t\t\tok = s.validateForm(w, r.WithContext(ctx), tpl, data, errs, form, false)\n\t\t\t\tif !ok {\n\t\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLBookings(), http.StatusSeeOther)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttimeCurrent = ParseTimeUnixLocal(form.Time, provider.User.TimeZone)\n\t\t\t\tif timeCurrent.IsZero() {\n\t\t\t\t\terrs[string(FieldErrDate)] = GetFieldErrText(string(FieldErrDate))\n\t\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttimeCurrent = data[TplParamCurrentTime].(time.Time)\n\t\t\t}\n\t\t\ttimeNext := timeCurrent.AddDate(0, ordersAllMonths, 0)\n\n\t\t\t//load the bookings\n\t\t\tctx, books, err := ListBookingsByProviderIDAndFilter(ctx, s.getDB(), provider.ID, user, filter, filterSub, timeCurrent)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"load bookings\", \"error\", err, \"id\", provider.ID, \"from\", timeCurrent, \"to\", timeNext)\n\t\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t//organize the bookings by day of week\n\t\t\tbooksByDate := &bookingsByDate{}\n\t\t\tfor _, book := range books {\n\t\t\t\tbookUI := s.createBookingUI(book)\n\t\t\t\tbooksByDate.AddBooking(bookUI, provider.User.TimeZone)\n\t\t\t}\n\t\t\tdata[TplParamBooks] = booksByDate\n\t\t}\n\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t}\n}", "func getAccountsWithoutTxnData(db *IndexerDb, maxRound uint32, specialAccounts idb.SpecialAccounts, accountsFirstUsed map[sdk_types.Address]txnID) ([]addressAccountData, error) {\n\t// Query accounts.\n\tres := []addressAccountData{}\n\n\toptions := idb.AccountQueryOptions{}\n\toptions.IncludeDeleted = true\n\n\tdb.log.Print(\"querying accounts\")\n\taccountCh, _ := db.GetAccounts(context.Background(), options)\n\n\t// Read all accounts.\n\tnumRows := 0\n\tdb.log.Print(\"started reading accounts\")\n\tfor accountRow := range accountCh {\n\t\tif accountRow.Error != nil {\n\t\t\treturn nil, fmt.Errorf(\"m7: problem querying accounts: %v\", accountRow.Error)\n\t\t}\n\n\t\tif (accountRow.Account.CreatedAtRound == nil) ||\n\t\t\t(*accountRow.Account.CreatedAtRound <= uint64(maxRound)) {\n\t\t\taddress, err := sdk_types.DecodeAddress(accountRow.Account.Address)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"m7: failed to decode address %s err: %v\",\n\t\t\t\t\taccountRow.Account.Address, err)\n\t\t\t}\n\n\t\t\t// Don't update special accounts (m10 fixes this)\n\t\t\tif (address != specialAccounts.FeeSink) && (address != specialAccounts.RewardsPool) {\n\t\t\t\tif _, ok := accountsFirstUsed[address]; !ok {\n\t\t\t\t\taccountData := initM7AccountData()\n\n\t\t\t\t\taccountData.account.createdValid = true\n\t\t\t\t\taccountData.account.created = 0\n\t\t\t\t\taccountData.account.deletedValid = true\n\t\t\t\t\taccountData.account.deleted = false\n\n\t\t\t\t\tres = append(res, addressAccountData{address, accountData})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnumRows++\n\t\t\tif numRows%1000000 == 0 {\n\t\t\t\tdb.log.Printf(\"m7: read %d accounts\", numRows)\n\t\t\t}\n\t\t}\n\t}\n\tdb.log.Print(\"m7: finished reading accounts\")\n\n\treturn res, nil\n}", "func (_Cakevault *CakevaultCaller) CalculateTotalPendingCakeRewards(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"calculateTotalPendingCakeRewards\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (b *backend) checkForProposalPayments(pool map[uuid.UUID]paywallPoolMember) (bool, []uuid.UUID) {\n\tvar userIDsToRemove []uuid.UUID\n\n\t// In theory poolMember could be raced during this call. In practice\n\t// a race will not occur as long as the paywall does not remove\n\t// poolMembers from the pool while in the middle of polling poolMember\n\t// addresses.\n\tfor userID, poolMember := range pool {\n\t\tuser, err := b.db.UserGetById(userID)\n\t\tif err != nil {\n\t\t\tif err == database.ErrShutdown {\n\t\t\t\t// The database is shutdown, so stop the thread.\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tlog.Errorf(\"cannot fetch user by id %v: %v\\n\", userID, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif poolMember.paywallType != paywallTypeProposal {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Tracef(\"Checking proposal paywall address for user %v...\", user.Email)\n\n\t\tpaywall := b.mostRecentProposalPaywall(user)\n\t\tif paywallHasExpired(paywall.PollExpiry) {\n\t\t\tuserIDsToRemove = append(userIDsToRemove, userID)\n\t\t\tlog.Tracef(\" removing from polling, poll has expired\")\n\t\t\tcontinue\n\t\t}\n\n\t\ttx, err := b.verifyProposalPayment(user)\n\t\tif err != nil {\n\t\t\tif err == database.ErrShutdown {\n\t\t\t\t// The database is shutdown, so stop the thread.\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tlog.Errorf(\"cannot update user with id %v: %v\", user.ID, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Removed paywall from the in-memory pool if it has\n\t\t// been marked as paid.\n\t\tif !b.userHasValidProposalPaywall(user) {\n\t\t\tuserIDsToRemove = append(userIDsToRemove, userID)\n\t\t\tlog.Tracef(\" removing from polling, user just paid\")\n\t\t} else if tx != nil {\n\t\t\t// Update pool member if payment tx was found but\n\t\t\t// does not have enough confimrations.\n\t\t\tpoolMember.txID = tx.TxID\n\t\t\tpoolMember.txAmount = tx.Amount\n\t\t\tpoolMember.txConfirmations = tx.Confirmations\n\n\t\t\tb.Lock()\n\t\t\tb.userPaywallPool[userID] = poolMember\n\t\t\tb.Unlock()\n\t\t}\n\n\t\ttime.Sleep(paywallCheckGap)\n\t}\n\n\treturn true, userIDsToRemove\n}", "func handleLeaseExpire(input *lambdaHandlerInput, prevLeaseStatus db.LeaseStatus, leaseStatusReason db.LeaseStatusReason) error {\n\t// Defer errors until the end, so we\n\t// can continue on error\n\tdeferredErrors := []error{}\n\n\t// Here we will save the update to the account status. From\n\t// there, a Lambda listening to the account status Dynamodb stream\n\t// and then forwarding events to SNS and SQS from there.\n\t_, err := input.dbSvc.TransitionLeaseStatus(\n\t\tinput.lease.AccountID,\n\t\tinput.lease.PrincipalID,\n\t\tprevLeaseStatus,\n\t\tinput.lease.LeaseStatus,\n\t\tleaseStatusReason,\n\t)\n\n\tif err != nil {\n\t\tlog.Printf(\"Failed to add account to reset queue for lease %s @ %s: %s\", input.lease.PrincipalID, input.lease.AccountID, err)\n\t\tdeferredErrors = append(deferredErrors, err)\n\t}\n\n\t// Update Account Status to \"NotReady\"\n\t_, err = input.dbSvc.TransitionAccountStatus(\n\t\tinput.lease.AccountID,\n\t\tdb.Leased,\n\t\tdb.NotReady,\n\t)\n\n\tif err != nil {\n\t\tlog.Printf(\"Account status update: Failed to add account to reset queue for lease %s @ %s: %s\", input.lease.PrincipalID, input.lease.AccountID, err)\n\t\tdeferredErrors = append(deferredErrors, err)\n\t}\n\n\t// Return errors\n\tif len(deferredErrors) > 0 {\n\t\treturn multierrors.NewMultiError(\"Failed to lock over-budget account: \", deferredErrors)\n\t}\n\n\treturn nil\n}", "func (t *Task) hasAllProgressReportingCompleted() (bool, error) {\n\tt.Owner.Status.RunningPods = []*migapi.PodProgress{}\n\tt.Owner.Status.FailedPods = []*migapi.PodProgress{}\n\tt.Owner.Status.SuccessfulPods = []*migapi.PodProgress{}\n\tt.Owner.Status.PendingPods = []*migapi.PodProgress{}\n\tunknownPods := []*migapi.PodProgress{}\n\tvar pendingSinceTimeLimitPods []string\n\tpvcMap := t.getPVCNamespaceMap()\n\tfor bothNs, vols := range pvcMap {\n\t\tns := getSourceNs(bothNs)\n\t\tfor _, vol := range vols {\n\t\t\toperation := t.Owner.Status.GetRsyncOperationStatusForPVC(&corev1.ObjectReference{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: vol.Name,\n\t\t\t})\n\t\t\tdvmp := migapi.DirectVolumeMigrationProgress{}\n\t\t\terr := t.Client.Get(context.TODO(), types.NamespacedName{\n\t\t\t\tName: getMD5Hash(t.Owner.Name + vol.Name + ns),\n\t\t\t\tNamespace: migapi.OpenshiftMigrationNamespace,\n\t\t\t}, &dvmp)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tpodProgress := &migapi.PodProgress{\n\t\t\t\tObjectReference: &corev1.ObjectReference{\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t\tName: dvmp.Status.PodName,\n\t\t\t\t},\n\t\t\t\tPVCReference: &corev1.ObjectReference{\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t\tName: vol.Name,\n\t\t\t\t},\n\t\t\t\tLastObservedProgressPercent: dvmp.Status.TotalProgressPercentage,\n\t\t\t\tLastObservedTransferRate: dvmp.Status.LastObservedTransferRate,\n\t\t\t\tTotalElapsedTime: dvmp.Status.RsyncElapsedTime,\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase dvmp.Status.PodPhase == corev1.PodRunning:\n\t\t\t\tt.Owner.Status.RunningPods = append(t.Owner.Status.RunningPods, podProgress)\n\t\t\tcase operation.Failed:\n\t\t\t\tt.Owner.Status.FailedPods = append(t.Owner.Status.FailedPods, podProgress)\n\t\t\tcase dvmp.Status.PodPhase == corev1.PodSucceeded:\n\t\t\t\tt.Owner.Status.SuccessfulPods = append(t.Owner.Status.SuccessfulPods, podProgress)\n\t\t\tcase dvmp.Status.PodPhase == corev1.PodPending:\n\t\t\t\tt.Owner.Status.PendingPods = append(t.Owner.Status.PendingPods, podProgress)\n\t\t\t\tif dvmp.Status.CreationTimestamp != nil {\n\t\t\t\t\tif time.Now().UTC().Sub(dvmp.Status.CreationTimestamp.Time.UTC()) > PendingPodWarningTimeLimit {\n\t\t\t\t\t\tpendingSinceTimeLimitPods = append(pendingSinceTimeLimitPods, fmt.Sprintf(\"%s/%s\", podProgress.Namespace, podProgress.Name))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase dvmp.Status.PodPhase == \"\":\n\t\t\t\tunknownPods = append(unknownPods, podProgress)\n\t\t\tcase !operation.Failed:\n\t\t\t\tt.Owner.Status.RunningPods = append(t.Owner.Status.RunningPods, podProgress)\n\t\t\t}\n\t\t}\n\t}\n\n\tisCompleted := len(t.Owner.Status.SuccessfulPods)+len(t.Owner.Status.FailedPods) == len(t.Owner.Spec.PersistentVolumeClaims)\n\tisAnyPending := len(t.Owner.Status.PendingPods) > 0\n\tisAnyRunning := len(t.Owner.Status.RunningPods) > 0\n\tisAnyUnknown := len(unknownPods) > 0\n\tif len(pendingSinceTimeLimitPods) > 0 {\n\t\tpendingMessage := fmt.Sprintf(\"Rsync Client Pods [%s] are stuck in Pending state for more than 10 mins\", strings.Join(pendingSinceTimeLimitPods[:], \", \"))\n\t\tt.Log.Info(pendingMessage)\n\t\tt.Owner.Status.SetCondition(migapi.Condition{\n\t\t\tType: RsyncClientPodsPending,\n\t\t\tStatus: migapi.True,\n\t\t\tReason: \"PodStuckInContainerCreating\",\n\t\t\tCategory: migapi.Warn,\n\t\t\tMessage: pendingMessage,\n\t\t})\n\t}\n\treturn !isAnyRunning && !isAnyPending && !isAnyUnknown && isCompleted, nil\n}", "func (lsn *listenerV2) checkReqsFulfilled(ctx context.Context, l logger.Logger, reqs []pendingRequest) ([]bool, error) {\n\tvar (\n\t\tstart = time.Now()\n\t\tcalls = make([]rpc.BatchElem, len(reqs))\n\t\tfulfilled = make([]bool, len(reqs))\n\t)\n\n\tfor i, req := range reqs {\n\t\tpayload, err := lsn.requestCommitmentPayload(req.req.RequestID())\n\t\tif err != nil {\n\t\t\t// This shouldn't happen\n\t\t\treturn fulfilled, errors.Wrap(err, \"creating getCommitment payload\")\n\t\t}\n\n\t\treqBlockNumber := new(big.Int).SetUint64(req.req.Raw().BlockNumber)\n\n\t\t// Subtract 5 since the newest block likely isn't indexed yet and will cause \"header not\n\t\t// found\" errors.\n\t\tcurrBlock := new(big.Int).SetUint64(lsn.getLatestHead() - 5)\n\t\tm := bigmath.Max(reqBlockNumber, currBlock)\n\n\t\tvar result string\n\t\tcalls[i] = rpc.BatchElem{\n\t\t\tMethod: \"eth_call\",\n\t\t\tArgs: []interface{}{\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"to\": lsn.coordinator.Address(),\n\t\t\t\t\t\"data\": hexutil.Bytes(payload),\n\t\t\t\t},\n\t\t\t\t// The block at which we want to make the call\n\t\t\t\thexutil.EncodeBig(m),\n\t\t\t},\n\t\t\tResult: &result,\n\t\t}\n\t}\n\n\terr := lsn.ethClient.BatchCallContext(ctx, calls)\n\tif err != nil {\n\t\treturn fulfilled, errors.Wrap(err, \"making batch call\")\n\t}\n\n\tvar errs error\n\tfor i, call := range calls {\n\t\tif call.Error != nil {\n\t\t\terrs = multierr.Append(errs, fmt.Errorf(\"checking request %s with hash %s: %w\",\n\t\t\t\treqs[i].req.RequestID().String(), reqs[i].req.Raw().TxHash.String(), call.Error))\n\t\t\tcontinue\n\t\t}\n\n\t\trString, ok := call.Result.(*string)\n\t\tif !ok {\n\t\t\terrs = multierr.Append(errs,\n\t\t\t\tfmt.Errorf(\"unexpected result %+v on request %s with hash %s\",\n\t\t\t\t\tcall.Result, reqs[i].req.RequestID().String(), reqs[i].req.Raw().TxHash.String()))\n\t\t\tcontinue\n\t\t}\n\t\tresult, err := hexutil.Decode(*rString)\n\t\tif err != nil {\n\t\t\terrs = multierr.Append(errs,\n\t\t\t\tfmt.Errorf(\"decoding batch call result %+v %s request %s with hash %s: %w\",\n\t\t\t\t\tcall.Result, *rString, reqs[i].req.RequestID().String(), reqs[i].req.Raw().TxHash.String(), err))\n\t\t\tcontinue\n\t\t}\n\n\t\tif utils.IsEmpty(result) {\n\t\t\tl.Infow(\"Request already fulfilled\",\n\t\t\t\t\"reqID\", reqs[i].req.RequestID().String(),\n\t\t\t\t\"attempts\", reqs[i].attempts,\n\t\t\t\t\"txHash\", reqs[i].req.Raw().TxHash)\n\t\t\tfulfilled[i] = true\n\t\t}\n\t}\n\n\tl.Debugw(\"Done checking fulfillment status\",\n\t\t\"numChecked\", len(reqs), \"time\", time.Since(start).String())\n\treturn fulfilled, errs\n}", "func (s *Storage) GetIncompletePulses() ([]models.Pulse, error) {\n\ttimer := prometheus.NewTimer(GetIncompletePulsesDuration)\n\tdefer timer.ObserveDuration()\n\n\tvar pulses []models.Pulse\n\terr := s.db.Where(\"is_complete = ?\", false).Find(&pulses).Error\n\treturn pulses, err\n}", "func deserializeSpendJournalEntry(serialized []byte, txns []*protos.MsgTx, vtxns []*protos.MsgTx) ([]txo.SpentTxOut, error) {\n\t// Calculate the total number of stxos.\n\tvar numStxos int\n\tfor _, tx := range txns {\n\t\tnumStxos += len(tx.TxIn)\n\t}\n\tfor _, tx := range vtxns {\n\t\tfor _, txin := range tx.TxIn {\n\t\t\tif asiutil.IsMintOrCreateInput(txin) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnumStxos++\n\t\t}\n\t}\n\n\t// When a block has no spent txouts there is nothing to serialize.\n\tif len(serialized) == 0 {\n\t\t// Ensure the block actually has no stxos. This should never\n\t\t// happen unless there is database corruption or an empty entry\n\t\t// erroneously made its way into the database.\n\t\tif numStxos != 0 {\n\t\t\treturn nil, common.AssertError(fmt.Sprintf(\"mismatched spend \"+\n\t\t\t\t\"journal serialization - no serialization for \"+\n\t\t\t\t\"expected %d stxos\", numStxos))\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\t// Loop backwards through all transactions so everything is read in\n\t// reverse order to match the serialization order.\n\toffset := 0\n\tstxos := make([]txo.SpentTxOut, numStxos)\n\tfor stxoIdx := numStxos - 1; stxoIdx > -1; stxoIdx-- {\n\t\tstxo := &stxos[stxoIdx]\n\t\tn, err := decodeSpentTxOut(serialized[offset:], stxo)\n\t\toffset += n\n\t\tif err != nil {\n\t\t\treturn nil, common.DeserializeError(fmt.Sprintf(\"unable \"+\n\t\t\t\t\"to decode stxo: %v\", err))\n\t\t}\n\t}\n\n\treturn stxos, nil\n}", "func RejectBooking(c *gin.Context) {\n\tvar input models.RejectInput\n\tif err := c.ShouldBindJSON(&input); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Check input bookingID\"})\n\t\tfmt.Println(\"Error in reading input NUSNET_ID. \" + err.Error() + \"\\n\")\n\t\treturn\n\t}\n\n\t// get ID to update status to\n\tstatusID, err := GetBookingStatusCode(DB, \"Rejected\")\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error(), \"message\": \"Unable to query for booking status ID.\"})\n\t\tfmt.Println(\"Unable to query for booking status ID. \" + err.Error() + \"\\n\")\n\t\treturn\n\t}\n\n\tcount, err := UpdateBookingsStatus(DB, models.MakeDeleteBookings{BookingID: []string{input.BookingID}}, statusID)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error(), \"message\": \"Unable to update booking successfully.\"})\n\t\tfmt.Println(\"Unable to update booking successfully. \" + err.Error() + \"\\n\")\n\t\treturn\n\t} else {\n\t\tsuccessMsg := fmt.Sprintf(\"Successfully rejected %d booking(s)!\", count)\n\t\tfmt.Println(successMsg)\n\t}\n\n\t// get booking to refund points\n\tbooking, exists, err := RetrieveBooking(DB, models.URLBooking{BookingID: input.BookingID})\n\tif !exists {\n\t\terrorMessage := fmt.Sprintf(\"No booking with ID %s exists.\", booking.ID)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"success\": false, \"message\": errorMessage})\n\t\tfmt.Println(errorMessage)\n\t\treturn\n\t}\n\tif err != nil {\n\t\terrorMessage := fmt.Sprintf(\"No booking with ID %s exists.\", booking.ID)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"success\": false, \"message\": errorMessage})\n\t\tfmt.Println(errorMessage)\n\t\treturn\n\t}\n\n\trefunded, err := AddPoints(DB, booking.Nusnetid, booking.Cost)\n\tif err != nil {\n\t\terrorMessage := fmt.Sprintf(\"Unable to refund points for booking with ID %s to user %s. \"+err.Error(), booking.ID, booking.Nusnetid)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error(), \"message\": errorMessage})\n\t\tfmt.Println(errorMessage)\n\t\treturn\n\t}\n\n\temailInfo, err := PopulateRejectEmailInfo(booking.ID.String(), input.Reason)\n\tif err != nil {\n\t\terrorMessage := fmt.Sprintf(\"Unable to populate reject email for booking with ID %s to user %s. \"+err.Error(), booking.ID, booking.Nusnetid)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error(), \"message\": errorMessage})\n\t\tfmt.Println(errorMessage)\n\t}\n\n\tif err := SendRejectBookingEmail(emailInfo); err != nil {\n\t\terrorMessage := fmt.Sprintf(\"Unable to send reject email for booking with ID %s to user %s. \"+err.Error(), booking.ID, booking.Nusnetid)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error(), \"message\": errorMessage})\n\t\tfmt.Println(errorMessage)\n\t}\n\n\tsuccessMessage := fmt.Sprintf(\"Successfully rejected booking with ID %s. Total of %.1f point(s) refunded to user %s.\",\n\t\tbooking.ID, refunded, booking.Nusnetid)\n\tc.JSON(http.StatusOK, gin.H{\"success\": true, \"message\": successMessage})\n\tfmt.Println(successMessage)\n}", "func (f Fortune) Savings() decimal.Decimal { return f.saving }", "func (s *Service) UpWithdraw(c context.Context, dateVersion string, from, limit int) (count int, upAccounts []*model.UpAccount, err error) {\n\tcount, err = s.dao.GetUpAccountCount(c, dateVersion)\n\tif err != nil {\n\t\tlog.Error(\"s.dao.GetUpAccountCount error(%v)\", err)\n\t\treturn\n\t}\n\tif count <= 0 {\n\t\treturn\n\t}\n\n\tupAccounts, err = s.dao.QueryUpAccountByDate(c, dateVersion, from, limit)\n\tif err != nil {\n\t\tlog.Error(\"s.dao.QueryUpAccountByDate error(%v)\", err)\n\t\treturn\n\t}\n\tif len(upAccounts) == 0 {\n\t\treturn\n\t}\n\n\tmids := make([]int64, len(upAccounts))\n\tfor i, up := range upAccounts {\n\t\tmids[i] = up.MID\n\t}\n\n\t// get up_income_withdraw by mids and date\n\tupIncomeWithdrawMap, err := s.dao.QueryUpWithdrawByMids(c, mids, dateVersion)\n\tif err != nil {\n\t\tlog.Error(\"s.dao.QueryUpWithdrawByMids error(%v)\", err)\n\t\treturn\n\t}\n\n\tfor _, up := range upAccounts {\n\t\tif _, ok := upIncomeWithdrawMap[up.MID]; !ok {\n\t\t\tupIncomeWithdraw := &model.UpIncomeWithdraw{\n\t\t\t\tMID: up.MID,\n\t\t\t\tWithdrawIncome: up.TotalUnwithdrawIncome,\n\t\t\t\tDateVersion: dateVersion,\n\t\t\t\tState: _withdrawing,\n\t\t\t}\n\n\t\t\terr = s.InsertUpWithdrawRecord(c, upIncomeWithdraw)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"s.InsertUpWithdrawRecord error(%v)\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (a *Account) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(a.lockedOutpoints))\n\ti := 0\n\tfor op := range a.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (c *ClaimPayment) TotalDue() decimal.Decimal {\n\ttotalDue := decimal.Zero\n\tfor _, sc := range c.ClaimsPayed {\n\t\ttotalDue = totalDue.Add(sc.EventSlot.Cost)\n\t}\n\treturn totalDue\n}", "func m7RewardsAndDatesPart2(db *IndexerDb, state *MigrationState) error {\n\tdb.log.Print(\"m7 account cumulative rewards migration starting\")\n\n\t// Skip the work if all accounts have previously been updated.\n\tif (state.PointerRound == nil) || (*state.PointerRound != 0) || (*state.PointerIntra != 0) {\n\t\tmaxRound := uint32(state.NextRound)\n\n\t\t// Get the number of accounts to potentially warn the user about high memory usage.\n\t\terr := warnUser(db, maxRound)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Get special accounts, so that we can ignore them throughout the migration. A later migration\n\t\t// handles them.\n\t\tspecialAccounts, err := db.GetSpecialAccounts()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"m7: unable to get special accounts: %v\", err)\n\t\t}\n\t\t// Get the transaction id that created each account. This function simple loops over all\n\t\t// transactions from rounds <= `maxRound` in arbitrary order.\n\t\taccountsFirstUsed, err := getAccountsFirstUsed(db, maxRound, specialAccounts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Get account data for accounts without transactions such as genesis accounts.\n\t\t// This function reads the `account` table but only considers accounts created before or at\n\t\t// `maxRound`.\n\t\treadyAccountData, err := getAccountsWithoutTxnData(\n\t\t\tdb, maxRound, specialAccounts, accountsFirstUsed)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Finally, read all transactions from most recent to oldest, update rewards and create/close dates,\n\t\t// and write this account data to the database. To save memory, this function removes account's\n\t\t// data as soon as we reach the transaction that created this account at which point older\n\t\t// transactions cannot update its state. It writes account data to the database in batches.\n\t\terr = updateAccounts(db, specialAccounts, accountsFirstUsed, readyAccountData, state)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Update migration state.\n\tstate.NextMigration++\n\tstate.NextRound = 0\n\tstate.PointerRound = nil\n\tstate.PointerIntra = nil\n\tmigrationStateJSON := encoding.EncodeJSON(state)\n\t_, err := db.db.Exec(setMetastateUpsert, migrationMetastateKey, migrationStateJSON)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"m7: failed to write final migration state: %v\", err)\n\t}\n\n\treturn nil\n}", "func (t *TaskChaincode) getBalance(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\t// 0\n\t// \"$account\"\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tfmt.Println(\"cacluate begins!\");\n\tif len(args[0]) <= 0 {\n\t\treturn shim.Error(\"1st argument must be a non-empty string\")\n\t}\n\n\taccount := args[0]\n\n\tqueryString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"objectType\\\":\\\"PayTX\\\",\\\"payer\\\":\\\"%s\\\"}}\", account)\n\tqueryResults, err := getResultForQueryString(stub, queryString)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tvar payerTXs []payTX\n\terr = json.Unmarshal(queryResults, &payerTXs)\n\tif err != nil {\n\t\tshim.Error(err.Error())\n\t}\n\n\t//fmt.Println(len(payTXs))\n\tvar i int\n\toutcomeVal := 0.0\n for i=0;i<len(payerTXs);i=i+1 {\n\t\tpayerTX := payerTXs[i]\n\t\toutcomeVal = outcomeVal + payerTX.Value\n\t}\n //fmt.Println(outcomeVal)\n\n\tqueryString = fmt.Sprintf(\"{\\\"selector\\\":{\\\"objectType\\\":\\\"PayTX\\\",\\\"payee\\\":\\\"%s\\\"}}\", account)\n\tqueryResults, err = getResultForQueryString(stub, queryString)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tvar payeeTXs []payTX\n\terr = json.Unmarshal(queryResults, &payeeTXs)\n\tif err != nil {\n\t\tshim.Error(err.Error())\n\t}\n\n\tincomeVal := 0.0\n for i=0;i<len(payeeTXs);i=i+1 {\n\t\tpayeeTX := payeeTXs[i]\n\t\tincomeVal = incomeVal + payeeTX.Value\n\t}\n //fmt.Println(incomeVal)\n\n\tbalance := incomeVal - outcomeVal\n\t//fmt.Println(balance)\n balanceStr := strconv.FormatFloat(balance, 'f', 6, 64)\n\n return shim.Success([]byte(balanceStr))\n}", "func TestGetEmptyPayrollReport(t *testing.T) {\n\tresetTables()\n\n\t// create and send request\n\trequest, err := http.NewRequest(\"GET\", \"/report\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// check for http.StatusOK\n\tresponse := sendRequest(request)\n\tcheckStatusCode(t, http.StatusOK, response.Code)\n}", "func main() {\n\tvar sides int = 10000\n\tlog.Printf(\"rolling a %v sided dice\\n\", sides)\n\tunique_rolls := map[int]bool{}\n\ti := 1\n\tfor len(unique_rolls) < sides {\n\t\tvar roll int = roll(sides)\n\t\tfmt.Println(\"rolled a\", roll)\n\t\tunique_rolls = updateUniqueRolls(roll, unique_rolls)\n\t\ti += 1\n\t}\n\tlog.Printf(\"got %v unique rolls in %v attempts \\n\", len(unique_rolls), i)\n}", "func CheckObstacles(party structs.Party, room *structs.Room) (structs.Party, *structs.Room) {\n\t//\n\troll := rand.Intn(20) + 1\n\tfmt.Println(\"TEST\")\n\tbonus := 0\n\tobstaclesPassed := 0\n\n\tfor _, obstacle := range room.Obstacles {\n\t\tif obstacle.ObstaclePassed {\n\t\t\tobstaclesPassed++\n\t\t\tcontinue\n\t\t}\n\t\t// Loop through party\n\t\tfor _, player := range party.Members {\n\t\t\tif player.Condition == \"Dead\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif obstacle.ObstacleType == \"Door\" {\n\t\t\t\t// Locked door -- lockpick it\n\t\t\t\tbonus = BonusAllocation(player.Proficiencies.Stealth)\n\t\t\t} else if obstacle.ObstacleType == \"Rubble\" || obstacle.ObstacleType == \"GiantMachine\" || obstacle.ObstacleType == \"Boulder\" {\n\t\t\t\t// Physique check\n\t\t\t\tbonus = BonusAllocation(player.Proficiencies.Fisticuffs)\n\t\t\t} else if obstacle.ObstacleType == \"Inactive Machine\" {\n\t\t\t\tbonus = BonusAllocation(player.Proficiencies.Engineering)\n\t\t\t}\n\n\t\t\tif roll+bonus > obstacle.ObstacleRequirement || roll == 20 {\n\t\t\t\t// Obstacle passed\n\t\t\t\tobstacle.ObstaclePassed = true\n\t\t\t\tobstaclesPassed++\n\t\t\t\tplayer.Stats.ObstaclesOvercome++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif obstaclesPassed == len(room.Obstacles) {\n\t\t\t// Break Locks on Room\n\t\t\troom.Locked = false\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn party, room\n}", "func (a *Account) ResetLockedOutpoints() {\n\ta.lockedOutpoints = map[btcwire.OutPoint]struct{}{}\n}", "func AdmitStatuses() admitStatus {\n\tonce.Do(func() {\n\t\t_admitStatus.Admitted = 9\n\t\t_admitStatus.Full = -2\n\t\t_admitStatus.Late = -3\n\t})\n\treturn _admitStatus\n}", "func (ros *RolloutState) startNextVeniceRollout() (int, error) {\n\tsm := ros.Statemgr\n\tversion := ros.Spec.Version\n\n\tpendingStatus := ros.getVenicePendingRolloutStatus()\n\tif len(pendingStatus) > 0 {\n\t\t// some node has been issued rollout spec and we are waiting for status update.\n\t\t// nothing to do now\n\t\treturn len(pendingStatus), nil\n\t}\n\n\t// all nodes which have been issued the request so far have responded.\n\t// if there is any node which has not yet been issued, issue it now\n\n\tveniceROs, err := sm.ListVeniceRollouts()\n\tif err != nil {\n\t\tlog.Errorf(\"Error %v listing VeniceRollouts\", err)\n\t\treturn len(pendingStatus), err\n\t}\n\tpendingVenice := getVenicePendingRolloutIssue(version, veniceROs)\n\tif len(pendingVenice) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tselectedVenice := pendingVenice[0]\n\tfor _, v := range veniceROs {\n\t\tif v.Name != selectedVenice {\n\t\t\tcontinue\n\t\t}\n\t\tv.Spec.Ops = append(v.Spec.Ops, protos.VeniceOpSpec{Op: protos.VeniceOp_VeniceRunVersion, Version: version})\n\n\t\tlog.Debugf(\"setting VeniceRollout for %v with version %v\", v.Name, version)\n\t\terr = sm.memDB.UpdateObject(v)\n\t\tif err == nil {\n\t\t\tlog.Infof(\"Setting Rollout Status %#v\", v.status[protos.VeniceOp_VenicePreCheck])\n\t\t\tros.setVenicePhase(v.Name, v.status[protos.VeniceOp_VenicePreCheck].OpStatus, v.status[protos.VeniceOp_VenicePreCheck].Message, roproto.RolloutPhase_PROGRESSING)\n\t\t}\n\t\treturn 1, err\n\n\t}\n\treturn 0, fmt.Errorf(\"unexpected error - unknown venice %s selected for next rollout\", selectedVenice)\n}", "func (rb *RbLdap) AlertUnPaid() error {\n\tusers, err := rb.SearchUsers(\"(&(|(yearspaid=0)(yearspaid=-1))(|(usertype=member)(usertype=associate)(usertype=staff))\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, user := range users {\n\t\tif err := rb.mailUnPaidWarning(user); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"%s has been warned\\n\", user.UID)\n\t}\n\treturn nil\n}", "func (wbs *impl) Incomes() incomes.Interface { return wbs.inc }", "func CheckInvoiceStatus(so *model.SalesOrder) (e error) {\n\tCalculateTotalPaidSO(so)\n\tso.Read()\n\n\to := orm.NewOrm()\n\tif so.TotalPaid == so.TotalCharge {\n\t\t_, e = o.Raw(\"update sales_order so set so.invoice_status = 'finished' where id = ?\", so.ID).Exec()\n\t\treturn e\n\t}\n\treturn nil\n}", "func MarkAsPaid(w http.ResponseWriter, r *http.Request) {\n\n\tvar err error\n\n\tjwt := r.URL.Query().Get(\"jwt\")\n\tif jwt == \"\" {\n\t\tb := []byte(\"[]\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Write(b)\n\t\treturn\n\t}\n\n\t// decode the jwt to grab the email.\n\tpassphrase := auth.GetPassphrase()\n\n\tstrPayload, _, err := jose.Decode(jwt, passphrase)\n\tpayload := []byte(strPayload)\n\n\tvar User pbu.User\n\terr = json.Unmarshal(payload, &User)\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\n\tvar b = []byte(\"[]\")\n\tif User.GetSocialID() != \"FB10153502750990419\" {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Write(b)\n\t\treturn\n\t}\n\n\ttblWinners := db.Table(\"Winners\")\n\n\twinnerid := r.URL.Query().Get(\"winnerid\")\n\tint64WinnerID, _ := strconv.ParseInt(winnerid, 10, 64)\n\tvar winners []pb.WinnerReply_Winner\n\terr = tblWinners.Scan().Filter(\"WinnerID = ?\", int64WinnerID).All(&winners)\n\tif err != nil {\n\t\tfmt.Printf(err.Error())\n\t}\n\n\twinner := winners[0]\n\n\tif winner.Paid == true {\n\t\tb = []byte(\"{\\\"failure\\\": \\\"already paid\\\"}\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Write(b)\n\t\treturn\n\t}\n\twinner.Paid = true\n\n\ttblUsers := db.Table(\"Users\")\n\n\tvar users []pbu.User\n\terr = tblUsers.Scan().Filter(\"SocialID = ?\", winner.WinningTicket.SocialID).All(&users)\n\tif err != nil {\n\t\tfmt.Printf(err.Error())\n\t}\n\n\tu := users[0]\n\tfmt.Println(u)\n\tu.Balance = u.Balance - winner.MoneyPot\n\n\ttblWinners.Put(winner).Run()\n\ttblUsers.Put(u).Run()\n\n\tb = []byte(\"{\\\"success\\\": \\\"paid\\\"}\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Write(b)\n\treturn\n}", "func (r *AutoRoller) updateCurrentRoll() error {\n\tcurrentRoll := r.recent.CurrentRoll()\n\tif currentRoll == nil {\n\t\treturn nil\n\t}\n\tcurrentResult := currentRoll.Result\n\n\tupdated, err := r.retrieveRoll(currentRoll.Issue)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// We have to rely on data we store for the dry run case.\n\tif !updated.Closed && util.In(currentResult, autoroll.DRY_RUN_RESULTS) {\n\t\tupdated.Result = currentResult\n\t}\n\n\t// If the current roll succeeded, we need to make sure we update the\n\t// repo so that we see the roll commit. This can take some time, so\n\t// we have to repeatedly update until we see the commit.\n\tif updated.Committed {\n\t\tsklog.Infof(\"Roll succeeded (%d); syncing the repo until it lands.\", currentRoll.Issue)\n\t\tfor {\n\t\t\tsklog.Info(\"Syncing...\")\n\t\t\tsklog.Infof(\"Looking for %s\", currentRoll.RollingTo)\n\t\t\tif err := r.rm.ForceUpdate(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trolledPast, err := r.rm.RolledPast(currentRoll.RollingTo)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif rolledPast {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t\tr.liveness.Reset()\n\t}\n\treturn r.recent.Update(updated)\n}", "func CheckFulfillmentStatus(so *model.SalesOrder) (e error) {\n\to := orm.NewOrm()\n\n\tvar quantitySOItem float64\n\n\tif e = o.Raw(\"SELECT sum(quantity) from sales_order_item soi inner join sales_order so on soi.sales_order_id = so.id\"+\n\t\t\" where so.document_status != 'approved_cancel' AND so.is_deleted = 0\"+\n\t\t\" AND sales_order_id = ?\", so.ID).QueryRow(&quantitySOItem); e != nil {\n\t\treturn e\n\t}\n\n\tvar quantityFItem float64\n\tif e = o.Raw(\"select sum(wfi.quantity) from workorder_fulfillment_item wfi \"+\n\t\t\"inner join workorder_fulfillment wf on wf.id = wfi.workorder_fulfillment_id \"+\n\t\t\"inner join sales_order_item soi on soi.id = wfi.sales_order_item_id \"+\n\t\t\"inner join sales_order so on so.id = soi.sales_order_id \"+\n\t\t\"where wf.is_deleted = 0 and wf.document_status = 'finished' and so.document_status != 'approved_cancel' \"+\n\t\t\"and so.is_deleted = 0 and wf.sales_order_id = ?\", so.ID).QueryRow(&quantityFItem); e != nil {\n\n\t\treturn e\n\t}\n\n\tif quantitySOItem > 0 && quantityFItem == quantitySOItem {\n\t\t_, e = o.Raw(\"update sales_order so set so.fulfillment_status = 'finished' where id = ?\", so.ID).Exec()\n\t\treturn e\n\t}\n\n\tCheckDocumentStatus(so)\n\n\treturn nil\n}", "func (q queryManager) checkQueryNeedsPayment(qp dbquery.QueryParsed) (float64, error) {\n\treturn 0, nil\n}", "func MonthlyTotalSpent(startDate, endDate time.Time) ([]MonthTotals, error) {\n // query to return budget and ledger amount spent by month and year\n rows, err := db.Query(`SELECT\n mon,\n yyyy,\n sum(actual) as actual,\n sum(budget) as budget\n FROM\n (\n SELECT\n to_char(trans_date,'Mon') as mon, extract(year from trans_date) as yyyy,\n sum(credit-debit) as actual , 0 as budget, date_trunc('month', trans_date) as num_month\n FROM ledger\n WHERE trans_date >= $1 AND trans_date < $2\n GROUP BY mon, yyyy, date_trunc('month', trans_date)\n UNION ALL\n SELECT to_char(trans_date,'Mon') as mon, extract(year from trans_date) as yyyy,\n 0 as actual, sum(credit-debit) as budget, date_trunc('month', trans_date) as num_month\n FROM budget\n WHERE trans_date >= $1 AND trans_date < $2\n GROUP BY mon, yyyy, date_trunc('month', trans_date)\n ) x\n GROUP BY mon, yyyy, num_month\n ORDER BY yyyy, num_month ASC`, startDate, endDate)\n\n if err != nil {\n fmt.Println(err)\n return nil, err\n }\n defer rows.Close()\n\n var arrMonthTotals []MonthTotals\n\n for rows.Next() {\n var mt MonthTotals\n err := rows.Scan(&mt.Month, &mt.Year, &mt.LedgerTotal, &mt.BudgetTotal)\n if err != nil {\n fmt.Println(\"err: \", err)\n return nil, err\n }\n arrMonthTotals = append(arrMonthTotals, mt)\n }\n\n if err = rows.Err(); err != nil {\n fmt.Println(\"error scanning a row\", err)\n return nil, err\n }\n\n return arrMonthTotals, nil\n}" ]
[ "0.57356566", "0.5479733", "0.54588735", "0.5436188", "0.52653223", "0.5260277", "0.5216394", "0.52141994", "0.5058578", "0.5051422", "0.49846932", "0.4954352", "0.48988274", "0.4898623", "0.489642", "0.48861998", "0.487734", "0.48717463", "0.48717365", "0.48683372", "0.48443824", "0.47670478", "0.47483823", "0.4744872", "0.46993053", "0.4694398", "0.4666296", "0.4665152", "0.46549463", "0.46543112", "0.4649727", "0.46456924", "0.4635887", "0.46183485", "0.46012926", "0.4597465", "0.45947474", "0.45946857", "0.45937982", "0.45918676", "0.45749223", "0.45696053", "0.4545921", "0.45333126", "0.45307332", "0.45195594", "0.451346", "0.44948685", "0.4490428", "0.44831735", "0.44820166", "0.44818774", "0.44793427", "0.44698724", "0.44612235", "0.44585317", "0.44570366", "0.44453916", "0.4436343", "0.44348335", "0.443181", "0.4431164", "0.44265985", "0.44174984", "0.4412016", "0.44115952", "0.4376666", "0.43765068", "0.43679252", "0.43659616", "0.4364632", "0.43611306", "0.4353533", "0.43482557", "0.43478", "0.43474835", "0.43468714", "0.43463543", "0.43427074", "0.43418333", "0.43398926", "0.43358338", "0.43248248", "0.43180153", "0.43136007", "0.4312642", "0.4308693", "0.4304554", "0.42973095", "0.42936027", "0.42931056", "0.42930204", "0.42905664", "0.4290508", "0.42839113", "0.42830268", "0.42816564", "0.42811596", "0.42806765", "0.42762724" ]
0.56810594
1
/ Description: Reverse the order of an array of DelegatedClient. Used when fisrt retreiving contracts because the Tezos RPC API returns the newest contract first. Param delegatedContracts ([]DelegatedClient) Delegated
func SortDelegateContracts(delegatedContracts []DelegatedContract) []DelegatedContract{ for i, j := 0, len(delegatedContracts)-1; i < j; i, j = i+1, j-1 { delegatedContracts[i], delegatedContracts[j] = delegatedContracts[j], delegatedContracts[i] } return delegatedContracts }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{\n for _, delegatedContract := range delegatedContracts {\n err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias)\n if (err != nil){\n return errors.New(\"Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: \" + err.Error())\n }\n }\n return nil\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func GetAllDelegatedContracts(delegateAddr string) ([]string, error){\n var rtnString []string\n delegatedContractsCmd := \"/chains/main/blocks/head/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n s, err := TezosRPCGet(delegatedContractsCmd)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts: TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1) //TODO Error checking\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get all delegated contracts: Regex failed\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func (_ConsortiumManagement *ConsortiumManagementCaller) Delegates(opts *bind.CallOpts) ([]common.Address, error) {\n\tvar out []interface{}\n\terr := _ConsortiumManagement.contract.Call(opts, &out, \"delegates\")\n\n\tif err != nil {\n\t\treturn *new([]common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address)\n\n\treturn out0, err\n\n}", "func (_ConsortiumManagement *ConsortiumManagementCallerSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func (k Querier) Redelegations(ctx context.Context, req *types.QueryRedelegationsRequest) (*types.QueryRedelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tvar redels types.Redelegations\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tstore := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))\n\tswitch {\n\tcase req.DelegatorAddr != \"\" && req.SrcValidatorAddr != \"\" && req.DstValidatorAddr != \"\":\n\t\tredels, err = queryRedelegation(ctx, k, req)\n\tcase req.DelegatorAddr == \"\" && req.SrcValidatorAddr != \"\" && req.DstValidatorAddr == \"\":\n\t\tredels, pageRes, err = queryRedelegationsFromSrcValidator(ctx, store, k, req)\n\tdefault:\n\t\tredels, pageRes, err = queryAllRedelegations(ctx, store, k, req)\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\tredelResponses, err := redelegationsToRedelegationResponses(ctx, k.Keeper, redels)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRedelegationsResponse{RedelegationResponses: redelResponses, Pagination: pageRes}, nil\n}", "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func GetDelegatedContractsForCycle(cycle int, delegateAddr string) ([]string, error){\n var rtnString []string\n snapShot, err := GetSnapShot(cycle)\n // fmt.Println(snapShot)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetSnapShot(cycle int) failed: \" + err.Error())\n }\n hash, err:= GetBlockLevelHash(snapShot.AssociatedBlock)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": GetBlockLevelHash(level int) failed: \" + err.Error())\n }\n // fmt.Println(hash)\n getDelegatedContracts := \"/chains/main/blocks/\" + hash + \"/context/delegates/\" + delegateAddr + \"/delegated_contracts\"\n\n s, err := TezosRPCGet(getDelegatedContracts)\n if (err != nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": TezosRPCGet(arg string) failed: \" + err.Error())\n }\n\n DelegatedContracts := reDelegatedContracts.FindAllStringSubmatch(s, -1)\n if (DelegatedContracts == nil){\n return rtnString, errors.New(\"Could not get delegated contracts for cycle \" + strconv.Itoa(cycle) + \": You have no contracts.\")\n }\n rtnString = addressesToArray(DelegatedContracts)\n return rtnString, nil\n}", "func (_ConsortiumManagement *ConsortiumManagementSession) Delegates() ([]common.Address, error) {\n\treturn _ConsortiumManagement.Contract.Delegates(&_ConsortiumManagement.CallOpts)\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) Delegations(arg0 [32]byte) (common.Address, error) {\n\treturn _PlasmaFramework.Contract.Delegations(&_PlasmaFramework.CallOpts, arg0)\n}", "func (k Querier) DelegatorDelegations(ctx context.Context, req *types.QueryDelegatorDelegationsRequest) (*types.QueryDelegatorDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegations, pageRes, err := query.CollectionPaginate(ctx, k.Delegations, req.Pagination,\n\t\tfunc(_ collections.Pair[sdk.AccAddress, sdk.ValAddress], del types.Delegation) (types.Delegation, error) {\n\t\t\treturn del, nil\n\t\t}, query.WithCollectionPaginationPairPrefix[sdk.AccAddress, sdk.ValAddress](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelegationResps, err := delegationsToDelegationResponses(ctx, k.Keeper, delegations)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorDelegationsResponse{DelegationResponses: delegationResps, Pagination: pageRes}, nil\n}", "func (_Bep20 *Bep20CallerSession) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) Delegations(opts *bind.CallOpts, arg0 [32]byte) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (_Bep20 *Bep20Caller) Delegates(opts *bind.CallOpts, delegator common.Address) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"delegates\", delegator)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_PlasmaFramework *PlasmaFrameworkSession) Delegations(arg0 [32]byte) (common.Address, error) {\n\treturn _PlasmaFramework.Contract.Delegations(&_PlasmaFramework.CallOpts, arg0)\n}", "func (k Querier) DelegatorUnbondingDelegations(ctx context.Context, req *types.QueryDelegatorUnbondingDelegationsRequest) (*types.QueryDelegatorUnbondingDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tvar unbondingDelegations types.UnbondingDelegations\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, pageRes, err := query.CollectionPaginate(\n\t\tctx,\n\t\tk.UnbondingDelegations,\n\t\treq.Pagination,\n\t\tfunc(key collections.Pair[[]byte, []byte], value types.UnbondingDelegation) (types.UnbondingDelegation, error) {\n\t\t\tunbondingDelegations = append(unbondingDelegations, value)\n\t\t\treturn value, nil\n\t\t},\n\t\tquery.WithCollectionPaginationPairPrefix[[]byte, []byte](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorUnbondingDelegationsResponse{\n\t\tUnbondingResponses: unbondingDelegations, Pagination: pageRes,\n\t}, nil\n}", "func (s *RoundsService) Delegates(ctx context.Context, id int64) (*GetDelegates, *http.Response, error) {\n\turi := fmt.Sprintf(\"rounds/%v/delegates\", id)\n\n\tvar responseStruct *GetDelegates\n\tresp, err := s.client.SendRequest(ctx, \"GET\", uri, nil, nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_Bep20 *Bep20Session) Delegates(delegator common.Address) (common.Address, error) {\n\treturn _Bep20.Contract.Delegates(&_Bep20.CallOpts, delegator)\n}", "func reverse(s []library.Service) []library.Service {\n\t// sort the list of services based off the service number\n\tsort.SliceStable(s, func(i, j int) bool {\n\t\treturn s[i].GetNumber() < s[j].GetNumber()\n\t})\n\n\treturn s\n}", "func (s *ArkClient) ListDelegates(params DelegateQueryParams) (DelegateResponse, *http.Response, error) {\n\trespData := new(DelegateResponse)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\treturn *respData, resp, err\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func (acc *Account) Delegations(args *struct {\n\tCursor *Cursor\n\tCount int32\n}) (*DelegationList, error) {\n\t// limit query size; the count can be either positive or negative\n\t// this controls the loading direction\n\targs.Count = listLimitCount(args.Count, listMaxEdgesPerRequest)\n\n\t// pull the list\n\tdl, err := repository.R().DelegationsByAddress(&acc.Address, (*string)(args.Cursor), args.Count)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// convert to resolvable list\n\treturn NewDelegationList(dl), nil\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func InterfaceSliceReversed(slice []interface{}) []interface{} {\n\treversed := make([]interface{}, len(slice))\n\tcopy(reversed, slice)\n\tfor i := len(reversed)/2 - 1; i >= 0; i-- {\n\t\topposite := len(reversed) - 1 - i\n\t\treversed[i], reversed[opposite] = reversed[opposite], reversed[i]\n\t}\n\treturn reversed\n}", "func (k Keeper) GetAllDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress) []types.Delegation {\n\tdelegations := make([]types.Delegation, 0)\n\n\tstore := ctx.KVStore(k.storeKey)\n\tdelegatorPrefixKey := types.GetDelegationsKey(delegator)\n\n\titerator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) //smallest to largest\n\tdefer iterator.Close()\n\n\ti := 0\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tdelegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value())\n\t\tdelegations = append(delegations, delegation)\n\t\ti++\n\t}\n\n\treturn delegations\n}", "func (k Querier) DelegatorValidators(ctx context.Context, req *types.QueryDelegatorValidatorsRequest) (*types.QueryDelegatorValidatorsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tvar validators types.Validators\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, pageRes, err := query.CollectionPaginate(ctx, k.Delegations, req.Pagination,\n\t\tfunc(_ collections.Pair[sdk.AccAddress, sdk.ValAddress], delegation types.Delegation) (types.Delegation, error) {\n\t\t\tvalAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())\n\t\t\tif err != nil {\n\t\t\t\treturn types.Delegation{}, err\n\t\t\t}\n\t\t\tvalidator, err := k.GetValidator(ctx, valAddr)\n\t\t\tif err != nil {\n\t\t\t\treturn types.Delegation{}, err\n\t\t\t}\n\n\t\t\tvalidators.Validators = append(validators.Validators, validator)\n\t\t\treturn types.Delegation{}, nil\n\t\t}, query.WithCollectionPaginationPairPrefix[sdk.AccAddress, sdk.ValAddress](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorValidatorsResponse{Validators: validators.Validators, Pagination: pageRes}, nil\n}", "func reverse(args []interface{}) []interface{} {\n\treversed := make([]interface{}, len(args))\n\n\tj := 0\n\tfor i := len(args) - 1; i >= 0; i-- {\n\t\treversed[j] = args[i]\n\t\tj++\n\t}\n\n\treturn reversed\n}", "func (k Querier) ValidatorDelegations(ctx context.Context, req *types.QueryValidatorDelegationsRequest) (*types.QueryValidatorDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tdels types.Delegations\n\t\tpageRes *query.PageResponse\n\t)\n\n\tdels, pageRes, err = query.CollectionPaginate(ctx, k.DelegationsByValidator,\n\t\treq.Pagination, func(key collections.Pair[sdk.ValAddress, sdk.AccAddress], _ []byte) (types.Delegation, error) {\n\t\t\tvalAddr, delAddr := key.K1(), key.K2()\n\t\t\tdelegation, err := k.Delegations.Get(ctx, collections.Join(delAddr, valAddr))\n\t\t\tif err != nil {\n\t\t\t\treturn types.Delegation{}, err\n\t\t\t}\n\n\t\t\treturn delegation, nil\n\t\t}, query.WithCollectionPaginationPairPrefix[sdk.ValAddress, sdk.AccAddress](valAddr),\n\t)\n\n\tif err != nil {\n\t\tdelegations, pageResponse, err := k.getValidatorDelegationsLegacy(ctx, req)\n\t\tif err != nil {\n\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t}\n\n\t\tdels = types.Delegations{}\n\t\tfor _, d := range delegations {\n\t\t\tdels = append(dels, *d)\n\t\t}\n\n\t\tpageRes = pageResponse\n\t}\n\n\tdelResponses, err := delegationsToDelegationResponses(ctx, k.Keeper, dels)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryValidatorDelegationsResponse{\n\t\tDelegationResponses: delResponses, Pagination: pageRes,\n\t}, nil\n}", "func (f Forwarder) Reverse() error {\n\terrs := []string{}\n\tfor container := range f.Config.Forwards {\n\t\terr := f.ReverseContainer(container)\n\t\tif err != nil {\n\t\t\terrs = append(errs, container)\n\t\t}\n\t}\n\n\tvar err error\n\tif len(errs) > 0 {\n\t\terr = fmt.Errorf(\"Unable to remove forwarding of ports for containers %s\", strings.Join(errs, \", \"))\n\t}\n\treturn err\n}", "func CalculateAllContractsForCycles(delegatedContracts []DelegatedContract, cycleStart int, cycleEnd int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var err error\n\n for cycleStart <= cycleEnd {\n //fmt.Println(cycleStart)\n delegatedContracts, err = CalculateAllContractsForCycle(delegatedContracts, cycleStart, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycles \" + strconv.Itoa(cycleStart) + \"-\" + strconv.Itoa(cycleEnd) + \":CalculateAllCommitmentsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64) failed: \" + err.Error())\n }\n cycleStart = cycleStart + 1\n }\n return delegatedContracts, nil\n}", "func reverse(d []library.Deployment) []library.Deployment {\n\tsort.SliceStable(d, func(i, j int) bool {\n\t\treturn d[i].GetID() < d[j].GetID()\n\t})\n\n\treturn d\n}", "func (del Delegation) Deactivation() ([]DeactivatedDelegation, error) {\n\t// pull the requests list from remote server\n\twr, err := del.repo.DeactivatedDelegation(&del.Address, &del.ToStakerId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// sort the list\n\tsort.Sort(types.DeactivatedDelegationByAge(wr))\n\n\t// create new result set\n\tlist := make([]DeactivatedDelegation, 0)\n\n\t// iterate over the sorted list and populate the output array\n\tfor _, req := range wr {\n\t\tlist = append(list, NewDeactivatedDelegation(req, del.repo))\n\t}\n\n\t// return the final resolvable list\n\treturn list, nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowFilterer) FilterDepositRedelegated(opts *bind.FilterOpts, previousOperator []common.Address, newOperator []common.Address, grantId []*big.Int) (*TokenStakingEscrowDepositRedelegatedIterator, error) {\n\n\tvar previousOperatorRule []interface{}\n\tfor _, previousOperatorItem := range previousOperator {\n\t\tpreviousOperatorRule = append(previousOperatorRule, previousOperatorItem)\n\t}\n\tvar newOperatorRule []interface{}\n\tfor _, newOperatorItem := range newOperator {\n\t\tnewOperatorRule = append(newOperatorRule, newOperatorItem)\n\t}\n\tvar grantIdRule []interface{}\n\tfor _, grantIdItem := range grantId {\n\t\tgrantIdRule = append(grantIdRule, grantIdItem)\n\t}\n\n\tlogs, sub, err := _TokenStakingEscrow.contract.FilterLogs(opts, \"DepositRedelegated\", previousOperatorRule, newOperatorRule, grantIdRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokenStakingEscrowDepositRedelegatedIterator{contract: _TokenStakingEscrow.contract, event: \"DepositRedelegated\", logs: logs, sub: sub}, nil\n}", "func ExampleDelegatedSubnetServiceClient_BeginDeleteDetails() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armdelegatednetwork.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := clientFactory.NewDelegatedSubnetServiceClient().BeginDeleteDetails(ctx, \"TestRG\", \"delegated1\", &armdelegatednetwork.DelegatedSubnetServiceClientBeginDeleteDetailsOptions{ForceDelete: nil})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t_, err = poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n}", "func (n *NetConf) SetDelegates(newDelegates []*DelegateNetConf) error {\n\tn.Delegates = newDelegates\n\treturn nil\n}", "func WrapClient(w ...client.Wrapper) error {\n\tfor i := len(w); i > 0; i-- {\n\t\tDefault.Client = w[i-1](Default.Client)\n\t}\n\treturn nil\n}", "func Reverse(operand []string) []string {\n\treversed := make([]string, len(operand))\n\tfor i := range operand {\n\t\treversed[len(operand)-i-1] = operand[i]\n\t}\n\treturn reversed\n}", "func (*Functions) Reverse(in interface{}) interface{} {\n\tv := reflect.ValueOf(in)\n\tc := v.Len()\n\tout := reflect.MakeSlice(v.Type(), c, c)\n\tfor i := 0; i < c; i++ {\n\t\tout.Index(i).Set(v.Index(c - i - 1))\n\t}\n\treturn out.Interface()\n}", "func (nrs *NaiveStrategy) UnrelayedSequencesOrdered(src, dst *Chain, sh *SyncHeaders) (*RelaySequences, error) {\n\treturn UnrelayedSequences(src, dst, sh)\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (k Keeper) GetAllUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddress) []types.UnbondingDelegation {\n\tunbondingDelegations := make([]types.UnbondingDelegation, 0)\n\n\tstore := ctx.KVStore(k.storeKey)\n\tdelegatorPrefixKey := types.GetUBDsKey(delegator)\n\n\titerator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest\n\tdefer iterator.Close()\n\n\tfor i := 0; iterator.Valid(); iterator.Next() {\n\t\tunbondingDelegation := types.MustUnmarshalUBD(k.cdc, iterator.Value())\n\t\tunbondingDelegations = append(unbondingDelegations, unbondingDelegation)\n\t\ti++\n\t}\n\n\treturn unbondingDelegations\n}", "func (o OfflineNotaryRepository) GetDelegationRoles() ([]data.Role, error) {\n\treturn nil, storage.ErrOffline{}\n}", "func reverseSlice(orderedSlice []Message) []Message {\n\tlast := len(orderedSlice) - 1\n\tfor i := 0; i < len(orderedSlice)/2; i++ {\n\t\torderedSlice[i], orderedSlice[last-i] = orderedSlice[last-i], orderedSlice[i]\n\t}\n\n\treturn orderedSlice\n}", "func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\taddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttokens := msg.Amount.Amount\n\tshares, err := k.ValidateUnbondAmount(\n\t\tctx, delegatorAddress, addr, tokens,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, addr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, addr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be decremented\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.DecreaseTotalLiquidStakedTokens(ctx, tokens); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.Keeper.Undelegate(ctx, delegatorAddress, addr, shares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"undelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeUnbond,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgUndelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func (gc *GovernanceContract) DelegationsBy(args struct{ From common.Address }) ([]common.Address, error) {\n\t// decide by the contract type\n\tswitch gc.Type {\n\tcase \"sfc\":\n\t\treturn gc.sfcDelegationsBy(args.From)\n\t}\n\n\t// no delegations by default\n\tgc.repo.Log().Debugf(\"unknown governance type of %s\", gc.Address.Hex())\n\treturn []common.Address{}, nil\n}", "func ReverseSlice(s interface{}) {\n\tsize := reflect.ValueOf(s).Len()\n\tswap := reflect.Swapper(s)\n\tfor i, j := 0, size-1; i < j; i, j = i+1, j-1 {\n\t\tswap(i, j)\n\t}\n}", "func (ifc *Interface) SyncRoutes(want []*RouteData) error {\n\tvar erracc error\n\n\troutes, err := ifc.GetRoutes(AF_INET)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgot := make([]*RouteData, 0, len(routes))\n\tfor _, r := range routes {\n\t\tv, err := r.ToRouteData()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgot = append(got, v)\n\t}\n\n\tadd, del := deltaRouteData(got, want)\n\n\tfor _, a := range del {\n\t\terr := ifc.DeleteRoute(&a.Destination, &a.NextHop)\n\t\tif err != nil {\n\t\t\terracc = err\n\t\t}\n\t}\n\n\terr = ifc.AddRoutes(add)\n\tif err != nil {\n\t\terracc = err\n\t}\n\n\treturn erracc\n}", "func (c BasicController) ReverseProxy(\n\tw http.ResponseWriter,\n\tr *http.Request,\n\tservice model.Service,\n\thandler proxy.ResponseHandler,\n) error {\n\tp, err := proxy.New(service, handler, c.logger.WithField(\"type\", \"proxy\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn p.ReverseProxy(w, r)\n}", "func Reverse(sort []string) {\n\tns := len(sort) - 1\n\tfor i := 0; i < (ns+1)/2; i++ {\n\t\tsort[i], sort[ns-i] = sort[ns-i], sort[i]\n\t}\n}", "func (_TokenStakingEscrow *TokenStakingEscrowTransactor) Redelegate(opts *bind.TransactOpts, previousOperator common.Address, amount *big.Int, extraData []byte) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.contract.Transact(opts, \"redelegate\", previousOperator, amount, extraData)\n}", "func (r *Roller) ReverseCallDoneAt(i int, g interface{}) {\n\tif len(r.doners) <= 0 {\n\t\treturn\n\t}\n\ttotal := len(r.doners) - 1\n\tloc := total - i\n\n\tif loc >= 0 {\n\t\tval := r.doners[loc]\n\t\tif val != nil {\n\t\t\tval(g, func(fval interface{}) {\n\n\t\t\t\tind := i + 1\n\t\t\t\tif fval == nil {\n\t\t\t\t\tr.ReverseCallDoneAt(ind, g)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tr.ReverseCallDoneAt(ind, fval)\n\t\t\t})\n\t\t}\n\t}\n}", "func Reverse(data interface{}) (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\tresult := makeSlice(dataType)\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn result.Interface()\n\t\t}\n\n\t\tfor i := 0; i < dataValueLen; i++ {\n\t\t\tresult = reflect.Append(result, dataValue.Index(dataValueLen-1-i))\n\t\t}\n\n\t\treturn result.Interface()\n\t}(&err)\n\n\treturn result, err\n}", "func (plugin *ProxyArpConfigurator) ResyncInterfaces(nbProxyArpIfs []*l3.ProxyArpInterfaces_InterfaceList) error {\n\tplugin.log.Debug(\"RESYNC proxy ARP interfaces begin. \")\n\tdefer func() {\n\t\tif plugin.stopwatch != nil {\n\t\t\tplugin.stopwatch.PrintLog()\n\t\t}\n\t}()\n\n\t// Re-initialize cache\n\tplugin.clearMapping()\n\n\t// Todo: dump proxy arp\n\n\tvar wasError error\n\tif len(nbProxyArpIfs) > 0 {\n\t\tfor _, entry := range nbProxyArpIfs {\n\t\t\twasError = plugin.AddInterface(entry)\n\t\t}\n\t}\n\n\tplugin.log.Debug(\"RESYNC proxy ARP interface end. \", wasError)\n\treturn nil\n}", "func (cs *CachingAuthClient) GetReverseTunnels() (tunnels []services.ReverseTunnel, err error) {\n\terr = cs.try(func() error {\n\t\ttunnels, err = cs.ap.GetReverseTunnels()\n\t\treturn err\n\t})\n\tif err != nil {\n\t\tif trace.IsConnectionProblem(err) {\n\t\t\ttunnels, err = cs.presence.GetReverseTunnels()\n\t\t}\n\t\treturn tunnels, err\n\t}\n\tif err := cs.presence.DeleteAllReverseTunnels(); err != nil {\n\t\tif !trace.IsNotFound(err) {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t}\n\tfor _, tunnel := range tunnels {\n\t\tcs.setTTL(tunnel)\n\t\tif err := cs.presence.UpsertReverseTunnel(tunnel); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t}\n\treturn tunnels, err\n}", "func reverseArray(a []int32) []int32 {\n swap := reflect.Swapper(a)\n for i:=0; i<len(a)/2; i++{\n swap(i, len(a)-i-1)\n }\n \n return a\n}", "func DeleteContract(ctx context.Context, t feature.T) {\n\tDelete(\"kafka-broker-brokers-triggers\", knative.KnativeNamespaceFromContext(ctx))(ctx, t)\n}", "func (a Slice[T]) Reverse() Slice[T] {\n\tfor i := len(a)/2 - 1; i >= 0; i-- {\n\t\topp := len(a) - 1 - i\n\t\ta[i], a[opp] = a[opp], a[i]\n\t}\n\treturn a\n}", "func (v *version) TLSCertificateDelegations() TLSCertificateDelegationInformer {\n\treturn &tLSCertificateDelegationInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}", "func (broadcast *Broadcast) DelegatorWithdraw(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegatorWithdrawMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (s *ListDelegatedServicesForAccountOutput) SetDelegatedServices(v []*DelegatedService) *ListDelegatedServicesForAccountOutput {\n\ts.DelegatedServices = v\n\treturn s\n}", "func reverse(commits []*vcsinfo.LongCommit) {\n\ttotal := len(commits)\n\tfor i := 0; i < total/2; i++ {\n\t\tcommits[i], commits[total-i-1] = commits[total-i-1], commits[i]\n\t}\n}", "func (instance *DBSyncSlave) Reverse() ([]int64, []error) {\n\tif nil != instance {\n\t\treturn instance.reverseSync()\n\t}\n\treturn nil, nil\n}", "func (u UninitializedNotaryRepository) GetDelegationRoles() ([]data.Role, error) {\n\treturn nil, client.ErrRepositoryNotExist{}\n}", "func (_DelegationController *DelegationControllerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (ifc *Interface) SyncAddresses(want []*net.IPNet) error {\n\tvar erracc error\n\n\tgot := ifc.UnicastIPNets\n\tadd, del := deltaNets(got, want)\n\tdel = excludeIPv6LinkLocal(del)\n\tfor _, a := range del {\n\t\terr := ifc.DeleteAddress(&a.IP)\n\t\tif err != nil {\n\t\t\terracc = err\n\t\t}\n\t}\n\n\terr := ifc.AddAddresses(add)\n\tif err != nil {\n\t\terracc = err\n\t}\n\n\tifc.UnicastIPNets = make([]*net.IPNet, len(want))\n\tcopy(ifc.UnicastIPNets, want)\n\treturn erracc\n}", "func (l LoadedWithNoSignersNotaryRepository) GetDelegationRoles() ([]data.Role, error) {\n\treturn []data.Role{}, nil\n}", "func (s *ArkClient) GetDelegateVoters(params DelegateQueryParams) (DelegateVoters, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\treturn *respData, resp, err\n}", "func Reverse(ctx *cli.Context) {\n\terr := reverse(service, ctx.Bool(\"all\"))\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func Reverse[T any](ss []T) []T {\n\t// Avoid the allocation. If there is one element or less it is already\n\t// reversed.\n\tif len(ss) < 2 {\n\t\treturn ss\n\t}\n\n\tsorted := make([]T, len(ss))\n\tfor i := 0; i < len(ss); i++ {\n\t\tsorted[i] = ss[len(ss)-i-1]\n\t}\n\n\treturn sorted\n}", "func (s *State) invertContractMaintenance() (diffs []OutputDiff) {\n\t// Repen all contracts that terminated, and remove the corresponding output.\n\tfor _, openContract := range s.currentBlockNode().ContractTerminations {\n\t\tid := openContract.ContractID\n\t\ts.openContracts[id] = openContract\n\t\tcontractStatus := openContract.Failures == openContract.FileContract.Tolerance\n\t\toutputID := ContractTerminationOutputID(id, contractStatus)\n\t\tdiff := OutputDiff{New: false, ID: outputID, Output: s.unspentOutputs[outputID]}\n\t\tdelete(s.unspentOutputs, outputID)\n\t\tdiffs = append(diffs, diff)\n\t}\n\n\t// Reverse all outputs created by missed storage proofs.\n\tfor _, missedProof := range s.currentBlockNode().MissedStorageProofs {\n\t\tcid, oid := missedProof.ContractID, missedProof.OutputID\n\t\ts.openContracts[cid].FundsRemaining += s.unspentOutputs[oid].Value\n\t\ts.openContracts[cid].Failures -= 1\n\t\tdiff := OutputDiff{New: false, ID: oid, Output: s.unspentOutputs[oid]}\n\t\tdelete(s.unspentOutputs, oid)\n\t\tdiffs = append(diffs, diff)\n\t}\n\n\t// Reset the window satisfied variable to true for all successful windows.\n\tfor _, id := range s.currentBlockNode().SuccessfulWindows {\n\t\ts.openContracts[id].WindowSatisfied = true\n\t}\n\treturn\n}", "func (k Keeper) UpdateDelegatorsBeforeSlashing(ctx sdk.Context, valAddr sdk.ValAddress) {\n\tdelegations := k.stakingKeeper.GetValidatorDelegations(ctx, valAddr)\n\n\tdefaultCoin := coins.GetDefaultCoin()\n\n\tfor _, delegation := range delegations {\n\t\tk.SavePosmined(ctx, delegation.DelegatorAddress, defaultCoin)\n\t}\n}", "func (o OfflineNotaryRepository) RemoveDelegationPaths(data.RoleName, []string) error {\n\treturn nil\n}", "func (k Querier) ValidatorUnbondingDelegations(ctx context.Context, req *types.QueryValidatorUnbondingDelegationsRequest) (*types.QueryValidatorUnbondingDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstore := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))\n\tkeys, pageRes, err := query.CollectionPaginate(\n\t\tctx,\n\t\tk.UnbondingDelegationByValIndex,\n\t\treq.Pagination,\n\t\tfunc(key collections.Pair[[]byte, []byte], value []byte) (collections.Pair[[]byte, []byte], error) {\n\t\t\treturn key, nil\n\t\t},\n\t\tquery.WithCollectionPaginationPairPrefix[[]byte, []byte](valAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\t// loop over the collected keys and fetch unbonding delegations\n\tvar ubds []types.UnbondingDelegation\n\tfor _, key := range keys {\n\t\tvalAddr := key.K1()\n\t\tdelAddr := key.K2()\n\t\tubdKey := types.GetUBDKey(delAddr, valAddr)\n\t\tstoreValue := store.Get(ubdKey)\n\n\t\tubd, err := types.UnmarshalUBD(k.cdc, storeValue)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tubds = append(ubds, ubd)\n\t}\n\n\treturn &types.QueryValidatorUnbondingDelegationsResponse{\n\t\tUnbondingResponses: ubds,\n\t\tPagination: pageRes,\n\t}, nil\n}", "func (l LoadedNotaryRepository) GetDelegationRoles() ([]data.Role, error) {\n\treturn loadedDelegationRoles, nil\n}", "func (e EmptyTargetsNotaryRepository) GetDelegationRoles() ([]data.Role, error) {\n\treturn []data.Role{}, nil\n}", "func ReverseSlice(s interface{}) {\n\treflectValue := reflect.ValueOf(s)\n\tif reflectValue.Kind() != reflect.Slice {\n\t\treturn\n\t}\n\tsize := reflectValue.Len()\n\tswap := reflect.Swapper(s)\n\tfor i, j := 0, size-1; i < j; i, j = i+1, j-1 {\n\t\tswap(i, j)\n\t}\n}", "func (t *TezTracker) AccountDelegatorsList(accountID string, limits Limiter) ([]models.AccountListView, int64, error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.Account{DelegateValue: accountID}\n\tcount, err := r.Count(filter)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\taccs, err := r.Filter(filter, limits.Limit(), limits.Offset())\n\treturn accs, count, err\n}", "func (t *TezTracker) AccountDelegatorsList(accountID string, limits Limiter) ([]models.AccountListView, int64, error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.Account{DelegateValue: accountID}\n\tcount, err := r.Count(filter)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\taccs, err := r.Filter(filter, limits.Limit(), limits.Offset())\n\treturn accs, count, err\n}", "func reverse(in []string) []string {\n\tif len(in) == 0 {\n\t\treturn in\n\t}\n\treturn append(reverse(in[1:]), in[0])\n}", "func DefaultProxies(qtumRPCClient *qtum.Qtum, agent *notifier.Agent) []ETHProxy {\n\tfilter := eth.NewFilterSimulator()\n\tgetFilterChanges := &ProxyETHGetFilterChanges{Qtum: qtumRPCClient, filter: filter}\n\tethCall := &ProxyETHCall{Qtum: qtumRPCClient}\n\n\tethProxies := []ETHProxy{\n\t\tethCall,\n\t\t&ProxyNetListening{Qtum: qtumRPCClient},\n\t\t&ProxyETHPersonalUnlockAccount{},\n\t\t&ProxyETHChainId{Qtum: qtumRPCClient},\n\t\t&ProxyETHBlockNumber{Qtum: qtumRPCClient},\n\t\t&ProxyETHHashrate{Qtum: qtumRPCClient},\n\t\t&ProxyETHMining{Qtum: qtumRPCClient},\n\t\t&ProxyETHNetVersion{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetTransactionByHash{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetTransactionByBlockNumberAndIndex{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetLogs{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetTransactionReceipt{Qtum: qtumRPCClient},\n\t\t&ProxyETHSendTransaction{Qtum: qtumRPCClient},\n\t\t&ProxyETHAccounts{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetCode{Qtum: qtumRPCClient},\n\n\t\t&ProxyETHNewFilter{Qtum: qtumRPCClient, filter: filter},\n\t\t&ProxyETHNewBlockFilter{Qtum: qtumRPCClient, filter: filter},\n\t\tgetFilterChanges,\n\t\t&ProxyETHGetFilterLogs{ProxyETHGetFilterChanges: getFilterChanges},\n\t\t&ProxyETHUninstallFilter{Qtum: qtumRPCClient, filter: filter},\n\n\t\t&ProxyETHEstimateGas{ProxyETHCall: ethCall},\n\t\t&ProxyETHGetBlockByNumber{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetBlockByHash{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetBalance{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetStorageAt{Qtum: qtumRPCClient},\n\t\t&ETHGetCompilers{},\n\t\t&ETHProtocolVersion{},\n\t\t&ETHGetUncleByBlockHashAndIndex{},\n\t\t&ETHGetUncleCountByBlockHash{},\n\t\t&ETHGetUncleCountByBlockNumber{},\n\t\t&Web3ClientVersion{},\n\t\t&Web3Sha3{},\n\t\t&ProxyETHSign{Qtum: qtumRPCClient},\n\t\t&ProxyETHGasPrice{Qtum: qtumRPCClient},\n\t\t&ProxyETHTxCount{Qtum: qtumRPCClient},\n\t\t&ProxyETHSignTransaction{Qtum: qtumRPCClient},\n\t\t&ProxyETHSendRawTransaction{Qtum: qtumRPCClient},\n\n\t\t&ETHSubscribe{Qtum: qtumRPCClient, Agent: agent},\n\t\t&ETHUnsubscribe{Qtum: qtumRPCClient, Agent: agent},\n\n\t\t&ProxyQTUMGetUTXOs{Qtum: qtumRPCClient},\n\t\t&ProxyQTUMGenerateToAddress{Qtum: qtumRPCClient},\n\n\t\t&ProxyNetPeerCount{Qtum: qtumRPCClient},\n\t}\n\n\tpermittedQtumCalls := []string{\n\t\tqtum.MethodGetHexAddress,\n\t\tqtum.MethodFromHexAddress,\n\t}\n\n\tfor _, qtumMethod := range permittedQtumCalls {\n\t\tethProxies = append(\n\t\t\tethProxies,\n\t\t\t&ProxyQTUMGenericStringArguments{\n\t\t\t\tQtum: qtumRPCClient,\n\t\t\t\tprefix: \"dev\",\n\t\t\t\tmethod: qtumMethod,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn ethProxies\n}", "func Reverse[T any](collection []T) []T {\n\tlength := len(collection)\n\thalf := length / 2\n\n\tfor i := 0; i < half; i = i + 1 {\n\t\tj := length - 1 - i\n\t\tcollection[i], collection[j] = collection[j], collection[i]\n\t}\n\n\treturn collection\n}", "func (r *Roller) ReverseOnceCallDoneAt(i int, g interface{}) {\n\tif len(r.onceDoners) <= 0 {\n\t\treturn\n\t}\n\ttotal := len(r.onceDoners) - 1\n\tloc := total - i\n\n\tif loc >= 0 {\n\t\tval := r.onceDoners[loc]\n\t\tif val != nil {\n\t\t\tval(g, func(fval interface{}) {\n\n\t\t\t\tind := i + 1\n\t\t\t\tif fval == nil {\n\t\t\t\t\tr.ReverseOnceCallDoneAt(ind, g)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tr.ReverseOnceCallDoneAt(ind, fval)\n\t\t\t})\n\t\t}\n\t} else {\n\t\tr.onceDoners = make([]Callable, 0)\n\t}\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (ctx *rollDPoSCtx) getRollingDelegates(epochNum uint64) ([]string, error) {\n\t// TODO: replace the pseudo roll delegates method with integrating with real delegate pool\n\treturn ctx.pool.RollDelegates(epochNum)\n}", "func (_DelegationController *DelegationControllerCallerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func ReverseEvents(s []cloudformation.StackEvent) []cloudformation.StackEvent {\n\ta := make([]cloudformation.StackEvent, len(s))\n\tcopy(a, s)\n\n\tfor i := len(a)/2 - 1; i >= 0; i-- {\n\t\topp := len(a) - 1 - i\n\t\ta[i], a[opp] = a[opp], a[i]\n\t}\n\n\treturn a\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func reverseAll(s []string) (reversed []string) {\n reversed = make([]string, len(s))\n for i := 0; i < len(s); i++ {\n reversed[i] = reverse(s[i])\n }\n return reversed\n}", "func (c *DPOS) ClaimRewardsFromAllValidators(ctx contract.Context, req *ClaimDelegatorRewardsRequest) (*ClaimDelegatorRewardsResponse, error) {\n\tif ctx.FeatureEnabled(features.DPOSVersion3_6, false) {\n\t\treturn c.claimRewardsFromAllValidators2(ctx, req)\n\t}\n\n\tdelegator := ctx.Message().Sender\n\tvalidators, err := ValidatorList(ctx)\n\tif err != nil {\n\t\treturn nil, logStaticDposError(ctx, err, req.String())\n\t}\n\n\ttotal := big.NewInt(0)\n\tchainID := ctx.Block().ChainID\n\tvar claimedFromValidators []*types.Address\n\tvar amounts []*types.BigUInt\n\tfor _, v := range validators {\n\t\tvalAddress := loom.Address{ChainID: chainID, Local: loom.LocalAddressFromPublicKey(v.PubKey)}\n\t\tdelegation, err := GetDelegation(ctx, REWARD_DELEGATION_INDEX, *valAddress.MarshalPB(), *delegator.MarshalPB())\n\t\tif err == contract.ErrNotFound {\n\t\t\t// Skip reward delegations that were not found.\n\t\t\tctx.Logger().Error(\"DPOS ClaimRewardsFromAllValidators\", \"error\", err, \"delegator\", delegator)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to load delegation\")\n\t\t}\n\n\t\tclaimedFromValidators = append(claimedFromValidators, valAddress.MarshalPB())\n\t\tamounts = append(amounts, delegation.Amount)\n\n\t\t// Set to UNBONDING and UpdateAmount == Amount, to fully unbond it.\n\t\tdelegation.State = UNBONDING\n\t\tdelegation.UpdateAmount = delegation.Amount\n\n\t\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to update delegation\")\n\t\t}\n\n\t\terr = c.emitDelegatorUnbondsEvent(ctx, delegation)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Add to the sum\n\t\ttotal.Add(total, delegation.Amount.Value.Int)\n\t}\n\n\tamount := &types.BigUInt{Value: *loom.NewBigUInt(total)}\n\n\terr = c.emitDelegatorClaimsRewardsEvent(ctx, delegator.MarshalPB(), claimedFromValidators, amounts, amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ClaimDelegatorRewardsResponse{\n\t\tAmount: amount,\n\t}, nil\n}", "func reverse(items []string) []string {\n\tl := len(items)\n\tvar reversed = make([]string, l)\n\tfor i, v := range items {\n\t\treversed[l-i-1] = v\n\t}\n\treturn reversed\n}", "func SortedRemotes() (res RemoteSlice) {\n\tres = make(RemoteSlice, 0, 2)\n\tfor _, remote := range Remotes {\n\t\tres = append(res, remote)\n\t}\n\tsort.Sort(res)\n\treturn res\n}", "func (nrs *NaiveStrategy) RelayAcknowledgements(src, dst *Chain, sp *RelaySequences) error {\n\t// set the maximum relay transaction constraints\n\tmsgs := &RelayMsgs{\n\t\tSrc: []sdk.Msg{},\n\t\tDst: []sdk.Msg{},\n\t\tMaxTxSize: nrs.MaxTxSize,\n\t\tMaxMsgLength: nrs.MaxMsgLength,\n\t}\n\tsrcUpdateMsg, err := src.UpdateClient(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdstUpdateMsg, err := dst.UpdateClient(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// add messages for sequences on src\n\tfor _, seq := range sp.Src {\n\t\t// SRC wrote ack, so we query packet and send to DST\n\t\trelayAckMsgs, err := acknowledgementFromSequence(src, dst, seq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmsgs.Dst = append(msgs.Dst, relayAckMsgs...)\n\t}\n\n\t// add messages for sequences on dst\n\tfor _, seq := range sp.Dst {\n\t\t// DST wrote ack, so we query packet and send to SRC\n\t\trelayAckMsgs, err := acknowledgementFromSequence(dst, src, seq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmsgs.Src = append(msgs.Src, relayAckMsgs...)\n\t}\n\n\tif !msgs.Ready() {\n\t\tsrc.Log(fmt.Sprintf(\"- No acknowledgements to relay between [%s]port{%s} and [%s]port{%s}\",\n\t\t\tsrc.ChainID, src.PathEnd.PortID, dst.ChainID, dst.PathEnd.PortID))\n\t\treturn nil\n\t}\n\n\t// Prepend non-empty msg lists with UpdateClient\n\tif len(msgs.Dst) != 0 {\n\t\tmsgs.Dst = append([]sdk.Msg{dstUpdateMsg}, msgs.Dst...)\n\t}\n\n\tif len(msgs.Src) != 0 {\n\t\tmsgs.Src = append([]sdk.Msg{srcUpdateMsg}, msgs.Src...)\n\t}\n\n\t// send messages to their respective chains\n\tif msgs.Send(src, dst); msgs.Success() {\n\t\tif len(msgs.Dst) > 1 {\n\t\t\tdst.logPacketsRelayed(src, len(msgs.Dst)-1)\n\t\t}\n\t\tif len(msgs.Src) > 1 {\n\t\t\tsrc.logPacketsRelayed(dst, len(msgs.Src)-1)\n\t\t}\n\t}\n\n\treturn nil\n}", "func ChainUnaryClient(interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor {\n\tn := len(interceptors)\n\n\t// interceptors length more than 1.\n\tif n > 1 {\n\t\t// chain callback function.\n\t\tvar chain func(idx int, ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error\n\n\t\tchain = func(idx int, ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {\n\t\t\tif idx == len(interceptors) {\n\t\t\t\treturn invoker(ctx, method, req, reply, cc, opts...)\n\t\t\t}\n\t\t\t// return next interceptor.\n\t\t\treturn interceptors[idx](ctx, method, req, reply, cc, func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error {\n\t\t\t\t// return next chain.\n\t\t\t\treturn chain(idx+1, ctx, method, req, reply, cc, invoker, opts...)\n\t\t\t}, opts...)\n\t\t}\n\n\t\treturn func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {\n\t\t\treturn chain(0, ctx, method, req, reply, cc, invoker, opts...)\n\t\t}\n\t} else if n == 1 {\n\t\t// interceptors length is 1.\n\t\treturn interceptors[0]\n\t}\n\t// interceptors length is 0.\n\t// Dummy interceptor maintained for backward compatibility to avoid returning nil.\n\treturn func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {\n\t\treturn invoker(ctx, method, req, reply, cc, opts...)\n\t}\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func NeuraxReverse() {\n\tconn, _ := net.Dial(N.ReverseProto, N.ReverseListener)\n\tfor {\n\t\tcommand, err := bufio.NewReader(conn).ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tcommand = strings.TrimSuffix(command, \"\\n\")\n\t\tgo handle_command(command)\n\t}\n}", "func GetDelegates(node client.ABCIClient) (map[address.Address][]address.Address, *rpctypes.ResultABCIQuery, error) {\n\t// perform the query\n\tres, err := node.ABCIQuery(query.DelegatesEndpoint, nil)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\tif code.ReturnCode(res.Response.Code) != code.OK {\n\t\tif res.Response.Log != \"\" {\n\t\t\treturn nil, res, errors.New(code.ReturnCode(res.Response.Code).String() + \": \" + res.Response.Log)\n\t\t}\n\t\treturn nil, res, errors.New(code.ReturnCode(res.Response.Code).String())\n\t}\n\n\tdr := query.DelegatesResponse{}\n\t// parse the response\n\t_, err = dr.UnmarshalMsg(res.Response.GetValue())\n\tif err != nil || dr == nil {\n\t\treturn nil, res, errors.Wrap(err, \"unmarshalling delegates response\")\n\t}\n\n\t// transform response into friendly form\n\tdelegates := make(map[address.Address][]address.Address)\n\tfor _, node := range dr {\n\t\tfor _, delegated := range node.Delegated {\n\t\t\tdelegates[node.Node] = append(delegates[node.Node], delegated)\n\t\t}\n\t}\n\treturn delegates, res, err\n}", "func Reverse(data Interface) Interface {\n\tif r, ok := data.(reverse); ok {\n\t\treturn r.Interface\n\t}\n\treturn reverse{data}\n}" ]
[ "0.57337046", "0.55681205", "0.55654866", "0.55000234", "0.52717584", "0.5166487", "0.51506835", "0.51504433", "0.5085649", "0.5070455", "0.50579536", "0.5023943", "0.50178355", "0.49947852", "0.4958182", "0.49256435", "0.49166426", "0.4889251", "0.4887035", "0.4856283", "0.48464695", "0.47607586", "0.47481006", "0.47188228", "0.46370298", "0.4598043", "0.4554161", "0.45413664", "0.45327678", "0.44917452", "0.44897428", "0.44618934", "0.4449264", "0.4439182", "0.43827432", "0.43236", "0.43227047", "0.431359", "0.42986467", "0.42948064", "0.42873847", "0.4253059", "0.4238869", "0.42324424", "0.42304865", "0.42280394", "0.42187908", "0.42007267", "0.41950232", "0.4193351", "0.4187945", "0.41849855", "0.4175974", "0.41678235", "0.4148855", "0.41333747", "0.4130196", "0.41234785", "0.41179463", "0.40859413", "0.40742388", "0.40717867", "0.40673402", "0.40642285", "0.40615815", "0.40590587", "0.40568244", "0.40549374", "0.4054884", "0.4048007", "0.4039655", "0.4035196", "0.4026098", "0.40195164", "0.40191433", "0.40190268", "0.4015263", "0.40108287", "0.3998235", "0.3997495", "0.3997495", "0.39968318", "0.39942142", "0.39823332", "0.39734125", "0.39694867", "0.39674935", "0.39670357", "0.39668903", "0.39510727", "0.39499068", "0.3949087", "0.39432797", "0.39318517", "0.39317384", "0.39202896", "0.39177382", "0.38949335", "0.38879555", "0.38802865" ]
0.64592606
0
BindStatusString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func BindStatusString(s string) (BindStatus, error) { if val, ok := _BindStatusNameToValueMap[s]; ok { return val, nil } return 0, fmt.Errorf("%s does not belong to BindStatus values", s) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ResponseStringToEnum(str string) ResponseStatus {\n\tswitch str {\n\tcase \"open\":\n\t\treturn Open\n\tcase \"accepted\":\n\t\treturn Accepted\n\tcase \"declined\":\n\t\treturn Declined\n\t}\n\t// TODO: Might just want to throw error\n\treturn Open\n}", "func ConvertStatusString(color string) int {\n\tswitch strings.ToLower(color) {\n\tcase \"green\":\n\t\treturn StatusGreen\n\tcase \"yellow\":\n\t\treturn StatusYellow\n\tcase \"red\":\n\t\treturn StatusRed\n\tdefault:\n\t\treturn StatusUnknown\n\t}\n}", "func DispatcherStatusString(s string) (DispatcherStatus, error) {\n\tif val, ok := _DispatcherStatusNameToValueMap[s]; ok {\n\t\treturn val, nil\n\t}\n\treturn 0, fmt.Errorf(\"%s does not belong to DispatcherStatus values\", s)\n}", "func UpgradeStatusEnumFromValue(value string) UpgradeStatusEnum {\r\n switch value {\r\n case \"kIdle\":\r\n return UpgradeStatus_KIDLE\r\n case \"kAccepted\":\r\n return UpgradeStatus_KACCEPTED\r\n case \"kStarted\":\r\n return UpgradeStatus_KSTARTED\r\n case \"kFinished\":\r\n return UpgradeStatus_KFINISHED\r\n default:\r\n return UpgradeStatus_KIDLE\r\n }\r\n}", "func (o *FindExecutionsParams) bindStatus(rawData []string, hasKey bool, formats strfmt.Registry) error {\n\tvar raw string\n\tif len(rawData) > 0 {\n\t\traw = rawData[len(rawData)-1]\n\t}\n\n\t// Required: false\n\t// AllowEmptyValue: false\n\tif raw == \"\" { // empty values pass all other validations\n\t\treturn nil\n\t}\n\n\to.Status = &raw\n\n\tif err := o.validateStatus(formats); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CartridgeStatusString(s string) (CartridgeStatus, error) {\n\tif val, ok := _CartridgeStatusNameToValueMap[s]; ok {\n\t\treturn val, nil\n\t}\n\treturn 0, fmt.Errorf(\"%s does not belong to CartridgeStatus values\", s)\n}", "func TaskStatusString(s string) (TaskStatus, error) {\n\tif val, ok := _TaskStatusNameToValueMap[s]; ok {\n\t\treturn val, nil\n\t}\n\treturn 0, fmt.Errorf(\"%s does not belong to TaskStatus values\", s)\n}", "func (p *Parser) EnumString(i int, context string, options ...string) string {\n\ts := p.String(i, context)\n\tif p.err != nil || s == \"\" {\n\t\treturn \"\"\n\t}\n\tfor _, o := range options {\n\t\tif o == s {\n\t\t\treturn s\n\t\t}\n\t}\n\tp.SetErr(context, s)\n\treturn \"\"\n}", "func HumidityStatusString(s string) (HumidityStatus, error) {\n\tif val, ok := _HumidityStatusNameToValueMap[s]; ok {\n\t\treturn val, nil\n\t}\n\treturn 0, fmt.Errorf(\"%s does not belong to HumidityStatus values\", s)\n}", "func statusConverter(e models.StatusEnum) pb.OrderStatus {\n\tvar status pb.OrderStatus\n\tswitch e {\n\tcase \"IN_PREPARATION\":\n\t\tstatus = pb.OrderStatus_IN_PREPARATION\n\tcase \"GROWING\":\n\t\tstatus = pb.OrderStatus_GROWING\n\tcase \"CANCELLED\":\n\t\tstatus = pb.OrderStatus_CANCELLED\n\tcase \"SHIPPED\":\n\t\tstatus = pb.OrderStatus_SHIPPED\n\t}\n\treturn status\n}", "func UpgradeStatusEnumToValue(upgradeStatusEnum UpgradeStatusEnum) string {\r\n switch upgradeStatusEnum {\r\n case UpgradeStatus_KIDLE:\r\n \t\treturn \"kIdle\"\t\t\r\n case UpgradeStatus_KACCEPTED:\r\n \t\treturn \"kAccepted\"\t\t\r\n case UpgradeStatus_KSTARTED:\r\n \t\treturn \"kStarted\"\t\t\r\n case UpgradeStatus_KFINISHED:\r\n \t\treturn \"kFinished\"\t\t\r\n default:\r\n \treturn \"kIdle\"\r\n }\r\n}", "func getStatus(n Status) string {\n\treturn status[n]\n}", "func parseEnumFromString(content string, param Ds3Enum, aggErr *AggregateError) {\n err := param.UnmarshalText([]byte(content))\n if err != nil {\n aggErr.Append(err)\n }\n}", "func (u Userstatus) String() string {\n\tvar enumVal string\n\tswitch u {\n\tcase UserstatusHealthy:\n\t\tenumVal = \"HEALTHY\"\n\n\tcase UserstatusPositive:\n\t\tenumVal = \"POSITIVE\"\n\n\tcase UserstatusRecovered:\n\t\tenumVal = \"RECOVERED\"\n\t}\n\n\treturn enumVal\n}", "func (cs *CredentialSpecResource) StatusString(status resourcestatus.ResourceStatus) string {\n\treturn CredentialSpecStatus(status).String()\n}", "func (m *AccessPackageAssignment) SetStatus(value *string)() {\n m.status = value\n}", "func getStatus(status string) gitea.StatusState {\n\tswitch status {\n\tcase model.StatusPending, model.StatusBlocked:\n\t\treturn gitea.StatusPending\n\tcase model.StatusRunning:\n\t\treturn gitea.StatusPending\n\tcase model.StatusSuccess:\n\t\treturn gitea.StatusSuccess\n\tcase model.StatusFailure, model.StatusError:\n\t\treturn gitea.StatusFailure\n\tcase model.StatusKilled:\n\t\treturn gitea.StatusFailure\n\tcase model.StatusDeclined:\n\t\treturn gitea.StatusWarning\n\tdefault:\n\t\treturn gitea.StatusFailure\n\t}\n}", "func UseStatusString(us int64) string {\n\ti := int(us)\n\tif i > len(RSUseStatus) {\n\t\ti = 0\n\t}\n\treturn RSUseStatus[i]\n}", "func ColorStatus(status string) string {\n\tswitch status {\n\tcase \"online\":\n\t\treturn Green(status).String()\n\tcase \"offline\", \"invisible\":\n\t\treturn status\n\tcase \"dnd\":\n\t\treturn Red(status).String()\n\tcase \"away\":\n\t\treturn Brown(status).String()\n\tdefault:\n\t\treturn status\n\t}\n}", "func (state Status) String() string {\n\t// declare an array of strings. operator counts how many items in the array (4)\n\tlistStatus := [...]string{\"Offline\", \"Online\", \"Warning\", \"Critical\"}\n\n\t// → `state`: It's one of the values of Status constants.\n\t// prevent panicking in case of `status` is out of range of Status\n\tif state < Offline || state > Critical {\n\t\treturn \"Unknown\"\n\t}\n\t// return the status string constant from the array above.\n\treturn listStatus[state]\n}", "func (o *PetListParams) bindParamStatus(formats strfmt.Registry) []string {\n\tstatusIR := o.Status\n\n\tvar statusIC []string\n\tfor _, statusIIR := range statusIR { // explode []string\n\n\t\tstatusIIV := statusIIR // string as string\n\t\tstatusIC = append(statusIC, statusIIV)\n\t}\n\n\t// items.CollectionFormat: \"multi\"\n\tstatusIS := swag.JoinByFormat(statusIC, \"multi\")\n\n\treturn statusIS\n}", "func StringToStatus(name string) (Status, error) {\n\tswitch name {\n\tcase Attach.String():\n\t\treturn Attach, nil\n\tcase AutoUpdate.String():\n\t\treturn AutoUpdate, nil\n\tcase Build.String():\n\t\treturn Build, nil\n\tcase Checkpoint.String():\n\t\treturn Checkpoint, nil\n\tcase Cleanup.String():\n\t\treturn Cleanup, nil\n\tcase Commit.String():\n\t\treturn Commit, nil\n\tcase Create.String():\n\t\treturn Create, nil\n\tcase Exec.String():\n\t\treturn Exec, nil\n\tcase ExecDied.String():\n\t\treturn ExecDied, nil\n\tcase Exited.String():\n\t\treturn Exited, nil\n\tcase Export.String():\n\t\treturn Export, nil\n\tcase HealthStatus.String():\n\t\treturn HealthStatus, nil\n\tcase History.String():\n\t\treturn History, nil\n\tcase Import.String():\n\t\treturn Import, nil\n\tcase Init.String():\n\t\treturn Init, nil\n\tcase Kill.String():\n\t\treturn Kill, nil\n\tcase LoadFromArchive.String():\n\t\treturn LoadFromArchive, nil\n\tcase Mount.String():\n\t\treturn Mount, nil\n\tcase NetworkConnect.String():\n\t\treturn NetworkConnect, nil\n\tcase NetworkDisconnect.String():\n\t\treturn NetworkDisconnect, nil\n\tcase Pause.String():\n\t\treturn Pause, nil\n\tcase Prune.String():\n\t\treturn Prune, nil\n\tcase Pull.String():\n\t\treturn Pull, nil\n\tcase Push.String():\n\t\treturn Push, nil\n\tcase Refresh.String():\n\t\treturn Refresh, nil\n\tcase Remove.String():\n\t\treturn Remove, nil\n\tcase Rename.String():\n\t\treturn Rename, nil\n\tcase Renumber.String():\n\t\treturn Renumber, nil\n\tcase Restart.String():\n\t\treturn Restart, nil\n\tcase Restore.String():\n\t\treturn Restore, nil\n\tcase Rotate.String():\n\t\treturn Rotate, nil\n\tcase Save.String():\n\t\treturn Save, nil\n\tcase Start.String():\n\t\treturn Start, nil\n\tcase Stop.String():\n\t\treturn Stop, nil\n\tcase Sync.String():\n\t\treturn Sync, nil\n\tcase Tag.String():\n\t\treturn Tag, nil\n\tcase Unmount.String():\n\t\treturn Unmount, nil\n\tcase Unpause.String():\n\t\treturn Unpause, nil\n\tcase Untag.String():\n\t\treturn Untag, nil\n\t}\n\treturn \"\", fmt.Errorf(\"unknown event status %q\", name)\n}", "func (m *TeamsAsyncOperation) SetStatus(value *TeamsAsyncOperationStatus)() {\n m.status = value\n}", "func Statusf(status int, format string, args ...interface{}) error {\n\treturn &StatusError{\n\t\tstatusCode: status,\n\t\tmessage: fmt.Sprintf(format, args...),\n\t}\n}", "func translateStatus(statuses map[string]string, status string) (string, error) {\n\tv, e := statuses[status]\n\tif !e {\n\t\treturn \"\", fmt.Errorf(\"Unexpected status %s\", status)\n\t}\n\n\treturn v, nil\n}", "func MyEnumFromString(s string) (MyEnum, error) {\n if v, ok := MyEnumToValue[s]; ok {\n return v, nil\n }\n return MyEnum(0), fmt.Errorf(\"not a valid MyEnum string\")\n}", "func GetStatus(statusDB int64, status *string) {\n\tresultStr := reverse(strconv.FormatInt(statusDB, 2))\n\n\tif count := strings.Count(resultStr, \"1\"); count == 1 {\n\t\tindex := strings.Index(resultStr, \"1\")\n\n\t\tif len(StatusValues) >= index+1 {\n\t\t\t*status = StatusValues[index]\n\t\t}\n\t}\n}", "func StatusText(status int) string {\n\ts, found := statusText[status]\n\tif !found {\n\t\ts = \"Status \" + strconv.Itoa(status)\n\t}\n\treturn s\n}", "func StatusValidator(s Status) error {\n\tswitch s {\n\tcase StatusOpen, StatusClose:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"ukm: invalid enum value for status field: %q\", s)\n\t}\n}", "func (s *StringEnum) String() string { return s.val }", "func statusFromStatus(xstatus string) string {\n\tif xstatus == \"\" {\n\t\treturn \"available\"\n\t}\n\treturn xstatus\n}", "func GetOperationStatusEnumStringValues() []string {\n\treturn []string{\n\t\t\"ACCEPTED\",\n\t\t\"IN_PROGRESS\",\n\t\t\"FAILED\",\n\t\t\"SUCCEEDED\",\n\t\t\"CANCELING\",\n\t\t\"CANCELED\",\n\t}\n}", "func tryjobStatusFromString(statusStr string) TryjobStatus {\n\tif s, ok := statusStringMap[statusStr]; ok {\n\t\treturn s\n\t}\n\treturn TRYJOB_UNKNOWN\n}", "func (v Severity) String() string {\n\t// same as proto.EnumName\n\ts, ok := severityName[v]\n\tif ok {\n\t\treturn s\n\t}\n\treturn strconv.Itoa(int(v))\n}", "func (r *Reconciler) setStatus(\n\tctx context.Context,\n\tinstance *v1alpha1.ServiceBindingRequest,\n\tstatus string,\n) error {\n\tinstance.Status.BindingStatus = status\n\treturn r.client.Status().Update(ctx, instance)\n}", "func parseStatus(s string) (code int, force bool, err error) {\n\tif strings.HasSuffix(s, \"!\") {\n\t\tforce = true\n\t\ts = strings.Replace(s, \"!\", \"\", -1)\n\t}\n\n\tcode, err = strconv.Atoi(s)\n\treturn\n}", "func (status Status) String() string { // nolint\n\tswitch status {\n\tcase StatusOk:\n\t\treturn \"OK\"\n\tcase StatusInvalidTransaction:\n\t\treturn \"INVALID_TRANSACTION\"\n\tcase StatusPayerAccountNotFound:\n\t\treturn \"PAYER_ACCOUNT_NOT_FOUND\"\n\tcase StatusInvalidNodeAccount:\n\t\treturn \"INVALID_NODE_ACCOUNT\"\n\tcase StatusTransactionExpired:\n\t\treturn \"TRANSACTION_EXPIRED\"\n\tcase StatusInvalidTransactionStart:\n\t\treturn \"INVALID_TRANSACTION_START\"\n\tcase StatusInvalidTransactionDuration:\n\t\treturn \"INVALID_TRANSACTION_DURATION\"\n\tcase StatusInvalidSignature:\n\t\treturn \"INVALID_SIGNATURE\"\n\tcase StatusMemoTooLong:\n\t\treturn \"MEMO_TOO_LONG\"\n\tcase StatusInsufficientTxFee:\n\t\treturn \"INSUFFICIENT_TX_FEE\"\n\tcase StatusInsufficientPayerBalance:\n\t\treturn \"INSUFFICIENT_PAYER_BALANCE\"\n\tcase StatusDuplicateTransaction:\n\t\treturn \"DUPLICATE_TRANSACTION\"\n\tcase StatusBusy:\n\t\treturn \"BUSY\"\n\tcase StatusNotSupported:\n\t\treturn \"NOT_SUPPORTED\"\n\tcase StatusInvalidFileID:\n\t\treturn \"INVALID_FILE_ID\"\n\tcase StatusInvalidAccountID:\n\t\treturn \"INVALID_ACCOUNT_ID\"\n\tcase StatusInvalidContractID:\n\t\treturn \"INVALID_CONTRACT_ID\"\n\tcase StatusInvalidTransactionID:\n\t\treturn \"INVALID_TRANSACTION_ID\"\n\tcase StatusReceiptNotFound:\n\t\treturn \"RECEIPT_NOT_FOUND\"\n\tcase StatusRecordNotFound:\n\t\treturn \"RECORD_NOT_FOUND\"\n\tcase StatusInvalidSolidityID:\n\t\treturn \"INVALID_SOLIDITY_ID\"\n\tcase StatusUnknown:\n\t\treturn \"UNKNOWN\"\n\tcase StatusSuccess:\n\t\treturn \"SUCCESS\"\n\tcase StatusFailInvalid:\n\t\treturn \"FAIL_INVALID\"\n\tcase StatusFailFee:\n\t\treturn \"FAIL_FEE\"\n\tcase StatusFailBalance:\n\t\treturn \"FAIL_BALANCE\"\n\tcase StatusKeyRequired:\n\t\treturn \"KEY_REQUIRED\"\n\tcase StatusBadEncoding:\n\t\treturn \"BAD_ENCODING\"\n\tcase StatusInsufficientAccountBalance:\n\t\treturn \"INSUFFICIENT_ACCOUNT_BALANCE\"\n\tcase StatusInvalidSolidityAddress:\n\t\treturn \"INVALID_SOLIDITY_ADDRESS\"\n\tcase StatusInsufficientGas:\n\t\treturn \"INSUFFICIENT_GAS\"\n\tcase StatusContractSizeLimitExceeded:\n\t\treturn \"CONTRACT_SIZE_LIMIT_EXCEEDED\"\n\tcase StatusLocalCallModificationException:\n\t\treturn \"LOCAL_CALL_MODIFICATION_EXCEPTION\"\n\tcase StatusContractRevertExecuted:\n\t\treturn \"CONTRACT_REVERT_EXECUTED\"\n\tcase StatusContractExecutionException:\n\t\treturn \"CONTRACT_EXECUTION_EXCEPTION\"\n\tcase StatusInvalidReceivingNodeAccount:\n\t\treturn \"INVALID_RECEIVING_NODE_ACCOUNT\"\n\tcase StatusMissingQueryHeader:\n\t\treturn \"MISSING_QUERY_HEADER\"\n\tcase StatusAccountUpdateFailed:\n\t\treturn \"ACCOUNT_UPDATE_FAILED\"\n\tcase StatusInvalidKeyEncoding:\n\t\treturn \"INVALID_KEY_ENCODING\"\n\tcase StatusNullSolidityAddress:\n\t\treturn \"NULL_SOLIDITY_ADDRESS\"\n\tcase StatusContractUpdateFailed:\n\t\treturn \"CONTRACT_UPDATE_FAILED\"\n\tcase StatusInvalidQueryHeader:\n\t\treturn \"INVALID_QUERY_HEADER\"\n\tcase StatusInvalidFeeSubmitted:\n\t\treturn \"INVALID_FEE_SUBMITTED\"\n\tcase StatusInvalidPayerSignature:\n\t\treturn \"INVALID_PAYER_SIGNATURE\"\n\tcase StatusKeyNotProvided:\n\t\treturn \"KEY_NOT_PROVIDED\"\n\tcase StatusInvalidExpirationTime:\n\t\treturn \"INVALID_EXPIRATION_TIME\"\n\tcase StatusNoWaclKey:\n\t\treturn \"NO_WACL_KEY\"\n\tcase StatusFileContentEmpty:\n\t\treturn \"FILE_CONTENT_EMPTY\"\n\tcase StatusInvalidAccountAmounts:\n\t\treturn \"INVALID_ACCOUNT_AMOUNTS\"\n\tcase StatusEmptyTransactionBody:\n\t\treturn \"EMPTY_TRANSACTION_BODY\"\n\tcase StatusInvalidTransactionBody:\n\t\treturn \"INVALID_TRANSACTION_BODY\"\n\tcase StatusInvalidSignatureTypeMismatchingKey:\n\t\treturn \"INVALID_SIGNATURE_TYPE_MISMATCHING_KEY\"\n\tcase StatusInvalidSignatureCountMismatchingKey:\n\t\treturn \"INVALID_SIGNATURE_COUNT_MISMATCHING_KEY\"\n\tcase StatusEmptyLiveHashBody:\n\t\treturn \"EMPTY_LIVE_HASH_BODY\"\n\tcase StatusEmptyLiveHash:\n\t\treturn \"EMPTY_LIVE_HASH\"\n\tcase StatusEmptyLiveHashKeys:\n\t\treturn \"EMPTY_LIVE_HASH_KEYS\"\n\tcase StatusInvalidLiveHashSize:\n\t\treturn \"INVALID_LIVE_HASH_SIZE\"\n\tcase StatusEmptyQueryBody:\n\t\treturn \"EMPTY_QUERY_BODY\"\n\tcase StatusEmptyLiveHashQuery:\n\t\treturn \"EMPTY_LIVE_HASH_QUERY\"\n\tcase StatusLiveHashNotFound:\n\t\treturn \"LIVE_HASH_NOT_FOUND\"\n\tcase StatusAccountIDDoesNotExist:\n\t\treturn \"ACCOUNT_ID_DOES_NOT_EXIST\"\n\tcase StatusLiveHashAlreadyExists:\n\t\treturn \"LIVE_HASH_ALREADY_EXISTS\"\n\tcase StatusInvalidFileWacl:\n\t\treturn \"INVALID_FILE_WACL\"\n\tcase StatusSerializationFailed:\n\t\treturn \"SERIALIZATION_FAILED\"\n\tcase StatusTransactionOversize:\n\t\treturn \"TRANSACTION_OVERSIZE\"\n\tcase StatusTransactionTooManyLayers:\n\t\treturn \"TRANSACTION_TOO_MANY_LAYERS\"\n\tcase StatusContractDeleted:\n\t\treturn \"CONTRACT_DELETED\"\n\tcase StatusPlatformNotActive:\n\t\treturn \"PLATFORM_NOT_ACTIVE\"\n\tcase StatusKeyPrefixMismatch:\n\t\treturn \"KEY_PREFIX_MISMATCH\"\n\tcase StatusPlatformTransactionNotCreated:\n\t\treturn \"PLATFORM_TRANSACTION_NOT_CREATED\"\n\tcase StatusInvalidRenewalPeriod:\n\t\treturn \"INVALID_RENEWAL_PERIOD\"\n\tcase StatusInvalidPayerAccountID:\n\t\treturn \"INVALID_PAYER_ACCOUNT_ID\"\n\tcase StatusAccountDeleted:\n\t\treturn \"ACCOUNT_DELETED\"\n\tcase StatusFileDeleted:\n\t\treturn \"FILE_DELETED\"\n\tcase StatusAccountRepeatedInAccountAmounts:\n\t\treturn \"ACCOUNT_REPEATED_IN_ACCOUNT_AMOUNTS\"\n\tcase StatusSettingNegativeAccountBalance:\n\t\treturn \"SETTING_NEGATIVE_ACCOUNT_BALANCE\"\n\tcase StatusObtainerRequired:\n\t\treturn \"OBTAINER_REQUIRED\"\n\tcase StatusObtainerSameContractID:\n\t\treturn \"OBTAINER_SAME_CONTRACT_ID\"\n\tcase StatusObtainerDoesNotExist:\n\t\treturn \"OBTAINER_DOES_NOT_EXIST\"\n\tcase StatusModifyingImmutableContract:\n\t\treturn \"MODIFYING_IMMUTABLE_CONTRACT\"\n\tcase StatusFileSystemException:\n\t\treturn \"FILE_SYSTEM_EXCEPTION\"\n\tcase StatusAutorenewDurationNotInRange:\n\t\treturn \"AUTORENEW_DURATION_NOT_IN_RANGE\"\n\tcase StatusErrorDecodingBytestring:\n\t\treturn \"ERROR_DECODING_BYTESTRING\"\n\tcase StatusContractFileEmpty:\n\t\treturn \"CONTRACT_FILE_EMPTY\"\n\tcase StatusContractBytecodeEmpty:\n\t\treturn \"CONTRACT_BYTECODE_EMPTY\"\n\tcase StatusInvalidInitialBalance:\n\t\treturn \"INVALID_INITIAL_BALANCE\"\n\tcase StatusInvalidReceiveRecordThreshold:\n\t\treturn \"INVALID_RECEIVE_RECORD_THRESHOLD\"\n\tcase StatusInvalidSendRecordThreshold:\n\t\treturn \"INVALID_SEND_RECORD_THRESHOLD\"\n\tcase StatusAccountIsNotGenesisAccount:\n\t\treturn \"ACCOUNT_IS_NOT_GENESIS_ACCOUNT\"\n\tcase StatusPayerAccountUnauthorized:\n\t\treturn \"PAYER_ACCOUNT_UNAUTHORIZED\"\n\tcase StatusInvalidFreezeTransactionBody:\n\t\treturn \"INVALID_FREEZE_TRANSACTION_BODY\"\n\tcase StatusFreezeTransactionBodyNotFound:\n\t\treturn \"FREEZE_TRANSACTION_BODY_NOT_FOUND\"\n\tcase StatusTransferListSizeLimitExceeded:\n\t\treturn \"TRANSFER_LIST_SIZE_LIMIT_EXCEEDED\"\n\tcase StatusResultSizeLimitExceeded:\n\t\treturn \"RESULT_SIZE_LIMIT_EXCEEDED\"\n\tcase StatusNotSpecialAccount:\n\t\treturn \"NOT_SPECIAL_ACCOUNT\"\n\tcase StatusContractNegativeGas:\n\t\treturn \"CONTRACT_NEGATIVE_GAS\"\n\tcase StatusContractNegativeValue:\n\t\treturn \"CONTRACT_NEGATIVE_VALUE\"\n\tcase StatusInvalidFeeFile:\n\t\treturn \"INVALID_FEE_FILE\"\n\tcase StatusInvalidExchangeRateFile:\n\t\treturn \"INVALID_EXCHANGE_RATE_FILE\"\n\tcase StatusInsufficientLocalCallGas:\n\t\treturn \"INSUFFICIENT_LOCAL_CALL_GAS\"\n\tcase StatusEntityNotAllowedToDelete:\n\t\treturn \"ENTITY_NOT_ALLOWED_TO_DELETE\"\n\tcase StatusAuthorizationFailed:\n\t\treturn \"AUTHORIZATION_FAILED\"\n\tcase StatusFileUploadedProtoInvalid:\n\t\treturn \"FILE_UPLOADED_PROTO_INVALID\"\n\tcase StatusFileUploadedProtoNotSavedToDisk:\n\t\treturn \"FILE_UPLOADED_PROTO_NOT_SAVED_TO_DISK\"\n\tcase StatusFeeScheduleFilePartUploaded:\n\t\treturn \"FEE_SCHEDULE_FILE_PART_UPLOADED\"\n\tcase StatusExchangeRateChangeLimitExceeded:\n\t\treturn \"EXCHANGE_RATE_CHANGE_LIMIT_EXCEEDED\"\n\tcase StatusMaxContractStorageExceeded:\n\t\treturn \"MAX_CONTRACT_STORAGE_EXCEEDED\"\n\tcase StatusTransferAccountSameAsDeleteAccount:\n\t\treturn \"TRANSFER_ACCOUNT_SAME_AS_DELETE_ACCOUNT\"\n\tcase StatusTotalLedgerBalanceInvalid:\n\t\treturn \"TOTAL_LEDGER_BALANCE_INVALID\"\n\tcase StatusExpirationReductionNotAllowed:\n\t\treturn \"EXPIRATION_REDUCTION_NOT_ALLOWED\"\n\tcase StatusMaxGasLimitExceeded:\n\t\treturn \"MAX_GAS_LIMIT_EXCEEDED\"\n\tcase StatusMaxFileSizeExceeded:\n\t\treturn \"MAX_FILE_SIZE_EXCEEDED\"\n\tcase StatusReceiverSigRequired:\n\t\treturn \"RECEIVER_SIG_REQUIRED\"\n\tcase StatusInvalidTopicID:\n\t\treturn \"INVALID_TOPIC_ID\"\n\tcase StatusInvalidAdminKey:\n\t\treturn \"INVALID_ADMIN_KEY\"\n\tcase StatusInvalidSubmitKey:\n\t\treturn \"INVALID_SUBMIT_KEY\"\n\tcase StatusUnauthorized:\n\t\treturn \"UNAUTHORIZED\"\n\tcase StatusInvalidTopicMessage:\n\t\treturn \"INVALID_TOPIC_MESSAGE\"\n\tcase StatusInvalidAutorenewAccount:\n\t\treturn \"INVALID_AUTORENEW_ACCOUNT\"\n\tcase StatusAutorenewAccountNotAllowed:\n\t\treturn \"AUTORENEW_ACCOUNT_NOT_ALLOWED\"\n\tcase StatusTopicExpired:\n\t\treturn \"TOPIC_EXPIRED\"\n\tcase StatusInvalidChunkNumber:\n\t\treturn \"INVALID_CHUNK_NUMBER\"\n\tcase StatusInvalidChunkTransactionID:\n\t\treturn \"INVALID_CHUNK_TRANSACTION_ID\"\n\tcase StatusAccountFrozenForToken:\n\t\treturn \"ACCOUNT_FROZEN_FOR_TOKEN\"\n\tcase StatusTokensPerAccountLimitExceeded:\n\t\treturn \"TOKENS_PER_ACCOUNT_LIMIT_EXCEEDED\"\n\tcase StatusInvalidTokenID:\n\t\treturn \"INVALID_TOKEN_ID\"\n\tcase StatusInvalidTokenDecimals:\n\t\treturn \"INVALID_TOKEN_DECIMALS\"\n\tcase StatusInvalidTokenInitialSupply:\n\t\treturn \"INVALID_TOKEN_INITIAL_SUPPLY\"\n\tcase StatusInvalidTreasuryAccountForToken:\n\t\treturn \"INVALID_TREASURY_ACCOUNT_FOR_TOKEN\"\n\tcase StatusInvalidTokenSymbol:\n\t\treturn \"INVALID_TOKEN_SYMBOL\"\n\tcase StatusTokenHasNoFreezeKey:\n\t\treturn \"TOKEN_HAS_NO_FREEZE_KEY\"\n\tcase StatusTransfersNotZeroSumForToken:\n\t\treturn \"TRANSFERS_NOT_ZERO_SUM_FOR_TOKEN\"\n\tcase StatusMissingTokenSymbol:\n\t\treturn \"MISSING_TOKEN_SYMBOL\"\n\tcase StatusTokenSymbolTooLong:\n\t\treturn \"TOKEN_SYMBOL_TOO_LONG\"\n\tcase StatusAccountKycNotGrantedForToken:\n\t\treturn \"ACCOUNT_KYC_NOT_GRANTED_FOR_TOKEN\"\n\tcase StatusTokenHasNoKycKey:\n\t\treturn \"TOKEN_HAS_NO_KYC_KEY\"\n\tcase StatusInsufficientTokenBalance:\n\t\treturn \"INSUFFICIENT_TOKEN_BALANCE\"\n\tcase StatusTokenWasDeleted:\n\t\treturn \"TOKEN_WAS_DELETED\"\n\tcase StatusTokenHasNoSupplyKey:\n\t\treturn \"TOKEN_HAS_NO_SUPPLY_KEY\"\n\tcase StatusTokenHasNoWipeKey:\n\t\treturn \"TOKEN_HAS_NO_WIPE_KEY\"\n\tcase StatusInvalidTokenMintAmount:\n\t\treturn \"INVALID_TOKEN_MINT_AMOUNT\"\n\tcase StatusInvalidTokenBurnAmount:\n\t\treturn \"INVALID_TOKEN_BURN_AMOUNT\"\n\tcase StatusTokenNotAssociatedToAccount:\n\t\treturn \"TOKEN_NOT_ASSOCIATED_TO_ACCOUNT\"\n\tcase StatusCannotWipeTokenTreasuryAccount:\n\t\treturn \"CANNOT_WIPE_TOKEN_TREASURY_ACCOUNT\"\n\tcase StatusInvalidKycKey:\n\t\treturn \"INVALID_KYC_KEY\"\n\tcase StatusInvalidWipeKey:\n\t\treturn \"INVALID_WIPE_KEY\"\n\tcase StatusInvalidFreezeKey:\n\t\treturn \"INVALID_FREEZE_KEY\"\n\tcase StatusInvalidSupplyKey:\n\t\treturn \"INVALID_SUPPLY_KEY\"\n\tcase StatusMissingTokenName:\n\t\treturn \"MISSING_TOKEN_NAME\"\n\tcase StatusTokenNameTooLong:\n\t\treturn \"TOKEN_NAME_TOO_LONG\"\n\tcase StatusInvalidWipingAmount:\n\t\treturn \"INVALID_WIPING_AMOUNT\"\n\tcase StatusTokenIsImmutable:\n\t\treturn \"TOKEN_IS_IMMUTABLE\"\n\tcase StatusTokenAlreadyAssociatedToAccount:\n\t\treturn \"TOKEN_ALREADY_ASSOCIATED_TO_ACCOUNT\"\n\tcase StatusTransactionRequiresZeroTokenBalances:\n\t\treturn \"TRANSACTION_REQUIRES_ZERO_TOKEN_BALANCES\"\n\tcase StatusAccountIsTreasury:\n\t\treturn \"ACCOUNT_IS_TREASURY\"\n\tcase StatusTokenIDRepeatedInTokenList:\n\t\treturn \"TOKEN_ID_REPEATED_IN_TOKEN_LIST\"\n\tcase StatusTokenTransferListSizeLimitExceeded:\n\t\treturn \"TOKEN_TRANSFER_LIST_SIZE_LIMIT_EXCEEDED\"\n\tcase StatusEmptyTokenTransferBody:\n\t\treturn \"EMPTY_TOKEN_TRANSFER_BODY\"\n\tcase StatusEmptyTokenTransferAccountAmounts:\n\t\treturn \"EMPTY_TOKEN_TRANSFER_ACCOUNT_AMOUNTS\"\n\tcase StatusInvalidScheduleID:\n\t\treturn \"INVALID_SCHEDULE_ID\"\n\tcase StatusScheduleIsImmutable:\n\t\treturn \"SCHEDULE_IS_IMMUTABLE\"\n\tcase StatusInvalidSchedulePayerID:\n\t\treturn \"INVALID_SCHEDULE_PAYER_ID\"\n\tcase StatusInvalidScheduleAccountID:\n\t\treturn \"INVALID_SCHEDULE_ACCOUNT_ID\"\n\tcase StatusNoNewValidSignatures:\n\t\treturn \"NO_NEW_VALID_SIGNATURES\"\n\tcase StatusUnresolvableRequiredSigners:\n\t\treturn \"UNRESOLVABLE_REQUIRED_SIGNERS\"\n\tcase StatusScheduledTransactionNotInWhitelist:\n\t\treturn \"SCHEDULED_TRANSACTION_NOT_IN_WHITELIST\"\n\tcase StatusSomeSignaturesWereInvalid:\n\t\treturn \"SOME_SIGNATURES_WERE_INVALID\"\n\tcase StatusTransactionIDFieldNotAllowed:\n\t\treturn \"TRANSACTION_ID_FIELD_NOT_ALLOWED\"\n\tcase StatusIdenticalScheduleAlreadyCreated:\n\t\treturn \"IDENTICAL_SCHEDULE_ALREADY_CREATED\"\n\tcase StatusInvalidZeroByteInString:\n\t\treturn \"INVALID_ZERO_BYTE_IN_STRING\"\n\tcase StatusScheduleAlreadyDeleted:\n\t\treturn \"SCHEDULE_ALREADY_DELETED\"\n\tcase StatusScheduleAlreadyExecuted:\n\t\treturn \"SCHEDULE_ALREADY_EXECUTED\"\n\tcase StatusMessageSizeTooLarge:\n\t\treturn \"MESSAGE_SIZE_TOO_LARGE\"\n\tcase StatusOperationRepeatedInBucketGroups:\n\t\treturn \"OPERATION_REPEATED_IN_BUCKET_GROUPS\"\n\tcase StatusBucketCapacityOverflow:\n\t\treturn \"BUCKET_CAPACITY_OVERFLOW\"\n\tcase StatusNodeCapacityNotSufficientForOperation:\n\t\treturn \"NODE_CAPACITY_NOT_SUFFICIENT_FOR_OPERATION\"\n\tcase StatusBucketHasNoThrottleGroups:\n\t\treturn \"BUCKET_HAS_NO_THROTTLE_GROUPS\"\n\tcase StatusThrottleGroupHasZeroOpsPerSec:\n\t\treturn \"THROTTLE_GROUP_HAS_ZERO_OPS_PER_SEC\"\n\tcase StatusSuccessButMissingExpectedOperation:\n\t\treturn \"SUCCESS_BUT_MISSING_EXPECTED_OPERATION\"\n\tcase StatusUnparseableThrottleDefinitions:\n\t\treturn \"UNPARSEABLE_THROTTLE_DEFINITIONS\"\n\tcase StatusInvalidThrottleDefinitions:\n\t\treturn \"INVALID_THROTTLE_DEFINITIONS\"\n\tcase StatusAccountExpiredAndPendingRemoval:\n\t\treturn \"ACCOUNT_EXPIRED_AND_PENDING_REMOVAL\"\n\tcase StatusInvalidTokenMaxSupply:\n\t\treturn \"INVALID_TOKEN_MAX_SUPPLY\"\n\tcase StatusInvalidTokenNftSerialNumber:\n\t\treturn \"INVALID_TOKEN_NFT_SERIAL_NUMBER\"\n\tcase StatusInvalidNftID:\n\t\treturn \"INVALID_NFT_ID\"\n\tcase StatusMetadataTooLong:\n\t\treturn \"METADATA_TOO_LONG\"\n\tcase StatusBatchSizeLimitExceeded:\n\t\treturn \"BATCH_SIZE_LIMIT_EXCEEDED\"\n\tcase StatusInvalidQueryRange:\n\t\treturn \"INVALID_QUERY_RANGE\"\n\tcase StatusFractionDividesByZero:\n\t\treturn \"FRACTION_DIVIDES_BY_ZERO\"\n\tcase StatusInsufficientPayerBalanceForCustomFee:\n\t\treturn \"INSUFFICIENT_PAYER_BALANCE_FOR_CUSTOM_FEE\"\n\tcase StatusCustomFeesListTooLong:\n\t\treturn \"CUSTOM_FEES_LIST_TOO_LONG\"\n\tcase StatusInvalidCustomFeeCollector:\n\t\treturn \"INVALID_CUSTOM_FEE_COLLECTOR\"\n\tcase StatusInvalidTokenIDInCustomFees:\n\t\treturn \"INVALID_TOKEN_ID_IN_CUSTOM_FEES\"\n\tcase StatusTokenNotAssociatedToFeeCollector:\n\t\treturn \"TOKEN_NOT_ASSOCIATED_TO_FEE_COLLECTOR\"\n\tcase StatusTokenMaxSupplyReached:\n\t\treturn \"TOKEN_MAX_SUPPLY_REACHED\"\n\tcase StatusSenderDoesNotOwnNftSerialNo:\n\t\treturn \"SENDER_DOES_NOT_OWN_NFT_SERIAL_NO\"\n\tcase StatusCustomFeeNotFullySpecified:\n\t\treturn \"CUSTOM_FEE_NOT_FULLY_SPECIFIED\"\n\tcase StatusCustomFeeMustBePositive:\n\t\treturn \"CUSTOM_FEE_MUST_BE_POSITIVE\"\n\tcase StatusTokenHasNoFeeScheduleKey:\n\t\treturn \"TOKEN_HAS_NO_FEE_SCHEDULE_KEY\"\n\tcase StatusCustomFeeOutsideNumericRange:\n\t\treturn \"CUSTOM_FEE_OUTSIDE_NUMERIC_RANGE\"\n\tcase StatusRoyaltyFractionCannotExceedOne:\n\t\treturn \"ROYALTY_FRACTION_CANNOT_EXCEED_ONE\"\n\tcase StatusFractionalFeeMaxAmountLessThanMinAmount:\n\t\treturn \"FRACTIONAL_FEE_MAX_AMOUNT_LESS_THAN_MIN_AMOUNT\"\n\tcase StatusCustomScheduleAlreadyHasNoFees:\n\t\treturn \"CUSTOM_SCHEDULE_ALREADY_HAS_NO_FEES\"\n\tcase StatusCustomFeeDenominationMustBeFungibleCommon:\n\t\treturn \"CUSTOM_FEE_DENOMINATION_MUST_BE_FUNGIBLE_COMMON\"\n\tcase StatusCustomFractionalFeeOnlyAllowedForFungibleCommon:\n\t\treturn \"CUSTOM_FRACTIONAL_FEE_ONLY_ALLOWED_FOR_FUNGIBLE_COMMON\"\n\tcase StatusInvalidCustomFeeScheduleKey:\n\t\treturn \"INVALID_CUSTOM_FEE_SCHEDULE_KEY\"\n\tcase StatusInvalidTokenMintMetadata:\n\t\treturn \"INVALID_TOKEN_MINT_METADATA\"\n\tcase StatusInvalidTokenBurnMetadata:\n\t\treturn \"INVALID_TOKEN_BURN_METADATA\"\n\tcase StatusCurrentTreasuryStillOwnsNfts:\n\t\treturn \"CURRENT_TREASURY_STILL_OWNS_NFTS\"\n\tcase StatusAccountStillOwnsNfts:\n\t\treturn \"ACCOUNT_STILL_OWNS_NFTS\"\n\tcase StatusTreasuryMustOwnBurnedNft:\n\t\treturn \"TREASURY_MUST_OWN_BURNED_NFT\"\n\tcase StatusAccountDoesNotOwnWipedNft:\n\t\treturn \"ACCOUNT_DOES_NOT_OWN_WIPED_NFT\"\n\tcase StatusAccountAmountTransfersOnlyAllowedForFungibleCommon:\n\t\treturn \"ACCOUNT_AMOUNT_TRANSFERS_ONLY_ALLOWED_FOR_FUNGIBLE_COMMON\"\n\tcase StatusMaxNftsInPriceRegimeHaveBeenMinted:\n\t\treturn \"MAX_NFTS_IN_PRICE_REGIME_HAVE_BEEN_MINTED\"\n\tcase StatusPayerAccountDeleted:\n\t\treturn \"PAYER_ACCOUNT_DELETED\"\n\tcase StatusCustomFeeChargingExceededMaxRecursionDepth:\n\t\treturn \"CUSTOM_FEE_CHARGING_EXCEEDED_MAX_RECURSION_DEPTH\"\n\tcase StatusCustomFeeChargingExceededMaxAccountAmounts:\n\t\treturn \"CUSTOM_FEE_CHARGING_EXCEEDED_MAX_ACCOUNT_AMOUNTS\"\n\tcase StatusInsufficientSenderAccountBalanceForCustomFee:\n\t\treturn \"INSUFFICIENT_SENDER_ACCOUNT_BALANCE_FOR_CUSTOM_FEE\"\n\tcase StatusSerialNumberLimitReached:\n\t\treturn \"SERIAL_NUMBER_LIMIT_REACHED\"\n\tcase StatusCustomRoyaltyFeeOnlyAllowedForNonFungibleUnique:\n\t\treturn \"CUSTOM_ROYALTY_FEE_ONLY_ALLOWED_FOR_NON_FUNGIBLE_UNIQUE\"\n\tcase StatusNoRemainingAutomaticAssociations:\n\t\treturn \"NO_REMAINING_AUTOMATIC_ASSOCIATIONS\"\n\tcase StatusExistingAutomaticAssociationsExceedGivenLimit:\n\t\treturn \"EXISTING_AUTOMATIC_ASSOCIATIONS_EXCEED_GIVEN_LIMIT\"\n\tcase StatusRequestedNumAutomaticAssociationsExceedsAssociationLimit:\n\t\treturn \"REQUESTED_NUM_AUTOMATIC_ASSOCIATIONS_EXCEEDS_ASSOCIATION_LIMIT\"\n\tcase StatusTokenIsPaused:\n\t\treturn \"TOKEN_IS_PAUSED\"\n\tcase StatusTokenHasNoPauseKey:\n\t\treturn \"TOKEN_HAS_NO_PAUSE_KEY\"\n\tcase StatusInvalidPauseKey:\n\t\treturn \"INVALID_PAUSE_KEY\"\n\tcase StatusFreezeUpdateFileDoesNotExist:\n\t\treturn \"FREEZE_UPDATE_FILE_DOES_NOT_EXIST\"\n\tcase StatusFreezeUpdateFileHashDoesNotMatch:\n\t\treturn \"FREEZE_UPDATE_FILE_HASH_DOES_NOT_MATCH\"\n\tcase StatusNoUpgradeHasBeenPrepared:\n\t\treturn \"NO_UPGRADE_HAS_BEEN_PREPARED\"\n\tcase StatusNoFreezeIsScheduled:\n\t\treturn \"NO_FREEZE_IS_SCHEDULED\"\n\tcase StatusUpdateFileHashChangedSincePrepareUpgrade:\n\t\treturn \"UPDATE_FILE_HASH_CHANGED_SINCE_PREPARE_UPGRADE\"\n\tcase StatusFreezeStartTimeMustBeFuture:\n\t\treturn \"FREEZE_START_TIME_MUST_BE_FUTURE\"\n\tcase StatusPreparedUpdateFileIsImmutable:\n\t\treturn \"PREPARED_UPDATE_FILE_IS_IMMUTABLE\"\n\tcase StatusFreezeAlreadyScheduled:\n\t\treturn \"FREEZE_ALREADY_SCHEDULED\"\n\tcase StatusFreezeUpgradeInProgress:\n\t\treturn \"FREEZE_UPGRADE_IN_PROGRESS\"\n\tcase StatusUpdateFileIDDoesNotMatchPrepared:\n\t\treturn \"UPDATE_FILE_ID_DOES_NOT_MATCH_PREPARED\"\n\tcase StatusUpdateFileHashDoesNotMatchPrepared:\n\t\treturn \"UPDATE_FILE_HASH_DOES_NOT_MATCH_PREPARED\"\n\tcase StatusConsensusGasExhausted:\n\t\treturn \"CONSENSUS_GAS_EXHAUSTED\"\n\tcase StatusRevertedSuccess:\n\t\treturn \"REVERTED_SUCCESS\"\n\tcase StatusMaxStorageInPriceRegimeHasBeenUsed:\n\t\treturn \"MAX_STORAGE_IN_PRICE_REGIME_HAS_BEEN_USED\"\n\tcase StatusInvalidAliasKey:\n\t\treturn \"INVALID_ALIAS_KEY\"\n\tcase StatusUnexpectedTokenDecimals:\n\t\treturn \"UNEXPECTED_TOKEN_DECIMALS\"\n\tcase StatusInvalidProxyAccountID:\n\t\treturn \"INVALID_PROXY_ACCOUNT_ID\"\n\tcase StatusInvalidTransferAccountID:\n\t\treturn \"INVALID_TRANSFER_ACCOUNT_ID\"\n\tcase StatusInvalidFeeCollectorAccountID:\n\t\treturn \"INVALID_FEE_COLLECTOR_ACCOUNT_ID\"\n\tcase StatusAliasIsImmutable:\n\t\treturn \"ALIAS_IS_IMMUTABLE\"\n\tcase StatusSpenderAccountSameAsOwner:\n\t\treturn \"SPENDER_ACCOUNT_SAME_AS_OWNER\"\n\tcase StatusAmountExceedsTokenMaxSupply:\n\t\treturn \"AMOUNT_EXCEEDS_TOKEN_MAX_SUPPLY\"\n\tcase StatusNegativeAllowanceAmount:\n\t\treturn \"NEGATIVE_ALLOWANCE_AMOUNT\"\n\tcase StatusCannotApproveForAllFungibleCommon:\n\t\treturn \"CANNOT_APPROVE_FOR_ALL_FUNGIBLE_COMMON\"\n\tcase StatusSpenderDoesNotHaveAllowance:\n\t\treturn \"SPENDER_DOES_NOT_HAVE_ALLOWANCE\"\n\tcase StatusAmountExceedsAllowance:\n\t\treturn \"AMOUNT_EXCEEDS_ALLOWANCE\"\n\tcase StatusMaxAllowancesExceeded:\n\t\treturn \"MAX_ALLOWANCES_EXCEEDED\"\n\tcase StatusEmptyAllowances:\n\t\treturn \"EMPTY_ALLOWANCES\"\n\tcase StatusSpenderAccountRepeatedInAllowance:\n\t\treturn \"SPENDER_ACCOUNT_REPEATED_IN_ALLOWANCES\"\n\tcase StatusRepeatedSerialNumsInNftAllowances:\n\t\treturn \"REPEATED_SERIAL_NUMS_IN_NFT_ALLOWANCES\"\n\tcase StatusFungibleTokenInNftAllowances:\n\t\treturn \"FUNGIBLE_TOKEN_IN_NFT_ALLOWANCES\"\n\tcase StatusNftInFungibleTokenAllowances:\n\t\treturn \"NFT_IN_FUNGIBLE_TOKEN_ALLOWANCES\"\n\tcase StatusInvalidAllowanceOwnerID:\n\t\treturn \"INVALID_ALLOWANCE_OWNER_ID\"\n\tcase StatusInvalidAllowanceSpenderID:\n\t\treturn \"INVALID_ALLOWANCE_SPENDER_ID\"\n\tcase StatusRepeatedAllowancesToDelete:\n\t\treturn \"REPEATED_ALLOWANCES_TO_DELETE\"\n\tcase StatusInvalidDelegatingSpender:\n\t\treturn \"INVALID_DELEGATING_SPENDER\"\n\tcase StatusDelegatingSpenderCannotGrantApproveForAll:\n\t\treturn \"DELEGATING_SPENDER_CANNOT_GRANT_APPROVE_FOR_ALL\"\n\tcase StatusDelegatingSpenderDoesNotHaveApproveForAll:\n\t\treturn \"DELEGATING_SPENDER_DOES_NOT_HAVE_APPROVE_FOR_ALL\"\n\tcase StatusScheduleExpirationTimeTooFarInFuture:\n\t\treturn \"SCHEDULE_EXPIRATION_TIME_TOO_FAR_IN_FUTURE\"\n\tcase StatusScheduleExpirationTimeMustBeHigherThanConsensusTime:\n\t\treturn \"SCHEDULE_EXPIRATION_TIME_MUST_BE_HIGHER_THAN_CONSENSUS_TIME\"\n\tcase StatusScheduleFutureThrottleExceeded:\n\t\treturn \"SCHEDULE_FUTURE_THROTTLE_EXCEEDED\"\n\tcase StatusScheduleFutureGasLimitExceeded:\n\t\treturn \"SCHEDULE_FUTURE_GAS_LIMIT_EXCEEDED\"\n\tcase StatusInvalidEthereumTransaction:\n\t\treturn \"INVALID_ETHEREUM_TRANSACTION\"\n\tcase StatusWrongChanID:\n\t\treturn \"WRONG_CHAIN_ID\"\n\tcase StatusWrongNonce:\n\t\treturn \"WRONG_NONCE\"\n\tcase StatusAccessListUnsupported:\n\t\treturn \"ACCESS_LIST_UNSUPPORTED\"\n\tcase StatusSchedulePendingExpiration:\n\t\treturn \"SCHEDULE_PENDING_EXPIRATION\"\n\tcase StatusContractIsTokenTreasury:\n\t\treturn \"CONTRACT_IS_TOKEN_TREASURY\"\n\tcase StatusContractHasNonZeroTokenBalances:\n\t\treturn \"CONTRACT_HAS_NON_ZERO_TOKEN_BALANCES\"\n\tcase StatusContractExpiredAndPendingRemoval:\n\t\treturn \"CONTRACT_EXPIRED_AND_PENDING_REMOVAL\"\n\tcase StatusContractHasNoAutoRenewAccount:\n\t\treturn \"CONTRACT_HAS_NO_AUTO_RENEW_ACCOUNT\"\n\tcase StatusPermanentRemovalRequiresSystemInitiation:\n\t\treturn \"PERMANENT_REMOVAL_REQUIRES_SYSTEM_INITIATION\"\n\tcase StatusProxyAccountIDFieldIsDeprecated:\n\t\treturn \"PROXY_ACCOUNT_ID_FIELD_IS_DEPRECATED \"\n\tcase StatusSelfStakingIsNotAllowed:\n\t\treturn \"SELF_STAKING_IS_NOT_ALLOWED\"\n\tcase StatusInvalidStakingID:\n\t\treturn \"INVALID_STAKING_ID\"\n\tcase StatusStakingNotEnabled:\n\t\treturn \"STAKING_NOT_ENABLED\"\n\tcase StatusInvalidRandomGenerateRange:\n\t\treturn \"INVALID_RANDOM_GENERATE_RANGE\"\n\tcase StatusMaxEntitiesInPriceRegimeHaveBeenCreated:\n\t\treturn \"MAX_ENTITIES_IN_PRICE_REGIME_HAVE_BEEN_CREATED\"\n\tcase StatusInvalidFullPrefixSignatureForPrecompile:\n\t\treturn \"INVALID_FULL_PREFIX_SIGNATURE_FOR_PRECOMPILE\"\n\tcase StatusInsufficientBalancesForStorageRent:\n\t\treturn \"INSUFFICIENT_BALANCES_FOR_STORAGE_RENT\"\n\tcase StatusMaxChildRecordsExceeded:\n\t\treturn \"MAX_CHILD_RECORDS_EXCEEDED\"\n\tcase StatusInsufficientBalancesForRenewalFees:\n\t\treturn \"INSUFFICIENT_BALANCES_FOR_RENEWAL_FEES\"\n\tcase StatusTransactionHasUnknownFields:\n\t\treturn \"TRANSACTION_HAS_UNKNOWN_FIELDS\"\n\tcase StatusAccountIsImmutable:\n\t\treturn \"ACCOUNT_IS_IMMUTABLE\"\n\tcase StatusAliasAlreadyAssigned:\n\t\treturn \"ALIAS_ALREADY_ASSIGNED\"\n\t}\n\n\tpanic(fmt.Sprintf(\"unreachable: Status.String() switch statement is non-exhaustive. Status: %v\", uint32(status)))\n}", "func StatusValidator(s Status) error {\n\tswitch s {\n\tcase StatusWAITING, StatusIN_PROGRESS, StatusDONE, StatusERROR:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"operation: invalid enum value for status field: %q\", s)\n\t}\n}", "func Status(status string) error {\n\treturn SdNotify(\"STATUS=\" + status)\n}", "func ParseStatus(state string) Status {\n\tswitch strings.ToUpper(state) {\n\tcase \"OUTAGE\":\n\t\treturn OUTAGE\n\tcase \"MAJOR\":\n\t\treturn MAJOR\n\tcase \"MINOR\":\n\t\treturn MINOR\n\tcase \"OK\":\n\t\treturn OK\n\tdefault:\n\t\treturn OUTAGE\n\t}\n}", "func GetAlarmStatusSummaryStatusEnumStringValues() []string {\n\treturn []string{\n\t\t\"FIRING\",\n\t\t\"OK\",\n\t\t\"SUSPENDED\",\n\t}\n}", "func (i GinBindType) ParseByName(s string) (GinBindType, error) {\n\tif val, ok := _GinBindTypeNameToValueMap[s]; ok {\n\t\t// parse ok\n\t\treturn val, nil\n\t}\n\n\t// error\n\treturn -1, fmt.Errorf(\"Enum Name of %s Not Expected In GinBindType Values List\", s)\n}", "func GetString(pname Enum) string {\n\treturn gl.GoStr(gl.GetString(uint32(pname)))\n}", "func (a *abaImpl) StatusString() string {\n\treturn fmt.Sprintf(\n\t\t\"{ABA:Mostefaoui, R=%v, %v, %v, %v, %v, out=%+v}\",\n\t\ta.round,\n\t\ta.varBinVals.statusString(),\n\t\ta.varAuxVals.statusString(),\n\t\ta.uponDecisionInputs.statusString(),\n\t\ta.varDone.statusString(),\n\t\ta.output,\n\t)\n}", "func SetStatus(status string) (int64, error) {\n\treg := make([]string, len(StatusValues))\n\n\tfor key := range StatusValues {\n\t\tif StatusValues[key] == status {\n\t\t\treg[key] = \"1\"\n\t\t} else {\n\t\t\treg[key] = \"0\"\n\t\t}\n\t}\n\n\tresultStr := reverse(strings.Join(reg[:], \"\"))\n\n\tstatusDB, err := strconv.ParseInt(resultStr, 2, 64)\n\treturn statusDB, err\n}", "func strStatefulSetStatus(status *apps.StatefulSetStatus) string {\n\treturn fmt.Sprintf(\n\t\t\"ObservedGeneration:%d Replicas:%d ReadyReplicas:%d CurrentReplicas:%d UpdatedReplicas:%d CurrentRevision:%s UpdateRevision:%s\",\n\t\tstatus.ObservedGeneration,\n\t\tstatus.Replicas,\n\t\tstatus.ReadyReplicas,\n\t\tstatus.CurrentReplicas,\n\t\tstatus.UpdatedReplicas,\n\t\tstatus.CurrentRevision,\n\t\tstatus.UpdateRevision,\n\t)\n}", "func ColorStatus(code int) string {\n\tstr := fmt.Sprintf(\"%3d\", code)\n\tswitch {\n\tcase code >= 200 && code < 300:\n\t\treturn ColorString(ColorCodeGreen, str)\n\tcase code >= 300 && code < 400:\n\t\treturn ColorString(ColorCodeWhite, str)\n\tcase code >= 400 && code < 500:\n\t\treturn ColorString(ColorCodeYellow, str)\n\tdefault:\n\t\treturn ColorString(ColorCodeRed, str)\n\t}\n}", "func BindStatusValues() []BindStatus {\n\treturn _BindStatusValues\n}", "func GetHealthCheckResultHealthCheckStatusEnumStringValues() []string {\n\treturn []string{\n\t\t\"OK\",\n\t\t\"INVALID_STATUS_CODE\",\n\t\t\"TIMED_OUT\",\n\t\t\"REGEX_MISMATCH\",\n\t\t\"CONNECT_FAILED\",\n\t\t\"IO_ERROR\",\n\t\t\"OFFLINE\",\n\t\t\"UNKNOWN\",\n\t}\n}", "func (sc StateEnum) String() string {\n\tif s, ok := stateText[sc]; ok {\n\t\treturn s\n\t}\n\treturn \"invalid\"\n}", "func ValidateStatusRequest(message *taskspb.StatusRequest) (err error) {\n\tif !(message.Status == \"Open\" || message.Status == \"Closed\" || message.Status == \"Pending\") {\n\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"message.status\", message.Status, []interface{}{\"Open\", \"Closed\", \"Pending\"}))\n\t}\n\treturn\n}", "func StatusText(code int) string {\n\treturn statusText[code]\n}", "func StatusText(code int) string {\n\treturn statusText[code]\n}", "func StatusText(code int) string {\n\treturn statusText[code]\n}", "func (e EnumByte) String() string {\n if e == EnumByte_ENUM_VALUE_0 {\n return \"ENUM_VALUE_0\"\n }\n if e == EnumByte_ENUM_VALUE_1 {\n return \"ENUM_VALUE_1\"\n }\n if e == EnumByte_ENUM_VALUE_2 {\n return \"ENUM_VALUE_2\"\n }\n if e == EnumByte_ENUM_VALUE_3 {\n return \"ENUM_VALUE_3\"\n }\n if e == EnumByte_ENUM_VALUE_4 {\n return \"ENUM_VALUE_4\"\n }\n if e == EnumByte_ENUM_VALUE_5 {\n return \"ENUM_VALUE_5\"\n }\n return \"<unknown>\"\n}", "func StatusContains(v string) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldStatus), v))\n\t})\n}", "func (m *ProgramControl) SetStatus(value *string)() {\n err := m.GetBackingStore().Set(\"status\", value)\n if err != nil {\n panic(err)\n }\n}", "func StatusValidator(s Status) error {\n\tswitch s {\n\tcase StatusPENDING, StatusPOSTED:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"transaction: invalid enum value for status field: %q\", s)\n\t}\n}", "func TribStatusToString(status int) string {\n\tswitch(status) {\n\tcase tribproto.OK:\n\t\treturn \"OK\"\n\tcase tribproto.ENOSUCHUSER:\n\t\treturn \"No such user\"\n\tcase tribproto.ENOSUCHFLIGHT:\n\t\treturn \"No such flight\"\n\tcase tribproto.ENOSUCHAIRLINE:\n\t\treturn \"No such airline\"\n\tcase tribproto.EEXISTS:\n\t\treturn \"Already exists\"\n\tcase tribproto.EBOOKINGFAILED:\n\t\treturn \"Booking failed\"\n\tcase tribproto.ENOAIRLINE:\n\t\treturn \"Airline doesn't exist\"\n\tcase tribproto.ENOTBOOKED:\n\t\treturn \"Remove unbooked tickets\"\n\t\t\n\t}\n\treturn \"Unknown error\"\n}", "func Status(httpCode int) string {\n\tswitch {\n\tcase httpCode >= 500:\n\t\treturn StatusError\n\tcase httpCode >= 400:\n\t\treturn StatusClientError\n\tcase httpCode >= 200:\n\t\treturn StatusOk\n\t}\n\treturn StatusOk\n}", "func assertSBRStatus(\n\tctx context.Context,\n\tf *framework.Framework,\n\tnamespacedName types.NamespacedName,\n) error {\n\tsbr := &v1alpha1.ServiceBindingRequest{}\n\tif err := f.Client.Get(ctx, namespacedName, sbr); err != nil {\n\t\treturn err\n\t}\n\n\tfor i, condition := range sbr.Status.Conditions {\n\t\tif condition.Type != servicebindingrequest.BindingReady && condition.Status != corev1.ConditionTrue {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"Condition.Type and Condition.Status is '%s' and '%s' instead of '%s' and '%s'\",\n\t\t\t\tsbr.Status.Conditions[i].Type,\n\t\t\t\tsbr.Status.Conditions[i].Status,\n\t\t\t\tservicebindingrequest.BindingReady,\n\t\t\t\tcorev1.ConditionTrue)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Status) UnmarshalGQL(val interface{}) error {\n\tstr, ok := val.(string)\n\tif !ok {\n\t\treturn fmt.Errorf(\"enum %T must be a string\", val)\n\t}\n\t*s = Status(str)\n\tif err := StatusValidator(*s); err != nil {\n\t\treturn fmt.Errorf(\"%s is not a valid Status\", str)\n\t}\n\treturn nil\n}", "func ParseEnum(name string) (Enum, error) {\n\tswitch name {\n\tcase \"tcp\":\n\t\treturn Tcp, nil\n\tcase \"http\":\n\t\treturn Http, nil\n\t}\n\tvar zero Enum\n\treturn zero, fmt.Errorf(\"%s is not a valid healthchecktype.Enum\", name)\n}", "func Status(v string) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldStatus), v))\n\t})\n}", "func (code StatusCode) String() string {\n\treturn strconv.Itoa(int(code))\n}", "func (code StatusCode) String() string {\n\treturn strconv.Itoa(int(code))\n}", "func (c *CryptohomeBinary) GetStatusString(ctx context.Context) (string, error) {\n\tout, err := c.call(ctx, \"--action=status\")\n\treturn string(out), err\n}", "func (o *FindExecutionsParams) validateStatus(formats strfmt.Registry) error {\n\n\tif err := validate.Enum(\"status\", \"query\", *o.Status, []interface{}{\"unknown\", \"queued\", \"running\", \"completed\", \"cancelled\", \"errored\"}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *SearchCall) Status(status string) *SearchCall {\n\tc.urlParams_.Set(\"status\", status)\n\treturn c\n}", "func ParseEnum(name string) (Enum, error) {\n\tswitch name {\n\tcase \"pending\":\n\t\treturn Pending, nil\n\tcase \"active\":\n\t\treturn Active, nil\n\tcase \"overdue\":\n\t\treturn Overdue, nil\n\tcase \"warning\":\n\t\treturn Warning, nil\n\tcase \"suspended\":\n\t\treturn Suspended, nil\n\tcase \"terminated\":\n\t\treturn Terminated, nil\n\tcase \"closed\":\n\t\treturn Closed, nil\n\tcase \"deleted\":\n\t\treturn Deleted, nil\n\t}\n\tvar zero Enum\n\treturn zero, fmt.Errorf(\"%s is not a valid accountstatus.Enum\", name)\n}", "func (s *StringEnum) Type() string { return \"string\" }", "func GetStatusString(status int) string {\n\tswitch status {\n\tcase DiskStatusSleep:\n\t\treturn \"Sleeping\"\n\n\tcase DiskStatusStandby:\n\t\treturn \"Standby\"\n\n\tcase DiskStatusActive:\n\t\treturn \"Active\"\n\n\tdefault:\n\t\treturn \"Unknown\"\n\t}\n}", "func (p *LegoPort) Status() (string, error) {\n\treturn stringFrom(attributeOf(p, status))\n}", "func (s SyncStatuses) GetStatus(n string) *SyncStatus {\n\tstatus, ok := s[n]\n\tif !ok {\n\t\tstatus = &SyncStatus{}\n\t\ts[n] = status\n\t}\n\treturn status\n}", "func STATUSBABYNAME(v string) predicate.Babystatus {\n\treturn predicate.Babystatus(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldSTATUSBABYNAME), v))\n\t})\n}", "func errToStatus(code string) *Status {\n\tecode, err := strconv.Atoi(code)\n\tif err != nil {\n\t\treturn UndefinedErr\n\t}\n\n\testatus, ok := _status.Load(ecode)\n\tif !ok {\n\t\treturn UndefinedErr\n\t}\n\n\treturn estatus.(*Status)\n}", "func GetMappingOperationStatusEnum(val string) (OperationStatusEnum, bool) {\n\tenum, ok := mappingOperationStatusEnumLowerCase[strings.ToLower(val)]\n\treturn enum, ok\n}", "func (s Status) String() string {\n\tswitch s {\n\tcase OUTAGE:\n\t\treturn \"OUTAGE\"\n\tcase MAJOR:\n\t\treturn \"MAJOR\"\n\tcase MINOR:\n\t\treturn \"MINOR\"\n\tcase OK:\n\t\treturn \"OK\"\n\t}\n\treturn \"INVALID\"\n}", "func StatusTextFunc(code int) string {\n\treturn statusText[code]\n}", "func Status(expected int) echo.Checker {\n\texpectedStr := \"\"\n\tif expected > 0 {\n\t\texpectedStr = strconv.Itoa(expected)\n\t}\n\treturn Each(func(r echoClient.Response) error {\n\t\tif r.Code != expectedStr {\n\t\t\treturn fmt.Errorf(\"expected response code `%s`, got %q. Response: %s\", expectedStr, r.Code, r)\n\t\t}\n\t\treturn nil\n\t})\n}", "func (s Status) String() string {\n\treturn status2String[s]\n}", "func STATUSDATA(v string) predicate.RoomStatus {\n\treturn predicate.RoomStatus(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldSTATUSDATA), v))\n\t})\n}", "func (e LegacyTabletStats) NamedStatusURL() string {\n\treturn \"/\" + topoproto.TabletAliasString(e.Tablet.Alias) + servenv.StatusURLPath()\n}", "func flattenImageStatusEnum(i interface{}) *ImageStatusEnum {\n\ts, ok := i.(string)\n\tif !ok {\n\t\treturn ImageStatusEnumRef(\"\")\n\t}\n\n\treturn ImageStatusEnumRef(s)\n}", "func GetWorkRequestStatusEnumStringValues() []string {\n\treturn []string{\n\t\t\"ACCEPTED\",\n\t\t\"IN_PROGRESS\",\n\t\t\"FAILED\",\n\t\t\"SUCCEEDED\",\n\t\t\"CANCELING\",\n\t\t\"CANCELED\",\n\t}\n}", "func statusText(code StatusCode) string {\n\tswitch code {\n\tcase StatusOK:\n\t\treturn \"ok\"\n\tcase StatusNotFound:\n\t\treturn \"not found\"\n\tcase StatusClassNotFound:\n\t\treturn \"class not found\"\n\tcase StatusShardNotFound:\n\t\treturn \"shard not found\"\n\tcase StatusConflict:\n\t\treturn \"conflict\"\n\tcase StatusPreconditionFailed:\n\t\treturn \"precondition failed\"\n\tcase StatusAlreadyExisted:\n\t\treturn \"already existed\"\n\tcase StatusNotReady:\n\t\treturn \"local index not ready\"\n\tcase StatusReadOnly:\n\t\treturn \"read only\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func (qf SlurmFacade) ResourceStatus(statusArray []string, smRecord *SMRecord) (string, error) {\n\tif smRecord.JobID == \"\" {\n\t\treturn \"available\", nil\n\t}\n\n\tres := \"\"\n\n\tfor _, status := range statusArray {\n\t\tif strings.Contains(status, smRecord.JobID) {\n\n\t\t\tfor _, statusLineToken := range strings.Fields(status) {\n\t\t\t\tswitch statusLineToken {\n\t\t\t\t\tcase \"PENDING\" :\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"initializing\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"PD\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"initializing\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"CONFIGURING\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"initializing\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"CF\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"initializing\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"RUNNING\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"running_sm\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"R\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"running_sm\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"COMPLETING\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"released\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"CG\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"released\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"COMPLETED\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"released\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"CD\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"released\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"CA\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"released\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"CANCELLED\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"released\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"FAILED\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"error\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"F\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"error\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"NODE_FAIL\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"error\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"NF\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"error\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"PREEMPTED\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"error\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"PR\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"error\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"SUSPENDED\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"error\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"S\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"error\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"TIMEOUT\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"error\"\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"TO\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"error\"\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres = \"\"\n\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif res != \"\" {\n\t\t\t\t\treturn res, nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn \"\", fmt.Errorf(status)\n\t\t}\n\t}\n\n\t// no such jobID\n\treturn \"released\", nil\n}", "func Severity1EnumFromValue(value string) Severity1Enum {\r\n switch value {\r\n case \"kCritical\":\r\n return Severity1_KCRITICAL\r\n case \"kWarning\":\r\n return Severity1_KWARNING\r\n case \"kInfo\":\r\n return Severity1_KINFO\r\n default:\r\n return Severity1_KCRITICAL\r\n }\r\n}", "func StatusCodeToString(status HttpStatus) string {\n\tmsg := \"null\"\n\tswitch status {\n\tcase Status200:\n\t\tmsg = \"200\"\n\tcase Status301:\n\t\tmsg = \"301\"\n\tcase Status302:\n\t\tmsg = \"302\"\n\tcase Status307:\n\t\tmsg = \"307\"\n\tcase Status400:\n\t\tmsg = \"400\"\n\tcase Status403:\n\t\tmsg = \"403\"\n\tcase Status404:\n\t\tmsg = \"404\"\n\tcase Status500:\n\t\tmsg = \"500\"\n\tcase Status503:\n\t\tmsg = \"503\"\n\t}\n\treturn msg\n}", "func (h *ReplicationGroupHandler) SetBindStatus(n types.NamespacedName, c client.Client, bound bool) error {\n\ti := &v1alpha1.ReplicationGroup{}\n\tif err := c.Get(ctx, n, i); err != nil {\n\t\tif kerrors.IsNotFound(err) && !bound {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrapf(err, \"cannot get instance %s\", n)\n\t}\n\ti.Status.SetBound(bound)\n\treturn errors.Wrapf(c.Update(ctx, i), \"cannot update instance %s\", n)\n}", "func (m *ThreatAssessmentRequest) SetStatus(value *ThreatAssessmentStatus)() {\n m.status = value\n}", "func (s Status) String() string {\n\tswitch s {\n\tcase Created:\n\t\treturn \"created\"\n\tcase Creating:\n\t\treturn \"creating\"\n\tcase Paused:\n\t\treturn \"paused\"\n\tcase Running:\n\t\treturn \"running\"\n\tcase Stopped:\n\t\treturn \"stopped\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n\n}", "func GroupDynamicGroupMetadataStatusStatusEnumRef(s string) *GroupDynamicGroupMetadataStatusStatusEnum {\n\tv := GroupDynamicGroupMetadataStatusStatusEnum(s)\n\treturn &v\n}", "func Status(statusCode int) AdditionalAttribute {\n return func(rb *Builder) error {\n rb.SetStatus(statusCode)\n return nil\n }\n}", "func (e Enum) String() string {\n\ts, ok := lookupEnum(e)\n\tif !ok {\n\t\treturn fmt.Sprintf(\"%[3]s(%[2]d)\", \"\", int(e), \"Enum\")\n\t}\n\treturn s\n}", "func ModelStatusText(code ModelStatusCode) string {\n\treturn modelStatusText[code]\n}", "func (m *ScheduleItem) SetStatus(value *FreeBusyStatus)() {\n err := m.GetBackingStore().Set(\"status\", value)\n if err != nil {\n panic(err)\n }\n}", "func translateECSStatus(status *string) cocoa.ECSStatus {\n\tif status == nil {\n\t\treturn cocoa.StatusUnknown\n\t}\n\tswitch *status {\n\tcase TaskStatusProvisioning, TaskStatusPending, TaskStatusActivating:\n\t\treturn cocoa.StatusStarting\n\tcase TaskStatusRunning:\n\t\treturn cocoa.StatusRunning\n\tcase TaskStatusDeactivating, TaskStatusStopping, TaskStatusDeprovisioning, TaskStatusStopped:\n\t\treturn cocoa.StatusStopped\n\tdefault:\n\t\treturn cocoa.StatusUnknown\n\t}\n}", "func (m *SchemaExtension) SetStatus(value *string)() {\n err := m.GetBackingStore().Set(\"status\", value)\n if err != nil {\n panic(err)\n }\n}", "func StatusText(c int) string {\n\treturn fmt.Sprintf(\"%d %s\", c, http.StatusText(c))\n}" ]
[ "0.65584415", "0.6357811", "0.62564325", "0.603373", "0.57799196", "0.5754323", "0.5751146", "0.56036144", "0.55948097", "0.5559084", "0.5543421", "0.5466031", "0.54613245", "0.53769064", "0.537138", "0.53685933", "0.53546983", "0.5352652", "0.53030354", "0.5284958", "0.5283547", "0.5283452", "0.52675337", "0.5264721", "0.5252228", "0.5243406", "0.5240442", "0.5226723", "0.5202905", "0.5193867", "0.5174182", "0.51661", "0.51359934", "0.5127352", "0.51093346", "0.5097478", "0.50893056", "0.5077876", "0.5077003", "0.50741524", "0.5046307", "0.504193", "0.5035164", "0.50350505", "0.503313", "0.50281334", "0.50196797", "0.5003558", "0.49787942", "0.49757665", "0.49745876", "0.49590224", "0.49590224", "0.49590224", "0.49503964", "0.49441326", "0.49418977", "0.49406195", "0.4940282", "0.49277326", "0.49164003", "0.49086586", "0.49075335", "0.4904183", "0.48980597", "0.48980597", "0.48945093", "0.48928314", "0.4888523", "0.48879173", "0.48731306", "0.4865011", "0.48525172", "0.4841124", "0.48387194", "0.4826575", "0.48237503", "0.48185545", "0.48181844", "0.48155132", "0.481318", "0.48121664", "0.47991568", "0.47973", "0.4773537", "0.47717905", "0.47637972", "0.4761554", "0.4746133", "0.4744097", "0.47398275", "0.4738764", "0.47353977", "0.47298366", "0.47286895", "0.47267604", "0.47205248", "0.4718907", "0.47158253", "0.47112918" ]
0.75342965
0
BindStatusValues returns all values of the enum
func BindStatusValues() []BindStatus { return _BindStatusValues }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Status_Values() []string {\n\treturn []string{\n\t\tStatusEnabled,\n\t\tStatusEnabling,\n\t\tStatusDisabled,\n\t\tStatusDisabling,\n\t}\n}", "func Status_Values() []string {\n\treturn []string{\n\t\tStatusPending,\n\t\tStatusDeployed,\n\t\tStatusPendingDeletion,\n\t}\n}", "func (StatusType) Values() []StatusType {\n\treturn []StatusType{\n\t\t\"passed\",\n\t\t\"failed\",\n\t\t\"insufficient-data\",\n\t\t\"initializing\",\n\t}\n}", "func (Status) Values() []Status {\n\treturn []Status{\n\t\t\"IGNORE\",\n\t\t\"RESOLVED\",\n\t\t\"PENDING\",\n\t\t\"RECURRING\",\n\t\t\"RECOVERING\",\n\t}\n}", "func (Status) Values() []Status {\n\treturn []Status{\n\t\t\"Active\",\n\t\t\"Expired\",\n\t}\n}", "func (GlobalTableStatus) Values() []GlobalTableStatus {\n\treturn []GlobalTableStatus{\n\t\t\"CREATING\",\n\t\t\"ACTIVE\",\n\t\t\"DELETING\",\n\t\t\"UPDATING\",\n\t}\n}", "func (Status) Values() []Status {\n\treturn []Status{\n\t\t\"PASS\",\n\t\t\"FAIL\",\n\t\t\"CANCELED\",\n\t\t\"PENDING\",\n\t\t\"RUNNING\",\n\t\t\"PASS_WITH_WARNINGS\",\n\t\t\"ERROR\",\n\t}\n}", "func (VolumeStatusInfoStatus) Values() []VolumeStatusInfoStatus {\n\treturn []VolumeStatusInfoStatus{\n\t\t\"ok\",\n\t\t\"impaired\",\n\t\t\"insufficient-data\",\n\t}\n}", "func (Status) Values() []Status {\n\treturn []Status{\n\t\t\"MoveInProgress\",\n\t\t\"InVpc\",\n\t\t\"InClassic\",\n\t}\n}", "func BotStatus_Values() []string {\n\treturn []string{\n\t\tBotStatusCreating,\n\t\tBotStatusAvailable,\n\t\tBotStatusInactive,\n\t\tBotStatusDeleting,\n\t\tBotStatusFailed,\n\t\tBotStatusVersioning,\n\t\tBotStatusImporting,\n\t\tBotStatusUpdating,\n\t}\n}", "func (InviteStatus) Values() []InviteStatus {\n\treturn []InviteStatus{\n\t\t\"Pending\",\n\t\t\"Accepted\",\n\t\t\"Failed\",\n\t}\n}", "func (HubStatus) Values() []HubStatus {\n\treturn []HubStatus{\n\t\t\"InService\",\n\t\t\"Creating\",\n\t\t\"Updating\",\n\t\t\"Deleting\",\n\t\t\"CreateFailed\",\n\t\t\"UpdateFailed\",\n\t\t\"DeleteFailed\",\n\t}\n}", "func (AttachmentStatus) Values() []AttachmentStatus {\n\treturn []AttachmentStatus{\n\t\t\"attaching\",\n\t\t\"attached\",\n\t\t\"detaching\",\n\t\t\"detached\",\n\t}\n}", "func (FlowDefinitionStatus) Values() []FlowDefinitionStatus {\n\treturn []FlowDefinitionStatus{\n\t\t\"Initializing\",\n\t\t\"Active\",\n\t\t\"Failed\",\n\t\t\"Deleting\",\n\t}\n}", "func (CallingNameStatus) Values() []CallingNameStatus {\n\treturn []CallingNameStatus{\n\t\t\"Unassigned\",\n\t\t\"UpdateInProgress\",\n\t\t\"UpdateSucceeded\",\n\t\t\"UpdateFailed\",\n\t}\n}", "func (UpdateStatus) Values() []UpdateStatus {\n\treturn []UpdateStatus{\n\t\t\"SUCCESS\",\n\t\t\"PENDING\",\n\t\t\"FAILED\",\n\t}\n}", "func (TableStatus) Values() []TableStatus {\n\treturn []TableStatus{\n\t\t\"CREATING\",\n\t\t\"UPDATING\",\n\t\t\"DELETING\",\n\t\t\"ACTIVE\",\n\t\t\"INACCESSIBLE_ENCRYPTION_CREDENTIALS\",\n\t\t\"ARCHIVING\",\n\t\t\"ARCHIVED\",\n\t}\n}", "func ModelStatus_Values() []string {\n\treturn []string{\n\t\tModelStatusInProgress,\n\t\tModelStatusFailed,\n\t\tModelStatusCompleted,\n\t}\n}", "func (BgpStatus) Values() []BgpStatus {\n\treturn []BgpStatus{\n\t\t\"up\",\n\t\t\"down\",\n\t}\n}", "func (ListingStatus) Values() []ListingStatus {\n\treturn []ListingStatus{\n\t\t\"active\",\n\t\t\"pending\",\n\t\t\"cancelled\",\n\t\t\"closed\",\n\t}\n}", "func (CEStatus) Values() []CEStatus {\n\treturn []CEStatus{\n\t\t\"CREATING\",\n\t\t\"UPDATING\",\n\t\t\"DELETING\",\n\t\t\"DELETED\",\n\t\t\"VALID\",\n\t\t\"INVALID\",\n\t}\n}", "func (InstanceStatus) Values() []InstanceStatus {\n\treturn []InstanceStatus{\n\t\t\"IN_USE\",\n\t\t\"PREPARING\",\n\t\t\"AVAILABLE\",\n\t\t\"NOT_AVAILABLE\",\n\t}\n}", "func (StatusName) Values() []StatusName {\n\treturn []StatusName{\n\t\t\"reachability\",\n\t}\n}", "func PossibleStatusValues() []Status {\n\treturn []Status{Disabled, Enabled}\n}", "func (ActivityStatus) Values() []ActivityStatus {\n\treturn []ActivityStatus{\n\t\t\"error\",\n\t\t\"pending_fulfillment\",\n\t\t\"pending_termination\",\n\t\t\"fulfilled\",\n\t}\n}", "func (IpamAssociatedResourceDiscoveryStatus) Values() []IpamAssociatedResourceDiscoveryStatus {\n\treturn []IpamAssociatedResourceDiscoveryStatus{\n\t\t\"active\",\n\t\t\"not-found\",\n\t}\n}", "func HubStatus_Values() []string {\n\treturn []string{\n\t\tHubStatusInService,\n\t\tHubStatusCreating,\n\t\tHubStatusUpdating,\n\t\tHubStatusDeleting,\n\t\tHubStatusCreateFailed,\n\t\tHubStatusUpdateFailed,\n\t\tHubStatusDeleteFailed,\n\t}\n}", "func AppStatus_Values() []string {\n\treturn []string{\n\t\tAppStatusCreating,\n\t\tAppStatusActive,\n\t\tAppStatusUpdating,\n\t\tAppStatusDeleting,\n\t\tAppStatusDeleted,\n\t\tAppStatusDeleteFailed,\n\t}\n}", "func (ModelCardStatus) Values() []ModelCardStatus {\n\treturn []ModelCardStatus{\n\t\t\"Draft\",\n\t\t\"PendingReview\",\n\t\t\"Approved\",\n\t\t\"Archived\",\n\t}\n}", "func PossibleStatusValues() []Status {\n\treturn []Status{\n\t\tStatusNotStarted,\n\t\tStatusNotStartedButGroupsExist,\n\t\tStatusStarted,\n\t\tStatusFailed,\n\t\tStatusCancelled,\n\t\tStatusCompleted,\n\t}\n}", "func ConnectorStatus_Values() []string {\n\treturn []string{\n\t\tConnectorStatusHealthy,\n\t\tConnectorStatusUnhealthy,\n\t}\n}", "func (PhoneNumberStatus) Values() []PhoneNumberStatus {\n\treturn []PhoneNumberStatus{\n\t\t\"AcquireInProgress\",\n\t\t\"AcquireFailed\",\n\t\t\"Unassigned\",\n\t\t\"Assigned\",\n\t\t\"ReleaseInProgress\",\n\t\t\"DeleteInProgress\",\n\t\t\"ReleaseFailed\",\n\t\t\"DeleteFailed\",\n\t}\n}", "func (FeatureGroupStatus) Values() []FeatureGroupStatus {\n\treturn []FeatureGroupStatus{\n\t\t\"Creating\",\n\t\t\"Created\",\n\t\t\"CreateFailed\",\n\t\t\"Deleting\",\n\t\t\"DeleteFailed\",\n\t}\n}", "func (NotebookInstanceStatus) Values() []NotebookInstanceStatus {\n\treturn []NotebookInstanceStatus{\n\t\t\"Pending\",\n\t\t\"InService\",\n\t\t\"Stopping\",\n\t\t\"Stopped\",\n\t\t\"Failed\",\n\t\t\"Deleting\",\n\t\t\"Updating\",\n\t}\n}", "func (AppStatus) Values() []AppStatus {\n\treturn []AppStatus{\n\t\t\"Deleted\",\n\t\t\"Deleting\",\n\t\t\"Failed\",\n\t\t\"InService\",\n\t\t\"Pending\",\n\t}\n}", "func (ModelVariantStatus) Values() []ModelVariantStatus {\n\treturn []ModelVariantStatus{\n\t\t\"Creating\",\n\t\t\"Updating\",\n\t\t\"InService\",\n\t\t\"Deleting\",\n\t\t\"Deleted\",\n\t}\n}", "func (UpdateStatus) Values() []UpdateStatus {\n\treturn []UpdateStatus{\n\t\t\"RESOLVED\",\n\t}\n}", "func EndpointStatus_Values() []string {\n\treturn []string{\n\t\tEndpointStatusOutOfService,\n\t\tEndpointStatusCreating,\n\t\tEndpointStatusUpdating,\n\t\tEndpointStatusSystemUpdating,\n\t\tEndpointStatusRollingBack,\n\t\tEndpointStatusInService,\n\t\tEndpointStatusDeleting,\n\t\tEndpointStatusFailed,\n\t\tEndpointStatusUpdateRollbackFailed,\n\t}\n}", "func (ConfigurationItemStatus) Values() []ConfigurationItemStatus {\n\treturn []ConfigurationItemStatus{\n\t\t\"OK\",\n\t\t\"ResourceDiscovered\",\n\t\t\"ResourceNotRecorded\",\n\t\t\"ResourceDeleted\",\n\t\t\"ResourceDeletedNotRecorded\",\n\t}\n}", "func (InstanceHealthStatus) Values() []InstanceHealthStatus {\n\treturn []InstanceHealthStatus{\n\t\t\"healthy\",\n\t\t\"unhealthy\",\n\t}\n}", "func ValidationStatus_Values() []string {\n\treturn []string{\n\t\tValidationStatusReadyForValidation,\n\t\tValidationStatusPending,\n\t\tValidationStatusInProgress,\n\t\tValidationStatusSucceeded,\n\t\tValidationStatusFailed,\n\t}\n}", "func (WorkforceStatus) Values() []WorkforceStatus {\n\treturn []WorkforceStatus{\n\t\t\"Initializing\",\n\t\t\"Updating\",\n\t\t\"Deleting\",\n\t\t\"Failed\",\n\t\t\"Active\",\n\t}\n}", "func (EndpointStatus) Values() []EndpointStatus {\n\treturn []EndpointStatus{\n\t\t\"created\",\n\t\t\"creating\",\n\t\t\"deleted\",\n\t\t\"deleting\",\n\t\t\"failed\",\n\t}\n}", "func AppStatus_Values() []string {\n\treturn []string{\n\t\tAppStatusDeleted,\n\t\tAppStatusDeleting,\n\t\tAppStatusFailed,\n\t\tAppStatusInService,\n\t\tAppStatusPending,\n\t}\n}", "func (BulkDeploymentStatus) Values() []BulkDeploymentStatus {\n\treturn []BulkDeploymentStatus{\n\t\t\"Initializing\",\n\t\t\"Running\",\n\t\t\"Completed\",\n\t\t\"Stopping\",\n\t\t\"Stopped\",\n\t\t\"Failed\",\n\t}\n}", "func (ReportStatusType) Values() []ReportStatusType {\n\treturn []ReportStatusType{\n\t\t\"ok\",\n\t\t\"impaired\",\n\t}\n}", "func (ExtensionStatus) Values() []ExtensionStatus {\n\treturn []ExtensionStatus{\n\t\t\"EXTENDED\",\n\t\t\"EXTENSION_ERROR\",\n\t\t\"NOT_EXTENDED\",\n\t}\n}", "func (OrderedPhoneNumberStatus) Values() []OrderedPhoneNumberStatus {\n\treturn []OrderedPhoneNumberStatus{\n\t\t\"Processing\",\n\t\t\"Acquired\",\n\t\t\"Failed\",\n\t}\n}", "func (HumanTaskUiStatus) Values() []HumanTaskUiStatus {\n\treturn []HumanTaskUiStatus{\n\t\t\"Active\",\n\t\t\"Deleting\",\n\t}\n}", "func (ReplicationSetStatus) Values() []ReplicationSetStatus {\n\treturn []ReplicationSetStatus{\n\t\t\"ACTIVE\",\n\t\t\"CREATING\",\n\t\t\"UPDATING\",\n\t\t\"DELETING\",\n\t\t\"FAILED\",\n\t}\n}", "func MemberStatus_Values() []string {\n\treturn []string{\n\t\tMemberStatusCreating,\n\t\tMemberStatusAvailable,\n\t\tMemberStatusCreateFailed,\n\t\tMemberStatusUpdating,\n\t\tMemberStatusDeleting,\n\t\tMemberStatusDeleted,\n\t\tMemberStatusInaccessibleEncryptionKey,\n\t}\n}", "func PossibleStatusValues() []Status {\n\treturn []Status{\n\t\tStatusAccessDenied,\n\t\tStatusCertificateExpired,\n\t\tStatusInvalid,\n\t\tStatusValid,\n\t}\n}", "func BotLocaleStatus_Values() []string {\n\treturn []string{\n\t\tBotLocaleStatusCreating,\n\t\tBotLocaleStatusBuilding,\n\t\tBotLocaleStatusBuilt,\n\t\tBotLocaleStatusReadyExpressTesting,\n\t\tBotLocaleStatusFailed,\n\t\tBotLocaleStatusDeleting,\n\t\tBotLocaleStatusNotBuilt,\n\t\tBotLocaleStatusImporting,\n\t\tBotLocaleStatusProcessing,\n\t}\n}", "func (ModelPackageGroupStatus) Values() []ModelPackageGroupStatus {\n\treturn []ModelPackageGroupStatus{\n\t\t\"Pending\",\n\t\t\"InProgress\",\n\t\t\"Completed\",\n\t\t\"Failed\",\n\t\t\"Deleting\",\n\t\t\"DeleteFailed\",\n\t}\n}", "func (IndexStatus) Values() []IndexStatus {\n\treturn []IndexStatus{\n\t\t\"CREATING\",\n\t\t\"UPDATING\",\n\t\t\"DELETING\",\n\t\t\"ACTIVE\",\n\t}\n}", "func (ImageStatus) Values() []ImageStatus {\n\treturn []ImageStatus{\n\t\t\"CREATING\",\n\t\t\"CREATED\",\n\t\t\"CREATE_FAILED\",\n\t\t\"UPDATING\",\n\t\t\"UPDATE_FAILED\",\n\t\t\"DELETING\",\n\t\t\"DELETE_FAILED\",\n\t}\n}", "func (DetailedModelPackageStatus) Values() []DetailedModelPackageStatus {\n\treturn []DetailedModelPackageStatus{\n\t\t\"NotStarted\",\n\t\t\"InProgress\",\n\t\t\"Completed\",\n\t\t\"Failed\",\n\t}\n}", "func (AppliedStatus) Values() []AppliedStatus {\n\treturn []AppliedStatus{\n\t\t\"APPLIED\",\n\t\t\"NOT_APPLIED\",\n\t}\n}", "func HealthStatus_Values() []string {\n\treturn []string{\n\t\tHealthStatusHealthy,\n\t\tHealthStatusUnhealthy,\n\t\tHealthStatusUnknown,\n\t}\n}", "func (FleetActivityStatus) Values() []FleetActivityStatus {\n\treturn []FleetActivityStatus{\n\t\t\"error\",\n\t\t\"pending_fulfillment\",\n\t\t\"pending_termination\",\n\t\t\"fulfilled\",\n\t}\n}", "func (EndpointStatus) Values() []EndpointStatus {\n\treturn []EndpointStatus{\n\t\t\"OutOfService\",\n\t\t\"Creating\",\n\t\t\"Updating\",\n\t\t\"SystemUpdating\",\n\t\t\"RollingBack\",\n\t\t\"InService\",\n\t\t\"Deleting\",\n\t\t\"Failed\",\n\t\t\"UpdateRollbackFailed\",\n\t}\n}", "func ResolverEndpointStatus_Values() []string {\n\treturn []string{\n\t\tResolverEndpointStatusCreating,\n\t\tResolverEndpointStatusOperational,\n\t\tResolverEndpointStatusUpdating,\n\t\tResolverEndpointStatusAutoRecovering,\n\t\tResolverEndpointStatusActionNeeded,\n\t\tResolverEndpointStatusDeleting,\n\t}\n}", "func (ManifestStatus) Values() []ManifestStatus {\n\treturn []ManifestStatus{\n\t\t\"ACTIVE\",\n\t\t\"DRAFT\",\n\t}\n}", "func BotAliasStatus_Values() []string {\n\treturn []string{\n\t\tBotAliasStatusCreating,\n\t\tBotAliasStatusAvailable,\n\t\tBotAliasStatusDeleting,\n\t\tBotAliasStatusFailed,\n\t}\n}", "func FirewallRuleGroupStatus_Values() []string {\n\treturn []string{\n\t\tFirewallRuleGroupStatusComplete,\n\t\tFirewallRuleGroupStatusDeleting,\n\t\tFirewallRuleGroupStatusUpdating,\n\t}\n}", "func (PullRequestStatusEnum) Values() []PullRequestStatusEnum {\n\treturn []PullRequestStatusEnum{\n\t\t\"OPEN\",\n\t\t\"CLOSED\",\n\t}\n}", "func (DomainStatus) Values() []DomainStatus {\n\treturn []DomainStatus{\n\t\t\"Deleting\",\n\t\t\"Failed\",\n\t\t\"InService\",\n\t\t\"Pending\",\n\t\t\"Updating\",\n\t\t\"Update_Failed\",\n\t\t\"Delete_Failed\",\n\t}\n}", "func (AccountStatus) Values() []AccountStatus {\n\treturn []AccountStatus{\n\t\t\"Suspended\",\n\t\t\"Active\",\n\t}\n}", "func PossibleStatusValues() []Status {\n\treturn []Status{\n\t\tStatusActive,\n\t\tStatusDeleted,\n\t\tStatusNone,\n\t}\n}", "func (RegistrationStatus) Values() []RegistrationStatus {\n\treturn []RegistrationStatus{\n\t\t\"REGISTRATION_PENDING\",\n\t\t\"REGISTRATION_SUCCESS\",\n\t\t\"REGISTRATION_FAILURE\",\n\t}\n}", "func (OrganizationResourceDetailedStatus) Values() []OrganizationResourceDetailedStatus {\n\treturn []OrganizationResourceDetailedStatus{\n\t\t\"CREATE_SUCCESSFUL\",\n\t\t\"CREATE_IN_PROGRESS\",\n\t\t\"CREATE_FAILED\",\n\t\t\"DELETE_SUCCESSFUL\",\n\t\t\"DELETE_FAILED\",\n\t\t\"DELETE_IN_PROGRESS\",\n\t\t\"UPDATE_SUCCESSFUL\",\n\t\t\"UPDATE_IN_PROGRESS\",\n\t\t\"UPDATE_FAILED\",\n\t}\n}", "func (SpaceStatus) Values() []SpaceStatus {\n\treturn []SpaceStatus{\n\t\t\"Deleting\",\n\t\t\"Failed\",\n\t\t\"InService\",\n\t\t\"Pending\",\n\t\t\"Updating\",\n\t\t\"Update_Failed\",\n\t\t\"Delete_Failed\",\n\t}\n}", "func (SummaryStatus) Values() []SummaryStatus {\n\treturn []SummaryStatus{\n\t\t\"ok\",\n\t\t\"impaired\",\n\t\t\"insufficient-data\",\n\t\t\"not-applicable\",\n\t\t\"initializing\",\n\t}\n}", "func ImportStatus_Values() []string {\n\treturn []string{\n\t\tImportStatusPending,\n\t\tImportStatusStarted,\n\t\tImportStatusFailed,\n\t\tImportStatusSucceeded,\n\t}\n}", "func PossibleStatusValues() []Status {\n\treturn []Status{StatusAvailable, StatusDisconnected, StatusDomainTrustRelationshipLost, StatusFSLogixNotHealthy, StatusNeedsAssistance, StatusNoHeartbeat, StatusNotJoinedToDomain, StatusShutdown, StatusSxSStackListenerNotReady, StatusUnavailable, StatusUpgradeFailed, StatusUpgrading}\n}", "func (RecorderStatus) Values() []RecorderStatus {\n\treturn []RecorderStatus{\n\t\t\"Pending\",\n\t\t\"Success\",\n\t\t\"Failure\",\n\t}\n}", "func (ExternalConnectionStatus) Values() []ExternalConnectionStatus {\n\treturn []ExternalConnectionStatus{\n\t\t\"Available\",\n\t}\n}", "func (VariantStatus) Values() []VariantStatus {\n\treturn []VariantStatus{\n\t\t\"Creating\",\n\t\t\"Updating\",\n\t\t\"Deleting\",\n\t\t\"ActivatingTraffic\",\n\t\t\"Baking\",\n\t}\n}", "func (ShippingLabelStatus) Values() []ShippingLabelStatus {\n\treturn []ShippingLabelStatus{\n\t\t\"InProgress\",\n\t\t\"TimedOut\",\n\t\t\"Succeeded\",\n\t\t\"Failed\",\n\t}\n}", "func TestSetStatus_Values() []string {\n\treturn []string{\n\t\tTestSetStatusImporting,\n\t\tTestSetStatusPendingAnnotation,\n\t\tTestSetStatusDeleting,\n\t\tTestSetStatusValidationError,\n\t\tTestSetStatusReady,\n\t}\n}", "func (IncidentRecordStatus) Values() []IncidentRecordStatus {\n\treturn []IncidentRecordStatus{\n\t\t\"OPEN\",\n\t\t\"RESOLVED\",\n\t}\n}", "func (FeatureStatus) Values() []FeatureStatus {\n\treturn []FeatureStatus{\n\t\t\"ENABLED\",\n\t\t\"DISABLED\",\n\t}\n}", "func (NetworkInterfaceStatus) Values() []NetworkInterfaceStatus {\n\treturn []NetworkInterfaceStatus{\n\t\t\"available\",\n\t\t\"associated\",\n\t\t\"attaching\",\n\t\t\"in-use\",\n\t\t\"detaching\",\n\t}\n}", "func (ReplicaStatus) Values() []ReplicaStatus {\n\treturn []ReplicaStatus{\n\t\t\"CREATING\",\n\t\t\"CREATION_FAILED\",\n\t\t\"UPDATING\",\n\t\t\"DELETING\",\n\t\t\"ACTIVE\",\n\t\t\"REGION_DISABLED\",\n\t\t\"INACCESSIBLE_ENCRYPTION_CREDENTIALS\",\n\t}\n}", "func (ModelPackageStatus) Values() []ModelPackageStatus {\n\treturn []ModelPackageStatus{\n\t\t\"Pending\",\n\t\t\"InProgress\",\n\t\t\"Completed\",\n\t\t\"Failed\",\n\t\t\"Deleting\",\n\t}\n}", "func (SagemakerServicecatalogStatus) Values() []SagemakerServicecatalogStatus {\n\treturn []SagemakerServicecatalogStatus{\n\t\t\"Enabled\",\n\t\t\"Disabled\",\n\t}\n}", "func (PipelineStatus) Values() []PipelineStatus {\n\treturn []PipelineStatus{\n\t\t\"Active\",\n\t}\n}", "func HumanTaskUiStatus_Values() []string {\n\treturn []string{\n\t\tHumanTaskUiStatusActive,\n\t\tHumanTaskUiStatusDeleting,\n\t}\n}", "func (CandidateStatus) Values() []CandidateStatus {\n\treturn []CandidateStatus{\n\t\t\"Completed\",\n\t\t\"InProgress\",\n\t\t\"Failed\",\n\t\t\"Stopped\",\n\t\t\"Stopping\",\n\t}\n}", "func ServiceStatus_Values() []string {\n\treturn []string{\n\t\tServiceStatusCreateInProgress,\n\t\tServiceStatusCreateFailedCleanupInProgress,\n\t\tServiceStatusCreateFailedCleanupComplete,\n\t\tServiceStatusCreateFailedCleanupFailed,\n\t\tServiceStatusCreateFailed,\n\t\tServiceStatusActive,\n\t\tServiceStatusDeleteInProgress,\n\t\tServiceStatusDeleteFailed,\n\t\tServiceStatusUpdateInProgress,\n\t\tServiceStatusUpdateFailedCleanupInProgress,\n\t\tServiceStatusUpdateFailedCleanupComplete,\n\t\tServiceStatusUpdateFailedCleanupFailed,\n\t\tServiceStatusUpdateFailed,\n\t\tServiceStatusUpdateCompleteCleanupFailed,\n\t}\n}", "func TableStatus_Values() []string {\n\treturn []string{\n\t\tTableStatusActive,\n\t\tTableStatusDeleting,\n\t\tTableStatusRestoring,\n\t}\n}", "func (StageStatus) Values() []StageStatus {\n\treturn []StageStatus{\n\t\t\"CREATING\",\n\t\t\"READYTODEPLOY\",\n\t\t\"STARTING\",\n\t\t\"INPROGRESS\",\n\t\t\"DEPLOYED\",\n\t\t\"FAILED\",\n\t\t\"STOPPING\",\n\t\t\"STOPPED\",\n\t}\n}", "func (ProjectStatus) Values() []ProjectStatus {\n\treturn []ProjectStatus{\n\t\t\"Pending\",\n\t\t\"CreateInProgress\",\n\t\t\"CreateCompleted\",\n\t\t\"CreateFailed\",\n\t\t\"DeleteInProgress\",\n\t\t\"DeleteFailed\",\n\t\t\"DeleteCompleted\",\n\t\t\"UpdateInProgress\",\n\t\t\"UpdateCompleted\",\n\t\t\"UpdateFailed\",\n\t}\n}", "func ImportStatus_Values() []string {\n\treturn []string{\n\t\tImportStatusInProgress,\n\t\tImportStatusCompleted,\n\t\tImportStatusFailed,\n\t\tImportStatusDeleting,\n\t}\n}", "func VersionStatus_Values() []string {\n\treturn []string{\n\t\tVersionStatusCreating,\n\t\tVersionStatusUpdating,\n\t\tVersionStatusDeleting,\n\t\tVersionStatusActive,\n\t\tVersionStatusFailed,\n\t}\n}", "func (WarmPoolResourceStatus) Values() []WarmPoolResourceStatus {\n\treturn []WarmPoolResourceStatus{\n\t\t\"Available\",\n\t\t\"Terminated\",\n\t\t\"Reused\",\n\t\t\"InUse\",\n\t}\n}", "func (LoadBalancerStateEnum) Values() []LoadBalancerStateEnum {\n\treturn []LoadBalancerStateEnum{\n\t\t\"active\",\n\t\t\"provisioning\",\n\t\t\"active_impaired\",\n\t\t\"failed\",\n\t}\n}", "func InstanceStatus_Values() []string {\n\treturn []string{\n\t\tInstanceStatusCreationInProgress,\n\t\tInstanceStatusActive,\n\t\tInstanceStatusCreationFailed,\n\t}\n}", "func (AgentStatus) Values() []AgentStatus {\n\treturn []AgentStatus{\n\t\t\"SUCCESS\",\n\t\t\"FAILED\",\n\t\t\"ACTIVE\",\n\t\t\"INACTIVE\",\n\t}\n}", "func PossibleStatusValues() []Status {\n\treturn []Status{TrialAvailable, TrialDisabled, TrialUsed}\n}" ]
[ "0.7045252", "0.6948299", "0.69238037", "0.6900158", "0.6811185", "0.67640686", "0.6762358", "0.67572373", "0.6752401", "0.6723062", "0.67229027", "0.6682362", "0.66753113", "0.6669603", "0.6653553", "0.6633867", "0.6629413", "0.6625645", "0.6625132", "0.6606851", "0.65963227", "0.6593539", "0.65919477", "0.6588135", "0.65458924", "0.6530521", "0.6527665", "0.6524339", "0.6510437", "0.6508317", "0.65028054", "0.6501126", "0.650112", "0.64934295", "0.64891416", "0.64828336", "0.64785904", "0.64779174", "0.64743537", "0.6472706", "0.64724576", "0.64631486", "0.6455303", "0.64350605", "0.64326835", "0.64292145", "0.64251536", "0.6423979", "0.64174443", "0.641649", "0.64151734", "0.64151573", "0.6414448", "0.6410144", "0.64051527", "0.6402247", "0.6401057", "0.6397537", "0.6395328", "0.6394747", "0.63863665", "0.6382626", "0.6379833", "0.6374176", "0.6373349", "0.637287", "0.63678527", "0.63622683", "0.6361095", "0.63583726", "0.6355081", "0.6354596", "0.634966", "0.63417095", "0.6341075", "0.6330023", "0.6329061", "0.63289666", "0.632872", "0.6327184", "0.6326228", "0.6322314", "0.63200617", "0.6316008", "0.63156694", "0.6310346", "0.6299967", "0.6298423", "0.6294842", "0.6289738", "0.62882036", "0.6285414", "0.6282175", "0.62820846", "0.6277686", "0.6275275", "0.627297", "0.62720937", "0.62686926", "0.62685996" ]
0.8167596
0
IsABindStatus returns "true" if the value is listed in the enum definition. "false" otherwise
func (i BindStatus) IsABindStatus() bool { for _, v := range _BindStatusValues { if i == v { return true } } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (E_OpenconfigPlatformTypes_FEC_STATUS_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address_State_Status) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address_State_Status) IsYANGGoEnum() {}", "func (E_OpenconfigAaaTypes_AAA_METHOD_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigAaaTypes_AAA_METHOD_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigAaaTypes_AAA_ACCOUNTING_EVENT_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigAaaTypes_AAA_ACCOUNTING_EVENT_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigAaaTypes_AAA_SERVER_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigAaaTypes_AAA_SERVER_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigPlatformTypes_COMPONENT_OPER_STATUS) IsYANGGoEnum() {}", "func (E_OpenconfigWifiTypes_CLIENT_STATE) IsYANGGoEnum() {}", "func (E_OpenconfigAlarmTypes_OPENCONFIG_ALARM_SEVERITY) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_Config_HealthIndicator) IsYANGGoEnum() {}", "func (E_OpenconfigMessages_DEBUG_SERVICE) IsYANGGoEnum() {}", "func (E_OpenconfigWifiTypes_CLIENT_CAPABILITIES) IsYANGGoEnum() {}", "func (E_OpenconfigPlatform_Components_Component_Transceiver_State_Present) IsYANGGoEnum() {}", "func (f Flags) IsStatus() bool {\n\treturn f&StatusMsg != 0\n}", "func (E_OnfTest1Identities_MYBASE) IsYANGGoEnum() {}", "func (E_OpenconfigLacp_LacpActivityType) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_State_AdminStatus) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_State_AdminStatus) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_State_AdminStatus) IsYANGGoEnum() {}", "func (E_OpenconfigAaaTypes_AAA_AUTHORIZATION_EVENT_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigAaaTypes_AAA_AUTHORIZATION_EVENT_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigAlarmTypes_OPENCONFIG_ALARM_TYPE_ID) IsYANGGoEnum() {}", "func (E_IETFInterfaces_InterfaceType) IsYANGGoEnum() {}", "func (E_IETFInterfaces_InterfaceType) IsYANGGoEnum() {}", "func (E_OpenconfigLacp_LacpSynchronizationType) IsYANGGoEnum() {}", "func (E_IETFInterfaces_InterfaceType) IsYANGGoEnum() {}", "func (E_Test1Identities_MYBASE) IsYANGGoEnum() {}", "func (E_OpenconfigIfEthernet_ETHERNET_SPEED) IsYANGGoEnum() {}", "func (E_OpenconfigIfEthernet_ETHERNET_SPEED) IsYANGGoEnum() {}", "func (E_OpenconfigSystem_System_Aaa_Accounting_Events_Event_Config_Record) IsYANGGoEnum() {}", "func (E_OpenconfigVlan_VlanModeType) IsYANGGoEnum() {}", "func (E_OpenconfigVlan_VlanModeType) IsYANGGoEnum() {}", "func (E_OnfSwitchTypes_Speed) IsYANGGoEnum() {}", "func (E_OpenconfigWifiTypes_CHANGE_REASON_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigVlanTypes_TPID_TYPES) IsYANGGoEnum() {}", "func (E_OpenconfigVlanTypes_TPID_TYPES) IsYANGGoEnum() {}", "func (E_OpenconfigTransportTypes_SONET_APPLICATION_CODE) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_Ethernet_Config_DuplexMode) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_Ethernet_Config_DuplexMode) IsYANGGoEnum() {}", "func (E_OpenconfigOfficeAp_System_Aaa_Accounting_Events_Event_Config_Record) IsYANGGoEnum() {}", "func (E_OpenconfigTransportTypes_ETHERNET_PMD_TYPE) IsYANGGoEnum() {}", "func (E_AristaIntfAugments_FallbackStateEnum) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_State_OperStatus) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_State_OperStatus) IsYANGGoEnum() {}", "func (E_OpenconfigTransportTypes_OTN_APPLICATION_CODE) IsYANGGoEnum() {}", "func (E_OnfTest1Choice_Vehicle_UnderCarriage_TrackType) IsYANGGoEnum() {}", "func (E_OpenconfigPlatformTypes_OPENCONFIG_SOFTWARE_COMPONENT) IsYANGGoEnum() {}", "func (E_OpenconfigPacketMatchTypes_TCP_FLAGS) IsYANGGoEnum() {}", "func (E_OpenconfigPacketMatchTypes_TCP_FLAGS) IsYANGGoEnum() {}", "func (E_AristaIntfAugments_FallbackEnum) IsYANGGoEnum() {}", "func (E_OnfTest1Choice_Vehicle_Battery_Material) IsYANGGoEnum() {}", "func (E_OpenconfigPlatformTypes_OPENCONFIG_HARDWARE_COMPONENT) IsYANGGoEnum() {}", "func (E_OnfTest1_Cont1A_Cont2D_Chocolate) IsYANGGoEnum() {}", "func (i DispatcherStatus) IsADispatcherStatus() bool {\n\tfor _, v := range _DispatcherStatusValues {\n\t\tif i == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (me TQualificationTypeStatus) IsActive() bool { return me.String() == \"Active\" }", "func (E_OpenconfigAcl_FORWARDING_ACTION) IsYANGGoEnum() {}", "func (E_OpenconfigPacketMatchTypes_IP_PROTOCOL) IsYANGGoEnum() {}", "func (E_OpenconfigPacketMatchTypes_IP_PROTOCOL) IsYANGGoEnum() {}", "func (E_OpenconfigAcl_ACL_COUNTER_CAPABILITY) IsYANGGoEnum() {}", "func (E_Test1_Cont1A_Cont2D_Chocolate) IsYANGGoEnum() {}", "func (E_OpenconfigAaaTypes_SYSTEM_DEFINED_ROLES) IsYANGGoEnum() {}", "func (E_OpenconfigAaaTypes_SYSTEM_DEFINED_ROLES) IsYANGGoEnum() {}", "func IsStatus(e error, sw uint16) bool {\n\tif e, ok := e.(CardError); ok {\n\t\treturn e.SW == sw\n\t}\n\treturn false\n}", "func (E_OpenconfigAcl_ACL_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigOfficeAp_Ssids_Ssid_Clients_Client_ClientRf_State_ConnectionMode) IsYANGGoEnum() {}", "func (E_OpenconfigWifiTypes_OPERATING_FREQUENCY) IsYANGGoEnum() {}", "func (b *BindingStatusPhase) IsBound() bool {\n\treturn b.Phase == BindingStateBound\n}", "func (E_OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv4_ProxyArp_Config_Mode) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv4_ProxyArp_Config_Mode) IsYANGGoEnum() {}", "func (E_OnfTest1Choice_Vehicle_EnginePosition) IsYANGGoEnum() {}", "func (E_OpenconfigSystem_System_GrpcServer_Config_ListenAddresses) IsYANGGoEnum() {}", "func (e *entry) hasStatus(status int) bool {\n\treturn e.getStatus() == status\n}", "func (me TxsdMovementStatus) IsA() bool { return me.String() == \"A\" }", "func (E_OpenconfigQos_Qos_Classifiers_Classifier_Config_Type) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Neighbors_Neighbor_State_NeighborState) IsYANGGoEnum() {}", "func (E_OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Neighbors_Neighbor_State_NeighborState) IsYANGGoEnum() {}", "func (me TxsdPaymentStatus) IsA() bool { return me.String() == \"A\" }", "func (E_OpenconfigSystemLogging_SYSLOG_FACILITY) IsYANGGoEnum() {}", "func (E_OpenconfigSystemLogging_SYSLOG_FACILITY) IsYANGGoEnum() {}", "func isEnumType(t *yang.YangType) bool {\n\treturn t.Kind == yang.Yenum || t.Kind == yang.Yidentityref\n}", "func (E_OpenconfigTransportTypes_FIBER_CONNECTOR_TYPE) IsYANGGoEnum() {}", "func (E_OpenconfigWifiTypes_DATA_RATE) IsYANGGoEnum() {}", "func (v Validator) IsBonded() bool {\n\treturn v.GetStatus().Equal(sdk.Bonded)\n}", "func (_SmartTgStats *SmartTgStatsCaller) Status(opts *bind.CallOpts) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _SmartTgStats.contract.Call(opts, out, \"status\")\n\treturn *ret0, err\n}", "func (E_OpenconfigPlatformTypes_FEC_MODE_TYPE) IsYANGGoEnum() {}", "func assertSBRStatus(\n\tctx context.Context,\n\tf *framework.Framework,\n\tnamespacedName types.NamespacedName,\n) error {\n\tsbr := &v1alpha1.ServiceBindingRequest{}\n\tif err := f.Client.Get(ctx, namespacedName, sbr); err != nil {\n\t\treturn err\n\t}\n\n\tfor i, condition := range sbr.Status.Conditions {\n\t\tif condition.Type != servicebindingrequest.BindingReady && condition.Status != corev1.ConditionTrue {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"Condition.Type and Condition.Status is '%s' and '%s' instead of '%s' and '%s'\",\n\t\t\t\tsbr.Status.Conditions[i].Type,\n\t\t\t\tsbr.Status.Conditions[i].Status,\n\t\t\t\tservicebindingrequest.BindingReady,\n\t\t\t\tcorev1.ConditionTrue)\n\t\t}\n\t}\n\treturn nil\n}", "func (E_OpenconfigLacp_LacpPeriodType) IsYANGGoEnum() {}", "func (o *WorkflowServiceItemDefinitionAllOf) HasStatus() bool {\n\tif o != nil && o.Status != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (envUC EnvUsecase) IsBind(e domain.Env, def *bool) bool {\n\tb := e.Bind\n\tif b == nil {\n\t\tif e.Prefix != nil {\n\t\t\treturn true\n\t\t}\n\t\tif def == nil {\n\t\t\treturn false\n\t\t}\n\t\treturn *def\n\t}\n\treturn *b\n}", "func (i TaskStatus) IsATaskStatus() bool {\n\tfor _, v := range _TaskStatusValues {\n\t\tif i == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (E_OpenconfigTransportTypes_TRANSCEIVER_FORM_FACTOR_TYPE) IsYANGGoEnum() {}", "func (o *ApplianceDeviceClaimAllOf) HasStatus() bool {\n\tif o != nil && o.Status != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *UcsdBackupInfoAllOf) HasStatus() bool {\n\tif o != nil && o.Status != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (E_OpenconfigPacketMatchTypes_ETHERTYPE) IsYANGGoEnum() {}", "func (E_OpenconfigPacketMatchTypes_ETHERTYPE) IsYANGGoEnum() {}", "func (me TxsdInvoiceStatus) IsA() bool { return me.String() == \"A\" }", "func (E_OpenconfigSystem_System_Cpus_Cpu_State_Index) IsYANGGoEnum() {}" ]
[ "0.63898927", "0.63313293", "0.6330146", "0.6265459", "0.6265459", "0.62408566", "0.62408566", "0.6233938", "0.623294", "0.6156298", "0.6128996", "0.6101668", "0.6093381", "0.60403997", "0.6033343", "0.6025906", "0.6011711", "0.5981339", "0.5962177", "0.595627", "0.595627", "0.595627", "0.5923323", "0.5922642", "0.59023225", "0.5882244", "0.5882244", "0.5880448", "0.58802044", "0.5874451", "0.58258426", "0.58243346", "0.58151597", "0.57876337", "0.57876337", "0.5786714", "0.57849854", "0.5770582", "0.57703793", "0.5763414", "0.5756023", "0.5754439", "0.57511467", "0.57382303", "0.5731866", "0.5728051", "0.5725959", "0.5719459", "0.5711515", "0.56967765", "0.56959933", "0.56959933", "0.56646013", "0.5650094", "0.56490886", "0.5632991", "0.56075794", "0.55617326", "0.555841", "0.5555422", "0.55547994", "0.55481684", "0.5540697", "0.5537632", "0.5537632", "0.5536253", "0.55235827", "0.55140996", "0.5507976", "0.54867935", "0.54842526", "0.5484158", "0.54694474", "0.5466835", "0.5453623", "0.5452338", "0.5446579", "0.5416348", "0.5415429", "0.5415181", "0.54021", "0.54021", "0.5398157", "0.53970295", "0.53956854", "0.53857183", "0.53762734", "0.5375081", "0.5368499", "0.53646183", "0.53615856", "0.5351143", "0.53501433", "0.53471804", "0.53259104", "0.52998227", "0.5298929", "0.5298929", "0.52919626", "0.52908087" ]
0.7918506
0
Returns Env backend which extends key provided for lookup with a `prefix` This is a shortcut for confita/backend/env + confitasugar/prefix
func NewEnvBackend(prefix string) confita_backend.Backend { return confita_sugar_prefix.WithPrefix(prefix, confita_backend_env.NewBackend()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetWithPrefix(prefix string) map[string]string {\n\tres := map[string]string{}\n\n\tfor key, val := range cli {\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\tres[key] = val\n\t\t}\n\t}\n\n\tfor key, val := range conf {\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\tres[key] = val\n\t\t}\n\t}\n\n\tfor _, e := range os.Environ() {\n\t\tpair := strings.SplitN(e, \"=\", 2)\n\t\tkey := pair[0]\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\tres[key] = pair[1]\n\t\t}\n\t}\n\n\treturn res\n}", "func Env(prefix string) Provider {\n\treturn &env{prefix}\n}", "func NewBackend(fns ...opt) backend.Backend {\n\treturn backend.Func(\"env\", func(ctx context.Context, key string) ([]byte, error) {\n\t\tkey = strings.Replace(key, \"-\", \"_\", -1)\n\t\tval, ok := os.LookupEnv(opts(key, fns...))\n\t\tif ok {\n\t\t\treturn []byte(val), nil\n\t\t}\n\t\tval, ok = os.LookupEnv(opts(strings.ToUpper(key), fns...))\n\t\tif ok {\n\t\t\treturn []byte(val), nil\n\t\t}\n\t\treturn nil, backend.ErrNotFound\n\t})\n}", "func (envUC EnvUsecase) GetPrefix(e domain.Env, gPrefix *string) string {\n\tif e.Prefix != nil {\n\t\treturn *e.Prefix\n\t}\n\tif gPrefix != nil {\n\t\treturn *gPrefix\n\t}\n\treturn \"\"\n}", "func Backend() (string, error) {\n\tbackend := strings.ToUpper(os.Getenv(backendKey))\n\n\tswitch backend {\n\tcase backendValueBEB:\n\t\treturn backendValueBEB, nil\n\tcase backendValueNats, \"\":\n\t\treturn backendValueNats, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"invalid BACKEND set: %v\", backend)\n\t}\n}", "func EnvironmentPrefix() string {\n\treturn _envPrefix\n}", "func getEnv(envPrefix, flagName string) string {\n\t// If we haven't set an EnvPrefix, don't lookup vals in the ENV\n\tif envPrefix == \"\" {\n\t\treturn \"\"\n\t}\n\tif !strings.HasSuffix(envPrefix, \"_\") {\n\t\tenvPrefix += \"_\"\n\t}\n\tflagName = strings.Replace(flagName, \".\", \"_\", -1)\n\tflagName = strings.Replace(flagName, \"-\", \"_\", -1)\n\tenvKey := strings.ToUpper(envPrefix + flagName)\n\treturn os.Getenv(envKey)\n}", "func getOSPrefixEnv(s string) *string {\n\tif e := strings.TrimSpace(os.Getenv(envPrefix + s)); len(e) > 0 {\n\t\treturn &e\n\t}\n\n\treturn nil\n}", "func (y *Yec) getKeyFromEnv(varKey string) (bool, string) {\n\t// Only care about variables that start with the y.appName\n\tprefix := strings.ToLower(y.appName) + \"_\"\n\tkey := strings.ToLower(varKey)\n\n\tif !strings.HasPrefix(key, prefix) {\n\t\treturn false, \"\"\n\t}\n\n\treturn true, strings.TrimPrefix(key, prefix)\n}", "func environment(prefix string) map[string]string {\n\tenv := make(map[string]string)\n\tfor _, setting := range os.Environ() {\n\t\tpair := strings.SplitN(setting, \"=\", 2)\n\t\tif strings.HasPrefix(pair[0], prefix) {\n\t\t\tenv[pair[0]] = pair[1]\n\t\t}\n\t}\n\treturn env\n}", "func environment(prefix string) map[string]string {\n\tenv := make(map[string]string)\n\tfor _, setting := range os.Environ() {\n\t\tpair := strings.SplitN(setting, \"=\", 2)\n\t\tif strings.HasPrefix(pair[0], prefix) {\n\t\t\tenv[pair[0]] = pair[1]\n\t\t}\n\t}\n\treturn env\n}", "func (c *Configurator) mergeWithEnvPrefix(in string) string {\n\tif c.envPrefix != \"\" {\n\t\treturn strings.ToUpper(c.envPrefix + \"_\" + in)\n\t}\n\n\treturn strings.ToUpper(in)\n}", "func (l *Loader) EnvironmentPrefix() string {\n\tl.lock.RLock()\n\tdefer l.lock.RUnlock()\n\n\treturn l.envPrefix\n}", "func LookupEnv(key string) (string, bool)", "func (b *taskBuilder) envPrefixes(key string, values ...string) {\n\tif b.Spec.EnvPrefixes == nil {\n\t\tb.Spec.EnvPrefixes = map[string][]string{}\n\t}\n\tfor _, value := range values {\n\t\tif !In(value, b.Spec.EnvPrefixes[key]) {\n\t\t\tb.Spec.EnvPrefixes[key] = append(b.Spec.EnvPrefixes[key], value)\n\t\t}\n\t}\n}", "func Prefix(p string) *EC {\n\treturn &EC{cfg{prefix: p}}\n}", "func FromEnviron(prefix string) Option {\n\treturn func(c Config, m ...OptionMeta) error {\n\t\treturn env.Process(prefix, c)\n\t}\n}", "func Getenv(env []string, key string) string {\n\tif len(key) == 0 {\n\t\treturn \"\"\n\t}\n\n\tprefix := strings.ToLower(key + \"=\")\n\tfor _, pair := range env {\n\t\tif len(pair) > len(prefix) && prefix == strings.ToLower(pair[:len(prefix)]) {\n\t\t\treturn pair[len(prefix):]\n\t\t}\n\t}\n\treturn \"\"\n}", "func Getenv(key string) string", "func (c *Config) Prefix(prefix string) *Config {\n\tc.GetContext().Prefix = prefix\n\treturn c\n}", "func getKvKeyWithPrefix(prefix string, key string) string {\n\tuse_key := prefix\n\tif len(key) > 0 {\n\t\tuse_key = fmt.Sprintf(\"%s/%s\", use_key, key)\n\t}\n\treturn use_key\n}", "func WithEnvVarPrefix(prefix string) Option {\n\treturn func(c *Context) {\n\t\tc.envVarPrefix = prefix\n\t}\n}", "func InitWithPrefix(conf interface{}, prefix string) error {\n\tvalue := reflect.ValueOf(conf)\n\tif value.Kind() != reflect.Ptr {\n\t\treturn errors.New(\"envconfig: value is not a pointer\")\n\t}\n\n\telem := value.Elem()\n\n\tswitch elem.Kind() {\n\tcase reflect.Ptr:\n\t\telem.Set(reflect.New(elem.Type().Elem()))\n\t\treturn readStruct(elem.Elem(), prefix, false)\n\tcase reflect.Struct:\n\t\treturn readStruct(elem, prefix, false)\n\tdefault:\n\t\treturn errors.New(\"envconfig: invalid value kind, only works on structs\")\n\t}\n}", "func (api *hostAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"hosts\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"hosts\", \"/\", name)\n}", "func GetVarWithPrefix(v string) string {\n\tval := GetVar(v)\n\tif val == \"\" {\n\t\treturn val\n\t}\n\tif strings.HasPrefix(val, debianPathSeparator) {\n\t\treturn val\n\t}\n\treturn vars[\"INSTALLPREFIX\"] + debianPathSeparator + val\n}", "func genPrefix(globalPrefix string, heritage []*node.Node) (prefix string) {\n\tif globalPrefix != \"\" {\n\t\tprefix = globalPrefix\n\t}\n\tfor _, hn := range heritage {\n\t\tenvName := nodeEnvName(hn)\n\t\tif envName == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif prefix == \"\" {\n\t\t\tprefix += envName\n\t\t} else {\n\t\t\tprefix += \"_\" + envName\n\t\t}\n\t}\n\n\treturn prefix\n}", "func (api *tenantAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"tenants\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"tenants\", \"/\", name)\n}", "func FromEnv(prefix string) (Config, error) {\n\treturn &envConfig{\n\t\tprefix: prefix,\n\t\tlookup: os.LookupEnv,\n\t\tconvert: DotToSnake,\n\t}, nil\n}", "func Env(def, key string, fallbacks ...string) string {\n\tif val, found := LookupEnv(key, fallbacks...); found {\n\t\treturn val\n\t}\n\treturn def\n}", "func (api *versionAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"version\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"version\", \"/\", name)\n}", "func (s envValueStore) get(key StoreKey) (string, error) {\n\tenvValueStoreKey := strings.ToUpper(s.prefix + string(key))\n\tval, found := os.LookupEnv(strings.ToUpper(envValueStoreKey))\n\tif !found {\n\t\treturn \"\", ParameterNotFoundError{key: key}\n\t}\n\n\treturn val, nil\n}", "func (api *credentialsAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"credentials\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"credentials\", \"/\", name)\n}", "func NewKeyringFromBackend(ctx Context, backend string) (keyring.Keyring, error) {\n\tif ctx.Simulate {\n\t\tbackend = keyring.BackendMemory\n\t}\n\n\treturn keyring.New(sdk.KeyringServiceName(), backend, ctx.KeyringDir, ctx.Input, ctx.Codec, ctx.KeyringOptions...)\n}", "func setSBRBackendGVK(\n\tsbr *v1alpha1.ServiceBindingRequest,\n\tresourceRef string,\n\tbackendGVK schema.GroupVersionKind,\n\tenvVarPrefix string,\n) {\n\tsbr.Spec.BackingServiceSelector = &v1alpha1.BackingServiceSelector{\n\t\tGroupVersionKind: metav1.GroupVersionKind{Group: backendGVK.Group, Version: backendGVK.Version, Kind: backendGVK.Kind},\n\t\tResourceRef: resourceRef,\n\t\tEnvVarPrefix: &envVarPrefix,\n\t}\n}", "func (api *snapshotrestoreAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"config-restore\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"config-restore\", \"/\", name)\n}", "func (km KeyValueMap) Prefix() string {\n\treturn km[kmPrefix]\n}", "func Lookup(key string) (string, bool) { return os.LookupEnv(key) }", "func (k Key) GetInstanceNamePrefix() digest.InstanceName {\n\treturn k.instanceNamePrefix\n}", "func WithEnv(prefix string) FillerOption {\n\treturn WithEnvRenamer(\n\t\tCompositeRenamer(PrefixRenamer(prefix), ScreamingSnakeRenamer()))\n}", "func prefix(k string) *goraptor.Uri {\n\tvar pref string\n\trest := k\n\tif i := strings.Index(k, \":\"); i >= 0 {\n\t\tpref = k[:i+1]\n\t\trest = k[i+1:]\n\t}\n\tif long, ok := rdfPrefixes[pref]; ok {\n\t\tpref = long\n\t}\n\turi := goraptor.Uri(pref + rest)\n\treturn &uri\n}", "func (api *dscprofileAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"dscprofiles\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"dscprofiles\", \"/\", name)\n}", "func (api *clusterAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"cluster\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"cluster\", \"/\", name)\n}", "func SetEnvironmentPrefix(envPrefix string) {\n\t_envPrefix = envPrefix\n}", "func (ms *memoryStore) GetWithPrefix(prefix string) (*NameSpace, error) {\n\tms.RLock()\n\tdefer ms.RUnlock()\n\tns, ok := ms.prefix2base[prefix]\n\tif !ok {\n\t\treturn nil, ErrNameSpaceNotFound\n\t}\n\treturn ns, nil\n}", "func (api *bucketAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"objstore\", \"/\", \"buckets\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"objstore\", \"/\", \"buckets\", \"/\", name)\n}", "func PathPrefixFrontend(pathPrefix string, options ...FrontendOpt) Frontend {\n\topts := getFrontendOptions(append([]FrontendOpt{PathPrefix(pathPrefix)}, options...))\n\n\treturn Frontend{\n\t\tKind: FrontendKindPathPrefix,\n\t\tPathPrefix: opts.pathPrefix,\n\t\tStripPathPrefix: opts.stripPathPrefix,\n\t\tAllowInsecureHTTP: opts.allowInsecureHTTP,\n\t}\n}", "func SetEnvPrefix(prefix string) {\n\tviper.SetEnvPrefix(prefix)\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\tviper.AutomaticEnv()\n}", "func (api *nodeAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"nodes\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"nodes\", \"/\", name)\n}", "func Prefix(l string) Option {\n\treturn func(c *Config) Option {\n\t\tprevious := c.Pfx\n\t\tc.Pfx = l\n\t\treturn Prefix(previous)\n\t}\n}", "func (h funcHandler) returnPlatformVar(key string) string {\n\t// lowercase the key\n\tkey = strings.ToLower(key)\n\n\t// iterate through the list of possible prefixes to look for\n\tfor _, prefix := range []string{\"deployment_parameter_\", \"vela_\"} {\n\t\t// trim the prefix from the input key\n\t\ttrimmed := strings.TrimPrefix(key, prefix)\n\t\t// check if the key exists within map\n\t\tif _, ok := h.envs[trimmed]; ok {\n\t\t\t// return the non-prefixed value if exists\n\t\t\treturn h.envs[trimmed]\n\t\t}\n\t}\n\n\t// return empty string if not exists\n\treturn \"\"\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\r\n\tif value, ok := os.LookupEnv(key); ok {\r\n\t\treturn value\r\n\t}\r\n\treturn fallback\r\n}", "func getEnv(key, fallback string) string {\n\tvalue, exists := os.LookupEnv(key)\n\tif !exists {\n\t\tvalue = fallback\n\t}\n\treturn value\n}", "func (e Provider) Provide() (map[string]string, error) {\n\t// Create an empty map to store the configuration\n\tcfg := map[string]string{}\n\n\t// Get the environment variables\n\tenv := os.Environ()\n\tif len(env) == 0 {\n\t\treturn nil, ErrNoEnvironmentVariables\n\t}\n\n\t// Convert the EnvProvider's prefix to upper case\n\tprefix := fmt.Sprintf(\"%s_\", strings.ToUpper(e.Prefix))\n\n\t// Loop over each environment variable and store the values matching the prefix. Strip the prefix from the key\n\t// name when storing the key/value pair in the map\n\tfor _, v := range env {\n\t\tif strings.HasPrefix(v, prefix) {\n\t\t\tpair := strings.Split(v, \"=\")\n\t\t\tcfg[strings.TrimPrefix(pair[0], prefix)] = pair[1]\n\t\t}\n\t}\n\n\t// Check if we found anything\n\tif len(cfg) == 0 {\n\t\treturn nil, ErrPrefixNotFound\n\t}\n\treturn cfg, nil\n}", "func (o BuildStrategySpecBuildStepsEnvFromOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsEnvFrom) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (api *objectAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"objstore\", \"/\", \"objects\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"objstore\", \"/\", \"objects\", \"/\", name)\n}", "func GetBackendConfig(backend string) (cnf *BackendConfig, err error) {\n\tvar u *url.URL\n\tu, err = url.Parse(backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcnf = &BackendConfig{}\n\tcnf.Params = map[string]string{}\n\tu.Scheme = strings.ToLower(u.Scheme)\n\n\tif u.Scheme == \"\" && u.Host == \"\" && u.Path != \"\" {\n\t\tcnf.Network, cnf.Address = \"unix\", u.Path\n\t}\n\tif u.Scheme == \"\" && u.Host != \"\" && u.Path == \"\" {\n\t\tcnf.Network, cnf.Address = \"tcp\", u.Host\n\t}\n\tif u.Scheme == \"unix\" && u.Path != \"\" {\n\t\tcnf.Network, cnf.Address = \"unix\", u.Path\n\t}\n\tif u.Scheme == \"tcp\" && u.Host != \"\" {\n\t\tcnf.Network, cnf.Address = \"tcp\", u.Host\n\t}\n\n\tfor k, v := range u.Query() {\n\t\tif len(v) < 1 {\n\t\t\tv = []string{\"\"}\n\t\t}\n\t\tcnf.Params[k] = v[0]\n\t}\n\n\tif cnf.Network == \"\" || cnf.Address == \"\" {\n\t\treturn nil, errors.New(\"Invalid fastcgi address (\" + backend + \") specified `malformed`\")\n\t}\n\n\treturn cnf, nil\n}", "func LookUpEnv(key string) string {\n\tif val, ok := os.LookupEnv(key); ok {\n\t\treturn val\n\t}\n\n\treturn \"\"\n}", "func (ctx *Ctx) Env(v string) string {\n\treturn os.Getenv(ctx.DSPrefix + v)\n}", "func (ctx NSContext) LookupPrefix(prefix string) (string, error) {\n\tif namespace, ok := ctx.prefixes[prefix]; ok {\n\t\treturn namespace, nil\n\t}\n\n\treturn \"\", ErrUndeclaredNSPrefix{\n\t\tPrefix: prefix,\n\t}\n}", "func getFlagsFromEnv(prefix string, fs *pflag.FlagSet) {\n\talreadySet := make(map[string]bool)\n\tfs.Visit(func(f *pflag.Flag) {\n\t\talreadySet[f.Name] = true\n\t})\n\tfs.VisitAll(func(f *pflag.Flag) {\n\t\tif !alreadySet[f.Name] {\n\t\t\tkey := strings.ToUpper(prefix + \"_\" + strings.Replace(f.Name, \"-\", \"_\", -1))\n\t\t\tval := os.Getenv(key)\n\t\t\tif val != \"\" {\n\t\t\t\tfs.Set(f.Name, val)\n\t\t\t}\n\t\t}\n\n\t})\n}", "func NewBackend(client *clientv3.Client, prefix string) *Backend {\n\treturn &Backend{\n\t\tclient: client,\n\t\tprefix: prefix,\n\t}\n}", "func Prefix(p string) Option {\n\treturn func(s *storage) {\n\t\ts.prefix = p\n\t}\n}", "func (e *OverlayEnv) Getenv(key string) string {\n\t// do we have a variable backing store to work with?\n\tif e == nil {\n\t\treturn \"\"\n\t}\n\n\t// search for this variable\n\tfor _, env := range e.envs {\n\t\tvalue, ok := env.LookupEnv(key)\n\t\tif ok {\n\t\t\treturn value\n\t\t}\n\t}\n\n\t// if we get here, then it doesn't exist\n\treturn \"\"\n}", "func (o ClusterBuildStrategySpecBuildStepsEnvFromOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsEnvFrom) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func getEnv(key string, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\tif value != \"\" {\n\t\t\treturn value\n\t\t}\n\t}\n\treturn fallback\n}", "func Getenv(key string, fallbacks ...string) (value string) {\n\tvalue, _ = LookupEnv(key, fallbacks...)\n\treturn\n}", "func Getenv(key string) (string, error) {\n\tfor _, b := range []byte(key) {\n\t\tif b == '(' || b == ')' || b == '_' ||\n\t\t\t'0' <= b && b <= '9' ||\n\t\t\t'a' <= b && b <= 'z' ||\n\t\t\t'A' <= b && b <= 'Z' {\n\t\t\tcontinue\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"wine: invalid character %q in variable name\", b)\n\t}\n\n\tserver.wg.Wait()\n\tout, err := exec.Command(\"wine\", \"cmd\", \"/c\", \"if defined\", key, \"echo\", \"%\"+key+\"%\").Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(bytes.TrimSuffix(out, []byte(\"\\r\\n\"))), nil\n}", "func Backend() *backend {\n\tvar b backend\n\tb.Backend = &framework.Backend{\n\t\tHelp: \"\",\n\t\tPaths: framework.PathAppend(\n\t\t\terrorPaths(&b),\n\t\t\tkvPaths(&b),\n\t\t\t[]*framework.Path{\n\t\t\t\tpathInternal(&b),\n\t\t\t\tpathSpecial(&b),\n\t\t\t\tpathRaw(&b),\n\t\t\t},\n\t\t),\n\t\tPathsSpecial: &logical.Paths{\n\t\t\tUnauthenticated: []string{\n\t\t\t\t\"special\",\n\t\t\t},\n\t\t},\n\t\tSecrets: []*framework.Secret{},\n\t\tInvalidate: b.invalidate,\n\t\tBackendType: logical.TypeLogical,\n\t}\n\tb.internal = \"bar\"\n\treturn &b\n}", "func Env(key, fallback string) string {\n\tif v := os.Getenv(key); v != \"\" {\n\t\treturn v\n\t}\n\n\treturn fallback\n}", "func (c *Configuration) Prefix() string { return \"mtlsproxy\" }", "func KeyPrefix() string {\n\treturn Keyword + \"/\"\n}", "func (api *licenseAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"licenses\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"licenses\", \"/\", name)\n}", "func WithDBPrefix(dbPrefix string) Option {\n\treturn func(opts *Provider) {\n\t\topts.dbPrefix = dbPrefix\n\t}\n}", "func env(key string, fallback string) string {\n\tif v := os.Getenv(key); v != \"\" {\n\t\treturn v\n\t}\n\treturn fallback\n}", "func Env(name string) string {\n\treturn fmt.Sprintf(\"PILADB_%s\", name)\n}", "func (l *LocalService) GetPrefix() string {\n\treturn \"datadog.serverless_agent\"\n}", "func (s DeploymentSecretType) Prefix() string {\n\treturn s.String() + \".\"\n}", "func (api *configurationsnapshotAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"config-snapshot\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"config-snapshot\", \"/\", name)\n}", "func (gobgp *GoBGP) LookupPrefix(\n\tctx context.Context,\n\tprefix string,\n) (*api.RoutesLookupResponse, error) {\n\treturn nil, fmt.Errorf(\"not implemented: LookupPrefix\")\n}", "func (s *searchServiceServer) PathPrefix() string {\n\treturn baseServicePath(s.pathPrefix, \"buf.alpha.registry.v1alpha1\", \"SearchService\")\n}", "func (c *Conn) bkpPathPrefix(backupPrefix string) string {\n\tif c.backupPathPrefix == \"\" {\n\t\treturn backupDir + \"/\" + backupPrefix\n\t}\n\treturn c.backupPathPrefix + \"/\" + backupDir + \"/\" + backupPrefix\n}", "func WithPrefix(p string) OptionFunc {\n\treturn func(b *Bot) {\n\t\tb.conf.Prefix = p\n\t}\n}", "func GetEnv(en []map[string]string, key string) string {\n\ts := \"\"\n\tfor _, e := range en {\n\t\tif v, ok := e[key]; ok {\n\t\t\ts = v\n\t\t}\n\t}\n\treturn s\n}", "func GetEtcdBackend(ctx context.Context, prefix string,\n\tetcdConfig *EtcdConfig) (Backend, er.R) {\n\n\t// Config translation is needed here in order to keep the\n\t// etcd package fully independent from the rest of the source tree.\n\tbackendConfig := etcd.BackendConfig{\n\t\tCtx: ctx,\n\t\tHost: etcdConfig.Host,\n\t\tUser: etcdConfig.User,\n\t\tPass: etcdConfig.Pass,\n\t\tCertFile: etcdConfig.CertFile,\n\t\tKeyFile: etcdConfig.KeyFile,\n\t\tInsecureSkipVerify: etcdConfig.InsecureSkipVerify,\n\t\tPrefix: prefix,\n\t\tCollectCommitStats: etcdConfig.CollectStats,\n\t}\n\n\treturn Open(EtcdBackendName, backendConfig)\n}", "func NewDBPrefixKey(dbName string) Key {\n\treturn Key{Prefix: prefix, DBName: dbName}\n}", "func Prefix(prefix string) Option {\n\treturn func(s *Store) {\n\t\ts.prefix = prefix\n\t}\n}", "func getEncryptionFromBase(\n\tctx context.Context,\n\tuser security.SQLUsername,\n\tmakeCloudStorage cloud.ExternalStorageFromURIFactory,\n\tbaseBackupURI string,\n\tencryptionParams backupEncryptionParams,\n) (*jobspb.BackupEncryptionOptions, error) {\n\tvar encryptionOptions *jobspb.BackupEncryptionOptions\n\tif encryptionParams.encryptMode != noEncryption {\n\t\texportStore, err := makeCloudStorage(ctx, baseBackupURI, user)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer exportStore.Close()\n\t\topts, err := readEncryptionOptions(ctx, exportStore)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch encryptionParams.encryptMode {\n\t\tcase passphrase:\n\t\t\tencryptionOptions = &jobspb.BackupEncryptionOptions{\n\t\t\t\tMode: jobspb.EncryptionMode_Passphrase,\n\t\t\t\tKey: storageccl.GenerateKey(encryptionParams.encryptionPassphrase, opts.Salt),\n\t\t\t}\n\t\tcase kms:\n\t\t\tdefaultKMSInfo, err := validateKMSURIsAgainstFullBackup(encryptionParams.kmsURIs,\n\t\t\t\tnewEncryptedDataKeyMapFromProtoMap(opts.EncryptedDataKeyByKMSMasterKeyID), encryptionParams.kmsEnv)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tencryptionOptions = &jobspb.BackupEncryptionOptions{\n\t\t\t\tMode: jobspb.EncryptionMode_KMS,\n\t\t\t\tKMSInfo: defaultKMSInfo}\n\t\t}\n\t}\n\treturn encryptionOptions, nil\n}", "func GetEnv(key string, fallback ...string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\n\treturn fallback[0]\n}", "func envOverrides() []string {\n\tvar envOverrides []string\n\tfor _, envMapping := range []struct {\n\t\told string\n\t\ttargetKey string\n\t}{\n\t\t{\"REDPANDA_BROKERS\", xKafkaBrokers},\n\t\t{\"REDPANDA_TLS_TRUSTSTORE\", xKafkaCACert},\n\t\t{\"REDPANDA_TLS_CA\", xKafkaCACert},\n\t\t{\"REDPANDA_TLS_CERT\", xKafkaClientCert},\n\t\t{\"REDPANDA_TLS_KEY\", xKafkaClientKey},\n\t\t{\"REDPANDA_SASL_MECHANISM\", xKafkaSASLMechanism},\n\t\t{\"REDPANDA_SASL_USERNAME\", xKafkaSASLUser},\n\t\t{\"REDPANDA_SASL_PASSWORD\", xKafkaSASLPass},\n\t\t{\"REDPANDA_API_ADMIN_ADDRS\", xAdminHosts},\n\t\t{\"REDPANDA_ADMIN_TLS_TRUSTSTORE\", xAdminCACert},\n\t\t{\"REDPANDA_ADMIN_TLS_CA\", xAdminCACert},\n\t\t{\"REDPANDA_ADMIN_TLS_CERT\", xAdminClientCert},\n\t\t{\"REDPANDA_ADMIN_TLS_KEY\", xAdminClientKey},\n\t\t{\"RPK_CLOUD_CLIENT_ID\", xCloudClientID},\n\t\t{\"RPK_CLOUD_CLIENT_SECRET\", xCloudClientSecret},\n\t} {\n\t\tif v, exists := os.LookupEnv(envMapping.old); exists {\n\t\t\tenvOverrides = append(envOverrides, envMapping.targetKey+\"=\"+v)\n\t\t}\n\t}\n\tfor _, k := range XFlags() {\n\t\ttargetKey := k\n\t\tk = strings.ReplaceAll(k, \".\", \"_\")\n\t\tk = strings.ToUpper(k)\n\t\tif v, exists := os.LookupEnv(\"RPK_\" + k); exists {\n\t\t\tenvOverrides = append(envOverrides, targetKey+\"=\"+v)\n\t\t}\n\t}\n\treturn envOverrides\n}", "func getComponentPrefix() string {\n\tprefixDir := \"\"\n\tif len(flagComponentFile) > 0 {\n\t\tprefixDir, _ = filepath.Split(flagComponentFile)\n\t}\n\treturn prefixDir\n}", "func GetEnv(key string, dfault string, combineWith ...string) string {\n\tvalue := os.Getenv(key)\n\tif value == \"\" {\n\t\tvalue = dfault\n\t}\n\n\tswitch len(combineWith) {\n\tcase 0:\n\t\treturn value\n\tcase 1:\n\t\treturn filepath.Join(value, combineWith[0])\n\tdefault:\n\t\tall := make([]string, len(combineWith)+1)\n\t\tall[0] = value\n\t\tcopy(all[1:], combineWith)\n\t\treturn filepath.Join(all...)\n\t}\n}" ]
[ "0.6347933", "0.63442594", "0.6122232", "0.60257626", "0.5933097", "0.5869394", "0.5828094", "0.5709107", "0.5504304", "0.54655296", "0.54655296", "0.5389238", "0.53578043", "0.5324864", "0.53159595", "0.5272734", "0.5266913", "0.52624804", "0.52579653", "0.52179086", "0.51772135", "0.51417845", "0.51267284", "0.50923204", "0.5085684", "0.5083961", "0.5083642", "0.5040523", "0.5022128", "0.5015097", "0.5010393", "0.5006577", "0.4983744", "0.4978168", "0.4955731", "0.49398196", "0.4929491", "0.4916143", "0.4910495", "0.49037525", "0.48999414", "0.4896864", "0.4896091", "0.4890737", "0.48885125", "0.48880622", "0.48720336", "0.48704863", "0.48645598", "0.48596668", "0.4857451", "0.4857451", "0.4857451", "0.4857451", "0.4857451", "0.4857451", "0.4857451", "0.4857451", "0.4857451", "0.48568514", "0.48553333", "0.48521367", "0.48517862", "0.48476583", "0.48420835", "0.48301548", "0.4829101", "0.4828993", "0.48212117", "0.47805488", "0.47782314", "0.47775728", "0.47565755", "0.47539786", "0.4750036", "0.4738846", "0.47360808", "0.47346345", "0.4734464", "0.47337818", "0.47317123", "0.47299394", "0.47274554", "0.47236243", "0.47083855", "0.47070983", "0.47068074", "0.47066873", "0.47045887", "0.46828857", "0.46788737", "0.4665408", "0.46560046", "0.46501037", "0.46500242", "0.4645533", "0.46429157", "0.464171", "0.46307117", "0.46270677" ]
0.6415679
0
to display incase of any issues during runtime
func exceptioncheck(e1 error) { if e1 != nil { log.Fatal(e1) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func printErr (err error){ // this function is used for printing error\r\n if err != nil{\r\n fmt.Println(err)\r\n }\r\n }", "func printErr (err error){ // this function is used for printing error\n if err != nil{\n fmt.Println(err)\n }\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 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) {\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 (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 DisplayInfo(projectType string) {\n\tfmt.Println(Info(\"Attention please\"))\n\tfmt.Println()\n\tif strings.Contains(projectType, \"http\") || strings.Contains(projectType, \"grpc\") {\n\t\tfmt.Println(Warn(\"port information\"))\n\t\tfmt.Println(Details(\"readyGo does not know whether the port is available or not.\"))\n\t\tfmt.Println(Details(\"User has to make sure that the port is available and not behind firewall\"))\n\t}\n\tfmt.Println()\n\tif strings.Contains(projectType, \"grpc\") {\n\t\tfmt.Println(Warn(\"grpc protocol buffer information\"))\n\t\tfmt.Println(Details(\"readyGo does not generate proto buffer go files for you.\"))\n\t\tfmt.Println(Details(\"User has to make sure that protoc , proto_gen_go and protoc_gen_go_grpc tools are installed w.r.t the OS\"))\n\t}\n\tfmt.Println()\n\tif strings.Contains(projectType, \"mongo\") {\n\t\tfmt.Println(Warn(\"mongo database information\"))\n\t\tfmt.Println(Details(\"readyGo does not start the database.\"))\n\t\tfmt.Println(Details(\"Make sure your mongodb database is started , up and running\"))\n\t}\n\tfmt.Println()\n\tif strings.Contains(projectType, \"sql\") {\n\t\tfmt.Println(Warn(\"sql database information\"))\n\t\tfmt.Println(Details(\"readyGo does not start the database.\"))\n\t\tfmt.Println(Details(\"Make sure your sql database is started , up and running\"))\n\t}\n\tfmt.Println()\n}", "func showError(errStr string) {\n\tfmt.Printf(\"\\n\\tError: %v\\n\\n\", errStr)\n\tfmt.Printf(\"\\t%v --help for usage information\\n\\n\", os.Args[0])\n}", "func (h Health) Display() {\n\tfor _, check := range h.Checks {\n\t\tif check.Result != 0 {\n\t\t\tutil.LogError(check.Details)\n\t\t} else {\n\t\t\tutil.LogOk(check.Details)\n\t\t}\n\t}\n}", "func show_happiness()bool{\nreturn flags['h']/* should lack of errors be announced? */\n}", "func (e *Error) Inspect() string { return \"bruh moment: \" + e.Message }", "func showUsage() {\n\tgenUsage().Render()\n}", "func displayError(txt string, err ...error) {\n\n\tvar errorStr string\n\n\tif len(err) == 0 {\n\t\terrorStr = fmt.Sprintf(\"%s\\n\", txt)\n\t} else {\n\t\terrorStr = fmt.Sprintf(\"%s: %v\\n\", txt, err)\n\t}\n\n\tdisplayRedText(strings.Trim(errorStr, \"\\n\"))\n\tdisplayText(prompt)\n}", "func printStatusErr(e error) {\n\tfmt.Println(\"Checking status of \" + AppName + \" failed\")\n\tfmt.Println(\"Details:\", e.Error())\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 showRandomProblem(w http.ResponseWriter, data TemplateData) {\n\t// Choose a problem with lowest dacu, starred first\n\tdata.Problems = problems.GetUnsolvedProblemRandom(data.UserID)\n\tif len(data.Problems) == 0 {\n\t\tdata = TemplateData{UsernameError: \"No problems to solve\", Username: data.Username}\n\t\trenderPage(w, \"index\", data)\n\t\treturn\n\t}\n\trenderPage(w, \"lucky\", data)\n}", "func check(err error, message string) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(message)\n}", "func PrintErr(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func ShowErr() {\r\n t, _ := template.New(\"test\").Parse(tpl)\r\n // data := map[string]string{\r\n // \"AppError\": fmt.Sprintf(\"%s:%v\", BConfig.AppName, err),\r\n // \"RequestMethod\": ctx.Input.Method(),\r\n // \"RequestURL\": ctx.Input.URI(),\r\n // \"RemoteAddr\": ctx.Input.IP(),\r\n // \"Stack\": stack,\r\n // \"BeegoVersion\": VERSION,\r\n // \"GoVersion\": runtime.Version(),\r\n // }\r\n //ctx.ResponseWriter.WriteHeader(500)\r\n t.Execute(Requests.W, nil)\r\n}", "func PrintErrors() {\n\tvar msg string\n\tfor {\n\t\terror := gl.GetError()\n\t\tif error == gl.NO_ERROR {\n\t\t\tlog.Print(\"PrintErrors: NO_ERROR: All error flags are reset\")\n\t\t\treturn\n\t\t}\n\t\tif error == gl.INVALID_ENUM {\n\t\t\tmsg = \"INVALID_ENUM: Enum argument out of range.\"\n\t\t} else if error == gl.INVALID_VALUE {\n\t\t\tmsg = \"INVALID_VALUE: Numeric argument out of range.\"\n\t\t} else if error == gl.INVALID_OPERATION {\n\t\t\tmsg = \"INVALID_OPERATION: Operation illegal in current state.\"\n\t\t} else if error == gl.INVALID_FRAMEBUFFER_OPERATION {\n\t\t\tmsg = \"INVALID_FRAMEBUFFER_OPERATION: Framebuffer is incomplete.\"\n\t\t} else if error == gl.OUT_OF_MEMORY {\n\t\t\tmsg = \"OUT_OF_MEMORY: Not enough memory left to execute command.\"\n\t\t}\n\t\tlog.Print(\"Error: \", msg)\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 main() {\n\terrs(\"aaabbbbhaijjjm\")\n}", "func (e *ErrFieldMismatch) String() string {\n\treturn fmt.Sprintf(\"datastore: cannot load field %q from key %q into a %q: %s\",\n\t\te.FieldName, e.Key, e.StructType, e.Reason)\n}", "func unexpectedError(msg string) {\n\tcolor.FgLightYellow.Println(msg + \" Please email me at [email protected] if this happens\")\n}", "func usage() {\n\tlog.Fatalf(usageStr)\n}", "func Check(info string, err error) {\r\n\tif err != nil {\r\n\t\tconsole.Error(info + err.Error())\r\n\t}\r\n}", "func (v *Provider) Diagnose() {\n\trr, err := v.rr()\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttw := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)\n\n\tsort.Slice(rr.OperationList.ServiceInfo, func(i, j int) bool {\n\t\treturn rr.OperationList.ServiceInfo[i].ServiceId < rr.OperationList.ServiceInfo[j].ServiceId\n\t})\n\n\tfor _, si := range rr.OperationList.ServiceInfo {\n\t\tif si.InvocationUrl.Content != \"\" {\n\t\t\tfmt.Fprintf(tw, \"%s:\\t%s\\n\", si.ServiceId, si.InvocationUrl.Content)\n\t\t}\n\t}\n\n\t// list remaining service\n\tservices := lo.FilterMap(rr.OperationList.ServiceInfo, func(si ServiceInfo, _ int) (string, bool) {\n\t\treturn si.ServiceId, si.InvocationUrl.Content == \"\"\n\t})\n\n\tfmt.Fprintf(tw, \"without uri:\\t%s\\n\", strings.Join(services, \",\"))\n\n\ttw.Flush()\n}", "func displayAddResponse(apiResp JobApiResponse) {\n\n\tif apiResp.Status == apiSuccess {\n\n\t\tvar display = template.Must(template.New(\"JobAddSuccess\").Parse(addTemplSuccess))\n\n\t\tif err := display.Execute(os.Stdout, apiResp); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t} else {\n\t\tvar display = template.Must(template.New(\"ApiError\").Parse(apiErrorTempl))\n\n\t\tif err := display.Execute(os.Stdout, apiResp); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n}", "func (hangman *Hangman) displayResult(screenOutputer ScreenOutputerInterface, result bool) {\n notFoundTemplate := template.New(\"Not Found Template\")\n notFoundTemplate, _ = notFoundTemplate.Parse(\"Sorry letter not found you have {{.Guesses}} guesses left \\n\")\n\n if (result == false) {\n fmt.Println(screenOutputer.selectImage(hangman.guesses))\n hangman.guesses++\n\n notFoundTemplate.Execute(os.Stdout, struct {\n Guesses int\n }{\n 11 - hangman.guesses,\n })\n\n\n } else {\n fmt.Println(\"Well done you guessed correctly\")\n }\n}", "func Complain(msg string) {\n\tfmt.Fprintf(stderr, \"\\033[31;1m%s\\033[m\\n\", msg)\n}", "func (st Student) display() {\n\tfmt.Println()\n\tfmt.Printf(\"Name: %s - Age: %d - Address: %s\", st.student_name, st.student_age, st.student_address)\n}", "func (e *err) DetailText() string {\n\tvar text string\n\tif e.chains != nil && len(e.chains) != 0 {\n\t\ttext = fmt.Sprintf(\"CallChains=%s, \", strings.Join(e.chains, \".\"))\n\t}\n\tif len(globalTag) != 0 {\n\t\ttext += fmt.Sprintf(\"GlobalTag=%s, \", globalTag)\n\t}\n\tif len(e.tag) != 0 {\n\t\ttext += fmt.Sprintf(\"Tag=%s, \", e.tag)\n\t}\n\tif globalFields != nil && len(globalFields) != 0 {\n\t\tb, _ := json.Marshal(globalFields)\n\t\ttext += fmt.Sprintf(\"GlobalFields=%s, \", b)\n\t}\n\tif e.fields != nil && len(e.fields) != 0 {\n\t\tb, _ := json.Marshal(e.fields)\n\t\ttext += fmt.Sprintf(\"Fields=%s, \", b)\n\t}\n\ttext += fmt.Sprintf(\"Code=%+v, \", e.code)\n\tif e.e != nil {\n\t\ttext += fmt.Sprintf(\"Error=%s \", e.e.Error())\n\t}\n\treturn text\n}", "func checkDatabase() {\n\tlog.Info().Msgf(\n\t\t\"found %d train numbers and %d log records in the database\",\n\t\tmodels.CountRecords(\"emu_latest\"),\n\t\tmodels.CountRecords(\"emu_log\"),\n\t)\n\tlog.Info().Msgf(\n\t\t\"found %d units and %d QR codes in the database\",\n\t\tmodels.CountRecords(\"emu_qr_code\", \"DISTINCT emu_no\"),\n\t\tmodels.CountRecords(\"emu_qr_code\"),\n\t)\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 (ui *UI) DisplayWarning(template string, templateValues ...map[string]interface{}) {\n\tfmt.Fprintf(ui.Err, \"%s\\n\", ui.TranslateText(template, templateValues...))\n}", "func (w *withCode) Error() string { return w.cause.Error() }", "func (ui *UI) DisplayWarnings(warnings []string) {\n\tfor _, warning := range warnings {\n\t\tfmt.Fprintf(ui.Err, \"%s\\n\", ui.TranslateText(warning))\n\t}\n}", "func display(v discord_version.Version) string {\n\tvar bn string\n\tif len(v.BuildNumber) == 0 {\n\t\tbn = \"unknown\"\n\t} else {\n\t\tbn = v.BuildNumber\n\t}\n\tvar date string\n\tif v.Date.IsZero() {\n\t\tdate = \"unknown date\"\n\t} else {\n\t\tdate = v.Date.String()\n\t}\n\treturn fmt.Sprintf(\"%s branches's Build ID is %s with hash of %s and released at %s\", v.Branch, bn, v.VersionHash, date)\n}", "func (a death) earlyDeathInfo() string {\n\tvar s, prmText, opText, dateEst string\n\n\tif a.PrmDth == 0 || a.PrmDth == -9 {\n\t\tprmText = \"Not applicable\"\n\t} else if a.PrmDth == 1 {\n\t\tprmText = \"Valve-related cause\"\n\t} else if a.PrmDth == 2 {\n\t\tprmText = \"Cardiac, non valve-related cause\"\n\t} else if a.PrmDth == 3 {\n\t\tprmText = \"Non-cardiac cause\"\n\t} else if a.PrmDth == 4 {\n\t\tprmText = \"Dissection (* Used only for David op FU, otherwise PRM_DTH=3)\"\n\t} else {\n\t\tprmText = \"no invalid primary death reason avaliable\"\n\t}\n\n\tif a.Operative == 1 {\n\t\topText = \"operative\"\n\t} else {\n\t\topText = \"non-operative\"\n\t}\n\n\tif a.DateEst == 1 {\n\t\tdateEst = \"date estimated\"\n\t} else {\n\t\tdateEst = \"date not estimated\"\n\t}\n\n\ts = \"another record had a different date: '\" + a.Date + \"', '\" + dateEst +\n\t\t\"', '\" + opText + \"', primary death reason: '\" + prmText + \"'\"\n\treturn s\n}", "func printError(format string, a ...interface{}) {\n\tif fetchConfig().verbosity < Error {\n\t\treturn\n\t}\n\tif fetchConfig().color {\n\t\tformat = color.FgRed.Render(format)\n\t}\n\tfmt.Fprintf(os.Stderr, format+\"\\n\", a...)\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tlog.Printf(err.Error())\n\t\tos.Exit(1)\n\t}\n}", "func (e exitCode) Error() string {\n\treturn \"\"\n}", "func (e exitCode) Error() string {\n\treturn \"\"\n}", "func Fatalln(v ...interface{}) {\n\tcheckInit()\n\ts := fmt.Sprintln(v...)\n\tstd.Report(s)\n\tlog.Fatal(s)\n}", "func check(e error, m string) {\n\tif e != nil {\n\t\tprintln(m)\n\t\tos.Exit(1)\n\t}\n}", "func (m *Main) PrintFailure() {\n\tfmt.Println(\"\")\n\tlog.Errorf(\"FAIL: %s\", m.Name)\n\tfmt.Println(\"\")\n}", "func showUsage(message string, args ...interface{}) {\n\tflag.PrintDefaults()\n\tif message != \"\" {\n\t\tfmt.Printf(\"\\n[error] \"+message+\"\\n\", args...)\n\t\tos.Exit(1)\n\t}\n\n\tos.Exit(0)\n}", "func checkError(err error, msg string) {\n if err != nil {\n fmt.Printf(\"%s\\n\", msg)\n panic(err)\n }\n}", "func Verbose() bool", "func printWarning(format string, a ...interface{}) {\n\tif fetchConfig().verbosity < Warning {\n\t\treturn\n\t}\n\tif fetchConfig().color {\n\t\tformat = color.FgYellow.Render(format)\n\t}\n\tfmt.Fprintf(os.Stderr, format+\"\\n\", a...)\n}", "func (p *httpMockProvider) displayMismatches(t *testing.T, mismatches []native.MismatchedRequest) {\n\tif len(mismatches) > 0 {\n\n\t\tif len(callerInfo()) > 0 {\n\t\t\tfmt.Printf(\"\\n\\n%s:\\n\", callerInfo()[len(callerInfo())-1])\n\t\t}\n\t\tfmt.Println(\"\\tPact Verification Failed for:\", t.Name())\n\t\tfmt.Println()\n\t\tfmt.Println(\"\\t\\tDiff:\")\n\t\tlog.Println(\"[INFO] pact validation failed, errors: \")\n\t\tfor _, m := range mismatches {\n\t\t\tformattedRequest := fmt.Sprintf(\"%s %s\", m.Request.Method, m.Request.Path)\n\t\t\tswitch m.Type {\n\t\t\tcase \"missing-request\":\n\t\t\t\tfmt.Printf(\"\\t\\texpected: \\t%s (Expected request that was not received)\\n\", formattedRequest)\n\t\t\tcase \"request-not-found\":\n\t\t\t\tfmt.Printf(\"\\t\\tactual: \\t%s (Unexpected request was received)\\n\", formattedRequest)\n\t\t\tdefault:\n\t\t\t\t// TODO:\n\t\t\t}\n\n\t\t\tfor _, detail := range m.Mismatches {\n\t\t\t\tswitch detail.Type {\n\t\t\t\tcase \"HeaderMismatch\":\n\t\t\t\t\tfmt.Printf(\"\\t\\t\\t%s\\n:\", detail.Mismatch)\n\t\t\t\t\tfmt.Println(\"\\t\\t\\texpected: \\t\", detail.Expected)\n\t\t\t\t\tfmt.Println(\"\\t\\t\\tactual: \\t\", detail.Actual)\n\t\t\t\tcase \"BodyMismatch\":\n\t\t\t\t\tfmt.Printf(\"\\t\\t\\t%s\\n\", detail.Mismatch)\n\t\t\t\t\tfmt.Println(\"\\t\\t\\texpected:\\t\", detail.Expected)\n\t\t\t\t\tfmt.Println(\"\\t\\t\\tactual:\\t\\t\", detail.Actual)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfmt.Println()\n\t\tfmt.Println()\n\t}\n}", "func errorIf(err error, msg string) {\n\tif err == nil {\n\t\treturn\n\t}\n\tlog.Println(\"ERROR\", msg, fmt.Sprintf(\"%+v\", err))\n\n\tif !globalDebug {\n\t\tconsole.Errorln(fmt.Sprintf(\"%s %s\", msg, err.Error()))\n\t\treturn\n\t}\n\tsysInfo := sysinfo.GetSysInfo()\n\tconsole.Errorln(fmt.Sprintf(\"%s %+v\", msg, err), \"\\n\", sysInfo)\n}", "func fatal(s string,t string){\nif len(s)!=0{\nfmt.Print(s)\n}\nerr_print(t)\nhistory= fatal_message\nos.Exit(wrap_up())\n}", "func checkIfYouLost(err error) {\n\tif strings.Contains(fmt.Sprintf(\"%s\", err), \"you lost\") {\n\t\tfmt.Println(\"▓██ ██▓ ▒█████ █ ██ ▓█████▄ ██▓▓█████ ▓█████▄ \")\n\t\tfmt.Println(\" ▒██ ██▒▒██▒ ██▒ ██ ▓██▒ ▒██▀ ██▌▓██▒▓█ ▀ ▒██▀ ██▌\")\n\t\tfmt.Println(\" ▒██ ██░▒██░ ██▒▓██ ▒██░ ░██ █▌▒██▒▒███ ░██ █▌\")\n\t\tfmt.Println(\" ░ ▐██▓░▒██ ██░▓▓█ ░██░ ░▓█▄ ▌░██░▒▓█ ▄ ░▓█▄ ▌\")\n\t\tfmt.Println(\" ░ ██▒▓░░ ████▓▒░▒▒█████▓ ░▒████▓ ░██░░▒████▒░▒████▓ \")\n\t\tfmt.Println(\" ██▒▒▒ ░ ▒░▒░▒░ ░▒▓▒ ▒ ▒ ▒▒▓ ▒ ░▓ ░░ ▒░ ░ ▒▒▓ ▒ \")\n\t\tfmt.Println(\" ▓██ ░▒░ ░ ▒ ▒░ ░░▒░ ░ ░ ░ ▒ ▒ ▒ ░ ░ ░ ░ ░ ▒ ▒ \")\n\t\tfmt.Println(\" ▒ ▒ ░░ ░ ░ ░ ▒ ░░░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ \")\n\t\tfmt.Println(\" ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ \")\n\t\tfmt.Println(\" ░ ░ ░ ░ \")\n\t\tos.Exit(0)\n\t}\n}", "func (task *Task) display() {\n\tterminalWidth, _ := terminal.Width()\n\ttheScreen := newScreen()\n\tif Config.Options.SingleLineDisplay {\n\n\t\tvar durString, etaString, stepString, errorString string\n\t\tdisplayString := \"\"\n\n\t\teffectiveWidth := int(terminalWidth)\n\n\t\tfillColor := color.ColorCode(strconv.Itoa(Config.Options.ColorSuccess) + \"+i\")\n\t\temptyColor := color.ColorCode(strconv.Itoa(Config.Options.ColorSuccess))\n\t\tif TaskStats.totalFailedTasks > 0 {\n\t\t\tfillColor = color.ColorCode(strconv.Itoa(Config.Options.ColorError) + \"+i\")\n\t\t\temptyColor = color.ColorCode(strconv.Itoa(Config.Options.ColorError))\n\t\t}\n\n\t\tnumFill := int(effectiveWidth) * TaskStats.completedTasks / TaskStats.totalTasks\n\n\t\tif Config.Options.ShowSummaryTimes {\n\t\t\tduration := time.Since(startTime)\n\t\t\tdurString = fmt.Sprintf(\" Runtime[%s]\", showDuration(duration))\n\n\t\t\ttotalEta := time.Duration(Config.totalEtaSeconds) * time.Second\n\t\t\tremainingEta := time.Duration(totalEta.Seconds()-duration.Seconds()) * time.Second\n\t\t\tetaString = fmt.Sprintf(\" ETA[%s]\", showDuration(remainingEta))\n\t\t}\n\n\t\tif TaskStats.completedTasks == TaskStats.totalTasks {\n\t\t\tetaString = \"\"\n\t\t}\n\n\t\tif Config.Options.ShowSummarySteps {\n\t\t\tstepString = fmt.Sprintf(\" Tasks[%d/%d]\", TaskStats.completedTasks, TaskStats.totalTasks)\n\t\t}\n\n\t\tif Config.Options.ShowSummaryErrors {\n\t\t\terrorString = fmt.Sprintf(\" Errors[%d]\", TaskStats.totalFailedTasks)\n\t\t}\n\n\t\tvalueStr := stepString + errorString + durString + etaString\n\n\t\tdisplayString = fmt.Sprintf(\"%[1]*s\", -effectiveWidth, fmt.Sprintf(\"%[1]*s\", (effectiveWidth+len(valueStr))/2, valueStr))\n\t\tdisplayString = fillColor + displayString[:numFill] + color.Reset + emptyColor + displayString[numFill:] + color.Reset\n\n\t\ttheScreen.Display(displayString, 0)\n\t} else {\n\t\ttheScreen.Display(task.String(int(terminalWidth)), task.Display.Index)\n\t}\n\n}", "func printSyntaxError(js string, off *[5000]int, err interface{}) {\r\n\tsyntax, ok := err.(*json.SyntaxError)\r\n\tif !ok {\r\n fmt.Println(\"*********** ERR trying to get syntax error location **************\\n\", err)\r\n\t\treturn\r\n\t}\r\n\t\r\n\tstart, end := strings.LastIndex(js[:syntax.Offset], \"\\n\")+1, len(js)\r\n\tif idx := strings.Index(js[start:], \"\\n\"); idx >= 0 {\r\n\t\tend = start + idx\r\n\t}\r\n\t\r\n\tline, pos := strings.Count(js[:start], \"\\n\"), int(syntax.Offset) - start -1\r\n\t\r\n\tfmt.Printf(\"Error in line %d: %s \\n\", off[line]+1, err)\r\n\tfmt.Printf(\"%s\\n%s^\\n\\n\", js[start:end], strings.Repeat(\" \", pos))\r\n}", "func (k *KeyringMembersWorklogDetails) Summary() string {\n\treturn fmt.Sprintf(\"This %s is missing access to one or more secrets.\", k.Type)\n}", "func (i *info) String() string {\n\tif len(i.detail.StackTrace) == 0 {\n\t\ti.prepare()\n\t\ti.detail = i.getDetail()\n\t}\n\n\treturn i.detail.String()\n}", "func Panicf(group string, format string, any ...interface{}) {\n\tfmt.Printf(redInverse(group) + \" \")\n\tfmt.Printf(redInverse(format), any...)\n}", "func printSysstat(v *gocui.View, s stat.Stat) error {\n\tvar err error\n\n\t/* line1: current time and load average */\n\t_, err = fmt.Fprintf(v, \"pgcenter: %s, load average: %.2f, %.2f, %.2f\\n\",\n\t\ttime.Now().Format(\"2006-01-02 15:04:05\"),\n\t\ts.LoadAvg.One, s.LoadAvg.Five, s.LoadAvg.Fifteen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/* line2: cpu usage */\n\t_, err = fmt.Fprintf(v, \" %%cpu: \\033[37;1m%4.1f\\033[0m us, \\033[37;1m%4.1f\\033[0m sy, \\033[37;1m%4.1f\\033[0m ni, \\033[37;1m%4.1f\\033[0m id, \\033[37;1m%4.1f\\033[0m wa, \\033[37;1m%4.1f\\033[0m hi, \\033[37;1m%4.1f\\033[0m si, \\033[37;1m%4.1f\\033[0m st\\n\",\n\t\ts.CpuStat.User, s.CpuStat.Sys, s.CpuStat.Nice, s.CpuStat.Idle,\n\t\ts.CpuStat.Iowait, s.CpuStat.Irq, s.CpuStat.Softirq, s.CpuStat.Steal)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/* line3: memory usage */\n\t_, err = fmt.Fprintf(v, \" MiB mem: \\033[37;1m%6d\\033[0m total, \\033[37;1m%6d\\033[0m free, \\033[37;1m%6d\\033[0m used, \\033[37;1m%8d\\033[0m buff/cached\\n\",\n\t\ts.Meminfo.MemTotal, s.Meminfo.MemFree, s.Meminfo.MemUsed,\n\t\ts.Meminfo.MemCached+s.Meminfo.MemBuffers+s.Meminfo.MemSlab)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/* line4: swap usage, dirty and writeback */\n\t_, err = fmt.Fprintf(v, \"MiB swap: \\033[37;1m%6d\\033[0m total, \\033[37;1m%6d\\033[0m free, \\033[37;1m%6d\\033[0m used, \\033[37;1m%6d/%d\\033[0m dirty/writeback\\n\",\n\t\ts.Meminfo.SwapTotal, s.Meminfo.SwapFree, s.Meminfo.SwapUsed,\n\t\ts.Meminfo.MemDirty, s.Meminfo.MemWriteback)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c CryptoServiceTester) errorMsg(message string, args ...interface{}) string {\n\tpc := make([]uintptr, 10) // at least 1 entry needed\n\truntime.Callers(2, pc) // the caller of errorMsg\n\tf := runtime.FuncForPC(pc[0])\n\treturn fmt.Sprintf(\"%s (role: %s, keyAlgo: %s): %s\", f.Name(), c.role,\n\t\tc.keyAlgo, fmt.Sprintf(message, args...))\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 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 main() {\n\tfmt.Println(\"Usual convention to have this program while learning new lang\")\n\tfmt.Println(\"Hello World :-) \")\n\t// fmt.Println returns to values (integer and error)\n\tn, err := fmt.Println(\"Hello GoLang\")\n\tfmt.Println(n)\n\tfmt.Println(err)\n\n\t// to void(ignore) the error value put \"_\" in the second place\n\tm, _ := fmt.Println(\"Hello GoLang\")\n\tfmt.Println(m)\n}", "func checkFatal(err error) {\n\tif err != nil {\n\t\ttracerr.PrintSourceColor(err)\n\t\tglobalRadioGroupCache.Dump()\n\t\tglobalRadioGroupMap.Dump()\n\t\tos.Exit(1)\n\t}\n}", "func (err *error_) String() string {\n\tif err.empty() {\n\t\treturn \"no error\"\n\t}\n\treturn fmt.Sprintf(\"%d: %s\", err.pos(), err.msg(nil, nil))\n}", "func (e Error) Desc() string { return e.d }", "func tableInfoFlowShow(meta *halproto.TableMetadata) {\n\tfMeta := meta.GetFlowMeta()\n\tinsStr := fmt.Sprintf(\"%d[%d]\", fMeta.GetNumInserts(), fMeta.GetNumInsertFailures())\n\tupdStr := fmt.Sprintf(\"%d[%d]\", fMeta.GetNumUpdates(), fMeta.GetNumUpdateFailures())\n\tdelStr := fmt.Sprintf(\"%d[%d]\", fMeta.GetNumDeletes(), fMeta.GetNumDeleteFailures())\n\tfmt.Printf(\"%-30s%-10d%-10s%-10d%-10d%-10d%-10d%-10s%-10s%-10s\\n\",\n\t\tmeta.GetTableName(),\n\t\tmeta.GetTableId(),\n\t\tutils.TableKindToStr(meta.GetKind()),\n\t\tfMeta.GetCapacity(),\n\t\tfMeta.GetCollCapacity(),\n\t\tfMeta.GetHashUsage(),\n\t\tfMeta.GetCollUsage(),\n\t\tinsStr,\n\t\tupdStr,\n\t\tdelStr)\n}", "func (store KeyValue) Errors() string {\n\treturn \"\"\n}", "func errorScreen(s string, conf config.UIConfig) ui.Drawable {\n\terrstyle := conf.GetStyle(config.STYLE_ERROR)\n\ttext := ui.NewText(s, errstyle).Strategy(ui.TEXT_CENTER)\n\tgrid := ui.NewGrid().Rows([]ui.GridSpec{\n\t\t{ui.SIZE_WEIGHT, ui.Const(1)},\n\t\t{ui.SIZE_EXACT, ui.Const(1)},\n\t\t{ui.SIZE_WEIGHT, ui.Const(1)},\n\t}).Columns([]ui.GridSpec{\n\t\t{ui.SIZE_WEIGHT, ui.Const(1)},\n\t})\n\tgrid.AddChild(ui.NewFill(' ')).At(0, 0)\n\tgrid.AddChild(text).At(1, 0)\n\tgrid.AddChild(ui.NewFill(' ')).At(2, 0)\n\treturn grid\n}", "func (e emp) display() {\n\tfmt.Println(e.name)\n}", "func check(e error, m string) {\n\tcolor.Set(color.FgHiRed)\n\tif e != nil {\n\t\tfmt.Println(m) // print a message\n\t\tpanic(e) // panic\n\t}\n\tcolor.Unset()\n}", "func (i *CmdLine) PrintFailure() {\n\tfmt.Printf(\"Oh, das war nicht richtig!\")\n}", "func (this *Undefined) Error() string {\n\tif this.Path != \"\" {\n\t\treturn fmt.Sprintf(\"%s is not defined\", this.Path)\n\t}\n\treturn fmt.Sprint(\"not defined\")\n}", "func (rt *operatorRuntime) errorDetailString(token *parser.LexToken, opVal interface{}) string {\n\tif !token.Identifier {\n\t\treturn token.Val\n\t}\n\n\tif opVal == nil {\n\t\topVal = \"NULL\"\n\t}\n\n\treturn fmt.Sprintf(\"%v=%v\", token.Val, opVal)\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 printHint() {\n\tprint(\"orbi - Embeddable Interactive ORuby Shell\\n\\n\")\n}", "func (s InternalFailureException) String() string {\n\treturn awsutil.Prettify(s)\n}", "func eprint(err error) {\n\tfmt.Println(DHT_PREFIX, err.Error())\n}", "func err_print(s string,a...interface{}){\nvar l int/* pointers into buffer */\nif len(s)> 0&&s[0]=='!'{\nfmt.Fprintf(os.Stdout,\"\\n\\n\"+s,a...)\n}else{\nfmt.Fprintf(os.Stdout,\"\\n\"+s,a...)\n}\nif len(file)> 0&&file[0]!=nil{\n\n\n/*71:*/\n\n\n//line gocommon.w:1097\n\n{\nif changing&&include_depth==change_depth{\nfmt.Printf(\". (change file %s:%d)\\n\",change_file_name,change_line)\n}else if include_depth==0&&len(line)> 0{\nfmt.Printf(\". (%s:%d)\\n\",file_name[include_depth],line[include_depth])\n}else if len(line)> include_depth{\nfmt.Printf(\". (include file %s:%d)\\n\",file_name[include_depth],line[include_depth])\n}\nl= len(buffer)\nif loc<l{\nl= loc\n}\nif l> 0{\nfor k:=0;k<l;k++{\nif buffer[k]=='\\t'{\nfmt.Print(\" \")\n}else{\nfmt.Printf(\"%c\",buffer[k])// print the characters already read \n}\n}\n\nfmt.Println()\nfmt.Printf(\"%*c\",l,' ')\n}\nfmt.Println(string(buffer[l:]))\nif len(buffer)> 0&&buffer[len(buffer)-1]=='|'{\nfmt.Print(\"|\")/* end of \\GO/ text in section names */\n}\nfmt.Print(\" \")/* to separate the message from future asterisks */\n}\n\n\n\n/*:71*/\n\n\n//line gocommon.w:1065\n\n}\nos.Stdout.Sync()\nmark_error()\n}", "func display(w http.ResponseWriter, tmpl string, data interface{}) {\n\terr := templates.ExecuteTemplate(w, tmpl, data)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func getErrorText(err error, message string) string {\n\tfor _, err := range err.(validator.ValidationErrors) {\n\t\tmessage += \"Field \" + err.Field() + \" with value \" + fmt.Sprintf(\"%v\", err.Value()) + \" failed \" + err.Tag() + \" tag validation. \"\n\t}\n\treturn message\n}", "func printBugsStats(frontEndBugs int, backEndBugs int, totalBugs int) {\r\n\tfmt.Println(\"Number of Frontend bugs: \", frontEndBugs)\r\n\tfmt.Println(\"Number of Backend bugs: \", backEndBugs)\r\n\tfmt.Println(\"Number of bugs yet to be classified: \", totalBugs-(frontEndBugs+backEndBugs))\r\n}", "func (quiz *quiz) report() {\n\tfmt.Printf(\n\t\t\"You answered %v questions out of a total of %v and got %v correct\",\n\t\tquiz.answered,\n\t\tlen(quiz.questions),\n\t\tquiz.answeredCorrectly,\n\t)\n}", "func check(err error, sType, sMessage string) {\n\tif err != nil {\n\t\tswitch sType {\n\t\tcase \"fatal\":\n\t\t\tlog.Fatalln(sMessage, err)\n\t\tdefault:\n\t\t\tlog.Println(sMessage, err)\n\t\t}\n\t}\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 ShowStack(err error) string {\n\treturn NewErr(err, 1).(*Error).ErrorWithStack()\n}", "func check_err(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func Details(err error) string {\n\treturn strings.Join(GetTrace(err), \"\\n\")\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 whicherrs(s selection, args []string) {\n\tfmt.Println(runWithStdin(s.archive(), \"guru\", \"-modified\", \"-scope\", scope(args), \"whicherrs\", s.pos()))\n}", "func write_std_error(err interface{}, stack string){\n\tif StdErr==true{\n\t\tfmt.Println(\"runtime error,panic:%v,stack:%s\", err, stack)\n\t}\n}", "func checkForErrors(err error) {\n\tif err != nil {\n\t\tpc, fn, line, _ := runtime.Caller(1)\n\t\tmsg := fmt.Sprintf(\"[Error] in %s[%s:%d] %v\",\n\t\t\truntime.FuncForPC(pc).Name(), fn, line, err)\n\t\tlog.Fatal(msg)\n\t}\n}", "func missingParametersError() {\n\n\tfmt.Println(\"ERROR: Parameters missing!\")\n\tfmt.Println(\"HELP:\")\n\tfmt.Println(\"decrypt-attack -i <input file>\")\n}", "func printMessageError() {\n\tfmt.Println()\n\tfmt.Println(\"Please enter a message!\")\n\tfmt.Println()\n}", "func displayQueueResponse(apiResp QueueApiResponse) {\n\n\tif apiResp.Status == apiSuccess {\n\n\t\tvar display = template.Must(\n\t\t\ttemplate.New(\"QueueStatusSuccess\").Funcs(template.FuncMap{\"convertUnixTime\": convertUnixTime}).Parse(queueStatusTempl))\n\n\t\tif err := display.Execute(os.Stdout, apiResp); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t} else {\n\t\tvar display = template.Must(template.New(\"ApiError\").Parse(apiErrorTempl))\n\n\t\tif err := display.Execute(os.Stdout, apiResp); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n}", "func printStackTraceIfPresent(args ...interface{}) {\n\tfor i := 0; i < len(args); i += 1 {\n\t\tswitch value := args[i].(type) {\n\t\t// If an error type and has a stacktrace then log it.\n\t\tcase error:\n\t\t\tif syncWriter != nil {\n\t\t\t\tif err, ok := value.(stackTracer); ok {\n\t\t\t\t\tfmt.Fprintf(syncWriter, \"%+v\\n\", err)\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\t// Ignore all other types\n\t\t}\n\t}\n}", "func recovery() {\n\n\tif r := recover(); r != nil {fmt.Println(\"some error has occured_______________________________________________\",r)}\n}" ]
[ "0.60609037", "0.575154", "0.57506365", "0.56893677", "0.5634726", "0.5575038", "0.5571827", "0.55591273", "0.5552392", "0.55358213", "0.55271757", "0.5439839", "0.5435654", "0.54065764", "0.5380266", "0.53692853", "0.5319684", "0.52985895", "0.5293844", "0.5269809", "0.52550316", "0.5217281", "0.5215789", "0.5209622", "0.51856405", "0.51777893", "0.517663", "0.51602453", "0.51517886", "0.5142912", "0.5141715", "0.5135464", "0.5115282", "0.5106524", "0.5106524", "0.5106524", "0.5097232", "0.50954515", "0.5080427", "0.5055589", "0.5053058", "0.50486016", "0.50479466", "0.5032077", "0.5032077", "0.5031339", "0.50246865", "0.501996", "0.50151795", "0.5014363", "0.50093484", "0.50069255", "0.50002337", "0.49949852", "0.49940667", "0.49858525", "0.4982869", "0.49724376", "0.49657872", "0.49604493", "0.49546757", "0.49542305", "0.49522647", "0.4946777", "0.4946777", "0.49404716", "0.49380538", "0.49373415", "0.49366832", "0.493298", "0.49186492", "0.49183849", "0.49117514", "0.49096137", "0.49082652", "0.4905251", "0.4903353", "0.49013394", "0.4900683", "0.48988506", "0.4898749", "0.4898276", "0.4896972", "0.489613", "0.48924863", "0.4888858", "0.48865822", "0.48830724", "0.48825803", "0.4880793", "0.4875762", "0.48676175", "0.48658198", "0.48505205", "0.48502627", "0.4832322", "0.48271236", "0.48253208", "0.48233494", "0.48139596", "0.48064053" ]
0.0
-1
GetMetrics gets the metrics preparing for flushing and reset the state.
func (p *StatsDParser) GetMetrics() pdata.Metrics { metrics := pdata.NewMetrics() rm := metrics.ResourceMetrics().AppendEmpty() for _, metric := range p.gauges { rm.InstrumentationLibraryMetrics().Append(metric) } for _, metric := range p.counters { rm.InstrumentationLibraryMetrics().Append(metric) } for _, metric := range p.timersAndDistributions { rm.InstrumentationLibraryMetrics().Append(metric) } for _, summaryMetric := range p.summaries { metrics.ResourceMetrics().At(0).InstrumentationLibraryMetrics().Append(buildSummaryMetric(summaryMetric)) } p.gauges = make(map[statsDMetricdescription]pdata.InstrumentationLibraryMetrics) p.counters = make(map[statsDMetricdescription]pdata.InstrumentationLibraryMetrics) p.timersAndDistributions = make([]pdata.InstrumentationLibraryMetrics, 0) p.summaries = make(map[statsDMetricdescription]summaryMetric) return metrics }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetMetrics() []prometheus.Collector {\n\treturn []prometheus.Collector{\n\t\treqCounter,\n\t\treqDuration,\n\t\tconnDuration,\n\t}\n}", "func (c *PromMetricsClient) GetMetrics() ([]*Metric, error) {\n\tres, err := http.Get(c.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, ErrUnexpectedHTTPStatusCode\n\t}\n\n\tdefer res.Body.Close()\n\treturn Parse(res.Body)\n}", "func (ds *dockServer) GetMetrics(context.Context, *pb.GetMetricsOpts) (*pb.GenericResponse, error) {\n\treturn nil, &model.NotImplementError{\"method GetMetrics has not been implemented yet\"}\n}", "func (_e *MockDataCoord_Expecter) GetMetrics(ctx interface{}, req interface{}) *MockDataCoord_GetMetrics_Call {\n\treturn &MockDataCoord_GetMetrics_Call{Call: _e.mock.On(\"GetMetrics\", ctx, req)}\n}", "func (c *Client) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treq = typeutil.Clone(req)\n\tcommonpbutil.UpdateMsgBase(\n\t\treq.GetBase(),\n\t\tcommonpbutil.FillMsgBaseFromClient(paramtable.GetNodeID()))\n\treturn wrapGrpcCall(ctx, c, func(client querypb.QueryNodeClient) (*milvuspb.GetMetricsResponse, error) {\n\t\treturn client.GetMetrics(ctx, req)\n\t})\n}", "func (_e *MockQueryCoord_Expecter) GetMetrics(ctx interface{}, req interface{}) *MockQueryCoord_GetMetrics_Call {\n\treturn &MockQueryCoord_GetMetrics_Call{Call: _e.mock.On(\"GetMetrics\", ctx, req)}\n}", "func (s *Server) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treturn s.querynode.GetMetrics(ctx, req)\n}", "func (c *Client) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treq = typeutil.Clone(req)\n\tcommonpbutil.UpdateMsgBase(\n\t\treq.GetBase(),\n\t\tcommonpbutil.FillMsgBaseFromClient(paramtable.GetNodeID(), commonpbutil.WithTargetID(c.grpcClient.GetNodeID())),\n\t)\n\treturn wrapGrpcCall(ctx, c, func(client querypb.QueryCoordClient) (*milvuspb.GetMetricsResponse, error) {\n\t\treturn client.GetMetrics(ctx, req)\n\t})\n}", "func (s *rabbitMQScaler) GetMetrics(ctx context.Context, metricName string, metricSelector labels.Selector) ([]external_metrics.ExternalMetricValue, error) {\n\tmessages, publishRate, err := s.getQueueStatus()\n\tif err != nil {\n\t\treturn []external_metrics.ExternalMetricValue{}, fmt.Errorf(\"error inspecting rabbitMQ: %s\", err)\n\t}\n\n\tvar metricValue resource.Quantity\n\tif s.metadata.mode == rabbitModeQueueLength {\n\t\tmetricValue = *resource.NewQuantity(int64(messages), resource.DecimalSI)\n\t} else {\n\t\tmetricValue = *resource.NewMilliQuantity(int64(publishRate*1000), resource.DecimalSI)\n\t}\n\n\tmetric := external_metrics.ExternalMetricValue{\n\t\tMetricName: metricName,\n\t\tValue: metricValue,\n\t\tTimestamp: metav1.Now(),\n\t}\n\n\treturn append([]external_metrics.ExternalMetricValue{}, metric), nil\n}", "func (s *azureServiceBusScaler) GetMetrics(ctx context.Context, metricName string, metricSelector labels.Selector) ([]external_metrics.ExternalMetricValue, error) {\n\tqueuelen, err := s.GetAzureServiceBusLength(ctx)\n\n\tif err != nil {\n\t\tazureServiceBusLog.Error(err, \"error getting service bus entity length\")\n\t\treturn []external_metrics.ExternalMetricValue{}, err\n\t}\n\n\tmetric := external_metrics.ExternalMetricValue{\n\t\tMetricName: metricName,\n\t\tValue: *resource.NewQuantity(int64(queuelen), resource.DecimalSI),\n\t\tTimestamp: metav1.Now(),\n\t}\n\n\treturn append([]external_metrics.ExternalMetricValue{}, metric), nil\n}", "func (m *MetricsCacheType) GetMetrics() ([]string, bool) {\n\tif m.IsAvailable() && !m.TimedOut() {\n\t\treturn m.metrics, true\n\t}\n\n\tif !m.updating {\n\t\tgo m.RefreshCache()\n\t}\n\treturn nil, false\n}", "func (session *Session) PerformanceGetMetrics() ([]Metric, error) {\n\tmsg, err := session.blockingSend(\"Performance.getMetrics\", &Params{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm := make([]Metric, 0)\n\tunmarshal(msg[\"metrics\"], &m)\n\treturn m, nil\n}", "func (c *standardComputation) GetMetrics() []string {\n\treturn c.fields\n}", "func (in *MonitoringDashboardChart) GetMetrics() []MonitoringDashboardMetric {\n\tif len(in.Metrics) == 0 {\n\t\treturn []MonitoringDashboardMetric{\n\t\t\t{\n\t\t\t\tMetricName: in.MetricName,\n\t\t\t\tDisplayName: in.Name,\n\t\t\t},\n\t\t}\n\t}\n\treturn in.Metrics\n}", "func (in *MonitoringDashboardChart) GetMetrics() []MonitoringDashboardMetric {\n\tif len(in.Metrics) == 0 {\n\t\treturn []MonitoringDashboardMetric{\n\t\t\t{\n\t\t\t\tMetricName: in.MetricName,\n\t\t\t\tDisplayName: in.Name,\n\t\t\t},\n\t\t}\n\t}\n\treturn in.Metrics\n}", "func (m *MockTaskManager) GetMetrics() handler.Metric {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(handler.Metric)\n\treturn ret0\n}", "func (c *ScalingScheduleCollector) GetMetrics() ([]CollectedMetric, error) {\n\tscalingScheduleInterface, exists, err := c.store.GetByKey(fmt.Sprintf(\"%s/%s\", c.objectReference.Namespace, c.objectReference.Name))\n\tif !exists {\n\t\treturn nil, ErrScalingScheduleNotFound\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected error retrieving the ScalingSchedule: %s\", err.Error())\n\t}\n\n\tscalingSchedule, ok := scalingScheduleInterface.(*v1.ScalingSchedule)\n\tif !ok {\n\t\treturn nil, ErrNotScalingScheduleFound\n\t}\n\treturn calculateMetrics(scalingSchedule.Spec, c.defaultScalingWindow, c.defaultTimeZone, c.rampSteps, c.now(), c.objectReference, c.metric)\n}", "func (o *DeviceMetricsAllOf) GetMetrics() []DeviceMetric {\n\tif o == nil || o.Metrics == nil {\n\t\tvar ret []DeviceMetric\n\t\treturn ret\n\t}\n\treturn *o.Metrics\n}", "func (a *Client) GetMetrics(params *GetMetricsParams, authInfo runtime.ClientAuthInfoWriter) (*GetMetricsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetMetricsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetMetrics\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/cdn/v1/stacks/{stack_id}/metrics\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetMetricsReader{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.(*GetMetricsOK), nil\n\n}", "func getMetrics() []Metric {\n\tms := make([]Metric, 0)\n\treturn append(ms, &SimpleEapMetric{})\n}", "func (o *MetricsAllOf) GetMetrics() []Metric {\n\tif o == nil || o.Metrics == nil {\n\t\tvar ret []Metric\n\t\treturn ret\n\t}\n\treturn *o.Metrics\n}", "func (c *CAdvisor) GetMetrics() (*Metrics, error) {\n\tlog.Printf(\"[DEBUG] [cadvisor] Get metrics\")\n\tnodeSpec, err := c.Client.MachineInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive machine info : %#v\",\n\t\tnodeSpec)\n\tnodeInfo, err := c.Client.ContainerInfo(\"/\", c.Query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive container info : %#v\",\n\t\tnodeInfo)\n\tcontainersInfo, err := c.Client.AllDockerContainers(c.Query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive all docker containers : %#v\",\n\t\tcontainersInfo)\n\tmetrics := &Metrics{\n\t\tNodeSpec: nodeSpec,\n\t\tNodeInfo: nodeInfo,\n\t\tContainersInfo: containersInfo,\n\t}\n\t//log.Printf(\"[INFO] [cadvisor] Metrics: %#v\", metrics)\n\treturn metrics, nil\n}", "func getMetrics(_ string) []string {\n\tvar (\n\t\terr error\n\t\tsession *Session\n\t\tclient orchestrator.OrchestratorClient\n\t\tres *orchestrator.ListMetricsResponse\n\t)\n\n\tif session, err = ContinueSession(); err != nil {\n\t\tfmt.Printf(\"Error while retrieving the session. Please re-authenticate.\\n\")\n\t\treturn nil\n\t}\n\n\tclient = orchestrator.NewOrchestratorClient(session)\n\n\tif res, err = client.ListMetrics(context.Background(), &orchestrator.ListMetricsRequest{}); err != nil {\n\t\treturn []string{}\n\t}\n\n\tvar metrics []string\n\tfor _, v := range res.Metrics {\n\t\tmetrics = append(metrics, fmt.Sprintf(\"%s\\t%s: %s\", v.Id, v.Name, v.Description))\n\t}\n\n\treturn metrics\n}", "func (e Entry) GetMetrics(timeout time.Duration, h heimdall.Doer, debug bool) (Metrics, error) {\n\tvar m Metrics\n\n\t// Let's set the stuff we know already.\n\tm.Address = e.Address\n\tm.Regexp = e.Regexp\n\tm.CapturedAt = time.Now().UTC()\n\n\t// Set a timeout.\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\t// Setup the request.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, e.Address, nil)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\tif debug {\n\t\tfmt.Printf(\"%#v\\n\", req)\n\t}\n\n\t// Let's do the request.\n\tstart := time.Now()\n\tres, err := h.Do(req)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\t// We don't need the body unless we've got a regexp.\n\tif e.Regexp != \"\" {\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\t// Do the regexp here and assign the value.\n\t\tmatch, _ := regexp.MatchString(e.Regexp, string(body))\n\t\tm.RegexpStatus = match\n\t}\n\ttook := time.Since(start)\n\n\t// Set the last few values\n\tm.StatusCode = res.StatusCode\n\tm.ResponseTime = took\n\n\tif debug {\n\t\tfmt.Printf(\"Result: %#v\\n\", res)\n\t\tfmt.Printf(\"Time Taken: %s\\n\", took)\n\t\tfmt.Printf(\"Metrics: %#v\\n\", m)\n\t}\n\n\tif ctx.Err() != nil {\n\t\treturn m, errors.New(\"context deadline exceeded\")\n\t}\n\treturn m, nil\n}", "func (s *GrpcServer) GetMetrics(ctx context.Context, in *api.ScaledObjectRef) (*v1beta1.ExternalMetricValueList, error) {\n\tv1beta1ExtMetrics := &v1beta1.ExternalMetricValueList{}\n\textMetrics, err := (*s.scalerHandler).GetScaledObjectMetrics(ctx, in.Name, in.Namespace, in.MetricName)\n\tif err != nil {\n\t\treturn v1beta1ExtMetrics, fmt.Errorf(\"error when getting metric values %w\", err)\n\t}\n\n\terr = v1beta1.Convert_external_metrics_ExternalMetricValueList_To_v1beta1_ExternalMetricValueList(extMetrics, v1beta1ExtMetrics, nil)\n\tif err != nil {\n\t\treturn v1beta1ExtMetrics, fmt.Errorf(\"error when converting metric values %w\", err)\n\t}\n\n\tlog.V(1).WithValues(\"scaledObjectName\", in.Name, \"scaledObjectNamespace\", in.Namespace, \"metrics\", v1beta1ExtMetrics).Info(\"Providing metrics\")\n\n\treturn v1beta1ExtMetrics, nil\n}", "func (s *postgreSQLScaler) GetMetrics(ctx context.Context, metricName string, metricSelector labels.Selector) ([]external_metrics.ExternalMetricValue, error) {\n\tnum, err := s.getActiveNumber(ctx)\n\tif err != nil {\n\t\treturn []external_metrics.ExternalMetricValue{}, fmt.Errorf(\"error inspecting postgreSQL: %s\", err)\n\t}\n\n\tmetric := GenerateMetricInMili(metricName, num)\n\n\treturn append([]external_metrics.ExternalMetricValue{}, metric), nil\n}", "func TestGetMetrics(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\t// Make a first call to a resource to make metrics middleware record some\n\t// stats. Prior to that, no stats will have been saved.\n\tresp, _ := client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Equalf(t, \"\", readBody(t, resp), \"expected first /metrics call to be empty\")\n\n\tresp, _ = client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Containsf(t, readBody(t, resp), `total_requests{method=\"GET\",path=\"/metrics\",statusCode=\"200\"} 1`, \"missing expected metric\")\n}", "func (o *MonitorSearchResult) GetMetrics() []string {\n\tif o == nil || o.Metrics == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.Metrics\n}", "func GetMetrics(c *providers.Provider) (providers.ClowderProvider, error) {\n\tmetricsMode := c.Env.Spec.Providers.Metrics.Mode\n\tswitch metricsMode {\n\tcase \"none\", \"\":\n\t\treturn NewNoneMetricsProvider(c)\n\tcase \"operator\":\n\t\treturn NewMetricsProvider(c)\n\tcase \"app-interface\":\n\t\treturn NewAppInterfaceMetrics(c)\n\tdefault:\n\t\terrStr := fmt.Sprintf(\"No matching metrics mode for %s\", metricsMode)\n\t\treturn nil, errors.New(errStr)\n\t}\n}", "func (client DDMetricsClient) GetMetrics() ([]ServiceStatisticsFromDD, error) {\n\n\tinfo, err := client.GetInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmetrics := []ServiceStatisticsFromDD{}\n\tfor _, s := range info.Head.Services {\n\t\tstatsURL := client.endpoint\n\t\tstatsURL.Path = fmt.Sprintf(\"/services/%v\", s.Name)\n\n\t\tresp, err := client.httpClient.Get(statsURL.String())\n\t\tstats := ServiceStatisticsFromDD{}\n\t\terr = json.NewDecoder(resp.Body).Decode(&stats)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmetrics = append(metrics, stats)\n\t}\n\n\treturn metrics, nil\n}", "func (y *YarnMetrics) getMetrics() *NMMetrics {\n\tjmxResp := &JmxResp{}\n\terr := y.requestUrl(metricsSuffix, jmxResp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"request nodemanager metrics err: %v\", err)\n\t\treturn nil\n\t}\n\tif len(jmxResp.Beans) == 0 {\n\t\tklog.V(5).Infof(\"request nodemanager metrics, empty beans\")\n\t\treturn nil\n\t}\n\treturn &jmxResp.Beans[0]\n}", "func (mr *MockTaskManagerMockRecorder) GetMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetMetrics\", reflect.TypeOf((*MockTaskManager)(nil).GetMetrics))\n}", "func ResetMetrics() {\n\tdroppedBatchVec.Reset()\n\tdroppedBytesVec.Reset()\n\trotateVec.Reset()\n\tputVec.Reset()\n\tgetVec.Reset()\n\tputBytesVec.Reset()\n\twakeupVec.Reset()\n\tgetBytesVec.Reset()\n\tcapVec.Reset()\n\tbatchSizeVec.Reset()\n\tmaxDataVec.Reset()\n\tsizeVec.Reset()\n\tdatafilesVec.Reset()\n\tgetLatencyVec.Reset()\n\tputLatencyVec.Reset()\n}", "func (r *Client) GetMetrics() metrics.MapMetricsOptions {\n\t_ = r.Service.GetMetrics()\n\tr.Metrics[ProviderName+\"_status\"] = &metrics.MetricOptions{\n\t\tMetric: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: ProviderName + \"_status\",\n\t\t\t\tHelp: ProviderName + \" status link to \" + utils.RedactedDSN(r.cfg.DSN),\n\t\t\t}),\n\t\tMetricFunc: func(m interface{}) {\n\t\t\t(m.(prometheus.Gauge)).Set(0)\n\t\t\t_, err := r.Conn.Ping(r.ctx).Result()\n\t\t\tif err == nil {\n\t\t\t\t(m.(prometheus.Gauge)).Set(1)\n\t\t\t}\n\t\t},\n\t}\n\treturn r.Metrics\n}", "func (k *KafkaConsumer) GetMetrics() *Metrics {\n\treturn k.metrics\n}", "func (c *Provider) GetMetrics() *metrics.ClientMetrics {\n\treturn c.clientMetrics\n}", "func (_class PIFClass) GetMetrics(sessionID SessionRef, self PIFRef) (_retval PIFMetricsRef, _err error) {\n\t_method := \"PIF.get_metrics\"\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 = convertPIFMetricsRefToGo(_method + \" -> \", _result.Value)\n\treturn\n}", "func (a *Client) GetMetrics(params *GetMetricsParams, opts ...ClientOption) (*GetMetricsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetMetricsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"GetMetrics\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/metrics/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetMetricsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetMetricsOK)\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 GetMetrics: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (e *Exporter) GetMetricsList() map[string]*QueryInstance {\n\tif e.allMetricMap == nil {\n\t\treturn nil\n\t}\n\treturn e.allMetricMap\n}", "func (state *State) GetDeviceMetrics() *metrics.DeviceMetric {\n\treturn state.deviceInfo.DeviceMetrics\n}", "func (h *singleLhcNodeHarness) getMetrics() *metrics {\n\treturn &metrics{\n\t\ttimeSinceLastCommitMillis: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.TimeSinceLastCommit.Millis\").(*metric.Histogram),\n\t\ttimeSinceLastElectionMillis: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.TimeSinceLastElection.Millis\").(*metric.Histogram),\n\t\tcurrentElectionCount: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.CurrentElection.Number\").(*metric.Gauge),\n\t\tcurrentLeaderMemberId: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.CurrentLeaderMemberId.Number\").(*metric.Text),\n\t\tlastCommittedTime: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.LastCommitted.TimeNano\").(*metric.Gauge),\n\t}\n}", "func (c *SkipperCollector) GetMetrics() ([]CollectedMetric, error) {\n\tcollector, err := c.getCollector(context.TODO())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalues, err := collector.GetMetrics()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(values) != 1 {\n\t\treturn nil, fmt.Errorf(\"expected to only get one metric value, got %d\", len(values))\n\t}\n\n\tvalue := values[0]\n\n\t// For Kubernetes <v1.14 we have to fall back to manual average\n\tif c.config.MetricSpec.Object.Target.AverageValue == nil {\n\t\t// get current replicas for the targeted scale object. This is used to\n\t\t// calculate an average metric instead of total.\n\t\t// targetAverageValue will be available in Kubernetes v1.12\n\t\t// https://github.com/kubernetes/kubernetes/pull/64097\n\t\treplicas, err := targetRefReplicas(c.client, c.hpa)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif replicas < 1 {\n\t\t\treturn nil, fmt.Errorf(\"unable to get average value for %d replicas\", replicas)\n\t\t}\n\n\t\tavgValue := float64(value.Custom.Value.MilliValue()) / float64(replicas)\n\t\tvalue.Custom.Value = *resource.NewMilliQuantity(int64(avgValue), resource.DecimalSI)\n\t}\n\n\treturn []CollectedMetric{value}, nil\n}", "func (c *ClusterScalingScheduleCollector) GetMetrics() ([]CollectedMetric, error) {\n\tclusterScalingScheduleInterface, exists, err := c.store.GetByKey(c.objectReference.Name)\n\tif !exists {\n\t\treturn nil, ErrClusterScalingScheduleNotFound\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected error retrieving the ClusterScalingSchedule: %s\", err.Error())\n\t}\n\n\t// The [cache.Store][0] returns the v1.ClusterScalingSchedule items as\n\t// a v1.ScalingSchedule when it first lists it. Once the objects are\n\t// updated/patched it asserts it correctly to the\n\t// v1.ClusterScalingSchedule type. It means we have to handle both\n\t// cases.\n\t// TODO(jonathanbeber): Identify why it happens and fix in the upstream.\n\t//\n\t// [0]: https://github.com/kubernetes/client-go/blob/v0.21.1/tools/cache/Store.go#L132-L140\n\tvar clusterScalingSchedule v1.ClusterScalingSchedule\n\tscalingSchedule, ok := clusterScalingScheduleInterface.(*v1.ScalingSchedule)\n\tif !ok {\n\t\tcss, ok := clusterScalingScheduleInterface.(*v1.ClusterScalingSchedule)\n\t\tif !ok {\n\t\t\treturn nil, ErrNotClusterScalingScheduleFound\n\t\t}\n\t\tclusterScalingSchedule = *css\n\t} else {\n\t\tclusterScalingSchedule = v1.ClusterScalingSchedule(*scalingSchedule)\n\t}\n\n\treturn calculateMetrics(clusterScalingSchedule.Spec, c.defaultScalingWindow, c.defaultTimeZone, c.rampSteps, c.now(), c.objectReference, c.metric)\n}", "func (mr *MockClientMockRecorder) GetMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetMetrics\", reflect.TypeOf((*MockClient)(nil).GetMetrics))\n}", "func (h *testMetricsHandler) GetRawMetrics(apiClient kubernetes.Interface, namespace, functionName string) ([]byte, error) {\n\tsvc, err := apiClient.CoreV1().Services(namespace).Get(functionName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tb, err := http.Get(svc.SelfLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer b.Body.Close()\n\treturn ioutil.ReadAll(b.Body)\n}", "func (m *MockClient) GetMetrics() *metrics.ClientMetrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(*metrics.ClientMetrics)\n\treturn ret0\n}", "func NewMetrics() *Metrics {\n\tm := &Metrics{}\n\tm.Reset()\n\treturn m\n}", "func (w *HotCache) ResetMetrics() {\n\thotCacheStatusGauge.Reset()\n}", "func (ms *Store) ClearMetrics() {\n\tms.Lock()\n\tdefer ms.Unlock()\n\tms.Metrics = make([]*Metric, 0)\n}", "func (n *RouterNode) GatherMetrics() {\n\tn.Lock()\n\tdefer n.Unlock()\n\n\tlevel.Debug(n.logger).Log(\n\t\t\"msg\", \"GatherMetrics() locked\",\n\t)\n\n\tif time.Now().Unix() < n.nextCollectionTicker {\n\t\treturn\n\t}\n\tstart := time.Now()\n\tif len(n.metrics) > 0 {\n\t\tn.metrics = n.metrics[:0]\n\t\tlevel.Debug(n.logger).Log(\n\t\t\t\"msg\", \"GatherMetrics() cleared metrics\",\n\t\t)\n\t}\n\tupValue := 1\n\n\t// What is RouterID and AS number of this GoBGP server?\n\tserver, err := n.client.GetBgp(context.Background(), &gobgpapi.GetBgpRequest{})\n\tif err != nil {\n\t\tn.IncrementErrorCounter()\n\t\tlevel.Error(n.logger).Log(\n\t\t\t\"msg\", \"failed query gobgp server\",\n\t\t\t\"error\", err.Error(),\n\t\t)\n\t\tif IsConnectionError(err) {\n\t\t\tn.connected = false\n\t\t\tupValue = 0\n\t\t}\n\t} else {\n\t\tn.routerID = server.Global.RouterId\n\t\tn.localAS = server.Global.Asn\n\t\tlevel.Debug(n.logger).Log(\n\t\t\t\"msg\", \"router info\",\n\t\t\t\"router_id\", n.routerID,\n\t\t\t\"local_asn\", n.localAS,\n\t\t)\n\t\tn.connected = true\n\t}\n\n\tif n.connected {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(2)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tn.GetRibCounters()\n\t\t}()\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tn.GetPeers()\n\t\t}()\n\t\twg.Wait()\n\n\t}\n\n\t// Generic Metrics\n\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\trouterUp,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(upValue),\n\t))\n\n\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\trouterErrors,\n\t\tprometheus.CounterValue,\n\t\tfloat64(n.errors),\n\t))\n\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\trouterNextScrape,\n\t\tprometheus.CounterValue,\n\t\tfloat64(n.nextCollectionTicker),\n\t))\n\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\trouterScrapeTime,\n\t\tprometheus.GaugeValue,\n\t\ttime.Since(start).Seconds(),\n\t))\n\n\t// Router ID and ASN\n\tif n.routerID != \"\" {\n\t\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\t\trouterID,\n\t\t\tprometheus.GaugeValue,\n\t\t\t1,\n\t\t\tn.routerID,\n\t\t))\n\t}\n\tif n.localAS > 0 {\n\t\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\t\trouterLocalAS,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(n.localAS),\n\t\t))\n\t}\n\n\tn.nextCollectionTicker = time.Now().Add(time.Duration(n.pollInterval) * time.Second).Unix()\n\n\tif upValue > 0 {\n\t\tn.result = \"success\"\n\t} else {\n\t\tn.result = \"failure\"\n\t}\n\tn.timestamp = time.Now().Format(time.RFC3339)\n\n\tlevel.Debug(n.logger).Log(\n\t\t\"msg\", \"GatherMetrics() returns\",\n\t)\n}", "func GetEncodedMetrics(config libkbfs.Config) func(context.Context) ([]byte, time.Time, error) {\n\treturn func(context.Context) ([]byte, time.Time, error) {\n\t\tif registry := config.MetricsRegistry(); registry != nil {\n\t\t\tb := bytes.NewBuffer(nil)\n\t\t\tmetricsutil.WriteMetrics(registry, b)\n\t\t\treturn b.Bytes(), time.Time{}, nil\n\t\t}\n\t\treturn []byte(\"Metrics have been turned off.\\n\"), time.Time{}, nil\n\t}\n}", "func scrapeMetrics(ctx context.Context, req httpGetter) (pbMetricMap, error) {\n\tbody, err := httpGetBodyRetry(ctx, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparser := expfmt.TextParser{}\n\treader := strings.NewReader(string(body))\n\tresult, err := parser.TextToMetricFamilies(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pbMetricMap(result), nil\n}", "func (state *State) GetAppMetrics() []*metrics.AppMetric {\n\treturn state.deviceInfo.AppMetrics\n}", "func (e *Endpoint) ReadMetrics(em *EndpointMetrics) {\n\te.metrics.Lock()\n\tdefer e.metrics.Unlock()\n\n\t*em = e.metrics.EndpointMetrics\n\t// Map still need to copied in a threadsafe manner.\n\tem.Statuses = make(map[string]int)\n\tfor k, v := range e.metrics.Statuses {\n\t\tem.Statuses[k] = v\n\t}\n}", "func (m *MockProviders) GetMetrics() *metrics.ClientMetrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(*metrics.ClientMetrics)\n\treturn ret0\n}", "func NewGetMetricsParams() *GetMetricsParams {\n\tvar (\n\t\tgranularityDefault = string(\"AUTO\")\n\t\tgroupByDefault = string(\"NONE\")\n\t\tsiteTypeFilterDefault = string(\"ALL\")\n\t)\n\treturn &GetMetricsParams{\n\t\tGranularity: &granularityDefault,\n\t\tGroupBy: &groupByDefault,\n\t\tSiteTypeFilter: &siteTypeFilterDefault,\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func FetchMetrics(ctx context.Context) {\n\tclient, err := docker.NewEnvClient()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tdefer client.Close()\n\n\tcontainers, err := client.ContainerList(ctx, types.ContainerListOptions{All: true})\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"err\": err}).Error(\"Error on fetching containers list\")\n\t\treturn\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(containers))\n\n\tfor _, container := range containers {\n\t\tgo func(container types.Container) {\n\t\t\tdefer wg.Done()\n\n\t\t\tif containerMetrics, err := fetchContainerMetrics(ctx, client, container); err != nil {\n\t\t\t\tlog.WithFields(log.Fields{\"err\": err, \"containerId\": container.ID, \"containerName\": container.Names[0][1:]}).Error(\"Error on fetching metrics\")\n\t\t\t} else if containerMetrics != nil {\n\t\t\t\tcontainerMetrics.ExportToRegistry()\n\t\t\t}\n\t\t}(container)\n\t}\n\n\twg.Wait()\n\n\treturn\n}", "func GetMetrics(addr string, pod string) (float64, error) {\n\tprom, err := api.NewClient(api.Config{Address:addr})\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\tv1api := v1.NewAPI(prom)\n\n\tresult, warnings, err := v1api.Query(context.Background(), fmt.Sprintf(\"avg(container_memory_rss{ pod_name=\\\"%s\\\", image=~\\\"tarun.*\\\"}/1024/1024)\", pod), time.Now())\n\tif err != nil {\n\t\tfmt.Printf(\"Error querying Prometheus: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tif len(warnings) > 0 {\n\t\tfmt.Printf(\"Warnings: %v\\n\", warnings)\n\t}\n\tfmt.Printf(\"\\nValue of Query %s:%v\",fmt.Sprintf(\"avg(container_memory_rss{ pod_name=\\\"%s\\\", image=~\\\"tarun.*\\\"}/1024/1024)\", pod), result)\n\n\tif len(result.(model.Vector)) >= 1 {\n\t\treturn float64(result.(model.Vector)[0].Value), nil\n\t}\n\n\treturn 0, errors.New(fmt.Sprintf(\"Zero metrics found for \", pod))\n}", "func (c *metricMetadataAPI) GetAllMetrics(context metadata.Context) ([]api.MetricKey, error) {\n\treturn c.metricMetadataAPI.GetAllMetrics(context)\n}", "func getMetricsConfig(cfg plugin.Config) (configReader.Metrics, error) {\n\tsetFilePath, err := cfg.GetString(setFileConfigVar)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfigs, err := configReader.GetMetricsConfig(setFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn configs, nil\n}", "func NewMetrics(scope tally.Scope) *Metrics {\n\tsuccessScope := scope.Tagged(map[string]string{\"result\": \"success\"})\n\tfailScope := scope.Tagged(map[string]string{\"result\": \"fail\"})\n\ttimeoutScope := scope.Tagged(map[string]string{\"result\": \"timeout\"})\n\tapiScope := scope.SubScope(\"api\")\n\tserverScope := scope.SubScope(\"server\")\n\tplacement := scope.SubScope(\"placement\")\n\trecovery := scope.SubScope(\"recovery\")\n\n\treturn &Metrics{\n\t\tAPIEnqueueGangs: apiScope.Counter(\"enqueue_gangs\"),\n\t\tEnqueueGangSuccess: successScope.Counter(\"enqueue_gang\"),\n\t\tEnqueueGangFail: failScope.Counter(\"enqueue_gang\"),\n\n\t\tAPIDequeueGangs: apiScope.Counter(\"dequeue_gangs\"),\n\t\tDequeueGangSuccess: successScope.Counter(\"dequeue_gangs\"),\n\t\tDequeueGangTimeout: timeoutScope.Counter(\"dequeue_gangs\"),\n\n\t\tAPIGetPreemptibleTasks: apiScope.Counter(\"get_preemptible_tasks\"),\n\t\tGetPreemptibleTasksSuccess: successScope.Counter(\"get_preemptible_tasks\"),\n\t\tGetPreemptibleTasksTimeout: timeoutScope.Counter(\"get_preemptible_tasks\"),\n\n\t\tAPISetPlacements: apiScope.Counter(\"set_placements\"),\n\t\tSetPlacementSuccess: successScope.Counter(\"set_placements\"),\n\t\tSetPlacementFail: failScope.Counter(\"set_placements\"),\n\n\t\tAPIGetPlacements: apiScope.Counter(\"get_placements\"),\n\t\tGetPlacementSuccess: successScope.Counter(\"get_placements\"),\n\t\tGetPlacementFail: failScope.Counter(\"get_placements\"),\n\n\t\tAPILaunchedTasks: apiScope.Counter(\"launched_tasks\"),\n\n\t\tRecoverySuccess: successScope.Counter(\"recovery\"),\n\t\tRecoveryFail: failScope.Counter(\"recovery\"),\n\t\tRecoveryRunningSuccessCount: successScope.Counter(\"task_count\"),\n\t\tRecoveryRunningFailCount: failScope.Counter(\"task_count\"),\n\t\tRecoveryEnqueueFailedCount: failScope.Counter(\"enqueue_task_count\"),\n\t\tRecoveryEnqueueSuccessCount: successScope.Counter(\"enqueue_task_count\"),\n\t\tRecoveryTimer: recovery.Timer(\"running_tasks\"),\n\n\t\tPlacementQueueLen: placement.Gauge(\"placement_queue_length\"),\n\t\tPlacementFailed: placement.Counter(\"fail\"),\n\n\t\tElected: serverScope.Gauge(\"elected\"),\n\t}\n}", "func (mr *MockProvidersMockRecorder) GetMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetMetrics\", reflect.TypeOf((*MockProviders)(nil).GetMetrics))\n}", "func (m Plugin) FetchMetrics() (map[string]float64, error) {\n\tresp, err := http.Get(fmt.Sprintf(\"http://%s/stats\", m.Target))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tstats := struct {\n\t\tConnections float64 `json:\"connections\"`\n\t\tTotalConnections float64 `json:\"total_connections\"`\n\t\tTotalMessages float64 `json:\"total_messages\"`\n\t\tConnectErrors float64 `json:\"connect_errors\"`\n\t\tMessageErrors float64 `json:\"message_errors\"`\n\t\tClosingConnections float64 `json:\"closing_connections\"`\n\t}{}\n\tif err := json.NewDecoder(resp.Body).Decode(&stats); err != nil {\n\t\treturn nil, err\n\t}\n\tret := make(map[string]float64, 6)\n\tret[\"conn_current\"] = stats.Connections\n\tret[\"conn_total\"] = stats.TotalConnections\n\tret[\"conn_errors\"] = stats.ConnectErrors\n\tret[\"conn_closing\"] = stats.ClosingConnections\n\tret[\"messages_total\"] = stats.TotalMessages\n\tret[\"messages_errors\"] = stats.MessageErrors\n\n\treturn ret, nil\n}", "func NewMetrics(scope tally.Scope) *Metrics {\n\treadyScope := scope.SubScope(\"ready\")\n\ttrackerScope := scope.SubScope(\"tracker\")\n\ttaskStateScope := scope.SubScope(\"tasks_state\")\n\n\treconcilerScope := scope.SubScope(\"reconciler\")\n\tleakScope := reconcilerScope.SubScope(\"leaks\")\n\tsuccessScope := reconcilerScope.Tagged(map[string]string{\"result\": \"success\"})\n\tfailScope := reconcilerScope.Tagged(map[string]string{\"result\": \"fail\"})\n\n\treturn &Metrics{\n\t\tReadyQueueLen: readyScope.Gauge(\"ready_queue_length\"),\n\t\tTasksCountInTracker: trackerScope.Gauge(\"task_len_tracker\"),\n\t\tTaskStatesGauge: map[task.TaskState]tally.Gauge{\n\t\t\ttask.TaskState_PENDING: taskStateScope.Gauge(\n\t\t\t\t\"task_state_pending\"),\n\t\t\ttask.TaskState_READY: taskStateScope.Gauge(\n\t\t\t\t\"task_state_ready\"),\n\t\t\ttask.TaskState_PLACING: taskStateScope.Gauge(\n\t\t\t\t\"task_state_placing\"),\n\t\t\ttask.TaskState_PLACED: taskStateScope.Gauge(\n\t\t\t\t\"task_state_placed\"),\n\t\t\ttask.TaskState_LAUNCHING: taskStateScope.Gauge(\n\t\t\t\t\"task_state_launching\"),\n\t\t\ttask.TaskState_LAUNCHED: taskStateScope.Gauge(\n\t\t\t\t\"task_state_launched\"),\n\t\t\ttask.TaskState_RUNNING: taskStateScope.Gauge(\n\t\t\t\t\"task_state_running\"),\n\t\t\ttask.TaskState_SUCCEEDED: taskStateScope.Gauge(\n\t\t\t\t\"task_state_succeeded\"),\n\t\t\ttask.TaskState_FAILED: taskStateScope.Gauge(\n\t\t\t\t\"task_state_failed\"),\n\t\t\ttask.TaskState_KILLED: taskStateScope.Gauge(\n\t\t\t\t\"task_state_killed\"),\n\t\t\ttask.TaskState_LOST: taskStateScope.Gauge(\n\t\t\t\t\"task_state_lost\"),\n\t\t\ttask.TaskState_PREEMPTING: taskStateScope.Gauge(\n\t\t\t\t\"task_state_preempting\"),\n\t\t},\n\t\tResourcesHeldByTaskState: map[task.TaskState]scalar.GaugeMaps{\n\t\t\ttask.TaskState_READY: scalar.NewGaugeMaps(\n\t\t\t\tscope.SubScope(\"task_state_ready\"),\n\t\t\t),\n\t\t\ttask.TaskState_PLACING: scalar.NewGaugeMaps(\n\t\t\t\tscope.SubScope(\"task_state_placing\"),\n\t\t\t),\n\t\t\ttask.TaskState_PLACED: scalar.NewGaugeMaps(\n\t\t\t\tscope.SubScope(\"task_state_placed\"),\n\t\t\t),\n\t\t\ttask.TaskState_LAUNCHING: scalar.NewGaugeMaps(\n\t\t\t\tscope.SubScope(\"task_state_launching\"),\n\t\t\t),\n\t\t\ttask.TaskState_LAUNCHED: scalar.NewGaugeMaps(\n\t\t\t\tscope.SubScope(\"task_state_launched\"),\n\t\t\t),\n\t\t\ttask.TaskState_RUNNING: scalar.NewGaugeMaps(\n\t\t\t\tscope.SubScope(\"task_state_running\"),\n\t\t\t),\n\t\t\ttask.TaskState_STARTING: scalar.NewGaugeMaps(\n\t\t\t\tscope.SubScope(\"task_state_starting\"),\n\t\t\t),\n\t\t\ttask.TaskState_PREEMPTING: scalar.NewGaugeMaps(\n\t\t\t\tscope.SubScope(\"task_state_preempting\"),\n\t\t\t),\n\t\t\ttask.TaskState_KILLING: scalar.NewGaugeMaps(\n\t\t\t\tscope.SubScope(\"task_state_killing\"),\n\t\t\t),\n\t\t},\n\t\tLeakedResources: scalar.NewGaugeMaps(leakScope),\n\t\tReconciliationSuccess: successScope.Counter(\"run\"),\n\t\tReconciliationFail: failScope.Counter(\"run\"),\n\t\tOrphanTasks: scope.Gauge(\"orphan_tasks\"),\n\t}\n}", "func (m RedisPlugin) FetchMetrics() (map[string]interface{}, error) {\n\n\tpubClient := redis.NewClient(&m.PubRedisOpt)\n\tsubClient := redis.NewClient(&m.SubRedisOpt)\n\n\tsubscribe, err := subClient.Subscribe(m.ChannelName)\n\tif err != nil {\n\t\tlogger.Errorf(\"Failed to subscribe. %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer subscribe.Close()\n\tif _, err := pubClient.Publish(m.ChannelName, m.Message).Result(); err != nil {\n\t\tlogger.Errorf(\"Failed to publish. %s\", err)\n\t\treturn nil, err\n\t}\n\tstart := time.Now()\n\tif _, err := subscribe.ReceiveMessage(); err != nil {\n\t\tlogger.Infof(\"Failed to calculate capacity. (The cause may be that AWS Elasticache Redis has no `CONFIG` command.) Skip these metrics. %s\", err)\n\t\treturn nil, err\n\t}\n\tduration := time.Now().Sub(start)\n\n\treturn map[string]interface{}{m.metricName(): float64(duration) / float64(time.Microsecond)}, nil\n\n}", "func httpGetMetrics(t *testing.T) []string {\n\tresp, err := http.Get(fmt.Sprintf(\"http://localhost%v%v\", addr, endpoint))\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn []string{}\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn []string{}\n\t}\n\tlines := strings.Split(string(body), \"\\n\")\n\tif len(lines) == 0 {\n\t\tt.Error(\"httpGetMetrics returned empty response\")\n\t\treturn []string{}\n\t}\n\treturn lines\n}", "func NewMetrics() *Metrics {\n\treturn &Metrics{items: make(map[string]*metric), rm: &sync.RWMutex{}}\n}", "func GetMetricsConfig(setFilePath string) (Metrics, error) {\n\tconfig, err := readMetricConfigFile(setFilePath)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\terr = validateMetricConfig(config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\treturn config, nil\n}", "func TestGetMetrics(t *testing.T) {\n\n\t//\t\tCreating mock request with custom params\n\t//\t\tand checking for error\n\trequest, err := http.NewRequest(\"GET\", \"/fizzbuzz-metrics\", nil)\n\tif err != nil {\n\t\tt.Errorf(\"GetMetrics() failed because of bad request: %v\", err)\n\t}\n\n\t//\t\tCreating a HTTP recorder for the test\n\trecorder := httptest.NewRecorder()\n\n\t//\t\tHitting endpoint\n\trouter := httprouter.New()\n\trouter.GET(\"/fizzbuzz-metrics\", GetMetrics)\n\trouter.ServeHTTP(recorder, request)\n\n\t//\t\tCheck status code\n\tif recorder.Code != http.StatusOK {\n\t\tt.Errorf(\"GetMetrics() failed because of status code: got %v instead of %v\", recorder.Code, http.StatusOK)\n\t}\n\n\t//\t\tCheck body\n\tgot := recorder.Body.String()\n\tif got == \"\" {\n\t\tt.Error(\"GetMetrics() failed because of empty body.\")\n\t}\n}", "func (o *Object) GetMetrics(text string) string {\n\treturn Grep(text, o.getMetrics())\n}", "func UpdateMetrics() error {\n\t// err is aggregation of errors while running each of the MetricFetchers\n\tvar err error\n\n\t// wg is go's way of concurrency control essentially a way to say when the main thread can resume execution\n\tvar wg sync.WaitGroup\n\t// main thread after spawning go routines should resume only once all go routines are done executing\n\twg.Add(len(MetricFetchers))\n\n\t// Loop over all the metric fetchers and spawn execution of each MetricFetcher as a go-routine(concurrent execution)\n\tfor _, metricFetcher := range MetricFetchers {\n\t\tgo func() {\n\t\t\t// execute the metricfetcher to get its corresponding clouwatch form\n\t\t\tnamespace, name, value, metaInfo, e := metricFetcher()\n\t\t\t// if err is not nil, accummulate it and error and later instead of failing fast...\n\t\t\t// So, that other metrics can be collected instead of failing completely for failure in collecting one/some\n\t\t\t// of the metrics\n\t\t\tif e != nil {\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = e\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\terr = fmt.Errorf(\"%s.%s\", err, e.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfmt.Println(namespace, name, value, metaInfo, e)\n\n\t\t\t// Push the metric just collected\n\t\t\te = PushMetricToCloudWatch(namespace, name, value, metaInfo)\n\t\t\t// If error accummulate error\n\t\t\tif e != nil {\n\t\t\t\t// ToDo(@Anmol Babu) handle the error concatenation better\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = e\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\terr = fmt.Errorf(\"%s.%s\", err, e.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Signal completion of one routine to be waited on\n\t\t\twg.Done()\n\t\t}()\n\t}\n\t// Wait until all go-routines are done executing\n\twg.Wait()\n\treturn err\n}", "func NewMetrics() *Metrics {\n\tm := &Metrics{\n\t\tTimeMetrics: make(map[string]*TimeStats),\n\t\tNumberMetrics: make(map[string]*NumberStats),\n\t\tBoolMetrics: make(map[string]*BoolStats),\n\t}\n\treturn m\n}", "func GetMetricsHandler(db *models.DB) func(echo.Context) error {\n\treturn func(c echo.Context) (err error) {\n\t\topts := new(models.GetMetricsOpts)\n\t\tif err = c.Bind(opts); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, err.Error())\n\t\t}\n\t\tmetrics, err := db.GetMetrics(*opts)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\treturn c.JSON(http.StatusOK, metrics)\n\t}\n}", "func NewMetrics() *Metrics {\n\treturn &Metrics{\n\t\tRangeFeedCatchupScanNanos: metric.NewCounter(metaRangeFeedCatchupScanNanos),\n\t\tRangeFeedSlowClosedTimestampLogN: log.Every(5 * time.Second),\n\t\tRangeFeedSlowClosedTimestampNudgeSem: make(chan struct{}, 1024),\n\t}\n}", "func PsMetrics() (L []*common.Metric) {\n\treturn nil\n}", "func (s *service) getMetrics(ctx context.Context, arrayID string, metrics []string) (*types.MetricQueryResult, error) {\n\tctx, log, _ := GetRunidLog(ctx)\n\n\t// Synchronize to allow only a single collection per array + metrics\n\treadLocked := false\n\tcacheRWLock.RLock()\n\treadLocked = true\n\tdefer func() {\n\t\tif readLocked {\n\t\t\tcacheRWLock.RUnlock()\n\t\t}\n\t}()\n\n\t// We cache the metrics collection ID for a give array + metric names\n\tcacheKey := fmt.Sprintf(\"%s:%s\", arrayID, strings.Join(metrics, \",\"))\n\tcollectionID, found := metricsCollectionCache.Load(cacheKey)\n\tif found {\n\t\t// Create a separate time to be used for metrics collection calls\n\t\tgetMetricCtx, getMetricCancel := context.WithTimeout(context.Background(), MetricsTimeout)\n\t\tdefer getMetricCancel()\n\t\t// Validate that the query works.\n\t\tresult, getErr := GetMetricsCollection(getMetricCtx, s, arrayID, collectionID.(int))\n\t\tif getErr == nil {\n\t\t\t// No error on query, but validate that it has the requested metric path\n\t\t\thasAllPaths := true\n\t\t\tfor _, entry := range result.Entries {\n\t\t\t\thasMetric := false\n\t\t\t\tfor _, metric := range metrics {\n\t\t\t\t\tif entry.Content.Path == metric {\n\t\t\t\t\t\thasMetric = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !hasMetric {\n\t\t\t\t\thasAllPaths = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif hasAllPaths {\n\t\t\t\tlog.Infof(\"Queried %v metrics collection %v for %s\", metrics, collectionID, arrayID)\n\t\t\t\t// All good, return the results\n\t\t\t\treturn result, nil\n\t\t\t}\n\t\t\tlog.Warnf(\"Stale cache: collection with ID %v doesn't apply to %v.\", collectionID, metrics)\n\t\t}\n\t}\n\n\t// Unlock read and upgrade to a write lock\n\tcacheRWLock.RUnlock()\n\treadLocked = false\n\tcacheRWLock.Lock()\n\tdefer cacheRWLock.Unlock()\n\n\t// If we are here, we have the write lock. Check the cache in case\n\t// another thread already created the collection while this thread\n\t// was waiting on the write lock.\n\tlatestCollectionID, foundAgain := metricsCollectionCache.Load(cacheKey)\n\tif foundAgain && latestCollectionID != collectionID {\n\t\t// There was a hit and it was different from what we had above.\n\t\t// Return the metrics data based on this latest collection ID.\n\t\tlog.Infof(\"Retrieving results from latest collection %v\", latestCollectionID)\n\t\t// Create a separate time to be used for metrics collection calls\n\t\tgetMetricCtx, getMetricCancel := context.WithTimeout(context.Background(), MetricsTimeout)\n\t\tdefer getMetricCancel()\n\t\treturn GetMetricsCollection(getMetricCtx, s, arrayID, latestCollectionID.(int))\n\t} else if foundAgain { // but collectionIds match, so a stale entry\n\t\t// Clean up a stale cache instance\n\t\tmetricsCollectionCache.Delete(cacheKey)\n\t}\n\n\t// If we are here, then we are going to be creating a metrics collection.\n\t// This should be done by a single thread. Subsequent calls to getMetrics\n\t// should return metrics based on the cached collection ID.\n\tlog.Infof(\"Attempting to create a %v metrics collection for %s\", metrics, arrayID)\n\n\t// Create a separate time to be used for metrics creation calls\n\tcreateMetricCtx, createMetricCancel := context.WithTimeout(context.Background(), MetricsTimeout)\n\tdefer createMetricCancel()\n\t// Create the metrics collection because it doesn't exist\n\tcollection, createErr := CreateMetricsCollection(createMetricCtx, s, arrayID, metrics, MetricsCollectionInterval)\n\tif createErr != nil {\n\t\treturn nil, createErr\n\t}\n\n\tlog.Infof(\"Metrics collection %d created for %s\", collection.Content.ID, arrayID)\n\n\t// Wait a bit before trying the first query\n\ttime.Sleep(time.Duration(CollectionWait) * time.Millisecond)\n\n\t// Create a separate time to be used for metrics collection calls\n\tgetMetricCtx, getMetricCancel := context.WithTimeout(context.Background(), MetricsTimeout)\n\tdefer getMetricCancel()\n\t// Cache the collection Id for subsequent use (above, when there is a cache hit)\n\tresults, getErr := GetMetricsCollection(getMetricCtx, s, arrayID, collection.Content.ID)\n\tif getErr != nil {\n\t\treturn nil, getErr\n\t}\n\tmetricsCollectionCache.Store(cacheKey, collection.Content.ID)\n\n\t// Reset this counter so that we can continue to \"keep-alive\" collections for some time.\n\trefreshCount.Store(0)\n\n\tlog.Infof(\"Successfully queried metrics collection %d for %s\", collection.Content.ID, arrayID)\n\n\treturn results, nil\n}", "func GetSandboxMetrics(sandboxID string) (string, error) {\n\tbody, err := shimclient.DoGet(sandboxID, defaultTimeout, containerdshim.MetricsUrl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(body), nil\n}", "func (w *HotCache) CollectMetrics() {\n\tw.writeFlow.CollectMetrics(\"write\")\n\tw.readFlow.CollectMetrics(\"read\")\n}", "func ReadMetrics(metrics []prometheus.Metric) []*Metric {\n\tres := make([]*Metric, len(metrics))\n\tfor i, m := range metrics {\n\t\tres[i] = ReadMetric(m)\n\t}\n\treturn res\n}", "func NewMetrics() *MetricsHolder {\n\tm := &MetricsHolder{\n\t\tlines: make(map[string]*Reading),\n\t\tchannel: make(chan interface{}),\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tw, ok := <-m.channel\n\t\t\treading := w.(*Reading)\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif val, ok := m.lines[reading.Key]; ok {\n\t\t\t\tm.lines[reading.Key] = val.Accept(reading)\n\t\t\t} else {\n\t\t\t\tm.lines[reading.Key] = reading\n\t\t\t}\n\t\t}\n\t}()\n\treturn m\n}", "func (g *GremlinQueryHelper) GetFlowMetrics(query interface{}) (map[string][]*flow.FlowMetric, error) {\n\tdata, err := g.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []map[string][]*flow.FlowMetric\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, ErrNoResult\n\t}\n\n\treturn result[0], nil\n}", "func (_m *MockDataCoord) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\tret := _m.Called(ctx, req)\n\n\tvar r0 *milvuspb.GetMetricsResponse\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error)); ok {\n\t\treturn rf(ctx, req)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) *milvuspb.GetMetricsResponse); ok {\n\t\tr0 = rf(ctx, req)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*milvuspb.GetMetricsResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, *milvuspb.GetMetricsRequest) error); ok {\n\t\tr1 = rf(ctx, req)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (s *sendClient) readMetrics() ([]byte, error) {\n\tresp, err := s.readClient.Get(s.readURL.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Read and close the rest of body.\n\t_, _ = io.Copy(io.Discard, resp.Body)\n\t_ = resp.Body.Close()\n\n\treturn body, nil\n}", "func (c Configuration) metrics() (*pkg.Metrics, error) {\n\tMetricsInitialised.Once.Do(func() {\n\t\tlogger := zerolog.New(os.Stderr).Level(zerolog.DebugLevel)\n\t\tmetrics := &pkg.Metrics{\n\t\t\tGraphiteHost: c.MetricsConfig.GraphiteHost,\n\t\t\tNamespace: c.MetricsConfig.NameSpace,\n\t\t\tGraphiteMode: c.MetricsConfig.GraphiteMode,\n\t\t\tMetricsInterval: c.MetricsConfig.CollectionInterval,\n\t\t\tLogger: logger,\n\t\t}\n\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\tMetricsInitialised.metrics, MetricsInitialised.err = nil, err\n\t\t\treturn\n\t\t}\n\t\tmetrics.Hostname = hostname\n\n\t\t// determine server Role name\n\t\tif c.MetricsConfig.HostRolePath != \"\" {\n\t\t\tfile, err := os.Open(c.MetricsConfig.HostRolePath)\n\t\t\tif err != nil {\n\t\t\t\tMetricsInitialised.metrics, MetricsInitialised.err = nil, err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tscanner := bufio.NewScanner(file)\n\t\t\tfor scanner.Scan() {\n\t\t\t\ttokens := strings.Split(scanner.Text(), c.MetricsConfig.HostRoleToken)\n\t\t\t\tif len(tokens) < puppetFileColumnCount {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif tokens[0] == c.MetricsConfig.HostRoleKey {\n\t\t\t\t\tmetrics.RoleName = tokens[1]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err = file.Close(); err != nil {\n\t\t\t\tlogger.Error().Err(err)\n\t\t\t\tMetricsInitialised.metrics, MetricsInitialised.err = nil, err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tmetrics.EveryHourRegister = goMetrics.NewPrefixedRegistry(metrics.Namespace)\n\t\tmetrics.EveryMinuteRegister = goMetrics.NewPrefixedRegistry(metrics.Namespace)\n\n\t\tMetricsInitialised.metrics, MetricsInitialised.err = metrics, nil\n\t})\n\n\treturn MetricsInitialised.metrics, MetricsInitialised.err\n}", "func (b *Backend) GetMetricsCollectors() []prometheus.Collector {\n\tif b.dbStats != nil {\n\t\treturn b.dbStats.Collectors()\n\t}\n\treturn nil\n}", "func (_m *MockQueryCoord) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\tret := _m.Called(ctx, req)\n\n\tvar r0 *milvuspb.GetMetricsResponse\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error)); ok {\n\t\treturn rf(ctx, req)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) *milvuspb.GetMetricsResponse); ok {\n\t\tr0 = rf(ctx, req)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*milvuspb.GetMetricsResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, *milvuspb.GetMetricsRequest) error); ok {\n\t\tr1 = rf(ctx, req)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func RegisterMetrics() {\n\n\tprometheus.MustRegister(metrics.TiKVBackoffHistogram)\n\tprometheus.MustRegister(metrics.TiKVCoprocessorHistogram)\n\tprometheus.MustRegister(metrics.TiKVLoadSafepointCounter)\n\tprometheus.MustRegister(metrics.TiKVLockResolverCounter)\n\tprometheus.MustRegister(metrics.TiKVRawkvCmdHistogram)\n\tprometheus.MustRegister(metrics.TiKVRawkvSizeHistogram)\n\tprometheus.MustRegister(metrics.TiKVRegionCacheCounter)\n\tprometheus.MustRegister(metrics.TiKVRegionErrorCounter)\n\tprometheus.MustRegister(metrics.TiKVSecondaryLockCleanupFailureCounter)\n\tprometheus.MustRegister(metrics.TiKVSendReqHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnCmdHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnRegionsNumHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnWriteKVCountHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnWriteSizeHistogram)\n\tprometheus.MustRegister(metrics.TiKVLocalLatchWaitTimeHistogram)\n\tprometheus.MustRegister(metrics.TiKVPendingBatchRequests)\n\tprometheus.MustRegister(metrics.TiKVStatusDuration)\n\tprometheus.MustRegister(metrics.TiKVStatusCounter)\n\tprometheus.MustRegister(metrics.TiKVBatchWaitDuration)\n\tprometheus.MustRegister(metrics.TiKVBatchClientUnavailable)\n\tprometheus.MustRegister(metrics.TiKVRangeTaskStats)\n\tprometheus.MustRegister(metrics.TiKVRangeTaskPushDuration)\n\tprometheus.MustRegister(metrics.TiKVTokenWaitDuration)\n\tprometheus.MustRegister(metrics.TiKVTxnHeartBeatHistogram)\n\tprometheus.MustRegister(metrics.TiKVPessimisticLockKeysDuration)\n\tprometheus.MustRegister(metrics.TiKVTTLLifeTimeReachCounter)\n\tprometheus.MustRegister(metrics.TiKVNoAvailableConnectionCounter)\n\n\tprometheus.MustRegister(TSFutureWaitDuration)\n\n\t// grpc metrics\n\tprometheus.MustRegister(CreateSessionCounter)\n\tprometheus.MustRegister(DeleteSessionCounter)\n\tprometheus.MustRegister(ReadCounter)\n\tprometheus.MustRegister(SparseReadCounter)\n\tprometheus.MustRegister(StreamReadCounter)\n\tprometheus.MustRegister(CommitCounter)\n\tprometheus.MustRegister(MutateCounter)\n\tprometheus.MustRegister(ExecuteMutateDuration)\n\tprometheus.MustRegister(ExecuteReadDuration)\n\n\t// session metrics\n\tprometheus.MustRegister(SessionRetry)\n\tprometheus.MustRegister(SessionCounter)\n\tprometheus.MustRegister(SessionRetryErrorCounter)\n\tprometheus.MustRegister(TransactionCounter)\n\tprometheus.MustRegister(TransactionDuration)\n\tprometheus.MustRegister(SchemaLeaseErrorCounter)\n\n\t//tables metrics\n\tprometheus.MustRegister(FetchRowsCounter)\n\tprometheus.MustRegister(FetchSparseCounter)\n\tprometheus.MustRegister(FetchRowsDuration)\n\tprometheus.MustRegister(FetchSparseDuration)\n\n\tprometheus.MustRegister(ScanSparseCounter)\n\tprometheus.MustRegister(ScanSparseDuration)\n\n\tprometheus.MustRegister(BatchSparseCounter)\n\tprometheus.MustRegister(BatchSparseDuration)\n}", "func (mr *MockFlowAggregatorQuerierMockRecorder) GetRecordMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetRecordMetrics\", reflect.TypeOf((*MockFlowAggregatorQuerier)(nil).GetRecordMetrics))\n}", "func (client IotHubResourceClient) GetQuotaMetrics(ctx context.Context, resourceGroupName string, resourceName string) (result IotHubQuotaMetricInfoListResultPage, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/IotHubResourceClient.GetQuotaMetrics\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.ihqmilr.Response.Response != nil {\n\t\t\t\tsc = result.ihqmilr.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tresult.fn = client.getQuotaMetricsNextResults\n\treq, err := client.GetQuotaMetricsPreparer(ctx, resourceGroupName, resourceName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"GetQuotaMetrics\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetQuotaMetricsSender(req)\n\tif err != nil {\n\t\tresult.ihqmilr.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"GetQuotaMetrics\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult.ihqmilr, err = client.GetQuotaMetricsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"GetQuotaMetrics\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\tif result.ihqmilr.hasNextLink() && result.ihqmilr.IsEmpty() {\n\t\terr = result.NextWithContext(ctx)\n\t\treturn\n\t}\n\n\treturn\n}", "func MetricsList(ctx context.Context, req *MetricsListReq) (*MetricsListResp, error) {\n\tif req == nil {\n\t\treturn nil, errors.New(\"nil request\")\n\t}\n\n\tif req.Host == \"\" {\n\t\treturn nil, errors.New(\"host must be specified\")\n\t}\n\n\tif req.Port == 0 {\n\t\treturn nil, errors.New(\"port must be specified\")\n\t}\n\n\treq.url = getMetricsURL(req.Host, req.Port)\n\n\tscraped, err := scrapeMetrics(ctx, req)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to list metrics\")\n\t}\n\n\tresp := new(MetricsListResp)\n\n\tlist := make([]*MetricSet, 0, len(scraped))\n\tfor _, name := range scraped.Keys() {\n\t\tmf := scraped[name]\n\t\tnewMetric := &MetricSet{\n\t\t\tName: name,\n\t\t\tDescription: mf.GetHelp(),\n\t\t\tType: metricTypeFromPrometheus(mf.GetType()),\n\t\t}\n\t\tlist = append(list, newMetric)\n\t}\n\n\tresp.AvailableMetricSets = list\n\treturn resp, nil\n}", "func NewMetrics() *Metrics {\n\treturn &Metrics{\n\t\tInputBytesTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_input_bytes_total\",\n\t\t\t\tHelp: \"Total number of bytes received\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tOutputBytesTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_output_bytes_total\",\n\t\t\t\tHelp: \"Total number of bytes sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tInputPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_input_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets received\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tOutputPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_output_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tDroppedPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_dropped_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets dropped by the router. This metric reports \" +\n\t\t\t\t\t\"the number of packets that were dropped because of errors.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tInterfaceUp: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_interface_up\",\n\t\t\t\tHelp: \"Either zero or one depending on whether the interface is up.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDInterfaceStateChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_state_changes_total\",\n\t\t\t\tHelp: \"Total number of BFD state changes.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDPacketsSent: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sent_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDPacketsReceived: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_received_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets received.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tServiceInstanceCount: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_service_instance_count\",\n\t\t\t\tHelp: \"Number of service instances known by the data plane.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"isd_as\"},\n\t\t),\n\t\tServiceInstanceChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_service_instance_changes_total\",\n\t\t\t\tHelp: \"Number of total service instance changes. Both addition and removal of a \" +\n\t\t\t\t\t\"service instance is accumulated.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"isd_as\"},\n\t\t),\n\t\tSiblingReachable: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_sibling_reachable\",\n\t\t\t\tHelp: \"Either zero or one depending on whether a sibling router \" +\n\t\t\t\t\t\"instance is reachable.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDPacketsSent: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sent_sibling_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets sent to sibling router instance.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDPacketsReceived: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_received_sibling_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets received from sibling router instance.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDStateChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sibling_state_changes_total\",\n\t\t\t\tHelp: \"Total number of BFD state changes for sibling router instances\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t}\n}", "func (shard *ShardedIncomingDataCache) FlushAllMetrics() {\n\tshard.lock.Lock()\n\tdefer shard.lock.Unlock()\n\tfor _, dataInterface := range shard.plugin {\n\t\tif collectd, ok := dataInterface.(*incoming.CollectdMetric); ok {\n\t\t\tif collectd.ISNew() {\n\t\t\t\tcollectd.SetNew(false)\n\t\t\t\tlog.Printf(\"New Metrics %#v\\n\", collectd)\n\t\t\t} else {\n\t\t\t\t//clean up if data is not access for max TTL specified\n\t\t\t\tif shard.Expired() {\n\t\t\t\t\tdelete(shard.plugin, collectd.GetItemKey())\n\t\t\t\t\tlog.Printf(\"Cleaned up plugin for %s\", collectd.GetItemKey())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func NewMetrics(consume ConsumeMetricsFunc, options ...Option) (consumer.Metrics, error) {\n\tif consume == nil {\n\t\treturn nil, errNilFunc\n\t}\n\treturn &baseMetrics{\n\t\tbaseConsumer: newBaseConsumer(options...),\n\t\tConsumeMetricsFunc: consume,\n\t}, nil\n}", "func (s *sendClient) readMetrics() ([]byte, error) {\n\tresp, err := http.Get(s.readURL.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\t_, _ = io.Copy(io.Discard, resp.Body)\n\t\t_ = resp.Body.Close()\n\t}()\n\n\treturn body, nil\n}", "func retrieveMetrics(ctx context.Context, statsConn *core.StatsConnection, segment *networkservice.PathSegment, isClient bool) {\n\tswIfIndex, ok := ifindex.Load(ctx, isClient)\n\tif !ok {\n\t\treturn\n\t}\n\tstats := new(api.InterfaceStats)\n\tif e := statsConn.GetInterfaceStats(stats); e != nil {\n\t\tlog.FromContext(ctx).Errorf(\"getting interface stats failed:\", e)\n\t\treturn\n\t}\n\n\taddName := \"server_\"\n\tif isClient {\n\t\taddName = \"client_\"\n\t}\n\tfor idx := range stats.Interfaces {\n\t\tiface := &stats.Interfaces[idx]\n\t\tif iface.InterfaceIndex != uint32(swIfIndex) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif segment.Metrics == nil {\n\t\t\tsegment.Metrics = make(map[string]string)\n\t\t}\n\t\tsegment.Metrics[addName+\"rx_bytes\"] = strconv.FormatUint(iface.Rx.Bytes, 10)\n\t\tsegment.Metrics[addName+\"tx_bytes\"] = strconv.FormatUint(iface.Tx.Bytes, 10)\n\t\tsegment.Metrics[addName+\"rx_packets\"] = strconv.FormatUint(iface.Rx.Packets, 10)\n\t\tsegment.Metrics[addName+\"tx_packets\"] = strconv.FormatUint(iface.Tx.Packets, 10)\n\t\tsegment.Metrics[addName+\"drops\"] = strconv.FormatUint(iface.Drops, 10)\n\t\tbreak\n\t}\n}", "func (engine *DockerStatsEngine) GetInstanceMetrics() (*ecstcs.MetricsMetadata, []*ecstcs.TaskMetric, error) {\n\tvar taskMetrics []*ecstcs.TaskMetric\n\tidle := engine.isIdle()\n\tmetricsMetadata := &ecstcs.MetricsMetadata{\n\t\tCluster: aws.String(engine.cluster),\n\t\tContainerInstance: aws.String(engine.containerInstanceArn),\n\t\tIdle: aws.Bool(idle),\n\t\tMessageId: aws.String(uuid.NewRandom().String()),\n\t}\n\n\tif idle {\n\t\tlog.Debug(\"Instance is idle. No task metrics to report\")\n\t\tfin := true\n\t\tmetricsMetadata.Fin = &fin\n\t\treturn metricsMetadata, taskMetrics, nil\n\t}\n\n\tfor taskArn := range engine.tasksToContainers {\n\t\tcontainerMetrics, err := engine.getContainerMetricsForTask(taskArn)\n\t\tif err != nil {\n\t\t\tlog.Debug(\"Error getting container metrics for task\", \"err\", err, \"task\", taskArn)\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(containerMetrics) == 0 {\n\t\t\tlog.Debug(\"Empty containerMetrics for task, ignoring\", \"task\", taskArn)\n\t\t\tcontinue\n\t\t}\n\n\t\ttaskDef, exists := engine.tasksToDefinitions[taskArn]\n\t\tif !exists {\n\t\t\tlog.Debug(\"Could not map task to definition\", \"task\", taskArn)\n\t\t\tcontinue\n\t\t}\n\n\t\tmetricTaskArn := taskArn\n\t\ttaskMetric := &ecstcs.TaskMetric{\n\t\t\tTaskArn: &metricTaskArn,\n\t\t\tTaskDefinitionFamily: &taskDef.family,\n\t\t\tTaskDefinitionVersion: &taskDef.version,\n\t\t\tContainerMetrics: containerMetrics,\n\t\t}\n\t\ttaskMetrics = append(taskMetrics, taskMetric)\n\t}\n\n\tif len(taskMetrics) == 0 {\n\t\t// Not idle. Expect taskMetrics to be there.\n\t\treturn nil, nil, fmt.Errorf(\"No task metrics to report\")\n\t}\n\n\t// Reset current stats. Retaining older stats results in incorrect utilization stats\n\t// until they are removed from the queue.\n\tengine.resetStats()\n\treturn metricsMetadata, taskMetrics, nil\n}", "func (p *Proxy) refreshMetrics() {\n\t// get a list of services to update\n\tp.RLock()\n\n\tservices := make([]string, 0, len(p.Routes))\n\n\tfor service := range p.Routes {\n\t\tservices = append(services, service)\n\t}\n\n\tp.RUnlock()\n\n\t// get and cache the routes for the service\n\tfor _, service := range services {\n\t\tp.cacheRoutes(service)\n\t}\n}", "func NewMetrics(name string, r prometheus.Registerer) *Metrics {\n\treg := prometheus.WrapRegistererWith(prometheus.Labels{\"controller\": name}, r)\n\tm := Metrics{\n\t\treg: reg,\n\t\treconcileErrorsCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_reconcile_errors_total\",\n\t\t\tHelp: \"Number of errors that occurred while reconciling the statefulset\",\n\t\t}),\n\t\ttriggerByCounter: prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_triggered_total\",\n\t\t\tHelp: \"Number of times a Kubernetes object add, delete or update event\" +\n\t\t\t\t\" triggered the Prometheus Operator to reconcile an object\",\n\t\t}, []string{\"triggered_by\", \"action\"}),\n\t\tstsDeleteCreateCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_reconcile_sts_delete_create_total\",\n\t\t\tHelp: \"Number of times that reconciling a statefulset required deleting and re-creating it\",\n\t\t}),\n\t\tlistCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_list_operations_total\",\n\t\t\tHelp: \"Total number of list operations\",\n\t\t}),\n\t\tlistFailedCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_list_operations_failed_total\",\n\t\t\tHelp: \"Total number of list operations that failed\",\n\t\t}),\n\t\twatchCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_watch_operations_total\",\n\t\t\tHelp: \"Total number of watch operations\",\n\t\t}),\n\t\twatchFailedCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_watch_operations_failed_total\",\n\t\t\tHelp: \"Total number of watch operations that failed\",\n\t\t}),\n\t}\n\tm.reg.MustRegister(\n\t\tm.reconcileErrorsCounter,\n\t\tm.triggerByCounter,\n\t\tm.stsDeleteCreateCounter,\n\t\tm.listCounter,\n\t\tm.listFailedCounter,\n\t\tm.watchCounter,\n\t\tm.watchFailedCounter,\n\t)\n\treturn &m\n}", "func updateMetrics(metrics map[string]*metricData) {\n\n\tfor _, metricClass := range mqmetric.Metrics.Classes {\n\t\tfor _, metricType := range metricClass.Types {\n\t\t\tif !strings.Contains(metricType.ObjectTopic, \"%s\") {\n\t\t\t\tfor _, metricElement := range metricType.Elements {\n\n\t\t\t\t\t// Unexpected metric elements (with no defined mapping) are handled in 'initialiseMetrics'\n\t\t\t\t\t// - if any exist, they are logged as errors and skipped (they are not added to the metrics map)\n\t\t\t\t\t// Therefore we can ignore handling any unexpected metric elements found here\n\t\t\t\t\t// - this avoids us logging excessive errors, as this function is called frequently\n\t\t\t\t\tmetric, ok := metrics[makeKey(metricElement)]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t// Clear existing metric values\n\t\t\t\t\t\tmetric.values = make(map[string]float64)\n\n\t\t\t\t\t\t// Update metric with cached values of publication data\n\t\t\t\t\t\tfor label, value := range metricElement.Values {\n\t\t\t\t\t\t\tnormalisedValue := mqmetric.Normalise(metricElement, label, value)\n\t\t\t\t\t\t\tmetric.values[label] = normalisedValue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Reset cached values of publication data for this metric\n\t\t\t\t\tmetricElement.Values = make(map[string]int64)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (sb ServiceBase) Metrics() metrics.Exposer {\n\treturn sb.options.Metrics\n}" ]
[ "0.6872508", "0.68246144", "0.6799083", "0.6752799", "0.67144287", "0.66702175", "0.66008884", "0.6562043", "0.6492844", "0.64852494", "0.64565706", "0.64405376", "0.63940954", "0.63932514", "0.63932514", "0.63554275", "0.63413274", "0.63183755", "0.6286743", "0.62805265", "0.626165", "0.624911", "0.62029195", "0.61684215", "0.6158137", "0.6116393", "0.6101872", "0.608723", "0.6002151", "0.59985715", "0.5994252", "0.5986196", "0.59782493", "0.5978121", "0.5918261", "0.5900576", "0.5888217", "0.58709896", "0.5861345", "0.5813517", "0.5808896", "0.5771851", "0.57406694", "0.5729255", "0.56778", "0.56505364", "0.5649667", "0.56434", "0.56304836", "0.5614432", "0.5612392", "0.5571884", "0.5548455", "0.55450386", "0.5529142", "0.5525083", "0.55249053", "0.55049074", "0.5493703", "0.54872584", "0.5478779", "0.546713", "0.54634035", "0.5423586", "0.5417631", "0.5403246", "0.54006445", "0.5393035", "0.5379847", "0.5353628", "0.53406197", "0.5340319", "0.53353745", "0.5324503", "0.5318984", "0.5318283", "0.531692", "0.53123707", "0.53044176", "0.5270657", "0.52701277", "0.52651745", "0.5264593", "0.52604127", "0.5255327", "0.52537686", "0.5239045", "0.52343893", "0.5228242", "0.5226834", "0.52206653", "0.5220601", "0.5218476", "0.5215341", "0.5203891", "0.51984745", "0.51981324", "0.5189148", "0.51857215", "0.5184902" ]
0.63757503
15
Aggregate for each metric line.
func (p *StatsDParser) Aggregate(line string) error { parsedMetric, err := parseMessageToMetric(line, p.enableMetricType) if err != nil { return err } switch parsedMetric.description.statsdMetricType { case statsdGauge: _, ok := p.gauges[parsedMetric.description] if !ok { p.gauges[parsedMetric.description] = buildGaugeMetric(parsedMetric, timeNowFunc()) } else { if parsedMetric.addition { savedValue := p.gauges[parsedMetric.description].Metrics().At(0).DoubleGauge().DataPoints().At(0).Value() parsedMetric.floatvalue = parsedMetric.floatvalue + savedValue p.gauges[parsedMetric.description] = buildGaugeMetric(parsedMetric, timeNowFunc()) } else { p.gauges[parsedMetric.description] = buildGaugeMetric(parsedMetric, timeNowFunc()) } } case statsdCounter: _, ok := p.counters[parsedMetric.description] if !ok { p.counters[parsedMetric.description] = buildCounterMetric(parsedMetric, timeNowFunc()) } else { savedValue := p.counters[parsedMetric.description].Metrics().At(0).IntSum().DataPoints().At(0).Value() parsedMetric.intvalue = parsedMetric.intvalue + savedValue p.counters[parsedMetric.description] = buildCounterMetric(parsedMetric, timeNowFunc()) } case statsdHistogram: switch p.observeHistogram { case "gauge": p.timersAndDistributions = append(p.timersAndDistributions, buildGaugeMetric(parsedMetric, timeNowFunc())) case "summary": eachSummaryMetric, ok := p.summaries[parsedMetric.description] if !ok { p.summaries[parsedMetric.description] = summaryMetric{ name: parsedMetric.description.name, summaryPoints: []float64{parsedMetric.floatvalue}, labelKeys: parsedMetric.labelKeys, labelValues: parsedMetric.labelValues, timeNow: timeNowFunc(), } } else { points := eachSummaryMetric.summaryPoints p.summaries[parsedMetric.description] = summaryMetric{ name: parsedMetric.description.name, summaryPoints: append(points, parsedMetric.floatvalue), labelKeys: parsedMetric.labelKeys, labelValues: parsedMetric.labelValues, timeNow: timeNowFunc(), } } } case statsdTiming: switch p.observeTimer { case "gauge": p.timersAndDistributions = append(p.timersAndDistributions, buildGaugeMetric(parsedMetric, timeNowFunc())) case "summary": eachSummaryMetric, ok := p.summaries[parsedMetric.description] if !ok { p.summaries[parsedMetric.description] = summaryMetric{ name: parsedMetric.description.name, summaryPoints: []float64{parsedMetric.floatvalue}, labelKeys: parsedMetric.labelKeys, labelValues: parsedMetric.labelValues, timeNow: timeNowFunc(), } } else { points := eachSummaryMetric.summaryPoints p.summaries[parsedMetric.description] = summaryMetric{ name: parsedMetric.description.name, summaryPoints: append(points, parsedMetric.floatvalue), labelKeys: parsedMetric.labelKeys, labelValues: parsedMetric.labelValues, timeNow: timeNowFunc(), } } } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AggregateMetric(metrics map[string]Metric, metric Metric) {\n\texistingMetric, metricExists := metrics[metric.Key]\n\n\t// If the metric exists in the specified map, we either take the last value or\n\t// sum the values and increment the hit count.\n\tif metricExists {\n\t\t// Occasionally metrics are sampled and may inflate their numbers.\n\t\texistingMetric.TotalHits += metric.TotalHits\n\n\t\texistingMetric.AllValues = append(existingMetric.AllValues, metric.LastValue)\n\n\t\tswitch {\n\t\tcase metric.MetricType == MetricTypeCounter:\n\t\t\texistingMetric.LastValue += metric.LastValue * metric.TotalHits\n\t\tcase metric.MetricType == MetricTypeGauge:\n\t\t\texistingMetric.LastValue = metric.LastValue\n\t\tcase metric.MetricType == MetricTypeSet:\n\t\t\texistingMetric.LastValue = metric.LastValue\n\t\tcase metric.MetricType == MetricTypeTimer:\n\t\t\texistingMetric.LastValue = metric.LastValue\n\t\t}\n\n\t\tmetrics[metric.Key] = existingMetric\n\t} else {\n\t\tmetrics[metric.Key] = metric\n\t}\n}", "func (o *Observer) AggregatedMetric() (float64, error) {\n\to.mutex.RLock()\n\tdefer o.mutex.RUnlock()\n\n\treturn o.Reducer.Reduce(o.measurements)\n}", "func (ligb *LineItemGroupBy) Aggregate(fns ...AggregateFunc) *LineItemGroupBy {\n\tligb.fns = append(ligb.fns, fns...)\n\treturn ligb\n}", "func (a SumAggregator) Aggregate(values []float64) float64 {\n\tresult := 0.0\n\tfor _, v := range values {\n\t\tresult += v\n\t}\n\treturn result\n}", "func (s *Statsd) aggregate(m metric) {\n\tswitch m.mtype {\n\tcase \"ms\", \"h\":\n\t\t// Check if the measurement exists\n\t\tcached, ok := s.timings[m.hash]\n\t\tif !ok {\n\t\t\tcached = cachedtimings{\n\t\t\t\tname: m.name,\n\t\t\t\tfields: make(map[string]RunningStats),\n\t\t\t}\n\t\t}\n\t\t// Check if the field exists. If we've not enabled multiple fields per timer\n\t\t// this will be the default field name, eg. \"value\"\n\t\tfield, ok := cached.fields[m.field]\n\t\tif !ok {\n\t\t\tfield = RunningStats{\n\t\t\t\tPercLimit: s.PercentileLimit,\n\t\t\t}\n\t\t}\n\t\tif m.samplerate > 0 {\n\t\t\tfor i := 0; i < int(1.0/m.samplerate); i++ {\n\t\t\t\tfield.AddValue(m.floatvalue)\n\t\t\t}\n\t\t} else {\n\t\t\tfield.AddValue(m.floatvalue)\n\t\t}\n\t\tcached.fields[m.field] = field\n\t\ts.timings[m.hash] = cached\n\tcase \"c\":\n\t\t// check if the measurement exists\n\t\t_, ok := s.counters[m.hash]\n\t\tif !ok {\n\t\t\ts.counters[m.hash] = cachedcounter{\n\t\t\t\tname: m.name,\n\t\t\t\tfields: make(map[string]interface{}),\n\t\t\t}\n\t\t}\n\t\t// check if the field exists\n\t\t_, ok = s.counters[m.hash].fields[m.field]\n\t\tif !ok {\n\t\t\ts.counters[m.hash].fields[m.field] = int64(0)\n\t\t}\n\t\ts.counters[m.hash].fields[m.field] =\n\t\t\ts.counters[m.hash].fields[m.field].(int64) + m.intvalue\n\tcase \"g\":\n\t\t// check if the measurement exists\n\t\t_, ok := s.gauges[m.hash]\n\t\tif !ok {\n\t\t\ts.gauges[m.hash] = cachedgauge{\n\t\t\t\tname: m.name,\n\t\t\t\tfields: make(map[string]interface{}),\n\t\t\t}\n\t\t}\n\t\t// check if the field exists\n\t\t_, ok = s.gauges[m.hash].fields[m.field]\n\t\tif !ok {\n\t\t\ts.gauges[m.hash].fields[m.field] = float64(0)\n\t\t}\n\t\tif m.additive {\n\t\t\ts.gauges[m.hash].fields[m.field] =\n\t\t\t\ts.gauges[m.hash].fields[m.field].(float64) + m.floatvalue\n\t\t} else {\n\t\t\ts.gauges[m.hash].fields[m.field] = m.floatvalue\n\t\t}\n\tcase \"s\":\n\t\t// check if the measurement exists\n\t\t_, ok := s.sets[m.hash]\n\t\tif !ok {\n\t\t\ts.sets[m.hash] = cachedset{\n\t\t\t\tname: m.name,\n\t\t\t\tfields: make(map[string]map[int64]bool),\n\t\t\t}\n\t\t}\n\t\t// check if the field exists\n\t\t_, ok = s.sets[m.hash].fields[m.field]\n\t\tif !ok {\n\t\t\ts.sets[m.hash].fields[m.field] = make(map[int64]bool)\n\t\t}\n\t\ts.sets[m.hash].fields[m.field][m.intvalue] = true\n\t}\n\n}", "func (omgb *OutcomeMeasureGroupBy) Aggregate(fns ...AggregateFunc) *OutcomeMeasureGroupBy {\n\tomgb.fns = append(omgb.fns, fns...)\n\treturn omgb\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 (rs *localRegion) aggregate(ctx *selectContext, h int64, row map[int64][]byte) error {\n\t// Put row data into evaluate context for later evaluation.\n\terr := rs.setColumnValueToCtx(ctx, h, row, ctx.aggColumns)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\t// Get group key.\n\tgk, err := rs.getGroupKey(ctx)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tif _, ok := ctx.groups[string(gk)]; !ok {\n\t\tctx.groups[string(gk)] = true\n\t\tctx.groupKeys = append(ctx.groupKeys, gk)\n\t}\n\t// Update aggregate funcs.\n\tfor _, agg := range ctx.aggregates {\n\t\tagg.currentGroup = gk\n\t\targs := make([]types.Datum, 0, len(agg.expr.Children))\n\t\t// Evaluate arguments.\n\t\tfor _, x := range agg.expr.Children {\n\t\t\tcv, err := ctx.eval.Eval(x)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Trace(err)\n\t\t\t}\n\t\t\targs = append(args, cv)\n\t\t}\n\t\tagg.update(ctx, args)\n\t}\n\treturn nil\n}", "func (mm *MetricManager) accumulate(metric config.CarbonMetric) {\n\tconfig.G.Log.System.LogDebug(\"MetricManager::accumulate %s=%v\", metric.Path, metric.Value)\n\n\t// Locate the metric in the map.\n\tvar currentRollup *rollup\n\tvar found bool\n\tif currentRollup, found = mm.byPath[metric.Path]; !found {\n\n\t\t// Initialize, and insert the new rollup into both maps.\n\t\tcurrentRollup = mm.addToMaps(metric.Path)\n\n\t\t// Send the entry off for writing to the path index.\n\t\tconfig.G.Channels.IndexStore <- metric\n\t}\n\n\t// Apply the incoming metric to each rollup bucket.\n\tfor i, v := range currentRollup.value {\n\t\tcurrentRollup.value[i] = mm.applyMethod(\n\t\t\tmm.rollup[currentRollup.expr].Method, v, metric.Value, currentRollup.count[i])\n\t\tcurrentRollup.count[i]++\n\t}\n}", "func (a *defaultAggregator) Aggregate(ctx context.Context, entries <-chan log.Entry) <-chan Traffic {\n\tstats := make(chan Traffic, 20)\n\tgo func() {\n\t\t//The ticker with slot duration\n\t\tticker := time.NewTicker(a.duration)\n\t\tstage := newAggregatorStage(a.start, a.duration)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase entry := <-entries: //a entry log, it adds it in the queue\n\t\t\t\tstage.add(entry)\n\t\t\tcase <-ticker.C:\n\t\t\t\t//it sends the stat\n\t\t\t\tstats <- stage.computeTraffic()\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn stats\n}", "func (ev *evaluator) aggregation(op itemType, grouping model.LabelNames, without bool, keepCommon bool, param Expr, vec vector) vector {\n\n\tresult := map[uint64]*groupedAggregation{}\n\tvar k int64\n\tif op == itemTopK || op == itemBottomK {\n\t\tk = ev.evalInt(param)\n\t\tif k < 1 {\n\t\t\treturn vector{}\n\t\t}\n\t}\n\tvar q float64\n\tif op == itemQuantile {\n\t\tq = ev.evalFloat(param)\n\t}\n\tvar valueLabel model.LabelName\n\tif op == itemCountValues {\n\t\tvalueLabel = model.LabelName(ev.evalString(param).Value)\n\t\tif !without {\n\t\t\tgrouping = append(grouping, valueLabel)\n\t\t}\n\t}\n\n\tfor _, s := range vec {\n\t\twithoutMetric := s.Metric\n\t\tif without {\n\t\t\tfor _, l := range grouping {\n\t\t\t\twithoutMetric.Del(l)\n\t\t\t}\n\t\t\twithoutMetric.Del(model.MetricNameLabel)\n\t\t\tif op == itemCountValues {\n\t\t\t\twithoutMetric.Set(valueLabel, model.LabelValue(s.Value.String()))\n\t\t\t}\n\t\t} else {\n\t\t\tif op == itemCountValues {\n\t\t\t\ts.Metric.Set(valueLabel, model.LabelValue(s.Value.String()))\n\t\t\t}\n\t\t}\n\n\t\tvar groupingKey uint64\n\t\tif without {\n\t\t\tgroupingKey = uint64(withoutMetric.Metric.Fingerprint())\n\t\t} else {\n\t\t\tgroupingKey = model.SignatureForLabels(s.Metric.Metric, grouping...)\n\t\t}\n\n\t\tgroupedResult, ok := result[groupingKey]\n\t\t// Add a new group if it doesn't exist.\n\t\tif !ok {\n\t\t\tvar m metric.Metric\n\t\t\tif keepCommon {\n\t\t\t\tm = s.Metric\n\t\t\t\tm.Del(model.MetricNameLabel)\n\t\t\t} else if without {\n\t\t\t\tm = withoutMetric\n\t\t\t} else {\n\t\t\t\tm = metric.Metric{\n\t\t\t\t\tMetric: model.Metric{},\n\t\t\t\t\tCopied: true,\n\t\t\t\t}\n\t\t\t\tfor _, l := range grouping {\n\t\t\t\t\tif v, ok := s.Metric.Metric[l]; ok {\n\t\t\t\t\t\tm.Set(l, v)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult[groupingKey] = &groupedAggregation{\n\t\t\t\tlabels: m,\n\t\t\t\tvalue: s.Value,\n\t\t\t\tvaluesSquaredSum: s.Value * s.Value,\n\t\t\t\tgroupCount: 1,\n\t\t\t}\n\t\t\tif op == itemTopK || op == itemQuantile {\n\t\t\t\tresult[groupingKey].heap = make(vectorByValueHeap, 0, k)\n\t\t\t\theap.Push(&result[groupingKey].heap, &sample{Value: s.Value, Metric: s.Metric})\n\t\t\t} else if op == itemBottomK {\n\t\t\t\tresult[groupingKey].reverseHeap = make(vectorByReverseValueHeap, 0, k)\n\t\t\t\theap.Push(&result[groupingKey].reverseHeap, &sample{Value: s.Value, Metric: s.Metric})\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// Add the sample to the existing group.\n\t\tif keepCommon {\n\t\t\tgroupedResult.labels = labelIntersection(groupedResult.labels, s.Metric)\n\t\t}\n\n\t\tswitch op {\n\t\tcase itemSum:\n\t\t\tgroupedResult.value += s.Value\n\t\tcase itemAvg:\n\t\t\tgroupedResult.value += s.Value\n\t\t\tgroupedResult.groupCount++\n\t\tcase itemMax:\n\t\t\tif groupedResult.value < s.Value || math.IsNaN(float64(groupedResult.value)) {\n\t\t\t\tgroupedResult.value = s.Value\n\t\t\t}\n\t\tcase itemMin:\n\t\t\tif groupedResult.value > s.Value || math.IsNaN(float64(groupedResult.value)) {\n\t\t\t\tgroupedResult.value = s.Value\n\t\t\t}\n\t\tcase itemCount, itemCountValues:\n\t\t\tgroupedResult.groupCount++\n\t\tcase itemStdvar, itemStddev:\n\t\t\tgroupedResult.value += s.Value\n\t\t\tgroupedResult.valuesSquaredSum += s.Value * s.Value\n\t\t\tgroupedResult.groupCount++\n\t\tcase itemTopK:\n\t\t\tif int64(len(groupedResult.heap)) < k || groupedResult.heap[0].Value < s.Value || math.IsNaN(float64(groupedResult.heap[0].Value)) {\n\t\t\t\tif int64(len(groupedResult.heap)) == k {\n\t\t\t\t\theap.Pop(&groupedResult.heap)\n\t\t\t\t}\n\t\t\t\theap.Push(&groupedResult.heap, &sample{Value: s.Value, Metric: s.Metric})\n\t\t\t}\n\t\tcase itemBottomK:\n\t\t\tif int64(len(groupedResult.reverseHeap)) < k || groupedResult.reverseHeap[0].Value > s.Value || math.IsNaN(float64(groupedResult.reverseHeap[0].Value)) {\n\t\t\t\tif int64(len(groupedResult.reverseHeap)) == k {\n\t\t\t\t\theap.Pop(&groupedResult.reverseHeap)\n\t\t\t\t}\n\t\t\t\theap.Push(&groupedResult.reverseHeap, &sample{Value: s.Value, Metric: s.Metric})\n\t\t\t}\n\t\tcase itemQuantile:\n\t\t\tgroupedResult.heap = append(groupedResult.heap, s)\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"expected aggregation operator but got %q\", op))\n\t\t}\n\t}\n\n\t// Construct the result vector from the aggregated groups.\n\tresultVector := make(vector, 0, len(result))\n\n\tfor _, aggr := range result {\n\t\tswitch op {\n\t\tcase itemAvg:\n\t\t\taggr.value = aggr.value / model.SampleValue(aggr.groupCount)\n\t\tcase itemCount, itemCountValues:\n\t\t\taggr.value = model.SampleValue(aggr.groupCount)\n\t\tcase itemStdvar:\n\t\t\tavg := float64(aggr.value) / float64(aggr.groupCount)\n\t\t\taggr.value = model.SampleValue(float64(aggr.valuesSquaredSum)/float64(aggr.groupCount) - avg*avg)\n\t\tcase itemStddev:\n\t\t\tavg := float64(aggr.value) / float64(aggr.groupCount)\n\t\t\taggr.value = model.SampleValue(math.Sqrt(float64(aggr.valuesSquaredSum)/float64(aggr.groupCount) - avg*avg))\n\t\tcase itemTopK:\n\t\t\t// The heap keeps the lowest value on top, so reverse it.\n\t\t\tsort.Sort(sort.Reverse(aggr.heap))\n\t\t\tfor _, v := range aggr.heap {\n\t\t\t\tresultVector = append(resultVector, &sample{\n\t\t\t\t\tMetric: v.Metric,\n\t\t\t\t\tValue: v.Value,\n\t\t\t\t\tTimestamp: ev.Timestamp,\n\t\t\t\t})\n\t\t\t}\n\t\t\tcontinue // Bypass default append.\n\t\tcase itemBottomK:\n\t\t\t// The heap keeps the lowest value on top, so reverse it.\n\t\t\tsort.Sort(sort.Reverse(aggr.reverseHeap))\n\t\t\tfor _, v := range aggr.reverseHeap {\n\t\t\t\tresultVector = append(resultVector, &sample{\n\t\t\t\t\tMetric: v.Metric,\n\t\t\t\t\tValue: v.Value,\n\t\t\t\t\tTimestamp: ev.Timestamp,\n\t\t\t\t})\n\t\t\t}\n\t\t\tcontinue // Bypass default append.\n\t\tcase itemQuantile:\n\t\t\taggr.value = model.SampleValue(quantile(q, aggr.heap))\n\t\tdefault:\n\t\t\t// For other aggregations, we already have the right value.\n\t\t}\n\t\tsample := &sample{\n\t\t\tMetric: aggr.labels,\n\t\t\tValue: aggr.value,\n\t\t\tTimestamp: ev.Timestamp,\n\t\t}\n\t\tresultVector = append(resultVector, sample)\n\t}\n\treturn resultVector\n}", "func aggregateDatapoints(\n\tlogger *zap.Logger,\n\tdps []*sfxpb.DataPoint,\n\tdimensionsKeys []string,\n\taggregation AggregationMethod,\n) []*sfxpb.DataPoint {\n\tif len(dps) == 0 {\n\t\treturn nil\n\t}\n\n\t// group datapoints by dimension values\n\tdimValuesToDps := make(map[string][]*sfxpb.DataPoint, len(dps))\n\tfor i, dp := range dps {\n\t\taggregationKey, err := getAggregationKey(dp.Dimensions, dimensionsKeys)\n\t\tif err != nil {\n\t\t\tlogger.Debug(\"datapoint is dropped\", zap.String(\"metric\", dp.Metric), zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := dimValuesToDps[aggregationKey]; !ok {\n\t\t\t// set slice capacity to the possible maximum = len(dps)-i to avoid reallocations\n\t\t\tdimValuesToDps[aggregationKey] = make([]*sfxpb.DataPoint, 0, len(dps)-i)\n\t\t}\n\t\tdimValuesToDps[aggregationKey] = append(dimValuesToDps[aggregationKey], dp)\n\t}\n\n\t// Get aggregated results\n\tresult := make([]*sfxpb.DataPoint, 0, len(dimValuesToDps))\n\tfor _, dps := range dimValuesToDps {\n\t\tdp := proto.Clone(dps[0]).(*sfxpb.DataPoint)\n\t\tdp.Dimensions = filterDimensions(dp.Dimensions, dimensionsKeys)\n\t\tswitch aggregation {\n\t\tcase AggregationMethodCount:\n\t\t\tgauge := sfxpb.MetricType_GAUGE\n\t\t\tdp.MetricType = &gauge\n\t\t\tvalue := int64(len(dps))\n\t\t\tdp.Value = sfxpb.Datum{\n\t\t\t\tIntValue: &value,\n\t\t\t}\n\t\tcase AggregationMethodSum:\n\t\t\tvar intValue int64\n\t\t\tvar floatValue float64\n\t\t\tvalue := sfxpb.Datum{}\n\t\t\tfor _, dp := range dps {\n\t\t\t\tif dp.Value.IntValue != nil {\n\t\t\t\t\tintValue += *dp.Value.IntValue\n\t\t\t\t\tvalue.IntValue = &intValue\n\t\t\t\t}\n\t\t\t\tif dp.Value.DoubleValue != nil {\n\t\t\t\t\tfloatValue += *dp.Value.DoubleValue\n\t\t\t\t\tvalue.DoubleValue = &floatValue\n\t\t\t\t}\n\t\t\t}\n\t\t\tdp.Value = value\n\t\t}\n\t\tresult = append(result, dp)\n\t}\n\n\treturn result\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 (rdgb *ResultsDefinitionGroupBy) Aggregate(fns ...AggregateFunc) *ResultsDefinitionGroupBy {\n\trdgb.fns = append(rdgb.fns, fns...)\n\treturn rdgb\n}", "func Aggregate(key Type, val time.Duration) {\n\tif globalStats != nil {\n\t\tmutex.Lock()\n\t\tdefer mutex.Unlock()\n\n\t\tglobalStats[key] = globalStats[key] + val\n\t}\n}", "func (p *AggregateOp) Apply(ctx api.StreamContext, data interface{}, fv *xsql.FunctionValuer, _ *xsql.AggregateFunctionValuer) interface{} {\n\tlog := ctx.GetLogger()\n\tlog.Debugf(\"aggregate plan receive %v\", data)\n\tgrouped := data\n\tif p.Dimensions != nil {\n\t\tswitch input := data.(type) {\n\t\tcase error:\n\t\t\treturn input\n\t\tcase xsql.SingleCollection:\n\t\t\twr := input.GetWindowRange()\n\t\t\tresult := make(map[string]*xsql.GroupedTuples)\n\t\t\terr := input.Range(func(i int, ir xsql.ReadonlyRow) (bool, error) {\n\t\t\t\tvar name string\n\t\t\t\ttr := ir.(xsql.TupleRow)\n\t\t\t\tve := &xsql.ValuerEval{Valuer: xsql.MultiValuer(tr, &xsql.WindowRangeValuer{WindowRange: wr}, fv)}\n\t\t\t\tfor _, d := range p.Dimensions {\n\t\t\t\t\tr := ve.Eval(d.Expr)\n\t\t\t\t\tif _, ok := r.(error); ok {\n\t\t\t\t\t\treturn false, fmt.Errorf(\"run Group By error: %v\", r)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tname += fmt.Sprintf(\"%v,\", r)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ts, ok := result[name]; !ok {\n\t\t\t\t\tresult[name] = &xsql.GroupedTuples{Content: []xsql.TupleRow{tr}, WindowRange: wr}\n\t\t\t\t} else {\n\t\t\t\t\tts.Content = append(ts.Content, tr)\n\t\t\t\t}\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif len(result) > 0 {\n\t\t\t\tg := make([]*xsql.GroupedTuples, 0, len(result))\n\t\t\t\tfor _, v := range result {\n\t\t\t\t\tg = append(g, v)\n\t\t\t\t}\n\t\t\t\tgrouped = &xsql.GroupedTuplesSet{Groups: g}\n\t\t\t} else {\n\t\t\t\tgrouped = nil\n\t\t\t}\n\t\t\treturn grouped\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"run Group By error: invalid input %[1]T(%[1]v)\", input)\n\t\t}\n\t}\n\treturn grouped\n}", "func (evsgb *ExValueScanGroupBy) Aggregate(fns ...AggregateFunc) *ExValueScanGroupBy {\n\tevsgb.fns = append(evsgb.fns, fns...)\n\treturn evsgb\n}", "func (rgb *RemedyGroupBy) Aggregate(fns ...AggregateFunc) *RemedyGroupBy {\n\trgb.fns = append(rgb.fns, fns...)\n\treturn rgb\n}", "func (a *Aggregator) Aggregate(statuses chan Status) {\n\tfor s := range statuses {\n\t\tif s.Application != \"\" && s.Version != \"\" {\n\t\t\ta.Data[s.Application+s.Version] += s.SuccessCount\n\t\t}\n\t}\n}", "func (esgb *EventSeverityGroupBy) Aggregate(fns ...AggregateFunc) *EventSeverityGroupBy {\n\tesgb.fns = append(esgb.fns, fns...)\n\treturn esgb\n}", "func (refreshProtocol *RefreshProtocol) Aggregate(share1, share2, shareOut *ring.Poly) {\n\trefreshProtocol.dckksContext.ringQ.AddLvl(len(share1.Coeffs)-1, share1, share2, shareOut)\n}", "func (irgb *InstanceRuntimeGroupBy) Aggregate(fns ...AggregateFunc) *InstanceRuntimeGroupBy {\n\tirgb.fns = append(irgb.fns, fns...)\n\treturn irgb\n}", "func (ksgb *KqiSourceGroupBy) Aggregate(fns ...AggregateFunc) *KqiSourceGroupBy {\n\tksgb.fns = append(ksgb.fns, fns...)\n\treturn ksgb\n}", "func (bcgb *BaselineClassGroupBy) Aggregate(fns ...AggregateFunc) *BaselineClassGroupBy {\n\tbcgb.fns = append(bcgb.fns, fns...)\n\treturn bcgb\n}", "func (s *Suite) Aggregate() {\n\t//totals := Totals{Tests: len(s.Tests)}\n\ttotals := &pb.TestTotal{\n\t\tTests: int64(len(s.Tests)),\n\t\tStatuses: make(map[string]int64),\n\t}\n\n\tfor _, test := range s.Tests {\n\t\ttotals.Duration += test.Duration\n\t\tswitch test.Status {\n\t\tcase string(apistructs.TestStatusPassed):\n\t\t\ttotals.Statuses[string(apistructs.TestStatusPassed)] += 1\n\t\tcase string(apistructs.TestStatusSkipped):\n\t\t\ttotals.Statuses[string(apistructs.TestStatusSkipped)] += 1\n\t\tcase string(apistructs.TestStatusFailed):\n\t\t\ttotals.Statuses[string(apistructs.TestStatusFailed)] += 1\n\t\tcase string(apistructs.TestStatusError):\n\t\t\ttotals.Statuses[string(apistructs.TestStatusError)] += 1\n\t\t}\n\t}\n\n\ts.Totals = totals\n}", "func (egb *EntryGroupBy) Aggregate(fns ...AggregateFunc) *EntryGroupBy {\n\tegb.fns = append(egb.fns, fns...)\n\treturn egb\n}", "func AggregateLogEntries(ch chan *LogEntry, importantDomains []string) Aggregation {\n\taggregation := make(Aggregation)\n\n\tfor entry := range ch {\n\t\t// Potentially Slow?\n\t\tif sliceutil.Contains(importantDomains, entry.Host) {\n\t\t\taggregation.updateEntry(entry.Host, entry)\n\t\t}\n\t\taggregation.updateEntry(\"total\", entry)\n\t}\n\n\treturn aggregation\n}", "func (rgb *ReceiptGroupBy) Aggregate(fns ...AggregateFunc) *ReceiptGroupBy {\n\trgb.fns = append(rgb.fns, fns...)\n\treturn rgb\n}", "func (a *Aggregate) Aggregate(message string) error {\n\tparts := strings.Split(message, protocol.AggregateDelimiter)\n\tif len(parts) < 4 {\n\t\treturn fmt.Errorf(\"aggregate message without any real data\")\n\t}\n\n\tgroupKey := parts[0]\n\tsamples, err := strconv.Atoi(parts[1])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse sample count '%s': %v\", parts[1], err)\n\t}\n\n\tfields := a.makeFields(parts[2:])\n\tset := a.group.GetSet(groupKey)\n\tvar addedSamples bool\n\n\tfor _, sc := range a.query.Select {\n\t\tif val, ok := fields[sc.FieldStorage]; ok {\n\t\t\tif err := set.Aggregate(sc.FieldStorage, sc.Operation, val, true); err != nil {\n\t\t\t\tdlog.Client.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taddedSamples = true\n\t\t}\n\t}\n\tif addedSamples {\n\t\tset.Samples += samples\n\t}\n\n\t// Merge data from group into global group.\n\tisMerged, err := a.globalGroup.MergeNoblock(a.query, a.group)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif isMerged {\n\t\t// Re-init local group (make it empty again).\n\t\ta.group.InitSet()\n\t}\n\treturn nil\n}", "func (t Timeline) Aggregate() *courses.CourseRecords {\n\trecords := courses.CourseRecords{}\n\tfor _, tr := range t.TermRecords {\n\t\tfor _, record := range tr.CourseRecords {\n\t\t\trecords = append(records, record)\n\t\t}\n\t}\n\treturn &records\n}", "func (ggb *GoodsGroupBy) Aggregate(fns ...AggregateFunc) *GoodsGroupBy {\n\tggb.fns = append(ggb.fns, fns...)\n\treturn ggb\n}", "func (rgb *RentGroupBy) Aggregate(fns ...AggregateFunc) *RentGroupBy {\n\trgb.fns = append(rgb.fns, fns...)\n\treturn rgb\n}", "func aggregate(ses gocqlx.Session, req operations.FindSensorAvgBySensorIDAndDayParams, avg []model.SensorAvg) ([]model.SensorAvg, bool) {\n\tid := req.ID.String()\n\tnow := time.Now().UTC()\n\tday := time.Time(req.Day)\n\n\t// can't aggregate data for post today's date\n\tif day.YearDay() > now.YearDay() {\n\t\treturn nil, false\n\t}\n\n\t// we can start from next missing hour. hours = [0, 23]. len = [0, 24]\n\tstartHour := len(avg)\n\tstartDate := time.Date(day.Year(), day.Month(), day.Day(), startHour, 0, 0, 0, time.UTC)\n\tendDate := time.Date(day.Year(), day.Month(), day.Day(), 23, 59, 59, 1e9-1, time.UTC)\n\n\ttimePoints, dataPoints, ok := loadData(ses, id, startDate, endDate)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tprevAvgSize := len(avg)\n\tavg = groupBy(avg, timePoints, dataPoints, startHour, day, now)\n\n\tsaveAggregate(ses, id, avg, prevAvgSize, startDate, day, now)\n\n\treturn avg, true\n}", "func (a QuantileAggregator) Aggregate(values []float64) float64 {\n\tsort.Float64s(values)\n\treturn quantile(values, a.quantile)\n}", "func (a *MetricAggregator) Flush(flushInterval time.Duration) {\n\ta.statser.Gauge(\"aggregator.metricmaps_received\", float64(a.metricMapsReceived), nil)\n\n\tflushInSeconds := float64(flushInterval) / float64(time.Second)\n\n\ta.metricMap.Counters.Each(func(key, tagsKey string, counter gostatsd.Counter) {\n\t\tcounter.PerSecond = float64(counter.Value) / flushInSeconds\n\t\ta.metricMap.Counters[key][tagsKey] = counter\n\t})\n\n\ta.metricMap.Timers.Each(func(key, tagsKey string, timer gostatsd.Timer) {\n\t\tif hasHistogramTag(timer) {\n\t\t\ttimer.Histogram = latencyHistogram(timer, a.histogramLimit)\n\t\t\ta.metricMap.Timers[key][tagsKey] = timer\n\t\t\treturn\n\t\t}\n\n\t\tif count := len(timer.Values); count > 0 {\n\t\t\tsort.Float64s(timer.Values)\n\t\t\ttimer.Min = timer.Values[0]\n\t\t\ttimer.Max = timer.Values[count-1]\n\t\t\tn := len(timer.Values)\n\t\t\tcount := float64(n)\n\n\t\t\tcumulativeValues := make([]float64, n)\n\t\t\tcumulSumSquaresValues := make([]float64, n)\n\t\t\tcumulativeValues[0] = timer.Min\n\t\t\tcumulSumSquaresValues[0] = timer.Min * timer.Min\n\t\t\tfor i := 1; i < n; i++ {\n\t\t\t\tcumulativeValues[i] = timer.Values[i] + cumulativeValues[i-1]\n\t\t\t\tcumulSumSquaresValues[i] = timer.Values[i]*timer.Values[i] + cumulSumSquaresValues[i-1]\n\t\t\t}\n\n\t\t\tvar sumSquares = timer.Min * timer.Min\n\t\t\tvar mean = timer.Min\n\t\t\tvar sum = timer.Min\n\t\t\tvar thresholdBoundary = timer.Max\n\n\t\t\tfor pct, pctStruct := range a.percentThresholds {\n\t\t\t\tnumInThreshold := n\n\t\t\t\tif n > 1 {\n\t\t\t\t\tnumInThreshold = int(round(math.Abs(pct) / 100 * count))\n\t\t\t\t\tif numInThreshold == 0 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif pct > 0 {\n\t\t\t\t\t\tthresholdBoundary = timer.Values[numInThreshold-1]\n\t\t\t\t\t\tsum = cumulativeValues[numInThreshold-1]\n\t\t\t\t\t\tsumSquares = cumulSumSquaresValues[numInThreshold-1]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthresholdBoundary = timer.Values[n-numInThreshold]\n\t\t\t\t\t\tsum = cumulativeValues[n-1] - cumulativeValues[n-numInThreshold-1]\n\t\t\t\t\t\tsumSquares = cumulSumSquaresValues[n-1] - cumulSumSquaresValues[n-numInThreshold-1]\n\t\t\t\t\t}\n\t\t\t\t\tmean = sum / float64(numInThreshold)\n\t\t\t\t}\n\n\t\t\t\tif !a.disabledSubtypes.CountPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.count, float64(numInThreshold))\n\t\t\t\t}\n\t\t\t\tif !a.disabledSubtypes.MeanPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.mean, mean)\n\t\t\t\t}\n\t\t\t\tif !a.disabledSubtypes.SumPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.sum, sum)\n\t\t\t\t}\n\t\t\t\tif !a.disabledSubtypes.SumSquaresPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.sumSquares, sumSquares)\n\t\t\t\t}\n\t\t\t\tif pct > 0 {\n\t\t\t\t\tif !a.disabledSubtypes.UpperPct {\n\t\t\t\t\t\ttimer.Percentiles.Set(pctStruct.upper, thresholdBoundary)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif !a.disabledSubtypes.LowerPct {\n\t\t\t\t\t\ttimer.Percentiles.Set(pctStruct.lower, thresholdBoundary)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsum = cumulativeValues[n-1]\n\t\t\tsumSquares = cumulSumSquaresValues[n-1]\n\t\t\tmean = sum / count\n\n\t\t\tvar sumOfDiffs float64\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tsumOfDiffs += (timer.Values[i] - mean) * (timer.Values[i] - mean)\n\t\t\t}\n\n\t\t\tmid := int(math.Floor(count / 2))\n\t\t\tif math.Mod(count, 2) == 0 {\n\t\t\t\ttimer.Median = (timer.Values[mid-1] + timer.Values[mid]) / 2\n\t\t\t} else {\n\t\t\t\ttimer.Median = timer.Values[mid]\n\t\t\t}\n\n\t\t\ttimer.Mean = mean\n\t\t\ttimer.StdDev = math.Sqrt(sumOfDiffs / count)\n\t\t\ttimer.Sum = sum\n\t\t\ttimer.SumSquares = sumSquares\n\n\t\t\ttimer.Count = int(round(timer.SampledCount))\n\t\t\ttimer.PerSecond = timer.SampledCount / flushInSeconds\n\t\t} else {\n\t\t\ttimer.Count = 0\n\t\t\ttimer.SampledCount = 0\n\t\t\ttimer.PerSecond = 0\n\t\t}\n\t\ta.metricMap.Timers[key][tagsKey] = timer\n\t})\n}", "func m_User_Aggregates(rs UserSet, fieldNames ...models.FieldName) []m.UserGroupAggregateRow {\n\tlines := rs.RecordCollection.Aggregates(fieldNames...)\n\tres := make([]m.UserGroupAggregateRow, len(lines))\n\tfor i, l := range lines {\n\t\tres[i] = UserGroupAggregateRow{\n\t\t\tvalues: l.Values.Wrap().(m.UserData),\n\t\t\tcount: l.Count,\n\t\t\tcondition: q.UserCondition{\n\t\t\t\tCondition: l.Condition,\n\t\t\t},\n\t\t}\n\t}\n\treturn res\n}", "func (a *Avg) Accum(_ io.TimeBucketKey, argMap *functions.ArgumentMap, cols io.ColumnInterface,\n) (*io.ColumnSeries, error) {\n\tif cols.Len() == 0 {\n\t\treturn a.Output(), nil\n\t}\n\tinputColDSV := argMap.GetMappedColumns(requiredColumns[0].Name)\n\tinputColName := inputColDSV[0].Name\n\tinputCol, err := uda.ColumnToFloat32(cols, inputColName)\n\tif err != nil {\n\t\tlog.Debug(\"COLS: \", cols)\n\t\treturn nil, err\n\t}\n\n\tfor _, value := range inputCol {\n\t\ta.Avg += float64(value)\n\t\ta.Count++\n\t}\n\treturn a.Output(), nil\n}", "func (klgb *K8sLabelGroupBy) Aggregate(fns ...AggregateFunc) *K8sLabelGroupBy {\n\tklgb.fns = append(klgb.fns, fns...)\n\treturn klgb\n}", "func (throttler *Throttler) aggregateMySQLMetrics(ctx context.Context) error {\n\tfor clusterName, probes := range throttler.mysqlInventory.ClustersProbes {\n\t\tmetricName := fmt.Sprintf(\"mysql/%s\", clusterName)\n\t\tignoreHostsCount := throttler.mysqlInventory.IgnoreHostsCount[clusterName]\n\t\tignoreHostsThreshold := throttler.mysqlInventory.IgnoreHostsThreshold[clusterName]\n\t\taggregatedMetric := aggregateMySQLProbes(ctx, probes, clusterName, throttler.mysqlInventory.InstanceKeyMetrics, ignoreHostsCount, config.Settings().Stores.MySQL.IgnoreDialTCPErrors, ignoreHostsThreshold)\n\t\tthrottler.aggregatedMetrics.Set(metricName, aggregatedMetric, cache.DefaultExpiration)\n\t}\n\treturn nil\n}", "func (a *AzureMonitor) Add(m telegraf.Metric) {\n\t// Azure Monitor only supports aggregates 30 minutes into the past and 4\n\t// minutes into the future. Future metrics are dropped when pushed.\n\tt := m.Time()\n\ttbucket := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), 0, 0, t.Location())\n\tif tbucket.Before(a.timeFunc().Add(-time.Minute * 30)) {\n\t\ta.MetricOutsideWindow.Incr(1)\n\t\treturn\n\t}\n\n\t// Azure Monitor doesn't have a string value type, so convert string fields\n\t// to dimensions (a.k.a. tags) if enabled.\n\tif a.StringsAsDimensions {\n\t\tfor _, f := range m.FieldList() {\n\t\t\tif v, ok := f.Value.(string); ok {\n\t\t\t\tm.AddTag(f.Key, v)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, f := range m.FieldList() {\n\t\tfv, ok := convert(f.Value)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Azure Monitor does not support fields so the field name is appended\n\t\t// to the metric name.\n\t\tname := m.Name() + \"-\" + sanitize(f.Key)\n\t\tid := hashIDWithField(m.HashID(), f.Key)\n\n\t\t_, ok = a.cache[tbucket]\n\t\tif !ok {\n\t\t\t// Time bucket does not exist and needs to be created.\n\t\t\ta.cache[tbucket] = make(map[uint64]*aggregate)\n\t\t}\n\n\t\t// Fetch existing aggregate\n\t\tvar agg *aggregate\n\t\tagg, ok = a.cache[tbucket][id]\n\t\tif !ok {\n\t\t\tagg := &aggregate{\n\t\t\t\tname: name,\n\t\t\t\tmin: fv,\n\t\t\t\tmax: fv,\n\t\t\t\tsum: fv,\n\t\t\t\tcount: 1,\n\t\t\t}\n\t\t\tfor _, tag := range m.TagList() {\n\t\t\t\tdim := dimension{\n\t\t\t\t\tname: tag.Key,\n\t\t\t\t\tvalue: tag.Value,\n\t\t\t\t}\n\t\t\t\tagg.dimensions = append(agg.dimensions, dim)\n\t\t\t}\n\t\t\tagg.updated = true\n\t\t\ta.cache[tbucket][id] = agg\n\t\t\tcontinue\n\t\t}\n\n\t\tif fv < agg.min {\n\t\t\tagg.min = fv\n\t\t}\n\t\tif fv > agg.max {\n\t\t\tagg.max = fv\n\t\t}\n\t\tagg.sum += fv\n\t\tagg.count++\n\t\tagg.updated = true\n\t}\n}", "func (iggb *ItemGroupGroupBy) Aggregate(fns ...AggregateFunc) *ItemGroupGroupBy {\n\tiggb.fns = append(iggb.fns, fns...)\n\treturn iggb\n}", "func (covList *CoverageList) summarize() {\n\tcovList.NumCoveredStmts = 0\n\tcovList.NumAllStmts = 0\n\tfor _, item := range covList.Group {\n\t\tcovList.NumCoveredStmts += item.NumCoveredStmts\n\t\tcovList.NumAllStmts += item.NumAllStmts\n\t}\n}", "func (sigb *SubItemGroupBy) Aggregate(fns ...AggregateFunc) *SubItemGroupBy {\n\tsigb.fns = append(sigb.fns, fns...)\n\treturn sigb\n}", "func (vgb *VehicleGroupBy) Aggregate(fns ...AggregateFunc) *VehicleGroupBy {\n\tvgb.fns = append(vgb.fns, fns...)\n\treturn vgb\n}", "func (evsq *ExValueScanQuery) Aggregate(fns ...AggregateFunc) *ExValueScanSelect {\n\treturn evsq.Select().Aggregate(fns...)\n}", "func (c *auditdCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (ulgb *UserLogGroupBy) Aggregate(fns ...AggregateFunc) *UserLogGroupBy {\n\tulgb.fns = append(ulgb.fns, fns...)\n\treturn ulgb\n}", "func (dagb *DrugAllergyGroupBy) Aggregate(fns ...AggregateFunc) *DrugAllergyGroupBy {\n\tdagb.fns = append(dagb.fns, fns...)\n\treturn dagb\n}", "func (osgb *OfflineSessionGroupBy) Aggregate(fns ...AggregateFunc) *OfflineSessionGroupBy {\n\tosgb.fns = append(osgb.fns, fns...)\n\treturn osgb\n}", "func (osgb *OfflineSessionGroupBy) Aggregate(fns ...AggregateFunc) *OfflineSessionGroupBy {\n\tosgb.fns = append(osgb.fns, fns...)\n\treturn osgb\n}", "func (egb *EntityGroupBy) Aggregate(fns ...AggregateFunc) *EntityGroupBy {\n\tegb.fns = append(egb.fns, fns...)\n\treturn egb\n}", "func (c *metricbeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (this *KxiWorker) Reduce(key interface{}, values []interface{}) (kv mr.KeyValue) {\n kv = mr.NewKeyValue()\n switch key.(mr.GroupKey).Group() {\n case GROUP_URL_SERV:\n vals := mr.ConvertAnySliceToFloat(values)\n kv[TIME_ALL] = stats.StatsSum(vals)\n kv[TIME_MAX] = stats.StatsMax(vals)\n kv[TIME_TOP] = stats.StatsSumTopN(vals, topsum)\n kv[TIME_AVG] = stats.StatsMean(vals)\n kv[TIME_STD] = stats.StatsSampleStandardDeviationCoefficient(vals)\n kv[CALL_ALL] = float64(stats.StatsCount(vals))\n case GROUP_KXI:\n vals := mr.ConvertAnySliceToFloat(values)\n kv[TIME_ALL] = stats.StatsSum(vals)\n kv[TIME_MIN] = stats.StatsMin(vals)\n kv[TIME_TOP] = stats.StatsSumTopN(vals, topsum)\n kv[TIME_MAX] = stats.StatsMax(vals)\n kv[TIME_AVG] = stats.StatsMean(vals)\n kv[TIME_STD] = stats.StatsSampleStandardDeviationCoefficient(vals)\n kv[CALL_ALL] = float64(stats.StatsCount(vals))\n case GROUP_URL_RID:\n vals := mr.ConvertAnySliceToFloat(values)\n kv[CALL_ALL] = float64(stats.StatsCount(vals))\n kv[TIME_ALL] = stats.StatsSum(vals)\n case GROUP_URL_SQL:\n vals := mr.ConvertAnySliceToFloat(values)\n kv[CALL_ALL] = float64(stats.StatsCount(vals))\n kv[TIME_MAX] = stats.StatsMax(vals)\n kv[TIME_AVG] = stats.StatsMean(vals)\n case GROUP_URL:\n vals := mr.ConvertAnySliceToString(values) // rids of this url\n c := stats.NewCounter(vals)\n kv[REQ_ALL] = float64(len(c))\n }\n\n return\n}", "func (fdgb *FurnitureDetailGroupBy) Aggregate(fns ...AggregateFunc) *FurnitureDetailGroupBy {\n\tfdgb.fns = append(fdgb.fns, fns...)\n\treturn fdgb\n}", "func (s *histValues[N]) Aggregate(value N, attr attribute.Set) {\n\t// Accept all types to satisfy the Aggregator interface. However, since\n\t// the Aggregation produced by this Aggregator is only float64, convert\n\t// here to only use this type.\n\tv := float64(value)\n\n\t// This search will return an index in the range [0, len(s.bounds)], where\n\t// it will return len(s.bounds) if value is greater than the last element\n\t// of s.bounds. This aligns with the buckets in that the length of buckets\n\t// is len(s.bounds)+1, with the last bucket representing:\n\t// (s.bounds[len(s.bounds)-1], +∞).\n\tidx := sort.SearchFloat64s(s.bounds, v)\n\n\ts.valuesMu.Lock()\n\tdefer s.valuesMu.Unlock()\n\n\tb, ok := s.values[attr]\n\tif !ok {\n\t\t// N+1 buckets. For example:\n\t\t//\n\t\t// bounds = [0, 5, 10]\n\t\t//\n\t\t// Then,\n\t\t//\n\t\t// buckets = (-∞, 0], (0, 5.0], (5.0, 10.0], (10.0, +∞)\n\t\tb = newBuckets(len(s.bounds) + 1)\n\t\t// Ensure min and max are recorded values (not zero), for new buckets.\n\t\tb.min, b.max = v, v\n\t\ts.values[attr] = b\n\t}\n\tb.bin(idx, v)\n}", "func addMetric(s *events.EventStream, metric string, period time.Duration, fn func(*swarming_api.SwarmingRpcsTaskRequestMetadata) (int64, error)) error {\n\ttags := map[string]string{\n\t\t\"metric\": metric,\n\t}\n\tf := func(ev []*events.Event) ([]map[string]string, []float64, error) {\n\t\tsklog.Infof(\"Computing value(s) for metric %q\", metric)\n\t\tif len(ev) == 0 {\n\t\t\treturn []map[string]string{}, []float64{}, nil\n\t\t}\n\t\ttasks, err := decodeTasks(ev)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ttagSets := map[string]map[string]string{}\n\t\ttotals := map[string]int64{}\n\t\tcounts := map[string]int{}\n\t\tfor _, t := range tasks {\n\t\t\tval, err := fn(t)\n\t\t\tif err == errNoValue {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\ttags := map[string]string{\n\t\t\t\t\"task-name\": t.TaskResult.Name,\n\t\t\t}\n\t\t\tfor d := range DIMENSION_WHITELIST {\n\t\t\t\ttags[d] = \"\"\n\t\t\t}\n\t\t\tfor _, dim := range t.Request.Properties.Dimensions {\n\t\t\t\tif _, ok := DIMENSION_WHITELIST[dim.Key]; ok {\n\t\t\t\t\ttags[dim.Key] = dim.Value\n\t\t\t\t}\n\t\t\t}\n\t\t\tkey, err := util.MD5Params(tags)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\ttagSets[key] = tags\n\t\t\ttotals[key] += val\n\t\t\tcounts[key]++\n\t\t}\n\t\ttagSetsList := make([]map[string]string, 0, len(tagSets))\n\t\tvals := make([]float64, 0, len(tagSets))\n\t\tfor key, tags := range tagSets {\n\t\t\ttagSetsList = append(tagSetsList, tags)\n\t\t\tvals = append(vals, float64(totals[key])/float64(counts[key]))\n\t\t}\n\t\treturn tagSetsList, vals, nil\n\t}\n\treturn s.DynamicMetric(tags, period, f)\n}", "func (hgb *HarborGroupBy) Aggregate(fns ...AggregateFunc) *HarborGroupBy {\n\thgb.fns = append(hgb.fns, fns...)\n\treturn hgb\n}", "func (a JSONDataAggregator) Aggregate() ([]byte, error) {\n\tdataContainer := map[string]interface{}{}\n\tfor key, provider := range a.Providers {\n\t\tdataPiece, err := provider.GetData()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdataContainer[key] = dataPiece\n\t}\n\tdata, err := json.Marshal(dataContainer)\n\treturn data, err\n}", "func (e *Exporter) toMetric(v *view.View, row *view.Row, vd *view.Data) []client.Metric {\n\tswitch data := row.Data.(type) {\n\tcase *view.CountData:\n\t\treturn []client.Metric{e.formatTimeSeriesMetric(data.Value, row, vd)}\n\tcase *view.SumData:\n\t\treturn []client.Metric{e.formatTimeSeriesMetric(data.Value, row, vd)}\n\tcase *view.LastValueData:\n\t\treturn []client.Metric{e.formatTimeSeriesMetric(data.Value, row, vd)}\n\tcase *view.DistributionData:\n\t\t// Graphite does not support histogram. In order to emulate one,\n\t\t// we use the accumulative count of the bucket.\n\t\tindicesMap := make(map[float64]int)\n\t\tbuckets := make([]float64, 0, len(v.Aggregation.Buckets))\n\t\tfor i, b := range v.Aggregation.Buckets {\n\t\t\tif _, ok := indicesMap[b]; !ok {\n\t\t\t\tindicesMap[b] = i\n\t\t\t\tbuckets = append(buckets, b)\n\t\t\t}\n\t\t}\n\t\tsort.Float64s(buckets)\n\n\t\tvar metrics []client.Metric\n\n\t\t// Now that the buckets are sorted by magnitude\n\t\t// we can create cumulative indicesmap them back by reverse index\n\t\tcumCount := uint64(0)\n\t\tfor _, b := range buckets {\n\t\t\ti := indicesMap[b]\n\t\t\tcumCount += uint64(data.CountPerBucket[i])\n\t\t\tnames := []string{sanitize(e.opts.Namespace), sanitize(vd.View.Name), \"bucket\"}\n\t\t\ttags := tagValues(row.Tags) + fmt.Sprintf(\";le=%.2f\", b)\n\t\t\tmetric := client.Metric{\n\t\t\t\tName: buildPath(names, tags, e.tags),\n\t\t\t\tValue: float64(cumCount),\n\t\t\t\tTimestamp: vd.End,\n\t\t\t}\n\t\t\tmetrics = append(metrics, metric)\n\t\t}\n\t\tnames := []string{sanitize(e.opts.Namespace), sanitize(vd.View.Name), \"bucket\"}\n\t\ttags := tagValues(row.Tags) + \";le=+Inf\"\n\t\tmetric := client.Metric{\n\t\t\tName: buildPath(names, tags, e.tags),\n\t\t\tValue: float64(cumCount),\n\t\t\tTimestamp: vd.End,\n\t\t}\n\t\tmetrics = append(metrics, metric)\n\t\treturn metrics\n\tdefault:\n\t\te.opts.onError(fmt.Errorf(\"aggregation %T is not yet supported\", data))\n\t\treturn nil\n\t}\n}", "func (rrgb *ReserveRoomGroupBy) Aggregate(fns ...AggregateFunc) *ReserveRoomGroupBy {\n\trrgb.fns = append(rrgb.fns, fns...)\n\treturn rrgb\n}", "func (tdgb *TCPDetectorGroupBy) Aggregate(fns ...AggregateFunc) *TCPDetectorGroupBy {\n\ttdgb.fns = append(tdgb.fns, fns...)\n\treturn tdgb\n}", "func (c *beatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func ProcessMetric(metric *Metric, flushDuration time.Duration, quantiles []int, logger Logger) {\n\tflushInterval := flushDuration / time.Second\n\n\tsort.Sort(metric.AllValues)\n\tswitch metric.MetricType {\n\tcase MetricTypeCounter:\n\t\tmetric.ValuesPerSecond = metric.LastValue / float64(flushInterval)\n\tcase MetricTypeGauge:\n\t\tmetric.MedianValue = metric.AllValues.Median()\n\t\tmetric.MeanValue = metric.AllValues.Mean()\n\tcase MetricTypeSet:\n\t\tmetric.LastValue = float64(metric.AllValues.UniqueCount())\n\tcase MetricTypeTimer:\n\t\tmetric.MinValue, metric.MaxValue, _ = metric.AllValues.Minmax()\n\t\tmetric.MedianValue = metric.AllValues.Median()\n\t\tmetric.MeanValue = metric.AllValues.Mean()\n\t\tmetric.ValuesPerSecond = metric.TotalHits / float64(flushInterval)\n\n\t\tmetric.Quantiles = make([]MetricQuantile, 0)\n\t\tfor _, q := range quantiles {\n\t\t\tpercentile := float64(q) / float64(100)\n\t\t\tquantile := new(MetricQuantile)\n\t\t\tquantile.Quantile = q\n\n\t\t\t// Make calculations based on the desired quantile.\n\t\t\tquantile.Boundary = metric.AllValues.Quantile(percentile)\n\t\t\tfor _, value := range metric.AllValues {\n\t\t\t\tif value > quantile.Boundary {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tquantile.AllValues = append(quantile.AllValues, value)\n\t\t\t}\n\t\t\t_, quantile.Max, _ = quantile.AllValues.Minmax()\n\t\t\tquantile.Mean = quantile.AllValues.Mean()\n\t\t\tquantile.Median = quantile.AllValues.Median()\n\t\t\tquantile.Sum = quantile.AllValues.Sum()\n\t\t\tmetric.Quantiles = append(metric.Quantiles, *quantile)\n\t\t}\n\t}\n}", "func (dtgb *DeviceTokenGroupBy) Aggregate(fns ...AggregateFunc) *DeviceTokenGroupBy {\n\tdtgb.fns = append(dtgb.fns, fns...)\n\treturn dtgb\n}", "func (hdgb *HTTPDetectorGroupBy) Aggregate(fns ...AggregateFunc) *HTTPDetectorGroupBy {\n\thdgb.fns = append(hdgb.fns, fns...)\n\treturn hdgb\n}", "func (rlgb *RuleLimitGroupBy) Aggregate(fns ...AggregateFunc) *RuleLimitGroupBy {\n\trlgb.fns = append(rlgb.fns, fns...)\n\treturn rlgb\n}", "func (cgb *CartGroupBy) Aggregate(fns ...AggregateFunc) *CartGroupBy {\n\tcgb.fns = append(cgb.fns, fns...)\n\treturn cgb\n}", "func (c *filebeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (lugb *LastUpdatedGroupBy) Aggregate(fns ...AggregateFunc) *LastUpdatedGroupBy {\n\tlugb.fns = append(lugb.fns, fns...)\n\treturn lugb\n}", "func (tgb *TweetGroupBy) Aggregate(fns ...AggregateFunc) *TweetGroupBy {\n\ttgb.fns = append(tgb.fns, fns...)\n\treturn tgb\n}", "func aggregateData(stmt parser.SelectStmt, records [][]string) ([][]driver.Value, []int, error) {\n\t// autoValue trims prefixes `auto` and returns a cleaned string.\n\t// Also indicates with the second parameter, if it's a automatic value or not.\n\tvar autoValued = func(s string) (v string, ok bool) {\n\t\tif ok = strings.HasPrefix(s, auto); !ok {\n\t\t\t// Not prefixed by auto keyword.\n\t\t\tv = s\n\t\t\treturn\n\t\t}\n\t\t// Trims the prefix `auto: `\n\t\tif v = strings.TrimPrefix(s, autoValue); v == s {\n\t\t\t// Removes only `auto` as prefix\n\t\t\tv = strings.TrimPrefix(s, auto)\n\t\t}\n\t\treturn\n\t}\n\t// lenFloat64 returns the length of the float by calculating the number of digit + point.\n\tvar lenFloat64 = func(f AggregatedNullFloat64) (i int) {\n\t\tif i = len(f.Layout); i > 0 {\n\t\t\t// It's a datetime.\n\t\t\treturn\n\t\t}\n\t\tswitch {\n\t\tcase f.NullFloat64.Float64 >= 1000000000000:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tcase f.NullFloat64.Float64 >= 100000000000:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tcase f.NullFloat64.Float64 >= 10000000000:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tcase f.NullFloat64.Float64 >= 1000000000:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tcase f.NullFloat64.Float64 >= 100000000:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tcase f.NullFloat64.Float64 >= 10000000:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tcase f.NullFloat64.Float64 >= 1000000:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tcase f.NullFloat64.Float64 >= 100000:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tcase f.NullFloat64.Float64 >= 10000:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tcase f.NullFloat64.Float64 >= 1000:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tcase f.NullFloat64.Float64 >= 100:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tcase f.NullFloat64.Float64 >= 10:\n\t\t\ti++\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\ti++\n\t\t}\n\t\tif f.Precision > 0 {\n\t\t\t// Manages `.01`\n\t\t\ti += f.Precision + 1\n\t\t}\n\t\treturn\n\t}\n\t// parsePercentNullFloat64 parses a string and returns it as double that can be a percentage.\n\tvar parsePercentNullFloat64 = func(s string) (d PercentNullFloat64, err error) {\n\t\tif s == doubleDash {\n\t\t\t// Not set, null value.\n\t\t\treturn\n\t\t}\n\t\tif d.Percent = strings.HasSuffix(s, \"%\"); d.Percent {\n\t\t\ts = strings.TrimSuffix(s, \"%\")\n\t\t}\n\t\tswitch s {\n\t\tcase almost10:\n\t\t\t// Sometimes, when it's less than 10, Google displays \"< 10%\".\n\t\t\td.NullFloat64.Float64 = 9.999\n\t\t\td.NullFloat64.Valid = true\n\t\t\td.Almost = true\n\t\tcase almost90:\n\t\t\t// Or \"> 90%\" when it is the opposite.\n\t\t\td.NullFloat64.Float64 = 90.001\n\t\t\td.NullFloat64.Valid = true\n\t\t\td.Almost = true\n\t\tdefault:\n\t\t\tif d.NullFloat64.Float64, err = strconv.ParseFloat(s, 64); err == nil {\n\t\t\t\td.NullFloat64.Valid = true\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\t// parseAutoExcludedNullInt64 parses a string and returns it as integer.\n\tvar parseAutoExcludedNullInt64 = func(s string) (d AutoExcludedNullInt64, err error) {\n\t\tif s == doubleDash {\n\t\t\t// Not set, null value.\n\t\t\treturn\n\t\t}\n\t\tif s == excluded {\n\t\t\t// Voluntary null by scope.\n\t\t\td.Excluded = true\n\t\t\treturn\n\t\t}\n\t\tif s, d.Auto = autoValued(s); s == \"\" {\n\t\t\t// Not set, null and automatic value.\n\t\t\treturn\n\t\t}\n\t\tif d.NullInt64.Int64, err = strconv.ParseInt(s, 10, 64); err == nil {\n\t\t\td.NullInt64.Valid = true\n\t\t}\n\t\treturn\n\t}\n\t// parseTime parses a string and returns its time representation by using the layout.\n\tvar parseTime = func(layout, s string) (Time, error) {\n\t\tif s == doubleDash {\n\t\t\t// Not set, null value.\n\t\t\treturn Time{Time: time.Time{}}, nil\n\t\t}\n\t\tt, err := time.Parse(layout, s)\n\n\t\treturn Time{Time: t, Layout: layout}, err\n\t}\n\t// parseString parses a string and returns a NullString.\n\tvar parseString = func(s string) (NullString, error) {\n\t\tif s == doubleDash {\n\t\t\treturn NullString{}, nil\n\t\t}\n\t\treturn NullString{Valid: true, String: s}, nil\n\t}\n\t// cast gives the type equivalences of API adwords type of data.\n\tvar cast = func(s, kind string) (driver.Value, error) {\n\t\tswitch strings.ToUpper(kind) {\n\t\tcase \"BID\", \"INT\", \"INTEGER\", \"LONG\", \"MONEY\":\n\t\t\treturn parseAutoExcludedNullInt64(s)\n\t\tcase \"DOUBLE\":\n\t\t\treturn parsePercentNullFloat64(s)\n\t\tcase \"DATE\":\n\t\t\treturn parseTime(\"2006-01-02\", s)\n\t\tcase \"DATETIME\":\n\t\t\treturn parseTime(\"2006/01/02 15:04:05\", s)\n\t\t}\n\t\treturn parseString(s)\n\t}\n\t// aggregate parses a string and returns it as a nullable double.\n\tvar aggregate = func(s string, kind string) (d AggregatedNullFloat64, err error) {\n\t\tvar v driver.Value\n\t\tif v, err = cast(s, kind); err != nil {\n\t\t\treturn\n\t\t}\n\t\tswitch c := v.(type) {\n\t\tcase AutoExcludedNullInt64:\n\t\t\td.NullFloat64.Float64 = float64(c.NullInt64.Int64)\n\t\t\td.NullFloat64.Valid = c.NullInt64.Valid\n\t\tcase PercentNullFloat64:\n\t\t\td.NullFloat64.Float64 = c.NullFloat64.Float64\n\t\t\td.NullFloat64.Valid = c.NullFloat64.Valid\n\t\tcase Time:\n\t\t\td.NullFloat64.Float64 = float64(c.Time.Unix())\n\t\t\td.NullFloat64.Valid = true\n\t\t\td.Layout = c.Layout\n\t\tdefault:\n\t\t\terr = ErrQuery\n\t\t}\n\t\treturn\n\t}\n\t// hash returns a numeric hash for the given string.\n\tvar hash = func(s string) uint64 {\n\t\th := fnv.New64a()\n\t\th.Write([]byte(s))\n\t\treturn h.Sum64()\n\t}\n\t// useAggregate returns the list of aggregate and a boolean as second parameter.\n\t// If at least one column uses a aggregate function, it will be true.\n\tvar useAggregate = func(stmt parser.SelectStmt) (aggr []int, ok bool) {\n\t\tfor p, c := range stmt.Columns() {\n\t\t\tif c.Distinct() {\n\t\t\t\taggr = append(aggr, p)\n\t\t\t\tok = true\n\t\t\t} else if _, use := c.UseFunction(); use {\n\t\t\t\tok = true\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\taggrList, distinctLine := useAggregate(stmt)\n\n\t// Bounds\n\tgroupSize := len(stmt.GroupList())\n\tcolumnSize := len(stmt.Columns())\n\n\t// Builds a map with group values as key.\n\tvar data map[string][]driver.Value\n\tdata = make(map[string][]driver.Value)\n\tcs := make([]int, columnSize)\n\tfor p, f := range records {\n\t\t// Picks the aggregate values.\n\t\tvar group []uint64\n\t\tif groupSize > 0 {\n\t\t\tfor _, gc := range stmt.GroupList() {\n\t\t\t\tgroup = append(group, hash(f[gc.Position()-1]))\n\t\t\t}\n\t\t} else if distinctLine {\n\t\t\tfor _, ap := range aggrList {\n\t\t\t\tgroup = append(group, hash(f[ap]))\n\t\t\t}\n\t\t} else {\n\t\t\tgroup = append(group, uint64(p))\n\t\t}\n\t\tkey := fmt.Sprint(group)\n\n\t\t// Converts string slice of the row as expected by SQL driver.\n\t\trow := make([]driver.Value, columnSize)\n\t\tfor i, c := range stmt.Columns() {\n\t\t\tif method, ok := c.UseFunction(); ok {\n\t\t\t\t// Retrieves the aggregate value if already set.\n\t\t\t\tvar v AggregatedNullFloat64\n\t\t\t\tif r, ok := data[key]; ok {\n\t\t\t\t\tv = r[i].(AggregatedNullFloat64)\n\t\t\t\t}\n\t\t\t\tif method == \"COUNT\" {\n\t\t\t\t\t// Increments the counter.\n\t\t\t\t\tv.NullFloat64.Float64++\n\t\t\t\t\tv.NullFloat64.Valid = true\n\t\t\t\t\t// Calculates the length of the column.\n\t\t\t\t\tcs[i] = lenFloat64(v)\n\t\t\t\t\trow[i] = v\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Casts to float the current column's value.\n\t\t\t\tcv, err := aggregate(f[i], c.(db.Field).Kind())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t\tif !cv.NullFloat64.Valid {\n\t\t\t\t\t// Nil value, skip it.\n\t\t\t\t\trow[i] = v\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Applies the aggregate method on it valid value.\n\t\t\t\tswitch method {\n\t\t\t\tcase \"AVG\":\n\t\t\t\t\t// (((previous average x number of elements seen) + current value) /\n\t\t\t\t\t// current number of elements)\n\t\t\t\t\tfi := float64(i)\n\t\t\t\t\tv.NullFloat64.Float64 = ((v.NullFloat64.Float64 * fi) + cv.NullFloat64.Float64) / (fi + 1)\n\t\t\t\tcase \"MAX\":\n\t\t\t\t\tif !v.NullFloat64.Valid || v.NullFloat64.Float64 < cv.NullFloat64.Float64 {\n\t\t\t\t\t\tv.NullFloat64.Float64 = cv.NullFloat64.Float64\n\t\t\t\t\t}\n\t\t\t\tcase \"MIN\":\n\t\t\t\t\tif !v.NullFloat64.Valid || v.NullFloat64.Float64 > cv.NullFloat64.Float64 {\n\t\t\t\t\t\tv.NullFloat64.Float64 = cv.NullFloat64.Float64\n\t\t\t\t\t}\n\t\t\t\tcase \"SUM\":\n\t\t\t\t\tv.NullFloat64.Float64 += cv.NullFloat64.Float64\n\t\t\t\t}\n\t\t\t\tv.NullFloat64.Valid = true\n\t\t\t\tv.Layout = cv.Layout\n\n\t\t\t\t// Determines the precision to use in order to round it.\n\t\t\t\tif strings.ToUpper(c.(db.Field).Kind()) == \"DOUBLE\" {\n\t\t\t\t\tv.Precision = 2\n\t\t\t\t}\n\t\t\t\t// Calculates the size of the column in order to keep its max length.\n\t\t\t\tcs[i] = lenFloat64(v)\n\t\t\t\trow[i] = v\n\t\t\t} else {\n\t\t\t\tv, err := cast(f[i], c.(db.Field).Kind())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t\t// Calculates the size of the column in order to keep its max length.\n\t\t\t\tcs[i] = maxLen(f[i], cs[i])\n\t\t\t\trow[i] = v\n\t\t\t}\n\t\t}\n\t\tdata[key] = row\n\t}\n\n\t// Builds the result set.\n\trs := make([][]driver.Value, len(data))\n\tvar i int\n\tfor _, r := range data {\n\t\trs[i] = r\n\t\ti++\n\t}\n\treturn rs, cs, nil\n}", "func (pgb *PrizeGroupBy) Aggregate(fns ...AggregateFunc) *PrizeGroupBy {\n\tpgb.fns = append(pgb.fns, fns...)\n\treturn pgb\n}", "func (c *VMCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, m := range c.getMetrics() {\n\t\tch <- m\n\t}\n}", "func (degb *DentalExpenseGroupBy) Aggregate(fns ...AggregateFunc) *DentalExpenseGroupBy {\n\tdegb.fns = append(degb.fns, fns...)\n\treturn degb\n}", "func (wtgb *WorkerTypeGroupBy) Aggregate(fns ...AggregateFunc) *WorkerTypeGroupBy {\n\twtgb.fns = append(wtgb.fns, fns...)\n\treturn wtgb\n}", "func (nimgb *NetInterfaceModeGroupBy) Aggregate(fns ...AggregateFunc) *NetInterfaceModeGroupBy {\n\tnimgb.fns = append(nimgb.fns, fns...)\n\treturn nimgb\n}", "func (wgb *WordGroupBy) Aggregate(fns ...AggregateFunc) *WordGroupBy {\n\twgb.fns = append(wgb.fns, fns...)\n\treturn wgb\n}", "func (mgb *MediaGroupBy) Aggregate(fns ...AggregateFunc) *MediaGroupBy {\n\tmgb.fns = append(mgb.fns, fns...)\n\treturn mgb\n}", "func (wgb *WifiGroupBy) Aggregate(fns ...AggregateFunc) *WifiGroupBy {\n\twgb.fns = append(wgb.fns, fns...)\n\treturn wgb\n}", "func (ecpgb *EntityContactPointGroupBy) Aggregate(fns ...AggregateFunc) *EntityContactPointGroupBy {\n\tecpgb.fns = append(ecpgb.fns, fns...)\n\treturn ecpgb\n}", "func (q *Counts) Aggregate() int {\n\tagg := 0\n\tfor _, count := range q.Counts {\n\t\tagg += count\n\t}\n\treturn agg\n}", "func (f *flush) addMetric(n *Client, metricType string, value float64, persecond float64, hostname string, tags gostatsd.Tags, name string, timestamp gostatsd.Nanotime) {\n\tstandardMetric := newMetricSet(n, f, name, metricType, value, tags, timestamp)\n\tif metricType == \"counter\" {\n\t\tstandardMetric[n.metricPerSecond] = persecond\n\t}\n\tf.ts.Metrics = append(f.ts.Metrics, standardMetric)\n}", "func (evss *ExValueScanSelect) Aggregate(fns ...AggregateFunc) *ExValueScanSelect {\n\tevss.fns = append(evss.fns, fns...)\n\treturn evss\n}", "func (clidgb *CheckListItemDefinitionGroupBy) Aggregate(fns ...Aggregate) *CheckListItemDefinitionGroupBy {\n\tclidgb.fns = append(clidgb.fns, fns...)\n\treturn clidgb\n}", "func (a *AzureMonitor) Push() []telegraf.Metric {\n\tvar metrics []telegraf.Metric\n\tfor tbucket, aggs := range a.cache {\n\t\t// Do not send metrics early\n\t\tif tbucket.After(a.timeFunc().Add(-time.Minute)) {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, agg := range aggs {\n\t\t\t// Only send aggregates that have had an update since the last push.\n\t\t\tif !agg.updated {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttags := make(map[string]string, len(agg.dimensions))\n\t\t\tfor _, tag := range agg.dimensions {\n\t\t\t\ttags[tag.name] = tag.value\n\t\t\t}\n\n\t\t\tm := metric.New(agg.name,\n\t\t\t\ttags,\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"min\": agg.min,\n\t\t\t\t\t\"max\": agg.max,\n\t\t\t\t\t\"sum\": agg.sum,\n\t\t\t\t\t\"count\": agg.count,\n\t\t\t\t},\n\t\t\t\ttbucket,\n\t\t\t)\n\n\t\t\tmetrics = append(metrics, m)\n\t\t}\n\t}\n\treturn metrics\n}", "func (e *E2eProcessingLatencyAggregate) Add(e2 *E2eProcessingLatencyAggregate) {\n\te.Addr = \"*\"\n\tp := e.Percentiles\n\te.Count += e2.Count\n\tfor _, value := range e2.Percentiles {\n\t\ti := -1\n\t\tfor j, v := range p {\n\t\t\tif value[\"quantile\"] == v[\"quantile\"] {\n\t\t\t\ti = j\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif i == -1 {\n\t\t\ti = len(p)\n\t\t\te.Percentiles = append(p, make(map[string]float64))\n\t\t\tp = e.Percentiles\n\t\t\tp[i][\"quantile\"] = value[\"quantile\"]\n\t\t}\n\t\tp[i][\"max\"] = math.Max(value[\"max\"], p[i][\"max\"])\n\t\tp[i][\"min\"] = math.Min(value[\"max\"], p[i][\"max\"])\n\t\tp[i][\"count\"] += value[\"count\"]\n\t\tif p[i][\"count\"] == 0 {\n\t\t\tp[i][\"average\"] = 0\n\t\t\tcontinue\n\t\t}\n\t\tdelta := value[\"average\"] - p[i][\"average\"]\n\t\tR := delta * value[\"count\"] / p[i][\"count\"]\n\t\tp[i][\"average\"] = p[i][\"average\"] + R\n\t}\n\tsort.Sort(e)\n}", "func (a *Action) AggregateResult(result map[string]interface{}) error {\n\ta.Lock()\n\tdefer a.Unlock()\n\n\tif a.agg == nil {\n\t\ta.agg = newActionAggregators(a)\n\t}\n\n\tfor k, v := range result {\n\t\ta.agg.aggregateItem(k, v)\n\t}\n\n\treturn nil\n}", "func (wgb *WidgetGroupBy) Aggregate(fns ...AggregateFunc) *WidgetGroupBy {\n\twgb.fns = append(wgb.fns, fns...)\n\treturn wgb\n}", "func (bigb *BankItemGroupBy) Aggregate(fns ...Aggregate) *BankItemGroupBy {\n\tbigb.fns = append(bigb.fns, fns...)\n\treturn bigb\n}", "func (sgb *ServerGroupBy) Aggregate(fns ...AggregateFunc) *ServerGroupBy {\n\tsgb.fns = append(sgb.fns, fns...)\n\treturn sgb\n}", "func (column TsTimestampColumn) Aggregate(aggs ...*TsTimestampAggregation) ([]TsTimestampAggregation, error) {\n\treturn nil, ErrNotImplemented\n}", "func (m *Metrics) accumulate(ids []string) []*docker.ContainerStats {\n\tvar metrics []*docker.ContainerStats\n\n\tfor _, id := range ids {\n\t\tif data, ok := m.load(id); ok {\n\t\t\tmetrics = append(metrics, data)\n\t\t}\n\t}\n\n\treturn metrics\n}", "func (p *promProducer) Collect(ch chan<- prometheus.Metric) {\n\tfor _, obj := range p.store.Objects() {\n\t\tmessage, ok := obj.(producers.MetricsMessage)\n\t\tif !ok {\n\t\t\tpromLog.Warnf(\"Unsupported message type %T\", obj)\n\t\t\tcontinue\n\t\t}\n\t\tdims := dimsToMap(message.Dimensions)\n\n\t\tfor _, d := range message.Datapoints {\n\t\t\tpromLog.Debugf(\"Processing datapoint %s\", d.Name)\n\t\t\tvar tagKeys []string\n\t\t\tvar tagVals []string\n\t\t\tfor k, v := range dims {\n\t\t\t\ttagKeys = append(tagKeys, sanitizeName(k))\n\t\t\t\ttagVals = append(tagVals, v)\n\t\t\t}\n\t\t\tfor k, v := range d.Tags {\n\t\t\t\ttagKeys = append(tagKeys, sanitizeName(k))\n\t\t\t\ttagVals = append(tagVals, v)\n\t\t\t}\n\n\t\t\tname := sanitizeName(d.Name)\n\t\t\tval, err := coerceToFloat(d.Value)\n\t\t\tif err != nil {\n\t\t\t\tpromLog.Warnf(\"Bad datapoint value %q: %s\", d.Value, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdesc := prometheus.NewDesc(name, \"DC/OS Metrics Datapoint\", tagKeys, nil)\n\t\t\tmetric, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, val, tagVals...)\n\t\t\tif err != nil {\n\t\t\t\tpromLog.Warnf(\"Could not create Prometheus metric %s: %s\", name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpromLog.Debugf(\"Emitting datapoint %s\", name)\n\t\t\tch <- metric\n\t\t}\n\n\t}\n}", "func CollectAllMetrics(client *statsd.Client, log *li.StandardLogger) {\n\n\tvar metrics []metric\n\tmetrics = append(metrics, metric{name: \"gpu.temperature\", cmd: \"vcgencmd measure_temp | egrep -o '[0-9]*\\\\.[0-9]*'\"})\n\tmetrics = append(metrics, metric{name: \"cpu.temperature\", cmd: \"cat /sys/class/thermal/thermal_zone0/temp | awk 'END {print $1/1000}'\"})\n\tmetrics = append(metrics, metric{name: \"threads\", cmd: \"ps -eo nlwp | tail -n +2 | awk '{ num_threads += $1 } END { print num_threads }'\"})\n\tmetrics = append(metrics, metric{name: \"processes\", cmd: \"ps axu | wc -l\"})\n\n\tfor range time.Tick(15 * time.Second) {\n\t\tlog.Info(\"Starting metric collection\")\n\t\tfor _, m := range metrics {\n\t\t\terr := collectMetric(m, client, log)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (rtg *RTGProtocol) Aggregate(share1, share2, shareOut *RTGShare) {\n\tfor i := 0; i < rtg.beta; i++ {\n\t\trtg.ringQP.Add(share1.Value[i], share2.Value[i], shareOut.Value[i])\n\t}\n}", "func (m *metricMysqlRowOperations) emit(metrics pmetric.MetricSlice) {\n\tif m.settings.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}", "func (goagb *GroupOfAgeGroupBy) Aggregate(fns ...AggregateFunc) *GroupOfAgeGroupBy {\n\tgoagb.fns = append(goagb.fns, fns...)\n\treturn goagb\n}", "func (wfgb *WithFieldsGroupBy) Aggregate(fns ...AggregateFunc) *WithFieldsGroupBy {\n\twfgb.fns = append(wfgb.fns, fns...)\n\treturn wfgb\n}", "func (ougb *OrgUnitGroupBy) Aggregate(fns ...AggregateFunc) *OrgUnitGroupBy {\n\tougb.fns = append(ougb.fns, fns...)\n\treturn ougb\n}", "func (e *exemplarSampler) updateAggregations(val float64) {\n\te.count++\n\tdelta := val - e.mean\n\te.mean += delta / float64(e.count)\n\tdelta2 := val - e.mean\n\te.m2 += delta * delta2\n}" ]
[ "0.6164411", "0.6074627", "0.5965507", "0.59597355", "0.5875254", "0.5875014", "0.5857528", "0.58197755", "0.58098197", "0.57449234", "0.56896526", "0.5595609", "0.5498448", "0.5466111", "0.54290247", "0.542065", "0.5410119", "0.5407931", "0.54046893", "0.53769755", "0.53733444", "0.53696483", "0.53681093", "0.53640234", "0.5356901", "0.53391385", "0.5327724", "0.5320373", "0.52725184", "0.5255765", "0.5250244", "0.52354604", "0.520076", "0.5167296", "0.5162243", "0.51585776", "0.51550245", "0.51536125", "0.5150263", "0.513963", "0.51107407", "0.5109846", "0.5108162", "0.5096647", "0.5093919", "0.50931185", "0.50874245", "0.50849074", "0.5052752", "0.5052752", "0.505077", "0.5042166", "0.5034769", "0.5031559", "0.502538", "0.50139487", "0.5011194", "0.50106204", "0.5006073", "0.499751", "0.49883246", "0.49879202", "0.49865353", "0.4983646", "0.49718225", "0.49709308", "0.4967618", "0.49638698", "0.4961107", "0.495162", "0.49507612", "0.49454057", "0.49380678", "0.49363953", "0.49314502", "0.4930156", "0.49275312", "0.49266106", "0.49225307", "0.49213392", "0.4920259", "0.49138653", "0.49108154", "0.49056178", "0.48986742", "0.48938456", "0.48908535", "0.48884884", "0.4887398", "0.48868152", "0.488481", "0.4882808", "0.48800883", "0.48754063", "0.4872939", "0.48721063", "0.48671806", "0.48650318", "0.48591754", "0.48560157" ]
0.7339924
0
ToPublicKeyWithGenerators creates PublicKeyWithGenerators from the PublicKey.
func (pk *PublicKey) ToPublicKeyWithGenerators(messagesCount int) (*PublicKeyWithGenerators, error) { offset := g2UncompressedSize + 1 data := calcData(pk, messagesCount) h0 := hashToG1(data) h := make([]*ml.G1, messagesCount) for i := 1; i <= messagesCount; i++ { dataCopy := make([]byte, len(data)) copy(dataCopy, data) iBytes := uint32ToBytes(uint32(i)) for j := 0; j < len(iBytes); j++ { dataCopy[j+offset] = iBytes[j] } h[i-1] = hashToG1(dataCopy) } return &PublicKeyWithGenerators{ h0: h0, h: h, w: pk.PointG2, messagesCount: messagesCount, }, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func generatePublicKey(privatekey *rsa.PublicKey) ([]byte, error) {\n\tpublicRsaKey, err := ssh.NewPublicKey(privatekey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)\n\treturn pubKeyBytes, nil\n\n}", "func (k *PrivateKey) PublicKey() *PublicKey {\n\tpointG2 := curve.GenG2.Mul(frToRepr(k.FR))\n\n\treturn &PublicKey{pointG2}\n}", "func (k *PrivateKey) PublicKey() *PublicKey {\n\tpubKeyG2Point := bls.G2AffineOne.MulFR(k.PrivKey.GetFRElement().ToRepr())\n\n\treturn &PublicKey{g2pubs.NewPublicKeyFromG2(pubKeyG2Point.ToAffine())}\n}", "func NewPublicKey(pk map[string]interface{}) PublicKey {\n\treturn pk\n}", "func ExportPublicKey(key *rsa.PublicKey) []byte {\n\tkeyBytes := x509.MarshalPKCS1PublicKey(key)\n\treturn pem.EncodeToMemory(&pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tBytes: keyBytes,\n\t})\n}", "func PublicKeyToProto(pub interfaces.PublicKey) *PublicKey {\n\tif pub == nil {\n\t\treturn nil\n\t}\n\tpb := NewEmptyPublicKey()\n\tpb.Raw = pub.SerializeCompressed()\n\treturn pb\n}", "func (a *Account) PublicKey() *PubKey {\n\tk := new(PubKey)\n\tcopy(k[:], a.pub[:])\n\treturn k\n}", "func convertPublicKey(pk []uint8) []uint8 {\n\tvar z = make([]uint8, 32)\n\tvar x = gf()\n\tvar a = gf()\n\tvar b = gf()\n\n\tunpack25519(x, pk)\n\n\tA(a, x, gf1)\n\tZ(b, x, gf1)\n\tinv25519(a, a)\n\tM(a, a, b)\n\n\tpack25519(z, a)\n\treturn z\n}", "func NewPublicKey(ki crypto.PubKey) PublicKey {\n\treturn &publicKey{ki: ki}\n}", "func (k *PrivateKey) PublicKey() *PublicKey {\n\tif k == nil {\n\t\treturn nil\n\t}\n\tp := new(PublicKey)\n\tp.Pk.Curve = k.Curve\n\tp.Pk.X = k.X\n\tp.Pk.Y = k.Y\n\treturn p\n}", "func (s Seed) PublicKey(index uint64) types.SiaPublicKey {\n\tkey := s.deriveKeyPair(index)\n\treturn types.SiaPublicKey{\n\t\tAlgorithm: types.SignatureEd25519,\n\t\tKey: key[len(key)-ed25519.PublicKeySize:],\n\t}\n}", "func (k *Keypair) PublicKey() *PubKey {\n\tpub := new(PubKey)\n\tcopy(pub[:], k.pub[:])\n\treturn pub\n}", "func GeneratePublicKey(key string) (string, error) {\n\n // decode PEM encoding to ANS.1 PKCS1 DER\n block, _ := pem.Decode([]byte(key))\n // if block == nil { fmt.Printf(\"No Block found in keyfile\\n\"); os.Exit(1) }\n // if block.Type != \"RSA PRIVATE KEY\" { fmt.Printf(\"Unsupported key type\"); os.Exit(1) }\n\n // parse DER format to a native type\n privateKey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)\n\n bb, _ := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)\n\n pemdata := pem.EncodeToMemory(\n &pem.Block{\n Type: \"PUBLIC KEY\",\n Bytes: bb,\n },\n )\n\n return string(pemdata), nil\n\n}", "func MakePublicKey(privateKey *[64]byte) (publicKey *[32]byte) {\n\tpublicKey = new([32]byte)\n\n\th := sha512.New()\n\th.Write(privateKey[:32])\n\tdigest := h.Sum(nil)\n\n\tdigest[0] &= 248\n\tdigest[31] &= 127\n\tdigest[31] |= 64\n\n\tvar A edwards25519.ExtendedGroupElement\n\tvar hBytes [32]byte\n\tcopy(hBytes[:], digest)\n\tedwards25519.GeScalarMultBase(&A, &hBytes)\n\tA.ToBytes(publicKey)\n\n\tcopy(privateKey[32:], publicKey[:])\n\treturn\n}", "func PublicKey(pemkey []byte) (pub []byte, err error) {\n\tvar (\n\t\tpkey *rsa.PrivateKey\n\t)\n\n\tblk, _ := pem.Decode(pemkey) // assumes a single valid pem encoded key.\n\n\tif pkey, err = x509.ParsePKCS1PrivateKey(blk.Bytes); err != nil {\n\t\treturn pub, err\n\t}\n\n\treturn x509.MarshalPKCS1PublicKey(&pkey.PublicKey), nil\n}", "func CreateTestPubKeys(numPubKeys int) []crypto.PubKey {\n\tvar publicKeys []crypto.PubKey\n\tvar buffer bytes.Buffer\n\n\t// start at 10 to avoid changing 1 to 01, 2 to 02, etc\n\tfor i := 100; i < (numPubKeys + 100); i++ {\n\t\tnumString := strconv.Itoa(i)\n\t\tbuffer.WriteString(\"0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AF\") // base pubkey string\n\t\tbuffer.WriteString(numString) // adding on final two digits to make pubkeys unique\n\t\tpublicKeys = append(publicKeys, NewPubKeyFromHex(buffer.String()))\n\t\tbuffer.Reset()\n\t}\n\n\treturn publicKeys\n}", "func NewPublicKey_List(s *capnp.Segment, sz int32) (PublicKey_List, error) {\n\tl, err := capnp.NewCompositeList(s, capnp.ObjectSize{DataSize: 32, PointerCount: 1}, sz)\n\treturn PublicKey_List{l}, err\n}", "func PublicKey(priv keyconf.Key) (keyconf.Key, error) {\n\tif priv.Type != keyconf.PrivateKey {\n\t\treturn keyconf.Key{}, serrors.New(\"provided key is not a private key\", \"type\", priv.Type)\n\t}\n\traw, err := scrypto.GetPubKey(priv.Bytes, priv.Algorithm)\n\tif err != nil {\n\t\treturn keyconf.Key{}, serrors.WrapStr(\"error generating public key\", err)\n\t}\n\tkey := keyconf.Key{\n\t\tID: keyconf.ID{\n\t\t\tUsage: priv.Usage,\n\t\t\tIA: priv.IA,\n\t\t\tVersion: priv.Version,\n\t\t},\n\t\tType: keyconf.PublicKey,\n\t\tAlgorithm: priv.Algorithm,\n\t\tValidity: priv.Validity,\n\t\tBytes: raw,\n\t}\n\treturn key, nil\n}", "func (param *Parameters) KeyGen() (pk *PublicKey, sk *SecretKey) {\n\n\tpk, sk = new(PublicKey), new(SecretKey)\n\tpk.SeedA = uniform(param.lseedA)\n\trLen, seedSE := 2*param.no*param.n*param.lenX, uniform((param.lseedSE)+1)\n\n\tseedSE[0] = 0x5F\n\tr := param.shake(seedSE, rLen)\n\n\trLen /= 2\n\tA := param.Gen(pk.SeedA)\n\tsk.S = param.SampleMatrix(r[:rLen], param.no, param.n)\n\tE := param.SampleMatrix(r[rLen:], param.no, param.n)\n\tpk.B = param.mulAddMatrices(A, sk.S, E)\n\n\treturn\n}", "func PublicKeyToBytes(publicKey *rsa.PublicKey) []byte {\n\tblock := &pem.Block{\n\t\tType: \"RSA PUBLIC KEY\",\n\t\tBytes: x509.MarshalPKCS1PublicKey(publicKey),\n\t}\n\n\tpublic := pem.EncodeToMemory(block)\n\n\treturn public\n}", "func NewPublicKey(keyType KeyType, keyData []byte, keyID string) PublicKey {\n\treturn PublicKey{\n\t\tKeyType: keyType,\n\t\tKeyData: keyData,\n\t\tID: keyID,\n\t}\n}", "func PublicKeyFromSlice(b []byte) (*PublicKey, error) {\n\tif len(b) != PublicKeySize {\n\t\treturn nil, ErrInvalidPublicKey\n\t}\n\n\tvar p PublicKey\n\tcopy(p[:], b)\n\treturn &p, nil\n}", "func PublicKeyToBytes(pub *rsa.PublicKey) []byte {\n\tpubASN1, err := x509.MarshalPKIXPublicKey(pub)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpubBytes := pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PUBLIC KEY\",\n\t\tBytes: pubASN1,\n\t})\n\n\treturn pubBytes\n}", "func (p PrivateKey) PublicKey() (PublicKey, error) {\n\tpub, err := curve25519.X25519(p, curve25519.Basepoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pub, nil\n}", "func CombinePublicKeys(pubs []*PublicKey) *PublicKey {\n\th := SUITE.Point().Null()\n\tfor i := range pubs {\n\t\th = h.Add(h, pubs[i].p)\n\t}\n\treturn &PublicKey{h}\n}", "func generateKeys(t *testing.T) (priv ssh.Signer, pub ssh.PublicKey) {\n\trnd := rand.New(rand.NewSource(time.Now().Unix()))\n\trsaKey, err := rsa.GenerateKey(rnd, 1024)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to generate RSA key pair: %v\", err)\n\t}\n\tpriv, err = ssh.NewSignerFromKey(rsaKey)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to generate signer: %v\", err)\n\t}\n\tpub, err = ssh.NewPublicKey(&rsaKey.PublicKey)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to generate public key: %v\", err)\n\t}\n\treturn priv, pub\n}", "func SignPublicKey(p PrivateKey, certType uint32, principals []string, ttl time.Duration, pub ssh.PublicKey) (*ssh.Certificate, error) {\n\t// OpenSSH controls what the key allows through extensions.\n\t// See https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys\n\tvar extensions map[string]string\n\tif certType == 1 {\n\t\textensions = map[string]string{\n\t\t\t\"permit-agent-forwarding\": \"\",\n\t\t\t\"permit-x11-forwarding\": \"\",\n\t\t\t\"permit-port-forwarding\": \"\",\n\t\t\t\"permit-pty\": \"\",\n\t\t\t\"permit-user-rc\": \"\",\n\t\t}\n\t}\n\n\tfrom := time.Now()\n\tto := time.Now().Add(ttl)\n\tcert := &ssh.Certificate{\n\t\tCertType: certType,\n\t\tKey: pub,\n\t\tValidAfter: uint64(from.Unix()),\n\t\tValidBefore: uint64(to.Unix()),\n\t\tValidPrincipals: principals,\n\t\tPermissions: ssh.Permissions{\n\t\t\tExtensions: extensions,\n\t\t},\n\t}\n\ts, err := NewSigner(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := cert.SignCert(rand.Reader, s); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cert, nil\n}", "func encodePublicKey(public *rsa.PublicKey) ([]byte, error) {\n\tpublicBytes, err := x509.MarshalPKIXPublicKey(public)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pem.EncodeToMemory(&pem.Block{\n\t\tBytes: publicBytes,\n\t\tType: \"PUBLIC KEY\",\n\t\tHeaders: nil,\n\t}), nil\n}", "func PublicKeyToBytes(pub *rsa.PublicKey) []byte {\n\tpubASN1, err := x509.MarshalPKIXPublicKey(pub)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n\n\tpubBytes := pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PUBLIC KEY\",\n\t\tBytes: pubASN1,\n\t})\n\n\treturn pubBytes\n}", "func (*FactorySECP256K1R) ToPublicKey(b []byte) (PublicKey, error) {\n\tkey, err := secp256k1.ParsePubKey(b)\n\treturn &PublicKeySECP256K1R{\n\t\tpk: key,\n\t\tbytes: b,\n\t}, err\n}", "func NewPublicKey(seed Trytes, index int) (Trytes, error) {\n\tbytesSec, err := seed.Trits().Bytes()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif mKey == nil {\n\t\tkey, err := hdkey.NewMaster(bytesSec, nil, 1)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tmKey = key\n\t}\n\n\tpubKey, err := mKey.Child(uint32(index))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpkCompressed := pubKey.PublicKey().Compress()\n\tpkInt := new(big.Int).SetBytes(pkCompressed[:])\n\tkeyTrit := make([]byte, 48)\n\tcopy(keyTrit, pkInt.Bytes())\n\ttrits, err := BytesToTrits(keyTrit)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn trits.Trytes(), err\n}", "func (s Keygen) PublicKey() *ecdsa.PublicKey {\n\treturn nil\n}", "func NewPublicKey(authenticatorType AuthenticatorType, signatureAlgorithm SignatureAlgorithm, keyData []byte, keyID string) (*PublicKey, error) {\n\tnewKeyID := \"\"\n\tswitch authenticatorType {\n\tcase Pgp:\n\t\tid, err := extractPgpKeyID(keyData)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnewKeyID = id\n\t\tif signatureAlgorithm != PGPUnused {\n\t\t\treturn nil, fmt.Errorf(\"expected undefined signature algorithm with PGP key type\")\n\t\t}\n\tcase Pkix, Jwt:\n\t\tid, err := extractPkixKeyID(keyData, keyID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnewKeyID = id\n\t\tif signatureAlgorithm == UnknownSigningAlgorithm || signatureAlgorithm == PGPUnused {\n\t\t\treturn nil, fmt.Errorf(\"expected signature algorithm with JWT/PKIX key type\")\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid AuthenticatorType\")\n\t}\n\n\treturn &PublicKey{\n\t\tAuthenticatorType: authenticatorType,\n\t\tSignatureAlgorithm: signatureAlgorithm,\n\t\tKeyData: keyData,\n\t\tID: newKeyID,\n\t}, nil\n}", "func (o PlaybackKeyPairOutput) PublicKey() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PlaybackKeyPair) pulumi.StringOutput { return v.PublicKey }).(pulumi.StringOutput)\n}", "func RuskPublicKey() *rusk.PublicKey {\n\treturn &rusk.PublicKey{\n\t\tPayload: make([]byte, 64),\n\t}\n}", "func (p *PrivateKey) PublicKey() *PublicKey {\n\tresult := PublicKey(p.PrivateKey.PublicKey)\n\treturn &result\n}", "func (x *Ed25519Credentials) PublicKey() PublicKey {\n\n\treturn PublicKey{\n\t\tAlgorithm: AlgorithmEd25519,\n\t\tPublic: base64.URLEncoding.EncodeToString(x.Public[:]),\n\t}\n\n}", "func genKey() *Key {\n\tprivKey := crypto.GenPrivKeyEd25519()\n\treturn &Key{\n\t\tAddress: privKey.PubKey().Address(),\n\t\tPubKey: privKey.PubKey(),\n\t\tPrivKey: privKey,\n\t}\n}", "func GeneratePublicRSAKey(publicKey *rsa.PublicKey) ([]byte, error) {\n\tpublicRsaKey, err := ssh.NewPublicKey(publicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)\n\n\treturn pubKeyBytes, nil\n}", "func PublicKeyFromPvk(privateKey []byte) []byte {\n\tvar A edwards25519.ExtendedGroupElement\n\tvar hBytes [32]byte\n\tcopy(hBytes[:], privateKey)\n\tedwards25519.GeScalarMultBase(&A, &hBytes)\n\tvar publicKeyBytes [32]byte\n\tA.ToBytes(&publicKeyBytes)\n\n\treturn publicKeyBytes[:]\n}", "func (s GPGSigner) PublicKey() ([]byte, error) {\n\tgpg2 := exec.Command(s.gpgExecutable, \"--export\", s.GPGUserName)\n\tif err := s.Rewriter(gpg2); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error invoking Rewrite: %v\", err)\n\t}\n\tout, err := gpg2.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error getting stdout pipe: %v\", err)\n\t}\n\tif err := gpg2.Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error starting gpg command: %v\", err)\n\t}\n\tpubkey, err := ioutil.ReadAll(out)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading pubkey data: %v\", err)\n\t}\n\tif err := gpg2.Wait(); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error running gpg: %v\", err)\n\t}\n\treturn pubkey, nil\n}", "func NewPublicKey(r io.Reader) (*PublicKey, error) {\n\trawPub, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey, _, _, _, err := ssh.ParseAuthorizedKey(rawPub)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &PublicKey{key: key}, nil\n}", "func NewPublicKey(name ndn.Name, key *rsa.PublicKey) (keychain.PublicKey, error) {\n\tif !keychain.IsKeyName(name) {\n\t\treturn nil, keychain.ErrKeyName\n\t}\n\tvar pub publicKey\n\tpub.name = name\n\tpub.key = key\n\treturn &pub, nil\n}", "func BytesToPublicKey(pubKey []byte) (PublicKey, error) {\n\treturn newSecp256k1PubKeyFromBytes(pubKey)\n}", "func (c *CertInfo) PublicKey() []byte {\n\tdata := c.KeyPair().Certificate[0]\n\treturn pem.EncodeToMemory(&pem.Block{Type: \"CERTIFICATE\", Bytes: data})\n}", "func GeneratePubKey(privateKeyBytes []byte) ([]byte, error) {\n\tvar privateKeyBytes32 [size]byte\n\tfor i := 0; i < size; i++ {\n\t\tprivateKeyBytes32[i] = privateKeyBytes[i]\n\t}\n\tsecp256k1.Start()\n\tpublicKeyBytes, success := secp256k1.Pubkey_create(privateKeyBytes32, false)\n\tsecp256k1.Stop()\n\n\tif !success {\n\t\treturn []byte{}, fmt.Errorf(\"Failed to generate public key\")\n\t}\n\treturn publicKeyBytes, nil\n}", "func KeyGenerator() (*Key, error) {\n\tlog.Info(\"Generate new ssh key\")\n\n\tkey := new(Key)\n\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\tlog.Errorf(\"PrivateKey generator failed reason: %s\", err.Error())\n\t\treturn key, err\n\t}\n\n\tprivateKeyPEM := &pem.Block{Type: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}\n\tkeyBuff := new(bytes.Buffer)\n\tif err := pem.Encode(keyBuff, privateKeyPEM); err != nil {\n\t\tlog.Errorf(\"PrivateKey generator failed reason: %s\", err.Error())\n\t\treturn key, err\n\t}\n\tkey.PrivateKeyData = keyBuff.String()\n\tlog.Debug(\"Private key generated.\")\n\n\tpub, err := ssh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\tlog.Errorf(\"PublicKey generator failed reason: %s\", err.Error())\n\t\treturn key, err\n\t}\n\tlog.Debug(\"Public key generated.\")\n\n\tkey.PublicKeyData = fmt.Sprintf(\"%s %s \\n\", strings.TrimSuffix(string(ssh.MarshalAuthorizedKey(pub)), \"\\n\"), \"[email protected]\")\n\n\tkey.PublicKeyFingerprint = ssh.FingerprintSHA256(pub)\n\tlog.Info(\"SSH key generated.\")\n\n\treturn key, nil\n}", "func MarshalPublicKey(pubkey *rsa.PublicKey) string {\n\tpk, err := ssh.NewPublicKey(pubkey)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn string(ssh.MarshalAuthorizedKey(pk))\n}", "func ToCmtProtoPublicKey(pk cryptotypes.PubKey) (cmtprotocrypto.PublicKey, error) {\n\tswitch pk := pk.(type) {\n\tcase *ed25519.PubKey:\n\t\treturn cmtprotocrypto.PublicKey{\n\t\t\tSum: &cmtprotocrypto.PublicKey_Ed25519{\n\t\t\t\tEd25519: pk.Key,\n\t\t\t},\n\t\t}, nil\n\tcase *secp256k1.PubKey:\n\t\treturn cmtprotocrypto.PublicKey{\n\t\t\tSum: &cmtprotocrypto.PublicKey_Secp256K1{\n\t\t\t\tSecp256K1: pk.Key,\n\t\t\t},\n\t\t}, nil\n\tdefault:\n\t\treturn cmtprotocrypto.PublicKey{}, errors.Wrapf(sdkerrors.ErrInvalidType, \"cannot convert %v to Tendermint public key\", pk)\n\t}\n}", "func ToPublic(sigType crypto.SigType, pk []byte) ([]byte, error) {\n\tsv, ok := sigs[sigType]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"cannot generate public key of unsupported type: %v\", sigType)\n\t}\n\n\treturn sv.ToPublic(pk)\n}", "func NewPublicKey(str string) (key PublicKey, err error) {\n\tbs, err := base58.Decode(str)\n\tif err != nil {\n\t\treturn key, err\n\t}\n\tif len(bs) != KeySize {\n\t\treturn key, errors.New(\"invalid key\")\n\t}\n\tcopy(key[:], bs)\n\treturn key, nil\n}", "func (o *WaitListParams) SetPublicKey(publicKey *string) {\n\to.PublicKey = publicKey\n}", "func (pk *PrivateKey) GetPublicKey() *PublicKey {\n var publicKeyBytes PublicKey\n copy(publicKeyBytes[:], pk[32:])\n return &publicKeyBytes\n}", "func (params *KeyParameters) GenerateKeys() (pk *PublicKey, sk *SecretKey) {\n\tvar err error\n\tsk = new(SecretKey)\n\tpk = new(PublicKey)\n\tsk.KeyParameters = *params\n\tpk.KeyParameters = *params\n\n\t// Choose a random secret key X.\n\tsk.P = params.P\n\tsk.G = params.G\n\tsk.Q = params.Q\n\t// Choose a random exponent in [0,Q-1).\n\tif sk.X, err = pk.KeyParameters.Sample(); err != nil {\n\t\treturn nil, nil\n\t}\n\tsk.qMinusX = new(big.Int)\n\tsk.qMinusX.Sub(params.Q, sk.X)\n\n\t// Compute Y = G^X mod P.\n\tpk.P = params.P\n\tpk.G = params.G\n\tpk.Q = params.Q\n\tpk.Y = new(big.Int)\n\tpk.Y.Exp(params.G, sk.X, params.P)\n\treturn\n}", "func marshalPublicKey(pub interface{}) ([]byte, error) {\n\tvar publicKeyBytes []byte\n\tvar err error\n\tswitch p := pub.(type) {\n\tcase *ecdsa.PublicKey:\n\t\t// Stolen from https://golang.org/src/crypto/x509/x509.go?s=2771:2829#L87\n\t\tpublicKeyBytes = elliptic.Marshal(p.Curve, p.X, p.Y)\n\tcase *rsa.PublicKey:\n\t\t// TODO: Append exponent\n\t\tpublicKeyBytes = p.N.Bytes()\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unsupported public key type: %T\", pub)\n\t}\n\treturn publicKeyBytes, err\n}", "func (o *PipelineSshKeyPairAllOf) SetPublicKey(v string) {\n\to.PublicKey = &v\n}", "func CreatePublicKeyX25519FromBase64(publicKeyBase64 string) (*X25519.PublicKey, error) {\n publicKeyBytes, err := base64.StdEncoding.DecodeString(publicKeyBase64)\n if err != nil {\n return nil, err\n }\n return X25519.NewPublicKey(publicKeyBytes), nil\n}", "func PublicKey(a *big.Int, p *big.Int, g int64) *big.Int {\n\tbigG := big.NewInt(g)\n\tbigG.Exp(bigG, a, p)\n\treturn bigG\n}", "func (keys_and_cert KeysAndCert) PublicKey() (key crypto.PublicKey, err error) {\n\tcert, err := keys_and_cert.Certificate()\n\tif err != nil {\n\t\treturn\n\t}\n\tcert_len, err := cert.Length()\n\tif err != nil {\n\t\treturn\n\t}\n\tif cert_len == 0 {\n\t\t// No Certificate is present, return the KEYS_AND_CERT_PUBKEY_SIZE byte\n\t\t// PublicKey space as ElgPublicKey.\n\t\tvar elg_key crypto.ElgPublicKey\n\t\tcopy(keys_and_cert[:KEYS_AND_CERT_PUBKEY_SIZE], elg_key[:])\n\t\tkey = elg_key\n\t} else {\n\t\t// A Certificate is present in this KeysAndCert\n\t\tcert_type, _ := cert.Type()\n\t\tif cert_type == CERT_KEY {\n\t\t\t// This KeysAndCert contains a Key Certificate, construct\n\t\t\t// a PublicKey from the data in the KeysAndCert and\n\t\t\t// any additional data in the Certificate.\n\t\t\tkey, err = KeyCertificate(cert).ConstructPublicKey(\n\t\t\t\tkeys_and_cert[:KEYS_AND_CERT_PUBKEY_SIZE],\n\t\t\t)\n\t\t} else {\n\t\t\t// Key Certificate is not present, return the KEYS_AND_CERT_PUBKEY_SIZE byte\n\t\t\t// PublicKey space as ElgPublicKey. No other Certificate\n\t\t\t// types are currently in use.\n\t\t\tvar elg_key crypto.ElgPublicKey\n\t\t\tcopy(keys_and_cert[:KEYS_AND_CERT_PUBKEY_SIZE], elg_key[:])\n\t\t\tkey = elg_key\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"at\": \"(KeysAndCert) PublicKey\",\n\t\t\t\t\"cert_type\": cert_type,\n\t\t\t}).Warn(\"unused certificate type observed\")\n\t\t}\n\n\t}\n\treturn\n}", "func PublicKey(private, p *big.Int, g int64) *big.Int {\n\n\t// calculate the public key based on the following formula\n\t// pubKey = g**privKey mod p\n\tG := big.NewInt(g)\n\tpubKey := G.Exp(G, private, p)\n\n\treturn pubKey\n}", "func (s NativeSigner) PublicKey() ([]byte, error) {\n\tkeybuf := new(bytes.Buffer)\n\tif err := (*openpgp.Entity)(&s).Serialize(keybuf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn keybuf.Bytes(), nil\n}", "func GetPublicKey(pub ssh.PublicKey) []byte {\n\tmarshaled := ssh.MarshalAuthorizedKey(pub)\n\t// Strip trailing newline\n\treturn marshaled[:len(marshaled)-1]\n}", "func (w *wrappedMultiSignerVerifier) PublicKey(opts ...signature.PublicKeyOption) (crypto.PublicKey, error) {\n\treturn w.signer.PublicKey(opts...)\n}", "func (k *PrivateKeySECP256K1R) PublicKey() PublicKey {\n\tif k.pk == nil {\n\t\tk.pk = &PublicKeySECP256K1R{pk: k.sk.PubKey()}\n\t}\n\treturn k.pk\n}", "func GeneratePublicKeyHash(recoveryFlag int, pubKey *btcec.PublicKey) []byte {\n\tif funk.ContainsInt(flags.Uncompressed(), recoveryFlag) {\n\t\treturn btcutil.Hash160(pubKey.SerializeUncompressed())\n\t}\n\n\treturn btcutil.Hash160(pubKey.SerializeCompressed())\n}", "func (c *publicKey) Encode() (*pb.PublicKey, error) {\n\tif c.ki == nil {\n\t\treturn nil, ErrPublicKeyCannotBeNil()\n\t}\n\n\tblob, err := crypto.MarshalPublicKey(c.ki)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpbuf := pb.PublicKey{Blob: blob}\n\n\treturn &pbuf, nil\n}", "func (pk PrivateKey) PublicKey() hotstuff.PublicKey {\n\treturn pk.Public()\n}", "func NewPublicKey(raw []byte, algo Algorithm) (PublicKey, error) {\n\tswitch algo {\n\tcase KeyAlgoSecp256k1:\n\t\treturn newSECP256K1PublicKey(raw)\n\tdefault:\n\t\treturn newSM2PublicKey(raw)\n\t}\n}", "func FromCmtProtoPublicKey(protoPk cmtprotocrypto.PublicKey) (cryptotypes.PubKey, error) {\n\tswitch protoPk := protoPk.Sum.(type) {\n\tcase *cmtprotocrypto.PublicKey_Ed25519:\n\t\treturn &ed25519.PubKey{\n\t\t\tKey: protoPk.Ed25519,\n\t\t}, nil\n\tcase *cmtprotocrypto.PublicKey_Secp256K1:\n\t\treturn &secp256k1.PubKey{\n\t\t\tKey: protoPk.Secp256K1,\n\t\t}, nil\n\tdefault:\n\t\treturn nil, errors.Wrapf(sdkerrors.ErrInvalidType, \"cannot convert %v from Tendermint public key\", protoPk)\n\t}\n}", "func BytesToPublicKey(public []byte) *rsa.PublicKey {\n\n\tblock, _ := pem.Decode(public)\n\tresult, _ := x509.ParsePKCS1PublicKey(block.Bytes)\n\treturn result\n}", "func (k *EdX25519Key) PublicKey() *EdX25519PublicKey {\n\treturn k.publicKey\n}", "func BytesToPublicKey(data []byte) (pk *PublicKey) {\n\tpk = new(PublicKey)\n\tpk.PubKey.Curve = getDefaultCurve()\n\t//fmt.Printf(\"begin pub key unmarshal, len=%v, data=%v.\\n\", len(data), data)\n\tx, y := elliptic.Unmarshal(pk.PubKey.Curve, data)\n\tif x == nil || y == nil {\n\t\tpanic(\"unmarshal public key failed.\")\n\t}\n\tpk.PubKey.X = x\n\tpk.PubKey.Y = y\n\treturn\n}", "func (v *Validator) PublicKeyBytes() []byte {\n\tif v.pubBytes == nil || len(v.pubBytes) == 0 {\n\t\tv.pubBytes = keys.FromPublicKey(&v.Key.PublicKey)\n\t}\n\treturn v.pubBytes\n}", "func (sk PrivateKey) PublicKey() PublicKey {\n\treturn PublicKey{publicKey: sk.privateKey.PublicKey()}\n}", "func NewPubKey() *PubKey {\n\tp := new(PubKey)\n\tp.newClient()\n\tp.load()\n\treturn p\n}", "func EncryptWithPublicKey(msg *[]byte, pub *rsa.PublicKey) []byte {\n\thash := sha512.New()\n\tciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pub, *msg, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn ciphertext\n}", "func PublicKey(private, p *big.Int, g int64) *big.Int {\n\treturn new(big.Int).Exp(big.NewInt(g), private, p)\n}", "func (x *X25519) PublicKey() []byte {\n\treturn x.publicKey[:]\n}", "func (ec *ECPoint) ToPublicKey() *ecdsa.PublicKey {\n\tres := new(ecdsa.PublicKey)\n\tres.X = ec.X\n\tres.Y = ec.Y\n\tres.Curve = ec.Curve\n\n\treturn res\n}", "func (obj *MessengerUser) PublicKey() (foundation.PublicKey, error) {\n\tproxyResult := /*pr4*/ C.vssq_messenger_user_public_key(obj.cCtx)\n\n\truntime.KeepAlive(obj)\n\n\treturn foundation.ImplementationWrapPublicKeyCopy(unsafe.Pointer(proxyResult)) /* r4.1 */\n}", "func (pb *PutBlock) ProducerPublicKey() crypto.PublicKey { return pb.SrcPubkey() }", "func ConvertPublicKey(key crypto.PublicKey) (PublicKey, error) {\n\tswitch typed := key.(type) {\n\tdefault:\n\t\treturn nil, errors.Wrapf(ErrKeyType, \"Unsupported key type: %v\", reflect.TypeOf(key))\n\tcase *rsa.PublicKey:\n\t\treturn &RSAPublicKey{typed}, nil\n\t}\n}", "func (kt KeyType) PublicKey() string {\n\treturn fmt.Sprintf(\"%s.pub\", kt.KeyBaseName)\n}", "func SshPublicKeySpecGenerator() gopter.Gen {\n\tif sshPublicKeySpecGenerator != nil {\n\t\treturn sshPublicKeySpecGenerator\n\t}\n\n\tgenerators := make(map[string]gopter.Gen)\n\tAddIndependentPropertyGeneratorsForSshPublicKeySpec(generators)\n\tsshPublicKeySpecGenerator = gen.Struct(reflect.TypeOf(SshPublicKeySpec{}), generators)\n\n\treturn sshPublicKeySpecGenerator\n}", "func GeneratePubKey(ctx *Context, seckey PrivKey) (int, []byte, error) {\n\tif len(seckey) != PrivateKeyLength {\n\t\treturn 0, nil, errors.New(PrivateKeySizeError)\n\t}\n\n\tvar pubkey = make([]byte, 64)\n\tvar pubkeyPtr *C.secp256k1_pubkey = (*C.secp256k1_pubkey)(unsafe.Pointer(&pubkey[0]))\n\n\tresult := int(C.secp256k1_ec_pubkey_create(ctx.ctx, pubkeyPtr, cBuf(seckey[:])))\n\tif result != 1 {\n\t\treturn result, nil, errors.New(PublicKeyCreateError)\n\t}\n\n\treturn result, pubkey, nil\n}", "func UnmarshalPublicKey(pubKeyBytes []byte) (*PublicKey, error) {\n\tif len(pubKeyBytes) != bls12381G2PublicKeyLen {\n\t\treturn nil, errors.New(\"invalid size of public key\")\n\t}\n\n\tpointG2, err := curve.NewG2FromCompressed(pubKeyBytes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"deserialize public key: %w\", err)\n\t}\n\n\treturn &PublicKey{\n\t\tPointG2: pointG2,\n\t}, nil\n}", "func (pk PublicKey) Encode() []byte {\n\treturn pk.publicKey.Encode()\n}", "func PublicKeyOf(v interface{}) (interface{}, error) {\n\t// may be a silly idea, but if the user gave us a non-pointer value...\n\tvar ptr interface{}\n\tswitch v := v.(type) {\n\tcase rsa.PrivateKey:\n\t\tptr = &v\n\tcase rsa.PublicKey:\n\t\tptr = &v\n\tcase ecdsa.PrivateKey:\n\t\tptr = &v\n\tcase ecdsa.PublicKey:\n\t\tptr = &v\n\tdefault:\n\t\tptr = v\n\t}\n\n\tswitch x := ptr.(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn &x.PublicKey, nil\n\tcase *rsa.PublicKey:\n\t\treturn x, nil\n\tcase *ecdsa.PrivateKey:\n\t\treturn &x.PublicKey, nil\n\tcase *ecdsa.PublicKey:\n\t\treturn x, nil\n\tcase []byte:\n\t\treturn x, nil\n\tdefault:\n\t\treturn nil, errors.Errorf(`invalid key type passed to PublicKeyOf (%T)`, v)\n\t}\n}", "func Ed25519PublicKey(pk crypto.PublicKey) PublicKey {\n\treturn PublicKey{\n\t\tAlgorithm: SignatureAlgoEd25519,\n\t\tKey: pk[:],\n\t}\n}", "func (o KeystoresAliasesPkcs12CertsInfoCertInfoOutput) PublicKey() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KeystoresAliasesPkcs12CertsInfoCertInfo) *string { return v.PublicKey }).(pulumi.StringPtrOutput)\n}", "func EncryptWithPublicKey(msg []byte, pub *rsa.PublicKey) []byte {\n\tciphertext, err := rsa.EncryptOAEP(sha512.New(), rand.Reader, pub, msg, nil)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn ciphertext\n}", "func ToTmProtoPublicKey(pk cryptotypes.PubKey) (cmtprotocrypto.PublicKey, error) {\n\treturn ToCmtProtoPublicKey(pk)\n}", "func NewPublicKeyFromBytes(rawKey []byte) (PublicKey, error) {\n\tif l := len(rawKey); l != CompressedPublicKeyLength {\n\t\treturn PublicKey{}, fmt.Errorf(\n\t\t\t\"wrong length for public key: %s of length %d\", rawKey, l)\n\t}\n\tvar k PublicKey\n\tif c := copy(k[:], rawKey); c != CompressedPublicKeyLength {\n\t\tpanic(fmt.Errorf(\"failed to copy entire key to return value\"))\n\t}\n\treturn k, nil\n}", "func PublicKey(key ssh.PublicKey) (crypto.PublicKey, error) {\n\t_, in, ok := parseString(key.Marshal())\n\tif !ok {\n\t\treturn nil, errors.New(\"public key is invalid\")\n\t}\n\n\tswitch key.Type() {\n\tcase ssh.KeyAlgoRSA:\n\t\treturn parseRSA(in)\n\tcase ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521, ssh.KeyAlgoSKECDSA256:\n\t\treturn parseECDSA(in)\n\tcase ssh.KeyAlgoED25519, ssh.KeyAlgoSKED25519:\n\t\treturn parseED25519(in)\n\tcase ssh.KeyAlgoDSA:\n\t\treturn parseDSA(in)\n\tdefault:\n\t\treturn nil, errors.Errorf(\"public key %s is not supported\", key.Type())\n\t}\n}", "func NewPopulatedProtoPubKey(_ randyNet) *ProtoPubKey {\n\t_, k, _ := crypto.GenerateKeyPair(crypto.RSA, 512)\n\treturn &ProtoPubKey{PubKey: k}\n}", "func SplitKey(privateKey *big.Int, publicKey *Key, n int) ([]*Trustee, []*big.Int, error) {\n\t// Choose n-1 random private keys and compute the nth as privateKey -\n\t// (key_1 + key_2 + ... + key_{n-1}). This computation must be\n\t// performed in the exponent group of g, which is\n\t// Z_{Key.ExponentPrime}.\n\ttrustees := make([]*Trustee, n)\n\tkeys := make([]*big.Int, n)\n\tsum := big.NewInt(0)\n\tvar err error\n\tfor i := 0; i < n-1; i++ {\n\t\tkeys[i], err = rand.Int(rand.Reader, publicKey.ExponentPrime)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\ttpk := &Key{\n\t\t\tGenerator: new(big.Int).Set(publicKey.Generator),\n\t\t\tPrime: new(big.Int).Set(publicKey.Prime),\n\t\t\tExponentPrime: new(big.Int).Set(publicKey.ExponentPrime),\n\t\t\tPublicValue: new(big.Int).Exp(publicKey.Generator, keys[i], publicKey.Prime),\n\t\t}\n\n\t\ttrustees[i] = &Trustee{PublicKey: tpk}\n\t\tsum.Add(sum, keys[i])\n\t\tsum.Mod(sum, publicKey.ExponentPrime)\n\t}\n\n\t// The choice of random private keys in the loop fully determines the\n\t// final key.\n\tkeys[n-1] = new(big.Int).Sub(privateKey, sum)\n\tkeys[n-1].Mod(keys[n-1], publicKey.ExponentPrime)\n\t//npok, err := NewSchnorrProof(keys[n-1], publicKey)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tntpk := &Key{\n\t\tGenerator: new(big.Int).Set(publicKey.Generator),\n\t\tPrime: new(big.Int).Set(publicKey.Prime),\n\t\tExponentPrime: new(big.Int).Set(publicKey.ExponentPrime),\n\t\tPublicValue: new(big.Int).Exp(publicKey.Generator, keys[n-1], publicKey.Prime),\n\t}\n\n\t//trustees[n-1] = &Trustee{PoK: npok, PublicKey: ntpk}\n\ttrustees[n-1] = &Trustee{PublicKey: ntpk}\n\n\treturn trustees, keys, nil\n}", "func genPubkey() ([]byte, []byte) {\n\t_, pub := btcec.PrivKeyFromBytes(btcec.S256(), randomBytes(32))\n\tpubkey := pub.SerializeCompressed()\n\tpkHash := btcutil.Hash160(pubkey)\n\treturn pubkey, pkHash\n}", "func TweakPubKey(pubKey *btcec.PublicKey, tweak []byte) *btcec.PublicKey {\n\n\tpath := getDerivationPathFromTweak(tweak) // get derivation path for tweak\n\n\t// set initial pubkey X/Y to current pubkey\n\tresX := pubKey.ToECDSA().X\n\tresY := pubKey.ToECDSA().Y\n\n\t// tweak pubkey for each path child\n\tfor _, pathChild := range path {\n\t\t// get tweaked pubkey\n\t\tresX, resY = tweakPubWithPathChild(pathChild, resX, resY)\n\t}\n\n\treturn (*btcec.PublicKey)(&ecdsa.PublicKey{btcec.S256(), resX, resY})\n}", "func TestPublicKey(t *testing.T) {\n\tconst jsonkey = `{\"keys\":\n [\n {\"kty\":\"EC\",\n \"crv\":\"P-256\",\n \"x\":\"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4\",\n \"y\":\"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM\",\n \"use\":\"enc\",\n \"kid\":\"1\"},\n\n {\"kty\":\"RSA\",\n \"n\": \"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw\",\n \"e\":\"AQAB\",\n \"alg\":\"RS256\",\n \"kid\":\"2011-04-29\"}\n ]\n }`\n\n\tjwt, err := Unmarshal([]byte(jsonkey))\n\tif err != nil {\n\t\tt.Fatal(\"Unmarshal: \", err)\n\t} else if len(jwt.Keys) != 2 {\n\t\tt.Fatalf(\"Expected 2 keys, got %d\", len(jwt.Keys))\n\t}\n\n\tkeys := make([]crypto.PublicKey, len(jwt.Keys))\n\tfor ii, jwt := range jwt.Keys {\n\t\tkeys[ii], err = jwt.DecodePublicKey()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to decode key %d: %v\", ii, err)\n\t\t}\n\t}\n\n\tif key0, ok := keys[0].(*ecdsa.PublicKey); !ok {\n\t\tt.Fatalf(\"Expected ECDSA key[0], got %T\", keys[0])\n\t} else if key1, ok := keys[1].(*rsa.PublicKey); !ok {\n\t\tt.Fatalf(\"Expected RSA key[1], got %T\", keys[1])\n\t} else if key0.Curve != elliptic.P256() {\n\t\tt.Fatal(\"Key[0] is not using P-256 curve\")\n\t} else if !bytes.Equal(key0.X.Bytes(), []byte{0x30, 0xa0, 0x42, 0x4c, 0xd2,\n\t\t0x1c, 0x29, 0x44, 0x83, 0x8a, 0x2d, 0x75, 0xc9, 0x2b, 0x37, 0xe7, 0x6e, 0xa2,\n\t\t0xd, 0x9f, 0x0, 0x89, 0x3a, 0x3b, 0x4e, 0xee, 0x8a, 0x3c, 0xa, 0xaf, 0xec, 0x3e}) {\n\t\tt.Fatalf(\"Bad key[0].X, got %v\", key0.X.Bytes())\n\t} else if !bytes.Equal(key0.Y.Bytes(), []byte{0xe0, 0x4b, 0x65, 0xe9, 0x24,\n\t\t0x56, 0xd9, 0x88, 0x8b, 0x52, 0xb3, 0x79, 0xbd, 0xfb, 0xd5, 0x1e, 0xe8,\n\t\t0x69, 0xef, 0x1f, 0xf, 0xc6, 0x5b, 0x66, 0x59, 0x69, 0x5b, 0x6c, 0xce,\n\t\t0x8, 0x17, 0x23}) {\n\t\tt.Fatalf(\"Bad key[0].Y, got %v\", key0.Y.Bytes())\n\t} else if key1.E != 0x10001 {\n\t\tt.Fatalf(\"Bad key[1].E: %d\", key1.E)\n\t} else if !bytes.Equal(key1.N.Bytes(), []byte{0xd2, 0xfc, 0x7b, 0x6a, 0xa, 0x1e,\n\t\t0x6c, 0x67, 0x10, 0x4a, 0xeb, 0x8f, 0x88, 0xb2, 0x57, 0x66, 0x9b, 0x4d, 0xf6,\n\t\t0x79, 0xdd, 0xad, 0x9, 0x9b, 0x5c, 0x4a, 0x6c, 0xd9, 0xa8, 0x80, 0x15, 0xb5,\n\t\t0xa1, 0x33, 0xbf, 0xb, 0x85, 0x6c, 0x78, 0x71, 0xb6, 0xdf, 0x0, 0xb, 0x55,\n\t\t0x4f, 0xce, 0xb3, 0xc2, 0xed, 0x51, 0x2b, 0xb6, 0x8f, 0x14, 0x5c, 0x6e, 0x84,\n\t\t0x34, 0x75, 0x2f, 0xab, 0x52, 0xa1, 0xcf, 0xc1, 0x24, 0x40, 0x8f, 0x79, 0xb5,\n\t\t0x8a, 0x45, 0x78, 0xc1, 0x64, 0x28, 0x85, 0x57, 0x89, 0xf7, 0xa2, 0x49, 0xe3,\n\t\t0x84, 0xcb, 0x2d, 0x9f, 0xae, 0x2d, 0x67, 0xfd, 0x96, 0xfb, 0x92, 0x6c, 0x19,\n\t\t0x8e, 0x7, 0x73, 0x99, 0xfd, 0xc8, 0x15, 0xc0, 0xaf, 0x9, 0x7d, 0xde, 0x5a,\n\t\t0xad, 0xef, 0xf4, 0x4d, 0xe7, 0xe, 0x82, 0x7f, 0x48, 0x78, 0x43, 0x24, 0x39,\n\t\t0xbf, 0xee, 0xb9, 0x60, 0x68, 0xd0, 0x47, 0x4f, 0xc5, 0xd, 0x6d, 0x90, 0xbf,\n\t\t0x3a, 0x98, 0xdf, 0xaf, 0x10, 0x40, 0xc8, 0x9c, 0x2, 0xd6, 0x92, 0xab, 0x3b,\n\t\t0x3c, 0x28, 0x96, 0x60, 0x9d, 0x86, 0xfd, 0x73, 0xb7, 0x74, 0xce, 0x7, 0x40,\n\t\t0x64, 0x7c, 0xee, 0xea, 0xa3, 0x10, 0xbd, 0x12, 0xf9, 0x85, 0xa8, 0xeb, 0x9f,\n\t\t0x59, 0xfd, 0xd4, 0x26, 0xce, 0xa5, 0xb2, 0x12, 0xf, 0x4f, 0x2a, 0x34, 0xbc,\n\t\t0xab, 0x76, 0x4b, 0x7e, 0x6c, 0x54, 0xd6, 0x84, 0x2, 0x38, 0xbc, 0xc4, 0x5, 0x87,\n\t\t0xa5, 0x9e, 0x66, 0xed, 0x1f, 0x33, 0x89, 0x45, 0x77, 0x63, 0x5c, 0x47, 0xa,\n\t\t0xf7, 0x5c, 0xf9, 0x2c, 0x20, 0xd1, 0xda, 0x43, 0xe1, 0xbf, 0xc4, 0x19, 0xe2,\n\t\t0x22, 0xa6, 0xf0, 0xd0, 0xbb, 0x35, 0x8c, 0x5e, 0x38, 0xf9, 0xcb, 0x5, 0xa, 0xea,\n\t\t0xfe, 0x90, 0x48, 0x14, 0xf1, 0xac, 0x1a, 0xa4, 0x9c, 0xca, 0x9e, 0xa0, 0xca, 0x83}) {\n\t\tt.Fatal(\"Bad key[1].N, got %v\", key1.N.Bytes())\n\t}\n}", "func (keyRing *KeyRing) WritePublicKey(w io.Writer) (err error) {\n\tfor _, e := range keyRing.entities {\n\t\tif err = e.Serialize(w); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}" ]
[ "0.63215303", "0.6122218", "0.60656816", "0.5980721", "0.5973156", "0.5932101", "0.58556116", "0.5846051", "0.5830888", "0.58299696", "0.5808409", "0.57987076", "0.5796231", "0.57778335", "0.5745133", "0.57280123", "0.57222223", "0.56852025", "0.5678289", "0.567394", "0.56536627", "0.5632926", "0.56253135", "0.5619963", "0.5598597", "0.5597443", "0.559093", "0.55881983", "0.55853933", "0.55623746", "0.55599767", "0.5545486", "0.5541024", "0.5536242", "0.54881185", "0.5479552", "0.54727894", "0.5441627", "0.5434457", "0.5408223", "0.5372954", "0.5365734", "0.53549474", "0.5351552", "0.5339457", "0.5335933", "0.5334246", "0.53324217", "0.53280467", "0.5317453", "0.5314704", "0.5311395", "0.53086656", "0.5307737", "0.52932656", "0.52883357", "0.5283074", "0.5280851", "0.52731776", "0.52693427", "0.52616566", "0.5255463", "0.5252772", "0.5250402", "0.5242333", "0.5236883", "0.52346534", "0.5234293", "0.5231691", "0.5226207", "0.52223086", "0.5219717", "0.5218468", "0.5218209", "0.521492", "0.5211056", "0.5203684", "0.5202729", "0.52026", "0.5195007", "0.51933897", "0.51774156", "0.5175556", "0.51744485", "0.5172396", "0.5156729", "0.5153938", "0.51510775", "0.5142169", "0.51354855", "0.5130028", "0.5129255", "0.51264906", "0.5122534", "0.510899", "0.5102411", "0.5102164", "0.5102076", "0.5098768", "0.5093247" ]
0.80368924
0
PublicKey returns a Public Key as G2 point generated from the Private Key.
func (k *PrivateKey) PublicKey() *PublicKey { pointG2 := curve.GenG2.Mul(frToRepr(k.FR)) return &PublicKey{pointG2} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k *PrivateKey) PublicKey() *PublicKey {\n\tpubKeyG2Point := bls.G2AffineOne.MulFR(k.PrivKey.GetFRElement().ToRepr())\n\n\treturn &PublicKey{g2pubs.NewPublicKeyFromG2(pubKeyG2Point.ToAffine())}\n}", "func (p PrivateKey) PublicKey() (PublicKey, error) {\n\tpub, err := curve25519.X25519(p, curve25519.Basepoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pub, nil\n}", "func PublicKey(private, p *big.Int, g int64) *big.Int {\n\n\t// calculate the public key based on the following formula\n\t// pubKey = g**privKey mod p\n\tG := big.NewInt(g)\n\tpubKey := G.Exp(G, private, p)\n\n\treturn pubKey\n}", "func (priv *PrivateKey) Public() crypto.PublicKey", "func (priv *PrivateKey) Public() crypto.PublicKey", "func (pk PrivateKey) PublicKey() hotstuff.PublicKey {\n\treturn pk.Public()\n}", "func PrivateKeyPublic(priv *rsa.PrivateKey,) crypto.PublicKey", "func PublicKey(private, p *big.Int, g int64) *big.Int {\n\treturn new(big.Int).Exp(big.NewInt(g), private, p)\n}", "func (k *PrivateKey) PublicKey() *PublicKey {\n\tif k == nil {\n\t\treturn nil\n\t}\n\tp := new(PublicKey)\n\tp.Pk.Curve = k.Curve\n\tp.Pk.X = k.X\n\tp.Pk.Y = k.Y\n\treturn p\n}", "func (k PrivateKey) Public() crypto.PublicKey {\n\treturn &k.PublicKey\n}", "func (p *PrivateKey) PublicKey() *ecdsa.PublicKey {\n\treturn &p.privateKey.PublicKey\n}", "func (priv *PrivateKey) Public() (*PublicKey, error) {\n\tslice, err := curve25519.X25519(priv[:], curve25519.Basepoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp, _ := PublicKeyFromSlice(slice)\n\treturn p, nil\n}", "func (sk PrivateKey) PublicKey() PublicKey {\n\treturn PublicKey{publicKey: sk.privateKey.PublicKey()}\n}", "func PublicKey(a *big.Int, p *big.Int, g int64) *big.Int {\n\tbigG := big.NewInt(g)\n\tbigG.Exp(bigG, a, p)\n\treturn bigG\n}", "func (k *PrivateKeySECP256K1R) PublicKey() PublicKey {\n\tif k.pk == nil {\n\t\tk.pk = &PublicKeySECP256K1R{pk: k.sk.PubKey()}\n\t}\n\treturn k.pk\n}", "func (p PrivateKey) Public() crypto.PublicKey {\n\tpub, _ := p.PublicKey()\n\treturn pub\n}", "func (priv ECDHPrivate) PublicKey() ECDHPublic {\n\ttoret := make([]byte, ECDHKeyLength)\n\tC.crypto_scalarmult_base((*C.uchar)(&toret[0]),\n\t\t(*C.uchar)(&priv[0]))\n\treturn toret\n}", "func PublicKey(priv keyconf.Key) (keyconf.Key, error) {\n\tif priv.Type != keyconf.PrivateKey {\n\t\treturn keyconf.Key{}, serrors.New(\"provided key is not a private key\", \"type\", priv.Type)\n\t}\n\traw, err := scrypto.GetPubKey(priv.Bytes, priv.Algorithm)\n\tif err != nil {\n\t\treturn keyconf.Key{}, serrors.WrapStr(\"error generating public key\", err)\n\t}\n\tkey := keyconf.Key{\n\t\tID: keyconf.ID{\n\t\t\tUsage: priv.Usage,\n\t\t\tIA: priv.IA,\n\t\t\tVersion: priv.Version,\n\t\t},\n\t\tType: keyconf.PublicKey,\n\t\tAlgorithm: priv.Algorithm,\n\t\tValidity: priv.Validity,\n\t\tBytes: raw,\n\t}\n\treturn key, nil\n}", "func (priv PrivateKey) Public() crypto.PublicKey {\n\tpub := ed25519.PrivateKey(priv).Public().(ed25519.PublicKey)\n\treturn PublicKey(pub)\n}", "func (sk *PrivateKey) Public() crypto.PublicKey {\n\treturn &PublicKey{\n\t\tsk.e.Public().(ed25519.PublicKey),\n\t\t*sk.d.Public().(*mode2.PublicKey),\n\t}\n}", "func (pk *PrivateKey) GetPublicKey() *PublicKey {\n var publicKeyBytes PublicKey\n copy(publicKeyBytes[:], pk[32:])\n return &publicKeyBytes\n}", "func (priv *PKCS11PrivateKeyRSA) Public() crypto.PublicKey {\n\treturn priv.key.PubKey\n}", "func (ec *ECPoint) ToPublicKey() *ecdsa.PublicKey {\n\tres := new(ecdsa.PublicKey)\n\tres.X = ec.X\n\tres.Y = ec.Y\n\tres.Curve = ec.Curve\n\n\treturn res\n}", "func (p *PrivateKey) PublicKey() *PublicKey {\n\tresult := PublicKey(p.PrivateKey.PublicKey)\n\treturn &result\n}", "func (n NodeID) Pubkey() (*ecdsa.PublicKey, error) {\n\tp := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}\n\thalf := len(n) / 2\n\tp.X.SetBytes(n[:half])\n\tp.Y.SetBytes(n[half:])\n\tif !p.Curve.IsOnCurve(p.X, p.Y) {\n\t\treturn nil, errors.New(\"id is invalid secp256k1 curve point\")\n\t}\n\treturn p, nil\n}", "func (kt KeyType) PublicKey() string {\n\treturn fmt.Sprintf(\"%s.pub\", kt.KeyBaseName)\n}", "func (k *Keypair) PublicKey() *PubKey {\n\tpub := new(PubKey)\n\tcopy(pub[:], k.pub[:])\n\treturn pub\n}", "func (x *Ed25519Credentials) PublicKey() PublicKey {\n\n\treturn PublicKey{\n\t\tAlgorithm: AlgorithmEd25519,\n\t\tPublic: base64.URLEncoding.EncodeToString(x.Public[:]),\n\t}\n\n}", "func generatePublicKey(privatekey *rsa.PublicKey) ([]byte, error) {\n\tpublicRsaKey, err := ssh.NewPublicKey(privatekey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)\n\treturn pubKeyBytes, nil\n\n}", "func (s NativeSigner) PublicKey() ([]byte, error) {\n\tkeybuf := new(bytes.Buffer)\n\tif err := (*openpgp.Entity)(&s).Serialize(keybuf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn keybuf.Bytes(), nil\n}", "func (priv *PrivateKey) Public() crypto.PublicKey {\n\treturn &priv.PublicKey\n}", "func (pk PrivateKey) GetPublicKey() PublicKey {\n\treturn NewPublicKey(pk[32:])\n}", "func (s Keygen) PublicKey() *ecdsa.PublicKey {\n\treturn nil\n}", "func (priv *PKCS11PrivateKeyECDSA) Public() crypto.PublicKey {\n\treturn priv.key.PubKey\n}", "func (p *PrivateKey) PubKey() *PublicKey {\n\treturn (*PublicKey)(&p.PublicKey)\n}", "func (a *Account) PublicKey() *PubKey {\n\tk := new(PubKey)\n\tcopy(k[:], a.pub[:])\n\treturn k\n}", "func (k *PrivateKey) Public() crypto.PublicKey {\n\treturn k.PublicKey()\n}", "func publicKey(privateKey string) (string, error) {\n\tdecoded, _ := pem.Decode([]byte(privateKey))\n\tif decoded == nil {\n\t\treturn \"\", errors.New(\"no PEM data found\")\n\t}\n\n\tprivKey, err := x509.ParsePKCS1PrivateKey(decoded.Bytes)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tder, err := x509.MarshalPKIXPublicKey(privKey.Public())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tblock := pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tBytes: der,\n\t}\n\treturn string(pem.EncodeToMemory(&block)), nil\n}", "func (k *EdX25519Key) PublicKey() *EdX25519PublicKey {\n\treturn k.publicKey\n}", "func (s GPGSigner) PublicKey() ([]byte, error) {\n\tgpg2 := exec.Command(s.gpgExecutable, \"--export\", s.GPGUserName)\n\tif err := s.Rewriter(gpg2); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error invoking Rewrite: %v\", err)\n\t}\n\tout, err := gpg2.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error getting stdout pipe: %v\", err)\n\t}\n\tif err := gpg2.Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error starting gpg command: %v\", err)\n\t}\n\tpubkey, err := ioutil.ReadAll(out)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading pubkey data: %v\", err)\n\t}\n\tif err := gpg2.Wait(); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error running gpg: %v\", err)\n\t}\n\treturn pubkey, nil\n}", "func (k *Ed25519PrivateKey) GetPublic() PubKey {\n\treturn &Ed25519PublicKey{k: k.pubKeyBytes()}\n}", "func (k *VrfablePrivateKey) Public() PublicKey {\n\treturn &VrfablePublicKey{&k.PublicKey}\n}", "func PublicKeyFromPvk(privateKey []byte) []byte {\n\tvar A edwards25519.ExtendedGroupElement\n\tvar hBytes [32]byte\n\tcopy(hBytes[:], privateKey)\n\tedwards25519.GeScalarMultBase(&A, &hBytes)\n\tvar publicKeyBytes [32]byte\n\tA.ToBytes(&publicKeyBytes)\n\n\treturn publicKeyBytes[:]\n}", "func (k otherKey) Public() crypto.PublicKey {\n\treturn nil\n}", "func (n Node) PublicKey() p2pcrypto.PublicKey {\n\treturn n.pubKey\n}", "func NewPublic(x,y []byte) (*ecdsa.PublicKey) {\n\treturn &ecdsa.PublicKey{ Curve: curve(len(x)), \n\t\t\t\t\t\t\t X:new(big.Int).SetBytes(x), \n\t\t\t\t\t\t\t Y:new(big.Int).SetBytes(y) }\n}", "func (c *CertInfo) PublicKey() []byte {\n\tdata := c.KeyPair().Certificate[0]\n\treturn pem.EncodeToMemory(&pem.Block{Type: \"CERTIFICATE\", Bytes: data})\n}", "func GetPublicKey() ed25519.PublicKey {\n\tkey, _ := DecodePublicKey(publicKey)\n\treturn key\n}", "func (o PlaybackKeyPairOutput) PublicKey() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PlaybackKeyPair) pulumi.StringOutput { return v.PublicKey }).(pulumi.StringOutput)\n}", "func (s Sig) PublicKey() ([]byte, error) {\n\treturn nil, fmt.Errorf(\"not implemented\")\n}", "func (id NodesID) Pubkey() (*ecdsa.PublicKey, error) {\n\tp := &ecdsa.PublicKey{Curve: bgmcrypto.S256(), X: new(big.Int), Y: new(big.Int)}\n\thalf := len(id) / 2\n\tptr.X.SetBytes(id[:half])\n\tptr.Y.SetBytes(id[half:])\n\tif !ptr.Curve.IsOnCurve(ptr.X, ptr.Y) {\n\t\treturn nil, errors.New(\"id is invalid secp256k1 curve point\")\n\t}\n\treturn p, nil\n}", "func PublicKey(pemkey []byte) (pub []byte, err error) {\n\tvar (\n\t\tpkey *rsa.PrivateKey\n\t)\n\n\tblk, _ := pem.Decode(pemkey) // assumes a single valid pem encoded key.\n\n\tif pkey, err = x509.ParsePKCS1PrivateKey(blk.Bytes); err != nil {\n\t\treturn pub, err\n\t}\n\n\treturn x509.MarshalPKCS1PublicKey(&pkey.PublicKey), nil\n}", "func NewPublicKey(pk map[string]interface{}) PublicKey {\n\treturn pk\n}", "func GetPublicKey(passphrase string, address string) (string, error) {\n\tkeys, err := GetPublicPrivateKey(passphrase, address)\n\n\treturn keys.PublicKey, err\n}", "func (s *p11Signer) Public() crypto.PublicKey {\n\tswitch s.keyType {\n\tcase crypki.RSA:\n\t\treturn publicRSA(s)\n\tcase crypki.ECDSA:\n\t\treturn publicECDSA(s)\n\tdefault: // RSA is the default\n\t\treturn publicRSA(s)\n\t}\n}", "func (k *KeyPairEd25519) GetPublicKey() PublicKey {\n\treturn PublicKey{\n\t\tType: ED25519,\n\t\tData: k.privateKey.Public().(ed25519.PublicKey),\n\t}\n}", "func NewPublicKey(ki crypto.PubKey) PublicKey {\n\treturn &publicKey{ki: ki}\n}", "func (sk *opensslPrivateKey) GetPublic() PubKey {\n\treturn &opensslPublicKey{key: sk.key}\n}", "func (s Seed) PublicKey(index uint64) types.SiaPublicKey {\n\tkey := s.deriveKeyPair(index)\n\treturn types.SiaPublicKey{\n\t\tAlgorithm: types.SignatureEd25519,\n\t\tKey: key[len(key)-ed25519.PublicKeySize:],\n\t}\n}", "func getRSAPublicKey(modulus []byte, exponent []byte) (*rsa.PublicKey, error) {\n\tn := new(big.Int).SetBytes(modulus)\n\te := new(big.Int).SetBytes(exponent)\n\teInt := int(e.Int64())\n\trsaPubKey := rsa.PublicKey{N: n, E: eInt}\n\treturn &rsaPubKey, nil\n}", "func (n *NetImpl) PubKey() kyber.Point {\n\treturn n.nodeKeyPair.Public\n}", "func (*FactorySECP256K1R) ToPublicKey(b []byte) (PublicKey, error) {\n\tkey, err := secp256k1.ParsePubKey(b)\n\treturn &PublicKeySECP256K1R{\n\t\tpk: key,\n\t\tbytes: b,\n\t}, err\n}", "func (opts *ECDSAGoPublicKeyImportOpts) PublicKey() *ecdsa.PublicKey {\n\treturn opts.PK\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCallerSession) PublicKey() ([]byte, error) {\n\treturn _BondedECDSAKeep.Contract.PublicKey(&_BondedECDSAKeep.CallOpts)\n}", "func GeneratePublicKey(key string) (string, error) {\n\n // decode PEM encoding to ANS.1 PKCS1 DER\n block, _ := pem.Decode([]byte(key))\n // if block == nil { fmt.Printf(\"No Block found in keyfile\\n\"); os.Exit(1) }\n // if block.Type != \"RSA PRIVATE KEY\" { fmt.Printf(\"Unsupported key type\"); os.Exit(1) }\n\n // parse DER format to a native type\n privateKey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)\n\n bb, _ := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)\n\n pemdata := pem.EncodeToMemory(\n &pem.Block{\n Type: \"PUBLIC KEY\",\n Bytes: bb,\n },\n )\n\n return string(pemdata), nil\n\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) PublicKey() ([]byte, error) {\n\treturn _BondedECDSAKeep.Contract.PublicKey(&_BondedECDSAKeep.CallOpts)\n}", "func (pk *PublicKey) Key() string {\n\treturn string(pk.PublicKeyHex.Value)\n}", "func (k *KeyPair) GetPublicKey() p2pCrypto.PubKey {\n\treturn k.pubKey\n}", "func (s *SMJWT) PublicKey() *rsa.PublicKey {\n\treturn s.publicKey\n}", "func getPublicKey(priv interface{}) interface{} {\n\tswitch k := priv.(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn &k.PublicKey\n\tcase *ecdsa.PrivateKey:\n\t\treturn &k.PublicKey\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (d *Device) PublicKey() string {\n\treturn d.pubKey\n}", "func (c *Client) GetPublicKey(scope ...string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET PUBLIC KEY ==========\")\n\turl := buildURL(path[\"client\"])\n\tdefaultScope := \"OAUTH|POST,USERS|POST,USERS|GET,USER|GET,USER|PATCH,SUBSCRIPTIONS|GET,SUBSCRIPTIONS|POST,SUBSCRIPTION|GET,SUBSCRIPTION|PATCH,CLIENT|REPORTS,CLIENT|CONTROLS\"\n\n\tif len(scope) > 0 {\n\t\tdefaultScope = scope[0]\n\t}\n\n\tqp := []string{\"issue_public_key=YES&scope=\" + defaultScope}\n\n\tif len(scope) > 1 {\n\t\tuserId := scope[1]\n\t\tqp[0] += \"&user_id=\" + userId\n\t}\n\n\treturn c.do(\"GET\", url, \"\", qp)\n}", "func GetPublicKey(pub ssh.PublicKey) []byte {\n\tmarshaled := ssh.MarshalAuthorizedKey(pub)\n\t// Strip trailing newline\n\treturn marshaled[:len(marshaled)-1]\n}", "func (priv *DHPrivateKey) Public() *DHPublicKey {\n\treturn &priv.DHPublicKey\n}", "func RuskPublicKey() *rusk.PublicKey {\n\treturn &rusk.PublicKey{\n\t\tPayload: make([]byte, 64),\n\t}\n}", "func (keyRing *KeyRing) GetPublicKey() (b []byte, err error) {\n\tvar outBuf bytes.Buffer\n\tif err = keyRing.WritePublicKey(&outBuf); err != nil {\n\t\treturn\n\t}\n\n\tb = outBuf.Bytes()\n\treturn\n}", "func (opts *RSAGoPublicKeyImportOpts) PublicKey() *rsa.PublicKey {\n\treturn opts.PK\n}", "func (s *Signer) Public() crypto.PublicKey {\n\treturn s.publicKey\n}", "func (x *X25519) PublicKey() []byte {\n\treturn x.publicKey[:]\n}", "func PublicKeyToProto(pub interfaces.PublicKey) *PublicKey {\n\tif pub == nil {\n\t\treturn nil\n\t}\n\tpb := NewEmptyPublicKey()\n\tpb.Raw = pub.SerializeCompressed()\n\treturn pb\n}", "func (s *SigningIdentity) Public() crypto.PublicKey {\n\treturn s.Certificate.PublicKey\n}", "func ToPublic(sigType crypto.SigType, pk []byte) ([]byte, error) {\n\tsv, ok := sigs[sigType]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"cannot generate public key of unsupported type: %v\", sigType)\n\t}\n\n\treturn sv.ToPublic(pk)\n}", "func (k *RSAPrivKey) Public() PubKey {\n\treturn &RSAPubKey{\n\t\tkey: &k.key.PublicKey,\n\t}\n}", "func (k *key) getPublicKey() (*ecdsa.PublicKey, error) {\n\tby, err := base64.StdEncoding.DecodeString(k.PublicKeyB64)\n\tif err != nil {\n\t\treturn (*ecdsa.PublicKey)(nil), err\n\t}\n\n\tblockPub, _ := pem.Decode([]byte(by))\n\tgenericPublicKey, err := x509.ParsePKIXPublicKey(blockPub.Bytes)\n\tif err != nil {\n\t\treturn (*ecdsa.PublicKey)(nil), err\n\t}\n\n\treturn genericPublicKey.(*ecdsa.PublicKey), nil\n}", "func MarshalPublic(key *ecdsa.PublicKey) (string, error) {\n\tif key == nil || key.Curve == nil || key.X == nil || key.Y == nil {\n\t\treturn \"\", fmt.Errorf(\"key or part of key is nil: %+v\", key)\n\t}\n\n\tkey.Curve = fixCurve(key.Curve)\n\n\trawPriv, err := x509.MarshalPKIXPublicKey(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkeyBlock := &pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tBytes: rawPriv,\n\t}\n\n\treturn string(pem.EncodeToMemory(keyBlock)), nil\n}", "func (j *JWK) PublicKey() (crypto.PublicKey, error) {\n\tswitch j.KeyType {\n\tcase \"EC\", \"EC-HSM\":\n\t\tpub, err := j.ecPublicKey()\n\t\tif err != nil {\n\t\t\t// Return nil interface instead of (*ecdsa.PublicKey)(nil)!\n\t\t\treturn nil, err\n\t\t}\n\t\treturn pub, nil\n\n\tcase \"RSA\", \"RSA-HSM\":\n\t\tkey, err := j.rsaPublicKey()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif key.N.Sign() <= 0 || key.E <= 0 {\n\t\t\treturn nil, errors.New(\"jwk: public key contains zero or negative value\")\n\t\t}\n\t\tif key.E > 1<<31-1 {\n\t\t\treturn nil, errors.New(\"jwk: public key contains large public exponent\")\n\t\t}\n\n\t\treturn key, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"jwk: unknown key type: %s\", j.KeyType)\n}", "func (d *DocsCrypto) GetPublic() *rsa.PublicKey {\n\td.Debug(\"gettting public key\")\n\treturn d.privateKey.Public().(*rsa.PublicKey)\n}", "func (r *Resolver) PubKey() ([32]byte, [32]byte, error) {\n\tnameHash, err := NameHash(r.domain)\n\tif err != nil {\n\t\treturn [32]byte{}, [32]byte{}, err\n\t}\n\tres, err := r.Contract.Pubkey(nil, nameHash)\n\treturn res.X, res.Y, err\n}", "func (obj *MessengerUser) PublicKey() (foundation.PublicKey, error) {\n\tproxyResult := /*pr4*/ C.vssq_messenger_user_public_key(obj.cCtx)\n\n\truntime.KeepAlive(obj)\n\n\treturn foundation.ImplementationWrapPublicKeyCopy(unsafe.Pointer(proxyResult)) /* r4.1 */\n}", "func (o *PipelineSshKeyPairAllOf) GetPublicKey() string {\n\tif o == nil || o.PublicKey == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PublicKey\n}", "func (r *Member) GetPublicKey() string {\n\tvar args [0]interface{}\n\n\tvar argsSerialized []byte\n\n\terr := proxyctx.Current.Serialize(args, &argsSerialized)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tres, err := proxyctx.Current.RouteCall(r.Reference, true, \"GetPublicKey\", argsSerialized)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tret := [1]interface{}{}\n\tvar ret0 string\n\tret[0] = &ret0\n\n\terr = proxyctx.Current.Deserialize(res, &ret)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn ret0\n}", "func (nodeKey *NodeKey) PubKey() crypto.PubKey {\n\treturn nodeKey.PrivKey.PubKey()\n}", "func ExportPublicKey(key *rsa.PublicKey) []byte {\n\tkeyBytes := x509.MarshalPKCS1PublicKey(key)\n\treturn pem.EncodeToMemory(&pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tBytes: keyBytes,\n\t})\n}", "func (nr NodeRecord) GetPublicKey() (string, error) {\n\treturn nr.Record.PublicKey, nil\n}", "func (r *gorumsReplica) PublicKey() hotstuff.PublicKey {\n\treturn r.pubKey\n}", "func (o *DKSharesInfo) GetPublicKey() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.PublicKey\n}", "func (keys_and_cert KeysAndCert) PublicKey() (key crypto.PublicKey, err error) {\n\tcert, err := keys_and_cert.Certificate()\n\tif err != nil {\n\t\treturn\n\t}\n\tcert_len, err := cert.Length()\n\tif err != nil {\n\t\treturn\n\t}\n\tif cert_len == 0 {\n\t\t// No Certificate is present, return the KEYS_AND_CERT_PUBKEY_SIZE byte\n\t\t// PublicKey space as ElgPublicKey.\n\t\tvar elg_key crypto.ElgPublicKey\n\t\tcopy(keys_and_cert[:KEYS_AND_CERT_PUBKEY_SIZE], elg_key[:])\n\t\tkey = elg_key\n\t} else {\n\t\t// A Certificate is present in this KeysAndCert\n\t\tcert_type, _ := cert.Type()\n\t\tif cert_type == CERT_KEY {\n\t\t\t// This KeysAndCert contains a Key Certificate, construct\n\t\t\t// a PublicKey from the data in the KeysAndCert and\n\t\t\t// any additional data in the Certificate.\n\t\t\tkey, err = KeyCertificate(cert).ConstructPublicKey(\n\t\t\t\tkeys_and_cert[:KEYS_AND_CERT_PUBKEY_SIZE],\n\t\t\t)\n\t\t} else {\n\t\t\t// Key Certificate is not present, return the KEYS_AND_CERT_PUBKEY_SIZE byte\n\t\t\t// PublicKey space as ElgPublicKey. No other Certificate\n\t\t\t// types are currently in use.\n\t\t\tvar elg_key crypto.ElgPublicKey\n\t\t\tcopy(keys_and_cert[:KEYS_AND_CERT_PUBKEY_SIZE], elg_key[:])\n\t\t\tkey = elg_key\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"at\": \"(KeysAndCert) PublicKey\",\n\t\t\t\t\"cert_type\": cert_type,\n\t\t\t}).Warn(\"unused certificate type observed\")\n\t\t}\n\n\t}\n\treturn\n}", "func GetPublicKey(stub shim.ChaincodeStubInterface) (string, error) {\r\n\tcert, err := GetCreatorCert(stub)\r\n\r\n\tbytePublicKey, _ := x509.MarshalPKIXPublicKey(cert.PublicKey)\r\n\treturn string(bytePublicKey), err\r\n}", "func GetPublicKeyFromSecret(secret string) []byte {\n\tsecretHash := GetSHA256Hash(secret)\n\tpKey, _, _ := ed25519.GenerateKey(bytes.NewReader(secretHash[:sha256.Size]))\n\n\treturn pKey\n}", "func (d Dispatcher) PublicKey() string {\n\treturn d.GetPubString()\n}" ]
[ "0.7776566", "0.7504776", "0.74967927", "0.74927574", "0.74927574", "0.7321769", "0.7213629", "0.7184853", "0.7168073", "0.7167755", "0.7131929", "0.7088816", "0.7077749", "0.70654327", "0.7048545", "0.70308244", "0.70007807", "0.69916946", "0.6985914", "0.69773185", "0.6966945", "0.6962568", "0.69535804", "0.69456697", "0.6943778", "0.6922639", "0.6898588", "0.68814915", "0.6881186", "0.68799347", "0.6874202", "0.6872921", "0.68479085", "0.68068457", "0.67828083", "0.6779678", "0.67657864", "0.6761838", "0.6749973", "0.6736019", "0.67313135", "0.6726579", "0.67172676", "0.6690271", "0.6663517", "0.66628075", "0.6657118", "0.66565835", "0.6643947", "0.66434747", "0.66346544", "0.6631772", "0.66303355", "0.6622308", "0.66020554", "0.65935785", "0.65915257", "0.659107", "0.6588257", "0.6569435", "0.6555783", "0.65303093", "0.65294176", "0.6519662", "0.65193623", "0.6518436", "0.65083116", "0.6504853", "0.6475748", "0.64638007", "0.645967", "0.64548993", "0.6450639", "0.64426845", "0.6431425", "0.64274275", "0.64238846", "0.6421731", "0.64131093", "0.6408426", "0.6407743", "0.6407142", "0.6381869", "0.6380774", "0.6378172", "0.6365795", "0.63586736", "0.6348062", "0.632598", "0.6325905", "0.632453", "0.63122976", "0.6310219", "0.63092285", "0.63072383", "0.63036484", "0.6300254", "0.6276219", "0.62759995", "0.6269269" ]
0.78501076
0
UnmarshalPublicKey parses a PublicKey from bytes.
func UnmarshalPublicKey(pubKeyBytes []byte) (*PublicKey, error) { if len(pubKeyBytes) != bls12381G2PublicKeyLen { return nil, errors.New("invalid size of public key") } pointG2, err := curve.NewG2FromCompressed(pubKeyBytes) if err != nil { return nil, fmt.Errorf("deserialize public key: %w", err) } return &PublicKey{ PointG2: pointG2, }, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *publicKey) Unmarshal(b []byte) error {\n\tpbuf := new(pb.PublicKey)\n\tif err := proto.Unmarshal(b, pbuf); err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Decode(pbuf)\n}", "func UnmarshalPublicKey(pubKeyBytes []byte) (*PublicKey, error) {\n\tif len(pubKeyBytes) != bls12381G2PublicKeyLen {\n\t\treturn nil, errors.New(\"invalid size of public key\")\n\t}\n\n\tvar pkBytesArr [bls12381G2PublicKeyLen]byte\n\n\tcopy(pkBytesArr[:], pubKeyBytes[:bls12381G2PublicKeyLen])\n\n\tpublicKey, err := g2pubs.DeserializePublicKey(pkBytesArr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"deserialize public key: %w\", err)\n\t}\n\n\treturn &PublicKey{\n\t\tPubKey: publicKey,\n\t}, nil\n}", "func ParsePublicKey(pemBytes []byte) (Unsigner, error) {\n\tblock, _ := pem.Decode(pemBytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"ssh: no key found\")\n\t}\n\n\tvar rawkey interface{}\n\tswitch block.Type {\n\tcase \"PUBLIC KEY\":\n\t\trsa, err := x509.ParsePKIXPublicKey(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trawkey = rsa\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"ssh: unsupported key type %q\", block.Type)\n\t}\n\n\treturn NewUnsignerFromKey(rawkey)\n}", "func parsePublicKey(pemBytes []byte) (Unsigner, error) {\n\tblock, _ := pem.Decode(pemBytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"ssh: no key found\")\n\t}\n\n\tvar rawkey interface{}\n\tswitch block.Type {\n\tcase \"PUBLIC KEY\":\n\t\trsa, err := x509.ParsePKIXPublicKey(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trawkey = rsa\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"ssh: unsupported key type %q\", block.Type)\n\t}\n\n\treturn newUnsignerFromKey(rawkey)\n}", "func parsePublicKey(pemBytes []byte) (SignatureValidator, error) {\r\n\tgob.Register(rsaPrivateKey{})\r\n\tblock, _ := pem.Decode(pemBytes)\r\n\tif block == nil {\r\n\t\treturn nil, errors.New(\"no key found\")\r\n\t}\r\n\r\n\tswitch block.Type {\r\n\tcase \"PUBLIC KEY\":\r\n\t\treturn ParsePublicKey(block.Bytes)\r\n\tdefault:\r\n\t\treturn nil, fmt.Errorf(\"unsupported key block type %q\", block.Type)\r\n\t}\r\n}", "func ParsePublicKey(keyBytes []byte) (interface{}, error) {\n\tpk := PublicKeyData{}\n\twebauthncbor.Unmarshal(keyBytes, &pk)\n\n\tswitch COSEKeyType(pk.KeyType) {\n\tcase OctetKey:\n\t\tvar o OKPPublicKeyData\n\n\t\twebauthncbor.Unmarshal(keyBytes, &o)\n\t\to.PublicKeyData = pk\n\n\t\treturn o, nil\n\tcase EllipticKey:\n\t\tvar e EC2PublicKeyData\n\n\t\twebauthncbor.Unmarshal(keyBytes, &e)\n\t\te.PublicKeyData = pk\n\n\t\treturn e, nil\n\tcase RSAKey:\n\t\tvar r RSAPublicKeyData\n\n\t\twebauthncbor.Unmarshal(keyBytes, &r)\n\t\tr.PublicKeyData = pk\n\n\t\treturn r, nil\n\tdefault:\n\t\treturn nil, ErrUnsupportedKey\n\t}\n}", "func (pk *PublicKey) UnmarshalJSON(b []byte) error {\n\tvar str string\n\tif err := json.Unmarshal(b, &str); err != nil {\n\t\treturn err\n\t}\n\treturn pk.LoadString(str)\n}", "func parsePublicKey(pemBytes []byte) (interface{}, error) {\n\tblock, _ := pem.Decode(pemBytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"ssh: no key found\")\n\t}\n\tswitch block.Type {\n\tcase \"PUBLIC KEY\":\n\t\trsa, err := x509.ParsePKIXPublicKey(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn rsa, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"ssh: unsupported key type %q\", block.Type)\n\t}\n}", "func (pub *PublicKey) FromBytes(b []byte) (err error) {\n\t/* See Certicom SEC1 2.3.4, pg. 11 */\n\n\tif len(b) < 33 {\n\t\treturn fmt.Errorf(\"Invalid public key bytes length %d, expected at least 33.\", len(b))\n\t}\n\n\tif b[0] == 0x02 || b[0] == 0x03 {\n\t\t/* Compressed public key */\n\n\t\tif len(b) != 33 {\n\t\t\treturn fmt.Errorf(\"Invalid public key bytes length %d, expected 33.\", len(b))\n\t\t}\n\n\t\tP, err := secp256k1.Decompress(new(big.Int).SetBytes(b[1:33]), uint(b[0]&0x1))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Invalid compressed public key bytes, decompression error: %v\", err)\n\t\t}\n\n\t\tpub.X = P.X\n\t\tpub.Y = P.Y\n\n\t} else if b[0] == 0x04 {\n\t\t/* Uncompressed public key */\n\n\t\tif len(b) != 65 {\n\t\t\treturn fmt.Errorf(\"Invalid public key bytes length %d, expected 65.\", len(b))\n\t\t}\n\n\t\tpub.X = new(big.Int).SetBytes(b[1:33])\n\t\tpub.Y = new(big.Int).SetBytes(b[33:65])\n\n\t\t/* Check that the point is on the curve */\n\t\tif !secp256k1.IsOnCurve(pub.Point) {\n\t\t\treturn fmt.Errorf(\"Invalid public key bytes: point not on curve.\")\n\t\t}\n\n\t} else {\n\t\treturn fmt.Errorf(\"Invalid public key prefix byte 0x%02x, expected 0x02, 0x03, or 0x04.\", b[0])\n\t}\n\n\treturn nil\n}", "func parsePublicKey(pemBytes []byte) (interface{}, error) {\n block, _ := pem.Decode(pemBytes)\n if block == nil {\n return nil, errors.New(\"ssh: no key found\")\n }\n\n var rawkey interface{}\n switch block.Type {\n case \"PUBLIC KEY\":\n rsa, err := x509.ParsePKIXPublicKey(block.Bytes)\n if err != nil {\n return nil, err\n }\n rawkey = rsa\n default:\n return nil, fmt.Errorf(\"ssh: unsupported key type %q\", block.Type)\n }\n\n return rawkey, nil\n}", "func (c *publicKey) UnmarshalJSON(data []byte) error {\n\tpbuf := pb.PublicKey{}\n\tif err := json.Unmarshal(data, &pbuf); err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Decode(&pbuf)\n}", "func (pk *PublicKey) UnmarshalBinary(data []byte) error {\n\tif len(data) != PublicKeySize {\n\t\treturn errors.New(\"packed public key must be of eddilithium2.PublicKeySize bytes\")\n\t}\n\tvar buf [PublicKeySize]byte\n\tcopy(buf[:], data)\n\tpk.Unpack(&buf)\n\treturn nil\n}", "func (c *publicKey) Decode(pbuf *pb.PublicKey) error {\n\tki, err := crypto.UnmarshalPublicKey(pbuf.Blob)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.ki = ki\n\n\treturn nil\n}", "func DecodePublicKey(pbuf *pb.PublicKey) (PublicKey, error) {\n\tpbKey := publicKey{}\n\tif err := pbKey.Decode(pbuf); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &pbKey, nil\n}", "func (pk *PublicKey) Unmarshal(data []byte) error {\n\tvar json = jsoniter.ConfigCompatibleWithStandardLibrary\n\terr := json.Unmarshal(data, pk)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (h *FormatHandler) ExtractPublicKey(data []byte) (key [32]byte, err error) {\n\tvar obj map[string]interface{}\n\tif err = Unmarshal(data, &obj); err != nil {\n\t\treturn\n\t}\n\treturn format.ExtractPublicKeyHelper(obj)\n}", "func ParsePublicKey(data []byte) (SignatureValidator, error) {\r\n\ttmpKey, err := x509.ParsePKIXPublicKey(data)\r\n\trsaKey, ok := tmpKey.(*rsa.PublicKey)\r\n\tif err != nil || !ok {\r\n\t\treturn nil, errors.New(\"invalid key type, only RSA is supported\")\r\n\t}\r\n\treturn &rsaPublicKey{rsaKey}, nil\r\n}", "func UnmarshalPublic(key string) (*ecdsa.PublicKey, error) {\n\tblock, _ := pem.Decode([]byte(key))\n\tif block == nil {\n\t\treturn nil, errors.New(\"no PEM block found in public key\")\n\t}\n\tpubKey, err := x509.ParsePKIXPublicKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tecdsaPubKey, ok := pubKey.(*ecdsa.PublicKey)\n\tif !ok {\n\t\treturn nil, errors.New(\"invalid public key\")\n\t}\n\treturn ecdsaPubKey, nil\n}", "func LoadPublicKey(data []byte) (interface{}, error) {\n\tinput := data\n\n\tblock, _ := pem.Decode(data)\n\tif block != nil {\n\t\tinput = block.Bytes\n\t}\n\n\t// Try to load SubjectPublicKeyInfo\n\tpub, err0 := x509.ParsePKIXPublicKey(input)\n\tif err0 == nil {\n\t\treturn pub, nil\n\t}\n\n\tcert, err1 := x509.ParseCertificate(input)\n\tif err1 == nil {\n\t\treturn cert.PublicKey, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"square/go-jose: parse error, got '%s' and '%s'\", err0, err1)\n}", "func UnmarshalPublicKeyResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(PublicKeyResponse)\n\terr = core.UnmarshalPrimitive(m, \"public_key\", &obj.PublicKey)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func loadPublicKey(data []byte) (interface{}, error) {\n\tinput := data\n\n\tblock, _ := pem.Decode(data)\n\tif block != nil {\n\t\tinput = block.Bytes\n\t}\n\n\t// Try to load SubjectPublicKeyInfo\n\tpub, err0 := x509.ParsePKIXPublicKey(input)\n\tif err0 == nil {\n\t\treturn pub, nil\n\t}\n\n\tcert, err1 := x509.ParseCertificate(input)\n\tif err1 == nil {\n\t\treturn cert.PublicKey, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"square/go-jose: parse error, got '%s' and '%s'\", err0, err1)\n}", "func loadPublicKey(data []byte) (interface{}, error) {\n\tinput := data\n\n\tblock, _ := pem.Decode(data)\n\tif block != nil {\n\t\tinput = block.Bytes\n\t}\n\n\t// Try to load SubjectPublicKeyInfo\n\tpub, err0 := x509.ParsePKIXPublicKey(input)\n\tif err0 == nil {\n\t\treturn pub, nil\n\t}\n\n\tcert, err1 := x509.ParseCertificate(input)\n\tif err1 == nil {\n\t\treturn cert.PublicKey, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"square/go-jose: parse error, got '%s' and '%s'\", err0, err1)\n}", "func UnmarshalPubkey(pub []byte) (PublicKey, error) {\n\tx, y := elliptic.Unmarshal(S256(), pub)\n\tif x == nil {\n\t\treturn nil, ErrInvalidPubkey\n\t}\n\n\tpubKey := new(VrfablePublicKey)\n\tpubKey.PublicKey = &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}\n\treturn pubKey, nil\n}", "func parsePublicKey(base64EncodedPublicKey string) (*rsa.PublicKey, error) {\n\tpubKeyBytes, err := base64.StdEncoding.DecodeString(base64EncodedPublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpublicKey, err := x509.ParsePKIXPublicKey(pubKeyBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trsaPublicKey, ok := publicKey.(*rsa.PublicKey)\n\tif !ok {\n\t\treturn nil, ErrUnexpectedKeyType\n\t}\n\n\treturn rsaPublicKey, nil\n}", "func LoadPublicKey(path string) (Unsigner, error) {\n dat, _ := ioutil.ReadFile(path)\n return ParsePublicKey([]byte(dat))\n}", "func (p *publicKey) UnmarshalBinary(data []byte) error {\n\treturn p.PublicKey.DecodeBytes(data)\n}", "func PublicKeyFromBytes(publicKeyStr []byte) (*PublicKey, error) {\n\tpublicKey, err := btcec.ParsePubKey(publicKeyStr, secp256k1Curve)\n\treturn (*PublicKey)(publicKey), err\n}", "func UnmarshalPubkey(pub []byte) (*ecdsa.PublicKey, error) {\n\tx, y := elliptic.Unmarshal(S256(), pub)\n\tif x == nil {\n\t\treturn nil, errInvalidPubkey\n\t}\n\treturn &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil\n}", "func LoadTupuPublicKey() (Verifier, error) {\n\treturn parsePublicKey([]byte(`-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDyZneSY2eGnhKrArxaT6zswVH9\n/EKz+CLD+38kJigWj5UaRB6dDUK9BR6YIv0M9vVQZED2650tVhS3BeX04vEFhThn\nNrJguVPidufFpEh3AgdYDzOQxi06AN+CGzOXPaigTurBxZDIbdU+zmtr6a8bIBBj\nWQ4v2JR/BA6gVHV5TwIDAQAB\n-----END PUBLIC KEY-----`))\n}", "func ParsePubKey(pubKeyStr []byte) (key *PublicKey, err error) {\n\tpubkey := PublicKey{}\n\n\tif len(pubKeyStr) == 0 {\n\t\treturn nil, errors.New(\"pubkey string is empty\")\n\t}\n\n\tformat := pubKeyStr[0]\n\tybit := (format & 0x1) == 0x1\n\tformat &= ^byte(0x1)\n\n\tswitch len(pubKeyStr) {\n\tcase PubKeyBytesLenUncompressed:\n\t\tif format != pubKeyUncompressed && format != pubKeyHybrid {\n\t\t\treturn nil, fmt.Errorf(\"invalid magic in pubkey str: \"+\n\t\t\t\t\"%d\", pubKeyStr[0])\n\t\t}\n\n\t\tpubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])\n\t\tpubkey.Y = new(big.Int).SetBytes(pubKeyStr[33:])\n\t\t// hybrid keys have extra information, make use of it.\n\t\tif format == pubKeyHybrid && ybit != isOdd(pubkey.Y) {\n\t\t\treturn nil, fmt.Errorf(\"ybit doesn't match oddness\")\n\t\t}\n\tcase PubKeyBytesLenCompressed:\n\t\t// format is 0x2 | solution, <X coordinate>\n\t\t// solution determines which solution of the curve we use.\n\t\t/// y^2 = x^3 + Curve.B\n\t\tif format != pubKeyCompressed {\n\t\t\treturn nil, fmt.Errorf(\"invalid magic in compressed \"+\n\t\t\t\t\"pubkey string: %d\", pubKeyStr[0])\n\t\t}\n\t\tpubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])\n\t\tpubkey.Y, err = decompressPoint(pubkey.X, ybit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault: // wrong!\n\t\treturn nil, fmt.Errorf(\"invalid pub key length %d\",\n\t\t\tlen(pubKeyStr))\n\t}\n\n\tif pubkey.X.Cmp(secp256k1.Params().P) >= 0 {\n\t\treturn nil, fmt.Errorf(\"pubkey X parameter is >= to P\")\n\t}\n\tif pubkey.Y.Cmp(secp256k1.Params().P) >= 0 {\n\t\treturn nil, fmt.Errorf(\"pubkey Y parameter is >= to P\")\n\t}\n\tif !secp256k1.IsOnCurve(pubkey.X, pubkey.Y) {\n\t\treturn nil, fmt.Errorf(\"pubkey isn't on secp256k1 curve\")\n\t}\n\treturn &pubkey, nil\n}", "func LoadPublicKey(data []byte) (interface{}, error) {\n\tinput := data\n\n\tblock, _ := pem.Decode(data)\n\tif block != nil {\n\t\tinput = block.Bytes\n\t}\n\n\t// Try to load SubjectPublicKeyInfo\n\tpub, err0 := x509.ParsePKIXPublicKey(input)\n\tif err0 == nil {\n\t\treturn pub, nil\n\t}\n\n\tcert, err1 := x509.ParseCertificate(input)\n\tif err1 == nil {\n\t\treturn cert.PublicKey, nil\n\t}\n\n\tjwk, err2 := LoadJSONWebKey(data, true)\n\tif err2 == nil {\n\t\treturn jwk, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"JOSE: parse error, got '%s', '%s' and '%s'\", err0, err1, err2)\n}", "func (key *PublicKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPublicKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func UnmarshalPubkey(curveName string, pub []byte) (*ecdsa.PublicKey, error) {\n\tvar (\n\t\tx, y *big.Int\n\t)\n\tswitch curveName {\n\tcase P256:\n\t\tx, y = elliptic.Unmarshal(CurveType(curveName), pub)\n\tcase S256:\n\t\tx, y = elliptic.Unmarshal(CurveType(curveName), pub)\n\tcase SM2P256:\n\t\treturn gmsm.DecompressPubkey(pub)\n\n\t}\n\tif x == nil {\n\t\treturn nil, errInvalidPubkey\n\t}\n\treturn &ecdsa.PublicKey{Curve: CurveType(curveName), X: x, Y: y}, nil\n}", "func (k *RSAPubKey) Deserialize(key []byte) error {\n\tblock, _ := pem.Decode(key)\n\tif block == nil {\n\t\treturn ErrorDeserializeKey\n\t}\n\tpubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.key = pubInterface.(*rsa.PublicKey)\n\treturn nil\n}", "func DecodePublicKey(keyVal string) (*big.Int, *big.Int, error) {\n\tbytesToUnmarshal, err := base64.StdEncoding.DecodeString(keyVal)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tkey := Asn1GooglePublicKey{}\n\t_, err = asn1.Unmarshal(bytesToUnmarshal, &key)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tx := new(big.Int)\n\tx.SetBytes(key.Bits.Bytes[1:33])\n\ty := new(big.Int)\n\ty.SetBytes(key.Bits.Bytes[33:65])\n\n\treturn x, y, nil\n}", "func ParsePublicKeyInfo(keyBytes []byte) (*PublicKeyInfo, error) {\n\tif len(keyBytes) < 33 {\n\t\treturn nil, errors.New(\"Invalid length of public key\")\n\t}\n\n\tvar pkFormat btcutil.PubKeyFormat\n\tswitch keyBytes[0] {\n\tcase 0x02, 0x03:\n\t\tpkFormat = btcutil.PKFCompressed\n\tcase 0x04:\n\t\tpkFormat = btcutil.PKFUncompressed\n\tcase 0x06, 0x07:\n\t\tpkFormat = btcutil.PKFHybrid\n\tdefault:\n\t\treturn nil, errors.New(\"Invalid prefix for public key\")\n\t}\n\n\tpubKey, err := btcec.ParsePubKey(keyBytes, btcec.S256())\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parse PublicKeyInfo failed\")\n\t}\n\n\treturn &PublicKeyInfo{\n\t\tFormat: pkFormat,\n\t\tKey: pubKey,\n\t}, nil\n}", "func NewPublicKeyFromBytes(b []byte) (*PublicKey, error) {\n\tcurve := secp256k1.S256()\n\n\tswitch b[0] {\n\tcase 0x02, 0x03:\n\t\tif len(b) != 33 {\n\t\t\treturn nil, fmt.Errorf(\"cannot parse public key\")\n\t\t}\n\n\t\tx := new(big.Int).SetBytes(b[1:])\n\t\tvar ybit uint\n\t\tswitch b[0] {\n\t\tcase 0x02:\n\t\t\tybit = 0\n\t\tcase 0x03:\n\t\t\tybit = 1\n\t\t}\n\n\t\tif x.Cmp(curve.Params().P) >= 0 {\n\t\t\treturn nil, fmt.Errorf(\"cannot parse public key\")\n\t\t}\n\n\t\t// y^2 = x^3 + b\n\t\t// y = sqrt(x^3 + b)\n\t\tvar y, x3b big.Int\n\t\tx3b.Mul(x, x)\n\t\tx3b.Mul(&x3b, x)\n\t\tx3b.Add(&x3b, curve.Params().B)\n\t\tx3b.Mod(&x3b, curve.Params().P)\n\t\tif z := y.ModSqrt(&x3b, curve.Params().P); z == nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot parse public key\")\n\t\t}\n\n\t\tif y.Bit(0) != ybit {\n\t\t\ty.Sub(curve.Params().P, &y)\n\t\t}\n\t\tif y.Bit(0) != ybit {\n\t\t\treturn nil, fmt.Errorf(\"incorrectly encoded X and Y bit\")\n\t\t}\n\n\t\treturn &PublicKey{\n\t\t\tCurve: curve,\n\t\t\tX: x,\n\t\t\tY: &y,\n\t\t}, nil\n\tcase 0x04:\n\t\tif len(b) != 65 {\n\t\t\treturn nil, fmt.Errorf(\"cannot parse public key\")\n\t\t}\n\n\t\tx := new(big.Int).SetBytes(b[1:33])\n\t\ty := new(big.Int).SetBytes(b[33:])\n\n\t\tif x.Cmp(curve.Params().P) >= 0 || y.Cmp(curve.Params().P) >= 0 {\n\t\t\treturn nil, fmt.Errorf(\"cannot parse public key\")\n\t\t}\n\n\t\tx3 := new(big.Int).Sqrt(x).Mul(x, x)\n\t\tif t := new(big.Int).Sqrt(y).Sub(y, x3.Add(x3, curve.Params().B)); t.IsInt64() && t.Int64() == 0 {\n\t\t\treturn nil, fmt.Errorf(\"cannot parse public key\")\n\t\t}\n\n\t\treturn &PublicKey{\n\t\t\tCurve: curve,\n\t\t\tX: x,\n\t\t\tY: y,\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"cannot parse public key\")\n\t}\n}", "func parsePubkey(in string) (*ecdsa.PublicKey, error) {\n\tb, err := hex.DecodeString(in)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if len(b) != 64 {\n\t\treturn nil, fmt.Errorf(\"wrong length, want %d hex chars\", 128)\n\t}\n\tb = append([]byte{0x4}, b...)\n\treturn crypto.UnmarshalPubkey(b)\n}", "func LoadPublicKey(path string) (SignatureValidator, error) {\r\n\tgob.Register(rsaPublicKey{})\r\n\tdat, err := ioutil.ReadFile(path)\r\n\tLogErrorF(err)\r\n\treturn parsePublicKey(dat)\r\n}", "func (v *publicKey) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson94b2531bDecodeGitRonaksoftComRiverWebWasmConnection(&r, v)\n\treturn r.Error()\n}", "func (p *PublicKey) UnmarshalJSON(data []byte) error {\n\tvar pk struct {\n\t\tKeyID interface{} `json:\"key_id,string\"`\n\t\tKey *string `json:\"key\"`\n\t}\n\n\tif err := json.Unmarshal(data, &pk); err != nil {\n\t\treturn err\n\t}\n\n\tp.Key = pk.Key\n\n\tswitch v := pk.KeyID.(type) {\n\tcase nil:\n\t\treturn nil\n\tcase string:\n\t\tp.KeyID = &v\n\tcase float64:\n\t\tp.KeyID = String(strconv.FormatFloat(v, 'f', -1, 64))\n\tdefault:\n\t\treturn fmt.Errorf(\"unable to unmarshal %T as a string\", v)\n\t}\n\n\treturn nil\n}", "func DecodePublicKey(sigAlgo SignatureAlgorithm, b []byte) (PublicKey, error) {\n\tpubKey, err := crypto.DecodePublicKey(crypto.SigningAlgorithm(sigAlgo), b)\n\tif err != nil {\n\t\treturn PublicKey{}, err\n\t}\n\n\treturn PublicKey{\n\t\tpublicKey: pubKey,\n\t}, nil\n}", "func decodePublicKey(hexKey string) (crypto.PublicKey, error) {\n\tbz, err := hex.DecodeString(hexKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn crypto.DecodePublicKey(crypto.ECDSAP256, bz)\n}", "func decodePubkey(val []byte) (*ecdsa.PublicKey, error) {\n\tdata, err := base64.RawURLEncoding.DecodeString(string(val))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ethcrypto.UnmarshalPubkey(data)\n}", "func (p *PkixPublicKeyParser) ParsePublicKeyFromPemStr(publicKeyPem string) (publicKey *rsa.PublicKey, err error) {\n\tblock, _ := pem.Decode([]byte(publicKeyPem))\n\tif block == nil {\n\t\treturn nil, errors.New(key_parser.ERR_PARSE_PUBLIC_KEY)\n\t}\n\n\tresult, err := x509.ParsePKIXPublicKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpublicKey, ok := result.(*rsa.PublicKey)\n\tif !ok {\n\t\treturn nil, errors.New(key_parser.ERR_NOT_RSA_PUBLIC_KEY)\n\t}\n\n\treturn\n}", "func LoadPublicKey(filepath string) (*rsa.PublicKey, error) {\n\tbuf, err := loadFile(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := string(buf)\n\n\tif strings.HasPrefix(t, \"-----BEGIN PUBLIC KEY-----\") {\n\t\tblock, _ := pem.Decode(buf)\n\t\treturn x509.ParsePKCS1PublicKey(block.Bytes)\n\t}\n\n\treturn nil, errors.New(\"invalid public key file\")\n}", "func (pk *PublicKey) Unpack(buf []byte) {\n\tif len(buf) != PublicKeySize {\n\t\tpanic(\"buf must be of length PublicKeySize\")\n\t}\n\n\tpk.pk = new(cpapke.PublicKey)\n\tpk.pk.Unpack(buf)\n\n\t// Compute cached H(pk)\n\th := sha3.New256()\n\th.Write(buf)\n\th.Read(pk.hpk[:])\n}", "func NewPublicKeyFromBytes(rawKey []byte) (PublicKey, error) {\n\tif l := len(rawKey); l != CompressedPublicKeyLength {\n\t\treturn PublicKey{}, fmt.Errorf(\n\t\t\t\"wrong length for public key: %s of length %d\", rawKey, l)\n\t}\n\tvar k PublicKey\n\tif c := copy(k[:], rawKey); c != CompressedPublicKeyLength {\n\t\tpanic(fmt.Errorf(\"failed to copy entire key to return value\"))\n\t}\n\treturn k, nil\n}", "func (cpk *CompressedPublicKey) Uncompress() (*PublicKey, error) {\n\t// Should only execute the decompression branch of ParsePublicKey\n\tpk_s, err := btcec.ParsePubKey(cpk[:], S256)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newPublicKeyCoords(pk_s.X, pk_s.Y), nil\n}", "func Decode(r io.Reader) (Public, error) {\n\tversion, err := ReadVarInt(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstream, err := ReadVarInt(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := &obj.PubKeyData{}\n\tif version >= 3 {\n\t\terr = data.Decode(r)\n\t} else {\n\t\terr = data.DecodeSimple(r)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpk, err := NewPublicKey(data.Verification, data.Encryption)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpa, err := newPublicAddress(pk, version, stream)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newPublicID(pa, data.Behavior, data.Pow), nil\n}", "func (pk *PublicKey) Unpack(buf *[PublicKeySize]byte) {\n\tvar tmp [mode2.PublicKeySize]byte\n\tcopy(tmp[:], buf[:mode2.PublicKeySize])\n\tpk.d.Unpack(&tmp)\n\tpk.e = make([]byte, ed25519.PublicKeySize)\n\tcopy(pk.e, buf[mode2.PublicKeySize:])\n}", "func DecodePublicKeyHex(sigAlgo SignatureAlgorithm, s string) (PublicKey, error) {\n\tb, err := hex.DecodeString(s)\n\tif err != nil {\n\t\treturn PublicKey{}, err\n\t}\n\n\treturn DecodePublicKey(sigAlgo, b)\n}", "func _Ed25519PublicKeyFromBytes(bytes []byte) (*_Ed25519PublicKey, error) {\n\tlength := len(bytes)\n\tswitch length {\n\tcase 32:\n\t\treturn _Ed25519PublicKeyFromBytesRaw(bytes)\n\tcase 44:\n\t\treturn _Ed25519PublicKeyFromBytesDer(bytes)\n\tdefault:\n\t\treturn &_Ed25519PublicKey{}, _NewErrBadKeyf(\"invalid public key length: %v bytes\", len(bytes))\n\t}\n}", "func ParsePublicKey(data []byte) (tmcrypt.PubKey, sdk.AccAddress, error) {\n\t// Parse the secp256k1 public key.\n\tpk, err := btcec.ParsePubKey(data, btcec.S256())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\t// Create tendermint public key type and return with address.\n\ttmKey := tmcurve.PubKey(pk.SerializeCompressed()) // PubKeySecp256k1{}\n\n\treturn tmKey, tmKey.Address().Bytes(), nil\n}", "func PublicKeyFromBytes(bs []byte, curveType CurveType) (*PublicKey, error) {\n\tswitch curveType {\n\tcase CurveTypeEd25519:\n\t\tif len(bs) != ed25519.PublicKeySize {\n\t\t\treturn nil, fmt.Errorf(\"bytes passed have length %v but ed25519 public keys have %v bytes\",\n\t\t\t\tlen(bs), ed25519.PublicKeySize)\n\t\t}\n\tcase CurveTypeSecp256k1:\n\t\tif len(bs) != btcec.PubKeyBytesLenUncompressed {\n\t\t\treturn nil, fmt.Errorf(\"bytes passed have length %v but secp256k1 public keys have %v bytes\",\n\t\t\t\tlen(bs), btcec.PubKeyBytesLenUncompressed)\n\t\t}\n\tcase CurveTypeUnset:\n\t\tif len(bs) > 0 {\n\t\t\treturn nil, fmt.Errorf(\"attempting to create an 'unset' PublicKey but passed non-empty key bytes: %X\", bs)\n\t\t}\n\t\treturn nil, nil\n\tdefault:\n\t\treturn nil, ErrInvalidCurve(curveType)\n\t}\n\n\treturn &PublicKey{PublicKey: bs, CurveType: curveType}, nil\n}", "func PublicKeyFromSlice(b []byte) (*PublicKey, error) {\n\tif len(b) != PublicKeySize {\n\t\treturn nil, ErrInvalidPublicKey\n\t}\n\n\tvar p PublicKey\n\tcopy(p[:], b)\n\treturn &p, nil\n}", "func NewPublicKey(r io.Reader) (*PublicKey, error) {\n\trawPub, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey, _, _, _, err := ssh.ParseAuthorizedKey(rawPub)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &PublicKey{key: key}, nil\n}", "func (p *PublicKeyAlgorithm) UnmarshalJSON(b []byte) error {\n\tvar aux auxPublicKeyAlgorithm\n\tif err := json.Unmarshal(b, &aux); err != nil {\n\t\treturn err\n\t}\n\t*p = publicKeyNameToAlgorithm[aux.Name]\n\treturn nil\n}", "func BytesToPublicKey(data []byte) (pk *PublicKey) {\n\tpk = new(PublicKey)\n\tpk.PubKey.Curve = getDefaultCurve()\n\t//fmt.Printf(\"begin pub key unmarshal, len=%v, data=%v.\\n\", len(data), data)\n\tx, y := elliptic.Unmarshal(pk.PubKey.Curve, data)\n\tif x == nil || y == nil {\n\t\tpanic(\"unmarshal public key failed.\")\n\t}\n\tpk.PubKey.X = x\n\tpk.PubKey.Y = y\n\treturn\n}", "func loadPublicKey(path string) (*rsa.PublicKey, error) {\n\tdata, err := ioutil.ReadFile(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, _ := pem.Decode(data)\n\tif block == nil {\n\t\treturn nil, errors.New(\"No key is found.\")\n\t}\n\n\tswitch block.Type {\n\tcase \"CERTIFICATE\":\n\t\tcertificate, err := x509.ParseCertificate(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfinalKey, ok := certificate.PublicKey.(*rsa.PublicKey)\n\t\t\tif ok {\n\t\t\t\treturn finalKey, nil\n\t\t\t}\n\t\t\treturn nil, errors.New(\"Could not get RSA public key from the cert file.\")\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unsupported key type %q\", block.Type)\n\t}\n}", "func loadZhifubaoKey() (Unsigner, error) {\n\treturn parsePublicKey([]byte(`-----BEGIN PUBLIC KEY-----\n-----END PUBLIC KEY-----`))\n}", "func (spk *SiaPublicKey) UnmarshalJSON(b []byte) error {\n\tspk.LoadString(string(bytes.Trim(b, `\"`)))\n\tif spk.Key == nil {\n\t\t// fallback to old (base64) encoding\n\t\tvar oldSPK struct {\n\t\t\tAlgorithm Specifier\n\t\t\tKey []byte\n\t\t}\n\t\tif err := json.Unmarshal(b, &oldSPK); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tspk.Algorithm, spk.Key = oldSPK.Algorithm, oldSPK.Key\n\t}\n\treturn nil\n}", "func BytesToPublicKey(public []byte) *rsa.PublicKey {\n\n\tblock, _ := pem.Decode(public)\n\tresult, _ := x509.ParsePKCS1PublicKey(block.Bytes)\n\treturn result\n}", "func ExtractPublicKey(privateKeyPEM []byte) ([]byte, error) {\n\tblock, _ := pem.Decode(privateKeyPEM)\n\tif block == nil || block.Type != \"RSA PRIVATE KEY\" {\n\t\treturn nil, errors.New(\"failed to decode PEM block containing rsa private key\")\n\t}\n\n\tprivateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to parse rsa private key\")\n\t}\n\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to validate rsa private key\")\n\t}\n\n\tpub, err := ssh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to generate public key\")\n\t}\n\n\t// remove trailing \\n returned by ssh.MarshalAuthorizedKey\n\treturn bytes.TrimSuffix(ssh.MarshalAuthorizedKey(pub), []byte(\"\\n\")), nil\n}", "func UnmarshalPemToKey(rawKey []byte) (*rsa.PublicKey, error) {\n\tblock, _ := pem.Decode(rawKey)\n\tif block == nil || block.Type != \"PUBLIC KEY\" {\n\t\treturn nil, errors.New(\"Error decoding the key\")\n\t}\n\n\tvar pk rsa.PublicKey\n\t_, err := asn1.Unmarshal(block.Bytes, &pk)\n\tif err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Error on decoding pk: %v\", pk))\n\t}\n\n\treturn &pk, nil\n}", "func (d Driver) PubKeyFromBytes(b []byte) (crypto.PubKey, error) {\n\tif len(b) != pubkeyBytesLen && len(b) != 33 {\n\t\treturn nil, errors.New(\"invalid pub key byte,must be 65 bytes\")\n\t}\n\tif len(b) == 33 {\n\t\tp, err := ethcrypto.DecompressPubkey(b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb = ethcrypto.FromECDSAPub(p)\n\t}\n\tvar pubKeyBytes [pubkeyBytesLen]byte\n\t//pubKeyBytes := new([pubkeyBytesLen]byte)\n\tcopy(pubKeyBytes[:], b[:])\n\treturn PubKeySecp256k1Eth(pubKeyBytes), nil\n}", "func PubKeyFromBytes(pubKeyBytes []byte) (pubKey crypto.PubKey, err error) {\n\terr = cdc.UnmarshalBinaryBare(pubKeyBytes, &pubKey)\n\treturn\n}", "func (v *publicKey) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson94b2531bDecodeGitRonaksoftComRiverWebWasmConnection(l, v)\n}", "func ParsePKIXPublicKey(derBytes []byte) (interface{}, error) {\n\tvar pki publicKeyInfo\n\tif rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {\n\t\treturn nil, err\n\t} else if len(rest) != 0 {\n\t\treturn nil, errors.New(\"x509: trailing data after ASN.1 of public-key\")\n\t}\n\tif !oidPublicKeyECDSA.Equal(pki.Algorithm.Algorithm) {\n\t\treturn x509.ParsePKIXPublicKey(derBytes)\n\t}\n\n\tasn1Data := pki.PublicKey.RightAlign()\n\tparamsData := pki.Algorithm.Parameters.FullBytes\n\tnamedCurveOID := new(asn1.ObjectIdentifier)\n\trest, err := asn1.Unmarshal(paramsData, namedCurveOID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(rest) != 0 {\n\t\treturn nil, errors.New(\"x509: trailing data after ECDSA parameters\")\n\t}\n\tnamedCurve := namedCurveFromOID(*namedCurveOID)\n\tif namedCurve == nil {\n\t\treturn nil, errors.New(\"x509: unsupported elliptic curve\")\n\t}\n\tx, y := elliptic.Unmarshal(namedCurve, asn1Data)\n\tif x == nil {\n\t\treturn nil, errors.New(\"x509: failed to unmarshal elliptic curve point\")\n\t}\n\tpub := &ecdsa.PublicKey{\n\t\tCurve: namedCurve,\n\t\tX: x,\n\t\tY: y,\n\t}\n\treturn pub, nil\n}", "func NewUnsignerFromPublicKeyFile(pubkeyPath string) (Unsigner, error) {\n data, err := ioutil.ReadFile(pubkeyPath); if err != nil {\n return nil, fmt.Errorf(\"[ERR] cannot open public key file from %s : %v\", pubkeyPath, err)\n }\n rawkey, err := parsePublicKey(data); if err != nil {\n return nil, fmt.Errorf(\"[ERR] cannot parse pulic rawkey %v\", err)\n }\n return newUnsignerFromKey(rawkey)\n}", "func ParseX509PKIXPublicKey(data []byte) (*rsa.PublicKey, error) {\n\tpublicKeyImported, err := x509.ParsePKIXPublicKey(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trsaPub, ok := publicKeyImported.(*rsa.PublicKey)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected key to be of type *rsa.PublicKey, but actual was %T\", publicKeyImported)\n\t}\n\n\treturn rsaPub, nil\n}", "func rsaPublicKeyFromHex(publicKeyHex string) (*rsa.PublicKey, error) {\n\t// convert hex to bytes\n\tbytesPublicKey, err := util.HexToByte(publicKeyHex)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// convert byte to object\n\tblock, _ := pem.Decode(bytesPublicKey)\n\n\tif block == nil {\n\t\treturn nil, errors.New(\"RSA Public Key From Hex Fail: \" + \"Pem Block Nil\")\n\t}\n\n\tenc := x509.IsEncryptedPEMBlock(block)\n\tb := block.Bytes\n\n\tif enc {\n\t\tb, err = x509.DecryptPEMBlock(block, nil)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// parse key\n\tkey, err1 := x509.ParsePKCS1PublicKey(b)\n\n\tif err1 != nil {\n\t\treturn nil, err1\n\t}\n\n\t// return public key\n\treturn key, nil\n}", "func PublicKeyFromString(s string) (*ecdsa.PublicKey, error) {\n\tkeyBytes, err := base64.StdEncoding.DecodeString(s)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"base64 decoding ECDSA public key\")\n\t}\n\tkeyI, err := x509.ParsePKIXPublicKey(keyBytes)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unmarshaling ECDSA public key\")\n\t}\n\tkey, ok := keyI.(*ecdsa.PublicKey)\n\tif !ok {\n\t\treturn nil, errors.Wrap(err, \"public key not ECDSA key\")\n\t}\n\treturn key, nil\n}", "func (s *SMJWT) LoadPublicKey(filename string) error {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkey, err := jwt.ParseRSAPublicKeyFromPEM(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.publicKey = key\n\treturn nil\n}", "func PublicKey(key ssh.PublicKey) (crypto.PublicKey, error) {\n\t_, in, ok := parseString(key.Marshal())\n\tif !ok {\n\t\treturn nil, errors.New(\"public key is invalid\")\n\t}\n\n\tswitch key.Type() {\n\tcase ssh.KeyAlgoRSA:\n\t\treturn parseRSA(in)\n\tcase ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521, ssh.KeyAlgoSKECDSA256:\n\t\treturn parseECDSA(in)\n\tcase ssh.KeyAlgoED25519, ssh.KeyAlgoSKED25519:\n\t\treturn parseED25519(in)\n\tcase ssh.KeyAlgoDSA:\n\t\treturn parseDSA(in)\n\tdefault:\n\t\treturn nil, errors.Errorf(\"public key %s is not supported\", key.Type())\n\t}\n}", "func (k *PublicKey) UnmarshalText(text []byte) error {\n\tif err := k.SetFromHex(string(text)); err != nil {\n\t\treturn errors.Wrapf(err, \"while parsing %s as public key\", text)\n\t}\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepFilterer) ParsePublicKeyPublished(log types.Log) (*BondedECDSAKeepPublicKeyPublished, error) {\n\tevent := new(BondedECDSAKeepPublicKeyPublished)\n\tif err := _BondedECDSAKeep.contract.UnpackLog(event, \"PublicKeyPublished\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func ParseDERKey(block []byte) (Unsigner, error) {\n\n\tvar rawkey interface{}\n\trsa, err := x509.ParsePKIXPublicKey(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trawkey = rsa\n\n\treturn NewUnsignerFromKey(rawkey)\n}", "func UnarmorPubKeyBytes(armorStr string) (bz []byte, algo string, err error) {\n\tbz, header, err := unarmorBytes(armorStr, blockTypePubKey)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"couldn't unarmor bytes: %w\", err)\n\t}\n\n\tswitch header[headerVersion] {\n\tcase \"0.0.0\":\n\t\treturn bz, defaultAlgo, err\n\tcase \"0.0.1\":\n\t\tif header[headerType] == \"\" {\n\t\t\theader[headerType] = defaultAlgo\n\t\t}\n\n\t\treturn bz, header[headerType], err\n\tcase \"\":\n\t\treturn nil, \"\", errors.New(\"header's version field is empty\")\n\tdefault:\n\t\terr = fmt.Errorf(\"unrecognized version: %v\", header[headerVersion])\n\t\treturn nil, \"\", err\n\t}\n}", "func (sk *PrivKey) Unmarshal(bz []byte, curve elliptic.Curve, expectedSize int) error {\n\tif len(bz) != expectedSize {\n\t\treturn fmt.Errorf(\"wrong ECDSA SK bytes, expecting %d bytes\", expectedSize)\n\t}\n\n\tsk.Curve = curve\n\tsk.D = new(big.Int).SetBytes(bz)\n\tsk.X, sk.Y = curve.ScalarBaseMult(bz)\n\treturn nil\n}", "func _Ed25519PublicKeyFromBytesRaw(bytes []byte) (*_Ed25519PublicKey, error) {\n\tif bytes == nil {\n\t\treturn &_Ed25519PublicKey{}, errByteArrayNull\n\t}\n\tif len(bytes) != ed25519.PublicKeySize {\n\t\treturn &_Ed25519PublicKey{}, _NewErrBadKeyf(\"invalid public key length: %v bytes\", len(bytes))\n\t}\n\n\treturn &_Ed25519PublicKey{\n\t\tkeyData: bytes,\n\t}, nil\n}", "func (s *SSHPublicKey) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"keyData\":\n\t\t\terr = unpopulate(val, \"KeyData\", &s.KeyData)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func NewPublicKeyFromString(str string) (*PublicKey, error) {\n\tparts := strings.Split(str, \":\")\n\tif len(parts) == 1 {\n\t\tdata, err := base58.Decode(parts[0])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"decoding key string: %v\", err)\n\t\t}\n\t\treturn &PublicKey{Type: ED25519, Data: data}, nil\n\t} else if len(parts) == 2 {\n\t\tkeyType, err := stringToKeyType(parts[0])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"decoding key type string: %v\", err)\n\t\t}\n\t\tdata, err := base58.Decode(parts[1])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"decoding key data: %v\", err)\n\t\t}\n\t\treturn &PublicKey{Type: keyType, Data: data}, nil\n\t} else {\n\t\treturn nil, fmt.Errorf(\"invalid encoded key format, must be <curve>:<encoded key>\")\n\t}\n}", "func ReadPubKey(data []byte) (ssh.PublicKey, error) {\n\treadAuthd := func(data []byte) (ssh.PublicKey, error) {\n\t\tpub, _, _, _, err := ssh.ParseAuthorizedKey(data)\n\t\treturn pub, err\n\t}\n\n\tdecoded, err := base64.StdEncoding.DecodeString(string(data))\n\tif len(decoded) > 0 && err == nil {\n\t\tif pub, err := readAuthd(decoded); pub != nil && err == nil {\n\t\t\treturn pub, nil\n\t\t}\n\t\treturn ssh.ParsePublicKey(decoded)\n\t}\n\n\tif pub, err := readAuthd(data); pub != nil && err == nil {\n\t\treturn pub, nil\n\t}\n\treturn ssh.ParsePublicKey(data)\n}", "func _Ed25519PublicKeyFromString(s string) (*_Ed25519PublicKey, error) {\n\tbyt, err := hex.DecodeString(s)\n\tif err != nil {\n\t\treturn &_Ed25519PublicKey{}, err\n\t}\n\n\treturn _Ed25519PublicKeyFromBytes(byt)\n}", "func PubKeyFromBytes(data []byte) (PubKey, error) {\n\tkeyTypeByt := data[:KeyTypeBytLen]\n\tswitch string(keyTypeByt) {\n\tcase Sr25519Idx:\n\t\treturn SrPubKeyFromBytes(data[KeyTypeBytLen:]), nil\n\tcase Ed25519Idx:\n\t\treturn EdPubKeyFromBytes(data[KeyTypeBytLen:]), nil\n\tdefault:\n\t\treturn nil, NoKeyType\n\t}\n}", "func parseRSAKey(key ssh.PublicKey) (*rsa.PublicKey, error) {\n\tvar sshWire struct {\n\t\tName string\n\t\tE *big.Int\n\t\tN *big.Int\n\t}\n\tif err := ssh.Unmarshal(key.Marshal(), &sshWire); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal key %v: %v\", key.Type(), err)\n\t}\n\treturn &rsa.PublicKey{N: sshWire.N, E: int(sshWire.E.Int64())}, nil\n}", "func readPublicKey(d *pluginsdk.ResourceData, pubKey interface{}) error {\n\tpubKeyBytes, err := x509.MarshalPKIXPublicKey(pubKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal public key error: %s\", err)\n\t}\n\tpubKeyPemBlock := &pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tBytes: pubKeyBytes,\n\t}\n\n\td.Set(\"public_key_pem\", string(pem.EncodeToMemory(pubKeyPemBlock)))\n\n\tsshPubKey, err := ssh.NewPublicKey(pubKey)\n\tif err == nil {\n\t\t// Not all EC types can be SSH keys, so we'll produce this only\n\t\t// if an appropriate type was selected.\n\t\tsshPubKeyBytes := ssh.MarshalAuthorizedKey(sshPubKey)\n\t\td.Set(\"public_key_openssh\", string(sshPubKeyBytes))\n\t} else {\n\t\td.Set(\"public_key_openssh\", \"\")\n\t}\n\treturn nil\n}", "func (sig *Signature) RecoverPublicKey(hash []byte) (*PublicKey, error) {\n\tif !sig.HasV() {\n\t\treturn nil, errors.New(\"signature has no V value\")\n\t}\n\tif len(hash) == 0 || len(hash) > HashLen {\n\t\treturn nil, errors.New(\"message hash is illegal\")\n\t}\n\ts, err := sig.SerializeRSV()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParsePublicKey(secp256k1.RecoverPubkey(hash[:], s))\n}", "func BytesToPublicKey(pub []byte) *rsa.PublicKey {\n\tblock, _ := pem.Decode(pub)\n\tvar err error\n\tenc := x509.IsEncryptedPEMBlock(block)\n\tb := block.Bytes\n\tif enc {\n\t\tlogrus.Println(\"is encrypted pem block\")\n\t\tb, err = x509.DecryptPEMBlock(block, nil)\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t}\n\t}\n\tifc, err := x509.ParsePKIXPublicKey(b)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n\tkey, ok := ifc.(*rsa.PublicKey)\n\tif !ok {\n\t\tlogrus.Error(\"not ok\")\n\t}\n\treturn key\n}", "func ParsePublicKey(file string) (ssh.AuthMethod, ssh.PublicKey, error) {\n\tprivateKey, err := ioutil.ReadFile(file)\n\n\tvar pathError *os.PathError\n\tif errors.As(err, &pathError) { //if no keys are found, they are generated\n\t\tvar publicKey []byte\n\t\tbitSize := 4096\n\t\tprivateKey, publicKey, err = generateKeyPair(bitSize)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\terr := ioutil.WriteFile(file, privateKey, 0600)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\terr = ioutil.WriteFile(file+\".pub\", publicKey, 0600)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t} else if err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar passwordError *ssh.PassphraseMissingError\n\tvar signer ssh.Signer\n\tsigner, err = ssh.ParsePrivateKey(privateKey) //try to parse the key as if not password-protected\n\n\tif err != nil {\n\t\tif errors.As(err, &passwordError) { //if the key is password-protected, try to resolve it using the SSH-Agent, otherwise ask the user for the password\n\t\t\tpublicKey, err := ioutil.ReadFile(file + \".pub\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\n\t\t\tsigner, err = getSignerFromSSHAgent(publicKey)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Print(\"Enter SSH password: \")\n\n\t\t\t\tpassword, _ := term.ReadPassword(int(os.Stdin.Fd()))\n\t\t\t\tfmt.Println()\n\t\t\t\tsigner, err = ssh.ParsePrivateKeyWithPassphrase(privateKey, []byte(password))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\treturn ssh.PublicKeys(signer), signer.PublicKey(), nil\n}", "func BytesToPublicKey(pub []byte) *rsa.PublicKey {\n\tblock, _ := pem.Decode(pub)\n\tenc := x509.IsEncryptedPEMBlock(block)\n\tb := block.Bytes\n\tvar err error\n\tif enc {\n\t\tb, err = x509.DecryptPEMBlock(block, nil)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tifc, err := x509.ParsePKIXPublicKey(b)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tkey, ok := ifc.(*rsa.PublicKey)\n\tif !ok {\n\t\tlog.Fatal(\"Bad public key\")\n\t}\n\treturn key\n}", "func DecodePublicKeyPEM(sigAlgo SignatureAlgorithm, s string) (PublicKey, error) {\n\tblock, _ := pem.Decode([]byte(s))\n\n\tpublicKey, err := x509.ParsePKIXPublicKey(block.Bytes)\n\tif err != nil {\n\t\treturn PublicKey{}, fmt.Errorf(\"crypto: failed to parse PEM string: %w\", err)\n\t}\n\n\tgoPublicKey := publicKey.(*ecdsa.PublicKey)\n\n\trawPublicKey := append(\n\t\tgoPublicKey.X.Bytes(),\n\t\tgoPublicKey.Y.Bytes()...,\n\t)\n\n\treturn DecodePublicKey(sigAlgo, rawPublicKey)\n}", "func validatePubKey(publicKey string) error {\n\tpk, err := hex.DecodeString(publicKey)\n\tif err != nil {\n\t\tlog.Debugf(\"validatePubKey: decode hex string \"+\n\t\t\t\"failed for '%v': %v\", publicKey, err)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\t}\n\n\tvar emptyPK [identity.PublicKeySize]byte\n\tswitch {\n\tcase len(pk) != len(emptyPK):\n\t\tlog.Debugf(\"validatePubKey: invalid size: %v\",\n\t\t\tpublicKey)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\tcase bytes.Equal(pk, emptyPK[:]):\n\t\tlog.Debugf(\"validatePubKey: key is empty: %v\",\n\t\t\tpublicKey)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewPublicKeyFromString(key string) (*PublicKey, error) {\n\tprefixChain := addrPrefix\n\n\tprefix := key[:len(prefixChain)]\n\n\tif prefix != prefixChain {\n\t\treturn nil, ErrPublicKeyChainPrefixMismatch\n\t}\n\n\tb58 := base58.Decode(key[len(prefixChain):])\n\tif len(b58) < 5 {\n\t\treturn nil, ErrInvalidPublicKey\n\t}\n\n\tchk1 := b58[len(b58)-4:]\n\n\tkeyBytes := b58[:len(b58)-4]\n\tchk2, err := util.Ripemd160Checksum(keyBytes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Ripemd160Checksum, %+v\\n\", err)\n\t}\n\n\tif !bytes.Equal(chk1, chk2) {\n\t\treturn nil, ErrInvalidPublicKey\n\t}\n\n\tpub, err := btcec.ParsePubKey(keyBytes, btcec.S256())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ParsePubKey, %+v\\n\", err)\n\t}\n\n\tk := PublicKey{\n\t\tkey: pub,\n\t\tprefix: prefix,\n\t\tchecksum: chk1,\n\t}\n\n\treturn &k, nil\n}", "func (pk *PublicKey) LoadString(s string) error {\n\tparts := strings.SplitN(s, \":\", 2)\n\tif len(parts) != 2 {\n\t\treturn errors.New(\"invalid public key string\")\n\t}\n\terr := pk.Key.LoadString(parts[1])\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn pk.Algorithm.LoadString(parts[0])\n}", "func HexStringToPublicKey(pubKey string) (PublicKey, error) {\n\tb, err := hex.DecodeString(pubKey)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to decode public key %s\", pubKey)\n\t}\n\treturn BytesToPublicKey(b)\n}", "func LoadPublicKeyPair(addr string) (*PublicKeyPair, error) {\n\tp := new(PublicKeyPair)\n\tp.spendKey = edwards25519.NewIdentityPoint()\n\tp.viewKey = edwards25519.NewIdentityPoint()\n\ta := base58.Decode(addr)\n\th := sha3.NewLegacyKeccak256()\n\th.Write(a[:len(a)-4])\n\ts := h.Sum(nil)\n\tif !utils.TestBytes(a[len(a)-4:], s[:4]) {\n\t\treturn nil, fmt.Errorf(\"address checksum fail\")\n\t}\n\tif _, err := p.spendKey.SetBytes(a[1:33]); err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err := p.viewKey.SetBytes(a[33:65]); err != nil {\n\t\treturn nil, err\n\t}\n\treturn p, nil\n}", "func ReadPubKey(path string) (crypto.PublicKey, error) {\n\traw, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor {\n\t\tblock, rest := pem.Decode(raw)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\t\tif !strings.Contains(block.Type, \"CERTIFICATE\") {\n\t\t\tif strings.Contains(block.Type, \"RSA\") {\n\t\t\t\tkey, err := x509.ParsePKCS1PublicKey(block.Bytes)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Parsing error in x509.ParsePKCS1PublicKey: %v\", err)\n\t\t\t\t}\n\t\t\t\treturn key, nil\n\t\t\t}\n\t\t\tkey, err := x509.ParsePKIXPublicKey(block.Bytes)\n\t\t\tif err == nil {\n\t\t\t\tif key, ok := key.(crypto.PublicKey); ok {\n\t\t\t\t\treturn key, nil\n\t\t\t\t}\n\t\t\t\treturn nil, fmt.Errorf(\"found unknown public key type (%T) in PKIX wrapping\", key)\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\traw = rest\n\t}\n\treturn nil, fmt.Errorf(\"failed to parse public key\")\n}", "func DecompressPubkey(pubkey []byte) (x, y *big.Int) {\n\treturn secp256k1.DecompressPubkey(pubkey)\n}" ]
[ "0.76415914", "0.7532272", "0.74554783", "0.7387281", "0.6900951", "0.68235993", "0.67982626", "0.6771452", "0.6745591", "0.67185414", "0.6630032", "0.6628866", "0.6592083", "0.6578019", "0.656955", "0.6547178", "0.6482753", "0.6472057", "0.6451217", "0.64298695", "0.64150184", "0.64150184", "0.6370179", "0.63629633", "0.6355807", "0.63556176", "0.6307026", "0.6278486", "0.62571067", "0.62565744", "0.6254044", "0.6252756", "0.6239251", "0.62079084", "0.61894774", "0.61889327", "0.61693", "0.61552507", "0.61525726", "0.6111859", "0.60794616", "0.6053513", "0.6015836", "0.5951233", "0.5942307", "0.58946174", "0.5867799", "0.58456296", "0.58423805", "0.58360654", "0.58281803", "0.5827908", "0.58256775", "0.58222383", "0.5798688", "0.57805645", "0.57508934", "0.573835", "0.5737574", "0.5724552", "0.5713673", "0.5706076", "0.5682959", "0.56816524", "0.5680901", "0.56664985", "0.56637657", "0.56580824", "0.5645717", "0.5645298", "0.562328", "0.56180686", "0.56176597", "0.56084895", "0.557908", "0.55607694", "0.55602986", "0.55471474", "0.554276", "0.5509771", "0.55057716", "0.54999006", "0.5495328", "0.54902875", "0.5470517", "0.5454151", "0.5427373", "0.5419743", "0.54129994", "0.54120207", "0.54042286", "0.540335", "0.5400542", "0.53626776", "0.5350628", "0.5328814", "0.53267926", "0.53259224", "0.53164035", "0.5310594" ]
0.78284276
0
GenerateKeyPair generates BBS+ PublicKey and PrivateKey pair.
func GenerateKeyPair(h func() hash.Hash, seed []byte) (*PublicKey, *PrivateKey, error) { if len(seed) != 0 && len(seed) != seedSize { return nil, nil, errors.New("invalid size of seed") } okm, err := generateOKM(seed, h) if err != nil { return nil, nil, err } privKeyFr := frFromOKM(okm) privKey := &PrivateKey{privKeyFr} pubKey := privKey.PublicKey() return pubKey, privKey, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func generateKeyPair() (publicKey, privateKey *[32]byte, err error) {\n\treturn box.GenerateKey(rand.Reader)\n}", "func GenerateKeyPair() (pubkey, privkey []byte) {\n\tkey, err := ecdsa.GenerateKey(secp256k1.S256(), rand.Reader)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpubkey = elliptic.Marshal(secp256k1.S256(), key.X, key.Y)\n\tprivkey = make([]byte, 32)\n\tblob := key.D.Bytes()\n\tcopy(privkey[32-len(blob):], blob)\n\treturn\n}", "func GenerateKeyPair() (*rsa.PrivateKey, *rsa.PublicKey, error) {\n\tprivKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn privKey, &privKey.PublicKey, nil\n}", "func (n *nauth) GenerateKeyPair(passphrase string) ([]byte, []byte, error) {\n\tpriv, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tprivDer := x509.MarshalPKCS1PrivateKey(priv)\n\tprivBlock := pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tHeaders: nil,\n\t\tBytes: privDer,\n\t}\n\tprivPem := pem.EncodeToMemory(&privBlock)\n\n\tpub, err := ssh.NewPublicKey(&priv.PublicKey)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tpubBytes := ssh.MarshalAuthorizedKey(pub)\n\treturn privPem, pubBytes, nil\n}", "func GenerateKeyPair(group *schnorr.Group) (*SecKey, *PubKey) {\n\ts1 := common.GetRandomInt(group.Q)\n\ts2 := common.GetRandomInt(group.Q)\n\th1 := group.Exp(group.G, s1)\n\th2 := group.Exp(group.G, s2)\n\n\treturn NewSecKey(s1, s2), NewPubKey(h1, h2)\n}", "func GenerateKeyPair() (*ecdsa.PrivateKey, error ) {\n\tkey, err := ecdsa.GenerateKey(btcec.S256(), rand.Reader)\n\tif err != nil { return nil, err } \n\treturn key, nil\n}", "func (c *Curve25519) GenerateKeyPair() (KeyPair, error) {\n\n\tvar priv [32]byte\n\n\t// fill private key\n\t_, err := c.randSource.Read(priv[:])\n\tif err != nil {\n\t\treturn KeyPair{}, err\n\t}\n\n\tpriv[0] &= 248\n\tpriv[31] &= 127\n\tpriv[31] |= 64\n\n\tvar pubKey [32]byte\n\tcurve25519.ScalarBaseMult(&pubKey, &priv)\n\n\treturn KeyPair{\n\t\tPrivateKey: priv,\n\t\tPublicKey: pubKey,\n\t}, nil\n\n}", "func GenerateKeyPair() ([]byte, []byte) {\n\tconst seckeyLen = 32\n\tvar seckey []byte\n\tvar pubkey []byte\n\nnew_seckey:\n\tseckey = RandByte(seckeyLen)\n\tif secp.SeckeyIsValid(seckey) != 1 {\n\t\tgoto new_seckey // regen\n\t}\n\n\tpubkey = pubkeyFromSeckey(seckey)\n\tif pubkey == nil {\n\t\tlog.Panic(\"IMPOSSIBLE: pubkey invalid from valid seckey\")\n\t\tgoto new_seckey\n\t}\n\tif ret := secp.PubkeyIsValid(pubkey); ret != 1 {\n\t\tlog.Panicf(\"ERROR: Pubkey invalid, ret=%d\", ret)\n\t\tgoto new_seckey\n\t}\n\n\treturn pubkey, seckey\n}", "func GenerateKeyPair(h func() hash.Hash, seed []byte) (*PublicKey, *PrivateKey, error) {\n\tif len(seed) != 0 && len(seed) != seedSize {\n\t\treturn nil, nil, errors.New(\"invalid size of seed\")\n\t}\n\n\tokm, err := generateOKM(seed, h)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tprivKeyFr, err := frFromOKM(okm)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"convert OKM to FR: %w\", err)\n\t}\n\n\tprivKey := &PrivateKey{PrivKey: g2pubs.NewSecretKeyFromFR(privKeyFr)}\n\tpubKey := privKey.PublicKey()\n\n\treturn pubKey, privKey, nil\n}", "func generateKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error) {\n\tprivkey, err := rsa.GenerateKey(rand.Reader, bits)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn privkey, &privkey.PublicKey, nil\n}", "func (s *SkyСoinService) GenerateKeyPair() *KeysResponse {\n\tseed := getRand()\n\trand.Read(seed)\n\tpub, sec := cipher.GenerateDeterministicKeyPair(seed)\n\treturn &KeysResponse{\n\t\tPrivate: sec.Hex(),\n\t\tPublic: pub.Hex(),\n\t}\n}", "func GenKeyPair() (string, string, error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tprivateKeyPEM := &pem.Block{Type: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}\n\tvar private bytes.Buffer\n\tif err := pem.Encode(&private, privateKeyPEM); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\t// generate public key\n\tpub, err := ssh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tpublic := ssh.MarshalAuthorizedKey(pub)\n\treturn string(public), private.String(), nil\n}", "func GenKeyPair() (string, string, error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tprivateKeyPEM := &pem.Block{Type: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}\n\tvar private bytes.Buffer\n\tif err := pem.Encode(&private, privateKeyPEM); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\t// generate public key\n\tpub, err := ssh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tpublic := ssh.MarshalAuthorizedKey(pub)\n\treturn string(public), private.String(), nil\n}", "func GenerateKeyPair(rand io.Reader) (*PublicKey, *PrivateKey, error) {\n\tvar seed [KeySeedSize]byte\n\tif rand == nil {\n\t\trand = cryptoRand.Reader\n\t}\n\t_, err := io.ReadFull(rand, seed[:])\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tpk, sk := NewKeyFromSeed(seed[:])\n\treturn pk, sk, nil\n}", "func GenerateKeyPair() *rsa.PrivateKey {\n\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Error in generating key-value pair, error is\", err)\n\t}\n\treturn privateKey\n}", "func CreateKeyPair() (publicKeyBytes []byte, privateKeyBytes []byte, err error) {\n\tprivateKey, _ := rsa.GenerateKey(rand.Reader, 2048)\n\tpublicKey := privateKey.PublicKey\n\tpub, err := ssh.NewPublicKey(&publicKey)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpublicKeyBytes = ssh.MarshalAuthorizedKey(pub)\n\n\tpriBytes := x509.MarshalPKCS1PrivateKey(privateKey)\n\tprivateKeyBytes = pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"RSA PRIVATE KEY\",\n\t\t\tBytes: priBytes,\n\t\t},\n\t)\n\treturn publicKeyBytes, privateKeyBytes, nil\n}", "func KeyPairGenerate(IKM []byte, S []byte, W []byte) int {\n\tr := NewBIGints(CURVE_Order)\n\tL := ceil(3*ceil(r.nbits(),8),2)\n\tLEN:=core.InttoBytes(L, 2)\n\tAIKM:=make([]byte,len(IKM)+1) \n\tfor i:=0;i<len(IKM);i++ {\n\t\tAIKM[i]=IKM[i]\n\t}\n\tAIKM[len(IKM)]=0\n\n\tG := ECP2_generator()\n\tif G.Is_infinity() {\n\t\treturn BLS_FAIL\n\t}\n\tSALT := []byte(\"BLS-SIG-KEYGEN-SALT-\")\n\tPRK := core.HKDF_Extract(core.MC_SHA2,HASH_TYPE,SALT,AIKM)\n\tOKM := core.HKDF_Expand(core.MC_SHA2,HASH_TYPE,L,PRK,LEN)\n\n\tdx:= DBIG_fromBytes(OKM[:])\n\ts:= dx.Mod(r)\n\ts.ToBytes(S)\n// SkToPk\n\tG = G2mul(G, s)\n\tG.ToBytes(W,true)\n\treturn BLS_OK\n}", "func GenerateSigningKeyPair(publicFileName, privateFileName, curveType string) (err error) {\n\tvar publicKey, privateKey []byte\n\tswitch strings.ToLower(curveType) {\n\tcase CurveSecp256K1:\n\t\tpublicKey, privateKey, err = secp256k1.GenerateSigningKeyPair()\n\tcase CurveEd25519:\n\t\tpublicKey, privateKey, err = ed25519.GenerateSigningKeyPair()\n\tdefault:\n\t\tpublicKey, privateKey, err = ed25519.GenerateSigningKeyPair()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = utils.WriteKeyToPemFile(privateFileName, utils.PrivateKey, privateKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = utils.WriteKeyToPemFile(publicFileName, utils.PublicKey, publicKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewKeyPair() (ecdsa.PrivateKey, []byte) {\n\tellipticCurve := EllipticCurve()\n\n\tprivateKey, err := ecdsa.GenerateKey(ellipticCurve, rand.Reader)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tX := privateKey.PublicKey.X.Bytes()\n\tY := privateKey.PublicKey.Y.Bytes()\n\t//fmt.Println(len(X), X)\n\t//fmt.Println(len(Y), Y)\n\tpublicKey := append(\n\t\tX, // 32 bytes (P256)\n\t\tY..., // 32 bytes (P256)\n\t) // 64 bytes => 64 * 8 bits = 512 bits (perchè usiamo P256 o secp256k)\n\treturn *privateKey, publicKey\n}", "func GenerateNewKeyPair(bits int) (*rsa.PrivateKey, error) {\n\tprivKey, err := rsa.GenerateKey(rand.Reader, bits)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn privKey, err\n}", "func GenerateStrongKeyPair() ([]byte, []byte, []byte, error) {\n prv, pub, ssh, err := generateKeyPairs(rsaStrongKeySize)\n return pub, prv, ssh, err\n}", "func generateKeypair() ([]byte, []byte, error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to generate SSH private key: %v\", err)\n\t}\n\tprivatePEM := pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tHeaders: nil,\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t})\n\tpublicKey, err := cssh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to generate SSH public key: %v\", err)\n\t}\n\tpublicPEM := cssh.MarshalAuthorizedKey(publicKey)\n\treturn privatePEM, publicPEM, nil\n}", "func NewKeyPair() (*keyPair, error) {\n\tprivKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprivKey.Precompute()\n\n\tpubKey := &privKey.PublicKey\n\treturn &keyPair{Private: privKey, Public: pubKey}, nil\n}", "func (b *Base) GenerateKeyPair(req *GenerateKeyPairReq) (*GenerateKeyPairResp, error) {\n\treturn nil, ErrFunctionNotSupported\n}", "func GenerateKeypair() (*Keypair, error) {\n\tvar publicKey [32]byte\n\tvar privateKey [32]byte\n\t_, err := rand.Read(privateKey[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcurve25519.ScalarBaseMult(&publicKey, &privateKey)\n\treturn &Keypair{publicKey, privateKey}, nil\n}", "func CreateKeyPair() (pubKey PublicKey, secKey SecretKey, err error) {\n\terrorCode := C.crypto_sign_keypair((*C.uchar)(&pubKey[0]), (*C.uchar)(&secKey[0]))\n\tif errorCode != 0 {\n\t\terr = errors.New(\"call to crypto_sign_keypair failed\")\n\t}\n\treturn\n}", "func GenerateNewKeypair() *Keypair {\n\n\tpk, _ := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)\n\n\tb := bigJoin(KEY_SIZE, pk.PublicKey.X, pk.PublicKey.Y)\n\n\tpublic := base58.EncodeBig([]byte{}, b)\n\tprivate := base58.EncodeBig([]byte{}, pk.D)\n\n\tkp := Keypair{Public: public, Private: private}\n\n\treturn &kp\n}", "func GenSSHKeyPair(bits int) ([]byte, []byte, error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, bits)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tprivateKeyPEM := &pem.Block{Type: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}\n\n\tvar privateBuf bytes.Buffer\n\tif err := pem.Encode(&privateBuf, privateKeyPEM); err != nil {\n\t\treturn nil, nil, errors.New(\"failed to pem encode private key\")\n\t}\n\n\tpub, err := ssh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, nil, errors.New(\"failed to generate public key\")\n\t}\n\n\t// remove trailing \\n returned by ssh.MarshalAuthorizedKey\n\treturn privateBuf.Bytes(), bytes.TrimSuffix(ssh.MarshalAuthorizedKey(pub), []byte(\"\\n\")), nil\n}", "func GenKeyPairs(bits int) (privateKey ,publicKey string,err error) {\n\tpriKey, err := rsa.GenerateKey(rand.Reader, bits)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tderStream := x509.MarshalPKCS1PrivateKey(priKey)\n\tblock := &pem.Block{\n\t\tType: \"private key\",\n\t\tBytes: derStream,\n\t}\n\tb := pem.EncodeToMemory(block)\n\tprivateKey = string(b)\n\n\tpubKey := &priKey.PublicKey\n\tderPkix, err := x509.MarshalPKIXPublicKey(pubKey)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tblock = &pem.Block{\n\t\tType: \"public key\",\n\t\tBytes: derPkix,\n\t}\n\tb = pem.EncodeToMemory(block)\n\tpublicKey = string(b)\n\treturn privateKey, publicKey, nil\n}", "func GenerateKeyPair(bits int) (keypair *KeyPair, err error) {\n\tkeypair = new(KeyPair)\n\tkeypair.PublicKey = new(PublicKey)\n\tkeypair.PrivateKey = new(PrivateKey)\n\n\tif bits == 0 {\n\t\terr = errors.New(\"RSA modulus size must not be zero.\")\n\t\treturn\n\t}\n\tif bits%8 != 0 {\n\t\terr = errors.New(\"RSA modulus size must be a multiple of 8.\")\n\t\treturn\n\t}\n\n\tfor limit := 0; limit < 1000; limit++ {\n\t\tvar tempKey *rsa.PrivateKey\n\t\ttempKey, err = rsa.GenerateKey(rand.Reader, bits)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif len(tempKey.Primes) != 2 {\n\t\t\terr = errors.New(\"RSA package generated a weird set of primes (i.e. not two)\")\n\t\t\treturn\n\t\t}\n\n\t\tp := tempKey.Primes[0]\n\t\tq := tempKey.Primes[1]\n\n\t\tif p.Cmp(q) == 0 {\n\t\t\terr = errors.New(\"RSA keypair factors were equal. This is really unlikely dependent on the bitsize and it appears something horrible has happened.\")\n\t\t\treturn\n\t\t}\n\t\tif gcd := new(big.Int).GCD(nil, nil, p, q); gcd.Cmp(big.NewInt(1)) != 0 {\n\t\t\terr = errors.New(\"RSA primes were not relatively prime!\")\n\t\t\treturn\n\t\t}\n\n\t\tmodulus := new(big.Int).Mul(p, q)\n\n\t\tpublicExp := big.NewInt(3)\n\t\t//publicExp := big.NewInt(65537)\n\n\t\t//totient = (p-1) * (q-1)\n\t\ttotient := new(big.Int)\n\t\ttotient.Sub(p, big.NewInt(1))\n\t\ttotient.Mul(totient, new(big.Int).Sub(q, big.NewInt(1)))\n\n\t\tif gcd := new(big.Int).GCD(nil, nil, publicExp, totient); gcd.Cmp(big.NewInt(1)) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tprivateExp := new(big.Int).ModInverse(publicExp, totient)\n\t\tkeypair.PublicKey.Modulus = modulus\n\t\tkeypair.PrivateKey.Modulus = modulus\n\t\tkeypair.PublicKey.PublicExp = publicExp\n\t\tkeypair.PrivateKey.PrivateExp = privateExp\n\t\treturn\n\t}\n\terr = errors.New(\"Failed to generate a within the limit!\")\n\treturn\n\n}", "func newKeyPair() (ecdsa.PrivateKey, []byte) {\n\t// ECC generate private key\n\tcurve := elliptic.P256()\n\tprivate, err := ecdsa.GenerateKey(curve, rand.Reader)\n\tlog.Println(\"--------\", private)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\t// private key generate public key\n\tpubKey := append(private.PublicKey.X.Bytes(), private.PublicKey.Y.Bytes()...)\n\treturn *private, pubKey\n}", "func GenerateRSAKeyPair(opts GenerateRSAOptions) (*RSAKeyPair, error) {\n\t//creates the private key\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, opts.Bits)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error generating private key: %s\\n\", err)\n\t}\n\n\t//validates the private key\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error validating private key: %s\\n\", err)\n\t}\n\n\t// sets up the PEM block for private key\n\tprivateKeyBlock := pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tHeaders: nil,\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t}\n\n\t//check to see if we are applying encryption to this key\n\tif opts.Encryption != nil {\n\t\t//check to make sure we have a password specified\n\t\tpass := strings.TrimSpace(opts.Encryption.Password)\n\t\tif pass == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"need a password!\")\n\t\t}\n\t\t//check to make sure we're using a supported PEMCipher\n\t\tencCipher := opts.Encryption.PEMCipher\n\t\tif encCipher != x509.PEMCipherDES &&\n\t\t\tencCipher != x509.PEMCipher3DES &&\n\t\t\tencCipher != x509.PEMCipherAES128 &&\n\t\t\tencCipher != x509.PEMCipherAES192 &&\n\t\t\tencCipher != x509.PEMCipherAES256 {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"invalid PEMCipher\")\n\t\t}\n\t\t//encrypt the private key block\n\t\tencBlock, err := x509.EncryptPEMBlock(rand.Reader, \"RSA PRIVATE KEY\", privateKeyBlock.Bytes, []byte(pass), encCipher)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error encrypting pirvate key: %s\\n\", err)\n\t\t}\n\t\t//replaces the starting one with the one we encrypted\n\t\tprivateKeyBlock = *encBlock\n\t}\n\n\t// serializes the public key in a DER-encoded PKIX format (see docs for more)\n\tpublicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting up public key: %s\\n\", err)\n\t}\n\n\t// sets up the PEM block for public key\n\tpublicKeyBlock := pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tHeaders: nil,\n\t\tBytes: publicKeyBytes,\n\t}\n\n\t//returns the created key pair\n\treturn &RSAKeyPair{\n\t\tPrivateKey: string(pem.EncodeToMemory(&privateKeyBlock)),\n\t\tPublicKey: string(pem.EncodeToMemory(&publicKeyBlock)),\n\t}, nil\n}", "func generateKeys() (private, sshpub, tlspub []byte, err error) {\n\tprivateKey, publicKey, err := native.GenerateKeyPair()\n\tif err != nil {\n\t\treturn nil, nil, nil, trace.Wrap(err)\n\t}\n\n\tsshPrivateKey, err := ssh.ParseRawPrivateKey(privateKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, trace.Wrap(err)\n\t}\n\n\ttlsPublicKey, err := tlsca.MarshalPublicKeyFromPrivateKeyPEM(sshPrivateKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, trace.Wrap(err)\n\t}\n\n\treturn privateKey, publicKey, tlsPublicKey, nil\n}", "func generateKeys() (private, sshpub, tlspub []byte, err error) {\n\tprivateKey, publicKey, err := native.GenerateKeyPair()\n\tif err != nil {\n\t\treturn nil, nil, nil, trace.Wrap(err)\n\t}\n\n\tsshPrivateKey, err := ssh.ParseRawPrivateKey(privateKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, trace.Wrap(err)\n\t}\n\n\ttlsPublicKey, err := tlsca.MarshalPublicKeyFromPrivateKeyPEM(sshPrivateKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, trace.Wrap(err)\n\t}\n\n\treturn privateKey, publicKey, tlsPublicKey, nil\n}", "func newKeyPair() (ecdsa.PrivateKey, []byte) {\n\tcurve := elliptic.P256()\n\n\tpriKey, err := ecdsa.GenerateKey(curve, rand.Reader)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tpubKey := append(priKey.PublicKey.X.Bytes(), priKey.PublicKey.Y.Bytes()...)\n\n\treturn *priKey, pubKey\n}", "func (lib *PKCS11Lib) GenerateECDSAKeyPair(c elliptic.Curve) (*PKCS11PrivateKeyECDSA, error) {\n\treturn lib.GenerateECDSAKeyPairOnSlot(lib.Slot.id, nil, nil, c)\n}", "func GenerateKeypair() (privkey, pubkey []byte, err error) {\n\tpair, err := noise.DH25519.GenerateKeypair(rand.Reader)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// pair.Public is already filled in; assert here that PubkeyFromPrivkey\n\t// agrees with it.\n\tderivedPubkey := PubkeyFromPrivkey(pair.Private)\n\tif !bytes.Equal(derivedPubkey, pair.Public) {\n\t\tpanic(fmt.Sprintf(\"expected pubkey %x, got %x\", derivedPubkey, pair.Public))\n\t}\n\n\treturn pair.Private, pair.Public, nil\n}", "func (lib *PKCS11Lib) GenerateRSAKeyPair(bits int, purpose KeyPurpose) (*PKCS11PrivateKeyRSA, error) {\n\treturn lib.GenerateRSAKeyPairOnSlot(lib.Slot.id, nil, nil, bits, purpose)\n}", "func NewKeyPair(rootKey RootKeyable, chainKey ChainKeyable) *KeyPair {\n\tkeyPair := KeyPair{\n\t\tRootKey: rootKey,\n\t\tChainKey: chainKey,\n\t}\n\n\treturn &keyPair\n}", "func generateKeyPairs(keysize int) ([]byte, []byte, []byte, error) {\n var (\n privateKey *rsa.PrivateKey = nil\n privDer, pubDer, sshBytes []byte = nil, nil, nil\n privBlock, pubBlock *pem.Block = nil, nil\n privPem, pubPem []byte = nil, nil\n sshPub ssh.PublicKey\n err error = nil\n )\n\n // check key size\n if keysize != rsaStrongKeySize && keysize != rsaWeakKeySize {\n return nil, nil, nil, fmt.Errorf(\"[ERR] RSA key size should be either 1024 or 2048. Current %d\", keysize)\n }\n\n // generate private key\n privateKey, err = rsa.GenerateKey(rand.Reader, keysize)\n if err != nil {\n return nil, nil, nil, err\n }\n // check the key generated\n err = privateKey.Validate()\n if err != nil {\n return nil, nil, nil, err\n }\n // build private key\n privDer = x509.MarshalPKCS1PrivateKey(privateKey)\n privBlock = &pem.Block{\n Type: \"RSA PRIVATE KEY\",\n Headers: nil,\n Bytes: privDer,\n }\n privPem = pem.EncodeToMemory(privBlock)\n\n // generate and public key\n pubDer, err = x509.MarshalPKIXPublicKey(privateKey.Public())\n if err != nil {\n return nil, nil, nil, err\n }\n pubBlock = &pem.Block{\n Type: \"PUBLIC KEY\",\n Headers: nil,\n Bytes: pubDer,\n }\n pubPem = pem.EncodeToMemory(pubBlock)\n\n // generate ssh key\n sshPub, err = ssh.NewPublicKey(privateKey.Public())\n if err != nil {\n return nil, nil, nil, err\n }\n sshBytes = ssh.MarshalAuthorizedKey(sshPub)\n return privPem, pubPem, sshBytes, err\n}", "func (params *KeyParameters) GenerateKeys() (pk *PublicKey, sk *SecretKey) {\n\tvar err error\n\tsk = new(SecretKey)\n\tpk = new(PublicKey)\n\tsk.KeyParameters = *params\n\tpk.KeyParameters = *params\n\n\t// Choose a random secret key X.\n\tsk.P = params.P\n\tsk.G = params.G\n\tsk.Q = params.Q\n\t// Choose a random exponent in [0,Q-1).\n\tif sk.X, err = pk.KeyParameters.Sample(); err != nil {\n\t\treturn nil, nil\n\t}\n\tsk.qMinusX = new(big.Int)\n\tsk.qMinusX.Sub(params.Q, sk.X)\n\n\t// Compute Y = G^X mod P.\n\tpk.P = params.P\n\tpk.G = params.G\n\tpk.Q = params.Q\n\tpk.Y = new(big.Int)\n\tpk.Y.Exp(params.G, sk.X, params.P)\n\treturn\n}", "func generateKeyPair(algo string, ecCurve string) (privateKey interface{}, publicKey interface{}, err error) {\n\n // Make them case-insensitive\n switch strings.ToUpper(algo) {\n // If RSA, generate a pair of RSA keys\n case \"RSA\":\n // rsa.GenerateKey(): https://golang.org/pkg/crypto/rsa/#GenerateKey\n // Return value is of type *rsa.PrivateKey\n privateKey, err = rsa.GenerateKey(rand.Reader, 2048) // by default create a 2048 bit key\n\n // If ECDSA, use a provided curve\n case \"ECDSA\":\n // First check if ecCurve is provided\n if ecCurve == \"\" {\n return nil, nil, errors.New(\"ECDSA needs a curve\")\n }\n // Then generate the key based on the curve\n // Curves: https://golang.org/pkg/crypto/elliptic/#Curve\n // ecdsa.GenerateKey(): https://golang.org/pkg/crypto/ecdsa/#GenerateKey\n // Return value is of type *ecdsa.PrivateKey\n switch strings.ToUpper(ecCurve) {\n case \"P224\":\n privateKey, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)\n case \"P256\":\n privateKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n case \"P384\":\n \tprivateKey, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)\n case \"P521\":\n \tprivateKey, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)\n\n // If the curve is invalid\n default:\n return nil, nil, errors.New(\"Unrecognized curve, valid values are P224, P256, P384 and P521\")\n }\n\n // If neither RSA nor ECDSA return an error\n default:\n return nil, nil, errors.New(\"Unrecognized algorithm, valid options are RSA and ECDSA\")\n }\n\n // If we get here, then input parameters have been valid\n // Check if key generation has been successful by checking err\n if err != nil {\n return nil, nil, err\n }\n\n // Exporting the public key (needed later)\n switch tempPrivKey:= privateKey.(type) {\n case *rsa.PrivateKey:\n publicKey = &tempPrivKey.PublicKey\n case *ecdsa.PrivateKey:\n publicKey = &tempPrivKey.PublicKey\n }\n\n return privateKey, publicKey, err // or just return\n}", "func GenKeyP2PRand() (p2p_crypto.PrivKey, p2p_crypto.PubKey, error) {\n\treturn p2p_crypto.GenerateKeyPair(p2p_crypto.RSA, 2048)\n}", "func CreateKeyPair(conn *ec2.EC2) (KeyPair, error) {\n\tname := generateKeyPairName()\n\tvar kp KeyPair\n\tkp.KeyName = name\n\n\tparams := &ec2.CreateKeyPairInput{\n\t\tKeyName: aws.String(name),\n\t}\n\n\tresp, err := conn.CreateKeyPair(params)\n\tif err != nil {\n\t\treturn kp, err\n\t}\n\n\tkp.Fingerprint = *resp.KeyFingerprint\n\tkp.PrivateKeyPEM = *resp.KeyMaterial\n\tkp.Created = true\n\n\treturn kp, nil\n}", "func NewKeyPair(suite suites.Suite, random cipher.Stream) (kyber.Scalar, kyber.Point) {\n\tx := suite.G2().Scalar().Pick(random)\n\tX := suite.G2().Point().Mul(x, nil)\n\treturn x, X\n}", "func GenerateKey() (PrivateKey, error) {\n\treturn newSecp256k1PrvKey()\n}", "func ExampleSSHPublicKeysClient_GenerateKeyPair() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armcompute.NewSSHPublicKeysClient(\"{subscription-id}\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.GenerateKeyPair(ctx, \"myResourceGroup\", \"mySshPublicKeyName\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func GenerateDeterministicKeyPair(seed []byte) ([]byte, []byte) {\n\t_, pubkey, seckey := DeterministicKeyPairIterator(seed)\n\treturn pubkey, seckey\n}", "func GenerateDeterministicKeyPair(seed []byte) ([]byte, []byte) {\n\t_, pubkey, seckey := DeterministicKeyPairIterator(seed)\n\treturn pubkey, seckey\n}", "func GenLamportKeyPair() *Keypair {\n\tkp := Keypair{\n\t\tpublic: [256]*key{},\n\t\tprivate: [256]*key{},\n\t}\n\n\tpub, priv := genKeyPair()\n\tcopy(kp.public[:], pub)\n\tcopy(kp.private[:], priv)\n\treturn &kp\n}", "func genPubkey() ([]byte, []byte) {\n\t_, pub := btcec.PrivKeyFromBytes(btcec.S256(), randomBytes(32))\n\tpubkey := pub.SerializeCompressed()\n\tpkHash := btcutil.Hash160(pubkey)\n\treturn pubkey, pkHash\n}", "func newRsaKeyPair(config CreateKeyPairConfig) (KeyPair, error) {\n\tif config.Bits == 0 {\n\t\tconfig.Bits = defaultRsaBits\n\t}\n\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, config.Bits)\n\tif err != nil {\n\t\treturn KeyPair{}, err\n\t}\n\n\tsshPublicKey, err := gossh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn KeyPair{}, err\n\t}\n\n\tprivatePemBlock, err := rawPemBlock(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tHeaders: nil,\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t})\n\tif err != nil {\n\t\treturn KeyPair{}, err\n\t}\n\n\treturn KeyPair{\n\t\tPrivateKeyPemBlock: privatePemBlock,\n\t\tPublicKeyAuthorizedKeysLine: authorizedKeysLine(sshPublicKey, config.Comment),\n\t\tComment: config.Comment,\n\t}, nil\n}", "func GenerateWeakKeyPair() ([]byte, []byte, []byte, error) {\n prv, pub, ssh, err := generateKeyPairs(rsaWeakKeySize)\n return pub, prv, ssh, err\n}", "func NewKeyPair(pub crypto.PublicKey, privArmor string) KeyPair {\n\treturn KeyPair{\n\t\tPublicKey: pub,\n\t\tPrivKeyArmor: privArmor,\n\t}\n}", "func (s Seed) deriveKeyPair(index uint64) (keypair [64]byte) {\n\tbuf := make([]byte, len(s.siadSeed)+8)\n\tn := copy(buf, s.siadSeed[:])\n\tbinary.LittleEndian.PutUint64(buf[n:], index)\n\tseed := blake2b.Sum256(buf)\n\tcopy(keypair[:], ed25519.NewKeyFromSeed(seed[:]))\n\treturn\n}", "func (lib *PKCS11Lib) GenerateECDSAKeyPairWithLabel(label string, c elliptic.Curve) (*PKCS11PrivateKeyECDSA, error) {\n\treturn lib.GenerateECDSAKeyPairOnSlot(lib.Slot.id, nil, []byte(label), c)\n}", "func generateKey(curve elliptic.Curve) (private []byte, public []byte, err error) {\n\tvar x, y *big.Int\n\tprivate, x, y, err = elliptic.GenerateKey(curve, rand.Reader)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpublic = elliptic.Marshal(curve, x, y)\n\treturn\n}", "func generateKeys(t *testing.T) (priv ssh.Signer, pub ssh.PublicKey) {\n\trnd := rand.New(rand.NewSource(time.Now().Unix()))\n\trsaKey, err := rsa.GenerateKey(rnd, 1024)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to generate RSA key pair: %v\", err)\n\t}\n\tpriv, err = ssh.NewSignerFromKey(rsaKey)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to generate signer: %v\", err)\n\t}\n\tpub, err = ssh.NewPublicKey(&rsaKey.PublicKey)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to generate public key: %v\", err)\n\t}\n\treturn priv, pub\n}", "func (session *Session) GenerateRSAKeyPair(tokenLabel string, tokenPersistent bool, expDate time.Time, bits int) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {\n\tif session == nil || session.Ctx == nil {\n\t\treturn 0, 0, fmt.Errorf(\"session not initialized\")\n\t}\n\ttoday := time.Now()\n\tpublicKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte(tokenLabel)),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, tokenPersistent),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_START_DATE, today),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_END_DATE, expDate),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, []byte{1, 0, 1}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, bits),\n\t}\n\n\tprivateKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte(tokenLabel)),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, tokenPersistent),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_START_DATE, today),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_END_DATE, expDate),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SIGN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true),\n\t}\n\n\tpubKey, privKey, err := session.Ctx.GenerateKeyPair(\n\t\tsession.Handle,\n\t\t[]*pkcs11.Mechanism{\n\t\t\tpkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_KEY_PAIR_GEN, nil),\n\t\t},\n\t\tpublicKeyTemplate,\n\t\tprivateKeyTemplate,\n\t)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\treturn pubKey, privKey, nil\n}", "func GenerateKey() (publicKey PublicKey, privateKey PrivateKey, err error) {\n\tpub, priv, genErr := ed25519.GenerateKey(nil)\n\tcopy(publicKey[:], pub)\n\tcopy(privateKey[:], priv)\n\terr = genErr\n\n\treturn\n}", "func generateKeys() (pub, priv key, err error) {\n\treturn box.GenerateKey(rand.Reader)\n}", "func (w *Whisper) NewKeyPair() (string, error) {\n\tkey, err := crypto.GenerateKey()\n\tif err != nil || !validatePrivateKey(key) {\n\t\tkey, err = crypto.GenerateKey() // retry once\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif !validatePrivateKey(key) {\n\t\treturn \"\", fmt.Errorf(\"failed to generate valid key\")\n\t}\n\n\tid, err := GenerateRandomID()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to generate ID: %s\", err)\n\t}\n\n\tw.keyMu.Lock()\n\tdefer w.keyMu.Unlock()\n\n\tif w.privateKeys[id] != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to generate unique ID\")\n\t}\n\tw.privateKeys[id] = key\n\treturn id, nil\n}", "func NewKeyPair(config CreateKeyPairConfig) (KeyPair, error) {\n\tif config.Type == Default {\n\t\tconfig.Type = Ecdsa\n\t}\n\n\tswitch config.Type {\n\tcase Ecdsa:\n\t\treturn newEcdsaKeyPair(config)\n\tcase Rsa:\n\t\treturn newRsaKeyPair(config)\n\t}\n\n\treturn KeyPair{}, fmt.Errorf(\"Unable to generate new key pair, type %s is not supported\",\n\t\tconfig.Type.String())\n}", "func GenerateStrongKeyPairFiles(pubKeyPath, prvKeyPath, sshKeyPath string) error {\n return generateKeyFies(prvKeyPath, pubKeyPath, sshKeyPath, rsaStrongKeySize)\n}", "func GenerateKey() ([]byte, error) {\n\tlogger.Green(\"ssh\", \"Generating new key\")\n\tvar pemBuffer bytes.Buffer\n\n\t// Generate RSA keypair\n\trsaKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Encode RSA private key to pem\n\tpem.Encode(&pemBuffer, &pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(rsaKey),\n\t})\n\n\terr = ioutil.WriteFile(path.Join(configuration.StateDir, privateKeyFilename), pemBuffer.Bytes(), 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn pemBuffer.Bytes(), nil\n}", "func GenerateKey(rand io.Reader) (*PrivateKey, error) {\n\n\tc := SM2P256()\n\n\tk, err := randFieldElement(c, rand)\n\tfmt.Println(k)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpriv := new(PrivateKey)\n\tpriv.PublicKey.Curve= c\n\tpriv.D = k\n\n\tpriv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())\n\treturn priv, nil\n}", "func (p PrivateKey) calculateKeyPair() ([]byte, *edwards25519.Scalar, error) {\n\tvar pA edwards25519.Point\n\tvar sa edwards25519.Scalar\n\n\tk, err := (&edwards25519.Scalar{}).SetBytesWithClamping(p)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpub := pA.ScalarBaseMult(k).Bytes()\n\tsignBit := (pub[31] & 0x80) >> 7\n\n\tif signBit == 1 {\n\t\tsa.Negate(k)\n\t\t// Set sig bit to 0\n\t\tpub[31] &= 0x7F\n\t} else {\n\t\tsa.Set(k)\n\t}\n\n\treturn pub, &sa, nil\n}", "func NewPair(p *big.Int, g int64) (*big.Int, *big.Int) {\n\tprivateKey := PrivateKey(p)\n\tpublicKey := PublicKey(privateKey, p, g)\n\treturn privateKey, publicKey\n}", "func GeneratePrivateKey(keystorePath string) (bccsp.Key,\n\tcrypto.Signer, error) {\n\n\tvar err error\n\tvar priv bccsp.Key\n\tvar s crypto.Signer\n\n\topts := &factory.FactoryOpts{\n\t\tProviderName: \"GMSW\",\n\t\tSwOpts: &factory.SwOpts{\n\t\t\tHashFamily: \"SM3\",\n\t\t\tSecLevel: 256,\n\n\t\t\tFileKeystore: &factory.FileKeystoreOpts{\n\t\t\t\tKeyStorePath: keystorePath,\n\t\t\t},\n\t\t},\n\t}\n\tcsp, err := factory.GetBCCSPFromOpts(opts)\n\n //这个CSP也可能存在问题\n\n\tif err == nil {\n\t\t// generate a key\n\t\tpriv, err = csp.KeyGen(&bccsp.SM2KeyGenOpts{Temporary: false})\n\n\n\t\t//privsk:= gmsw.GetSM2PrivKey(priv)\n\t\t//fmt.Println(\"privsk11\",privsk)\n\n\t\tif err == nil {\n\t\t\t// create a crypto.Signer\n\t\t\ts, err = gmsigner.New(csp, priv)\n\t\t}\n\t}\n\n\t//return sm2sk, s, err\n\treturn priv, s, err\n}", "func GenerateKey() (*ecdsa.PrivateKey, error) {\n\tparams := elliptic.Sm2p256v1().Params()\n\tb := make([]byte, params.BitSize/8+8) // TODO: use params.N.BitLen()\n\t_, err := io.ReadFull(rand.Reader, b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tk := new(big.Int).SetBytes(b)\n\tn := new(big.Int).Sub(params.N, one)\n\tk.Mod(k, n)\n\tk.Add(k, one)\n\treturn ToSM2(k.Bytes())\n}", "func Keygen(pub *BswabePub,msk *BswabeMsk, attrs []string) *BswabePrv {\n\t//attrs := strings.Split(attr, \" \")\n\n\tprv := new(BswabePrv)\n\tvar g_r, r, beta_inv *pbc.Element\n\tvar pairing *pbc.Pairing\n\n\t/* initialize */\n\tpairing = pub.p\n\tprv.d = pairing.NewG2()\n\tg_r = pairing.NewG2()\n\tr = pairing.NewZr()\n\tbeta_inv = pairing.NewZr()\n\n\t/* compute */\n\tr.Rand()\n\tprv.r = r.NewFieldElement().Set(r)\n\tg_r = pub.gp.NewFieldElement().Set(pub.gp)\n\t//g_r = pub.g.NewFieldElement().Set(pub.g)\n\tg_r.PowZn(g_r, r)\n\n\tprv.d = msk.g_alpha.NewFieldElement().Set(msk.g_alpha)\n\tprv.d.Mul(prv.d, g_r)\n\tbeta_inv = msk.beta.NewFieldElement().Set(msk.beta)\n\tbeta_inv.Invert(beta_inv)\n\tprv.d.PowZn(prv.d, beta_inv)\n\n\tlen := len(attrs)\n\tfor i := 0; i < len; i++ {\n\t\tcomp := new(BswabePrvComp)\n\t\tvar h_rp, rp *pbc.Element\n\n\t\tcomp.attr = attrs[i]\n\t\tcomp.d = pairing.NewG2()\n\t\tcomp.dp = pairing.NewG1()\n\t\th_rp = pairing.NewG2()\n\t\trp = pairing.NewZr()\n\n\t\telementFromString(h_rp, comp.attr)\n\t\trp.Rand()\n\n\t\th_rp.PowZn(h_rp, rp)\n\n\t\tcomp.d = g_r.NewFieldElement().Set(g_r)\n\t\tcomp.d.Mul(comp.d, h_rp)\n\t\tcomp.dp = pub.g.NewFieldElement().Set(pub.g)\n\t\tcomp.dp.PowZn(comp.dp, rp)\n\n\t\tprv.comps = append(prv.comps, comp)\n\t}\n\treturn prv\n}", "func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error)", "func New() (*KeyPair, error) {\n\tp, v, err := p2pCrypto.GenerateKeyPairWithReader(p2pCrypto.Ed25519, 256, rand.Reader)\n\tif err == nil {\n\t\treturn &KeyPair{privKey: p, pubKey: v}, nil\n\t}\n\treturn nil, err\n}", "func Generate(bits int) (encoded []byte, err error) {\n\tvar (\n\t\tpkey *rsa.PrivateKey\n\t)\n\n\tif pkey, err = private(bits); err != nil {\n\t\treturn encoded, err\n\t}\n\n\t// Get ASN.1 DER format\n\tmarshalled := x509.MarshalPKCS1PrivateKey(pkey)\n\n\treturn pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: marshalled,\n\t}), nil\n}", "func GenerateKey(curve elliptic.Curve, rand io.Reader) ([]byte, *big.Int, *big.Int, error)", "func Generate() (*SSHKey, error) {\n\tdata := &SSHKey{}\n\n\trsaKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar pemBuf bytes.Buffer\n\tpem.Encode(&pemBuf, &pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(rsaKey),\n\t})\n\trsaPubKey, err := ssh.NewPublicKey(&rsaKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata.PublicKey = bytes.TrimSpace(ssh.MarshalAuthorizedKey(rsaPubKey))\n\tdata.PrivateKey = rsaKey\n\n\treturn data, nil\n}", "func GenerateKeys() (*string, *string, error) {\n\tsk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tpk := &(sk.PublicKey)\n\n\t// Encode to strings\n\t// TODO is there a better to do this than simply replacing chars we don't want to use?\n\treplacer := strings.NewReplacer(\" \", \"\", \"-\", \"\", \"BEGIN\", \"\", \"END\", \"\", \"\\n\", \"\")\n\n\tskx509Encoded, _ := x509.MarshalECPrivateKey(sk)\n\tskEncoded := string(pem.EncodeToMemory(&pem.Block{Bytes: skx509Encoded}))\n\tskEncoded = replacer.Replace(skEncoded)\n\n\tpkx509Encoded, _ := x509.MarshalPKIXPublicKey(pk)\n\tpkEncoded := string(pem.EncodeToMemory(&pem.Block{Bytes: pkx509Encoded}))\n\tpkEncoded = replacer.Replace(pkEncoded)\n\n\treturn &skEncoded, &pkEncoded, nil\n}", "func GenerateKey(password, extradata []byte) (keyfile, mpubkey, mprivkey []byte, err error) {\n\tpubkey, privkey, err := box.GenerateKey(rand.Reader) // Keypair\n\tif err != nil {\n\t\treturn\n\t}\n\treturn SaveKey(pubkey[:], privkey[:], password, extradata)\n}", "func GenerateKey(net bitcoin.Network) (*wallet.Key, error) {\r\n\tkey, err := bitcoin.GenerateKey(net)\r\n\tif err != nil {\r\n\t\treturn nil, errors.Wrap(err, \"Failed to generate key\")\r\n\t}\r\n\r\n\tresult := wallet.Key{\r\n\t\tKey: key,\r\n\t}\r\n\r\n\tresult.Address, err = key.RawAddress()\r\n\tif err != nil {\r\n\t\treturn nil, errors.Wrap(err, \"Failed to create key address\")\r\n\t}\r\n\r\n\treturn &result, nil\r\n}", "func genKey() (peerid string, privatekey string, err error) {\n\t// generate private key\n\tpriv, _, err := crypto.GenerateKeyPairWithReader(crypto.Ed25519, -1, crand.Reader)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\t// convert to bytes\n\tkBytes, err := crypto.MarshalPrivateKey(priv)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\t// Obtain Peer ID from public key\n\tpid, err := libp2p_peer.IDFromPublicKey(priv.GetPublic())\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\treturn pid.String(), base64.StdEncoding.EncodeToString(kBytes), nil\n}", "func (param *Parameters) KeyGen() (pk *PublicKey, sk *SecretKey) {\n\n\tpk, sk = new(PublicKey), new(SecretKey)\n\tpk.SeedA = uniform(param.lseedA)\n\trLen, seedSE := 2*param.no*param.n*param.lenX, uniform((param.lseedSE)+1)\n\n\tseedSE[0] = 0x5F\n\tr := param.shake(seedSE, rLen)\n\n\trLen /= 2\n\tA := param.Gen(pk.SeedA)\n\tsk.S = param.SampleMatrix(r[:rLen], param.no, param.n)\n\tE := param.SampleMatrix(r[rLen:], param.no, param.n)\n\tpk.B = param.mulAddMatrices(A, sk.S, E)\n\n\treturn\n}", "func GenerateHDKeyPair(seedLength uint8) (xPrivateKey, xPublicKey string, err error) {\r\n\r\n\t// Generate an HD master key\r\n\tvar masterKey *hdkeychain.ExtendedKey\r\n\tif masterKey, err = GenerateHDKey(seedLength); err != nil {\r\n\t\treturn\r\n\t}\r\n\r\n\t// Set the xPriv (string)\r\n\txPrivateKey = masterKey.String()\r\n\r\n\t// Set the xPub (string)\r\n\txPublicKey, err = GetExtendedPublicKey(masterKey)\r\n\r\n\treturn\r\n}", "func GeneratePrivateKey(algo ...Algorithm) (PrivateKey, error) {\n\tif len(algo) != 0 {\n\t\tswitch algo[0] {\n\t\tcase KeyAlgoSecp256k1:\n\t\t\treturn GenerateSECP256K1PrivateKey()\n\t\tdefault:\n\t\t\treturn GenerateSM2PrivateKey()\n\t\t}\n\t}\n\treturn GenerateSM2PrivateKey()\n}", "func (client *Client) CreateKeyPair(name string) (*model.KeyPair, error) {\n\treturn client.feclt.CreateKeyPair(name)\n}", "func (n *nauth) GetNewKeyPairFromPool() ([]byte, []byte, error) {\n\tselect {\n\tcase key := <-n.generatedKeysC:\n\t\treturn key.privPem, key.pubBytes, nil\n\tdefault:\n\t\treturn n.GenerateKeyPair(\"\")\n\t}\n}", "func GenerateKey() (vrfp.PrivateKey, vrfp.PublicKey) {\n\tkey, err := ecdsa.GenerateKey(curve, rand.Reader)\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\treturn &PrivateKey{PrivateKey: key}, &PublicKey{PublicKey: &key.PublicKey}\n}", "func GenerateCurve25519KeyPair() (*Curve25519KeyPair, error) {\n\treturn generateCurve25519KeyPairFromRandom(rand.Reader)\n}", "func GenerateSSHKey() ([]byte, error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar buf bytes.Buffer\n\n\tprivateKeyPEM := &pem.Block{Type: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}\n\tb := pem.EncodeToMemory(privateKeyPEM)\n\t_, err = buf.Write(b)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"private key write failure\")\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func GenerateKeys(params []*dpfpb.DpfParameters, alpha uint128.Uint128, betas []uint64) (*dpfpb.DpfKey, *dpfpb.DpfKey, error) {\n\tcParamsSize := C.int64_t(len(params))\n\tcParams, cParamPointers, err := createCParams(params)\n\tdefer freeCParams(cParams, cParamPointers)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tcAlpha := C.struct_CUInt128{lo: C.uint64_t(alpha.Lo), hi: C.uint64_t(alpha.Hi)}\n\n\tbetasSize := len(betas)\n\tcBetasSize := C.int64_t(betasSize)\n\tvar betasPointer *uint64\n\tif betasSize > 0 {\n\t\tbetasPointer = &betas[0]\n\t}\n\n\tcKey1 := C.struct_CBytes{}\n\tcKey2 := C.struct_CBytes{}\n\terrStr := C.struct_CBytes{}\n\tstatus := C.CGenerateKeys(cParams, cParamsSize, &cAlpha, (*C.uint64_t)(unsafe.Pointer(betasPointer)), cBetasSize, &cKey1, &cKey2, &errStr)\n\tdefer freeCBytes(cKey1)\n\tdefer freeCBytes(cKey2)\n\tdefer freeCBytes(errStr)\n\tif status != 0 {\n\t\treturn nil, nil, errors.New(C.GoStringN(errStr.c, errStr.l))\n\t}\n\n\tkey1 := &dpfpb.DpfKey{}\n\tif err := proto.Unmarshal(C.GoBytes(unsafe.Pointer(cKey1.c), cKey1.l), key1); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tkey2 := &dpfpb.DpfKey{}\n\tif err := proto.Unmarshal(C.GoBytes(unsafe.Pointer(cKey2.c), cKey2.l), key2); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn key1, key2, nil\n}", "func GeneratePubKey(privateKeyBytes []byte) ([]byte, error) {\n\tvar privateKeyBytes32 [size]byte\n\tfor i := 0; i < size; i++ {\n\t\tprivateKeyBytes32[i] = privateKeyBytes[i]\n\t}\n\tsecp256k1.Start()\n\tpublicKeyBytes, success := secp256k1.Pubkey_create(privateKeyBytes32, false)\n\tsecp256k1.Stop()\n\n\tif !success {\n\t\treturn []byte{}, fmt.Errorf(\"Failed to generate public key\")\n\t}\n\treturn publicKeyBytes, nil\n}", "func generateDeterministicKeyPair(seed []byte) ([]byte, []byte) {\n\tif seed == nil {\n\t\tlog.Panic()\n\t}\n\tif len(seed) != 32 {\n\t\tlog.Panic()\n\t}\n\n\tconst seckey_len = 32\n\tvar seckey []byte = make([]byte, seckey_len)\n\nnew_seckey:\n\tseed = SumSHA256(seed[0:32])\n\tcopy(seckey[0:32], seed[0:32])\n\n\tif bytes.Equal(seckey, seed) == false {\n\t\tlog.Panic()\n\t}\n\tif secp.SeckeyIsValid(seckey) != 1 {\n\t\tlog.Printf(\"generateDeterministicKeyPair, secp.SeckeyIsValid fail\")\n\t\tgoto new_seckey //regen\n\t}\n\n\tvar pubkey []byte = secp.GeneratePublicKey(seckey)\n\n\tif pubkey == nil {\n\t\tlog.Panic(\"ERROR: impossible, secp.BaseMultiply always returns true\")\n\t\tgoto new_seckey\n\t}\n\tif len(pubkey) != 33 {\n\t\tlog.Panic(\"ERROR: impossible, pubkey length wrong\")\n\t}\n\n\tif ret := secp.PubkeyIsValid(pubkey); ret != 1 {\n\t\tlog.Panic(\"ERROR: pubkey invalid, ret=%i\", ret)\n\t}\n\n\tif ret := VerifyPubkey(pubkey); ret != 1 {\n\t\tlog.Printf(\"seckey= %s\", hex.EncodeToString(seckey))\n\t\tlog.Printf(\"pubkey= %s\", hex.EncodeToString(pubkey))\n\n\t\tlog.Panic(\"ERROR: pubkey is invalid, for deterministic. ret=%i\", ret)\n\t\tgoto new_seckey\n\t}\n\n\treturn pubkey, seckey\n}", "func KeyPair() (publicKey, privateKey []byte, err error) {\n\treturn defaultPH.KeyPair()\n}", "func GenerateEncodedKeypair(passphrase string, bits int) (*EncodedKeypair, error) {\n\tkeypair, err := GenerateRSA(bits)\n\tif err != nil {\n\t\treturn nil, errs.Wrap(err, \"Could not generate RSA\")\n\t}\n\treturn EncodeKeypair(keypair, passphrase)\n}", "func GeneratePK(bits int) (key *PrivateKey, err error) {\n\tvar rsaKey *rsa.PrivateKey\n\trsaKey, err = rsa.GenerateKey(rand.Reader, bits)\n\tif err == nil {\n\t\tkey = &PrivateKey{rsaKey: rsaKey}\n\t}\n\treturn\n}", "func KeyGenerator() (*Key, error) {\n\tlog.Info(\"Generate new ssh key\")\n\n\tkey := new(Key)\n\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\tlog.Errorf(\"PrivateKey generator failed reason: %s\", err.Error())\n\t\treturn key, err\n\t}\n\n\tprivateKeyPEM := &pem.Block{Type: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}\n\tkeyBuff := new(bytes.Buffer)\n\tif err := pem.Encode(keyBuff, privateKeyPEM); err != nil {\n\t\tlog.Errorf(\"PrivateKey generator failed reason: %s\", err.Error())\n\t\treturn key, err\n\t}\n\tkey.PrivateKeyData = keyBuff.String()\n\tlog.Debug(\"Private key generated.\")\n\n\tpub, err := ssh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\tlog.Errorf(\"PublicKey generator failed reason: %s\", err.Error())\n\t\treturn key, err\n\t}\n\tlog.Debug(\"Public key generated.\")\n\n\tkey.PublicKeyData = fmt.Sprintf(\"%s %s \\n\", strings.TrimSuffix(string(ssh.MarshalAuthorizedKey(pub)), \"\\n\"), \"[email protected]\")\n\n\tkey.PublicKeyFingerprint = ssh.FingerprintSHA256(pub)\n\tlog.Info(\"SSH key generated.\")\n\n\treturn key, nil\n}", "func (client *Client) CreateKeyPair(name string) (*model.KeyPair, error) {\n\treturn client.osclt.CreateKeyPair(name)\n}", "func GeneratePrivKeyAddressPairs(n int) (keys []crypto.PrivKey, addrs []sdk.AccAddress) {\n\tr := rand.New(rand.NewSource(12345)) // make the generation deterministic\n\tkeys = make([]crypto.PrivKey, n)\n\taddrs = make([]sdk.AccAddress, n)\n\tfor i := 0; i < n; i++ {\n\t\tsecret := make([]byte, 32)\n\t\t_, err := r.Read(secret)\n\t\tif err != nil {\n\t\t\tpanic(\"Could not read randomness\")\n\t\t}\n\t\tkeys[i] = secp256k1.GenPrivKeySecp256k1(secret)\n\t\taddrs[i] = sdk.AccAddress(keys[i].PubKey().Address())\n\t}\n\treturn\n}", "func GeneratePrivKeyAddressPairs(n int) (keys []crypto.PrivKey, addrs []sdk.AccAddress) {\n\tr := rand.New(rand.NewSource(12345)) // make the generation deterministic\n\tkeys = make([]crypto.PrivKey, n)\n\taddrs = make([]sdk.AccAddress, n)\n\tfor i := 0; i < n; i++ {\n\t\tsecret := make([]byte, 32)\n\t\tif _, err := r.Read(secret); err != nil {\n\t\t\tpanic(\"Could not read randomness\")\n\t\t}\n\t\tkeys[i] = secp256k1.GenPrivKeySecp256k1(secret)\n\t\taddrs[i] = sdk.AccAddress(keys[i].PubKey().Address())\n\t}\n\treturn\n}", "func genKey() *Key {\n\tprivKey := crypto.GenPrivKeyEd25519()\n\treturn &Key{\n\t\tAddress: privKey.PubKey().Address(),\n\t\tPubKey: privKey.PubKey(),\n\t\tPrivKey: privKey,\n\t}\n}", "func createKeypair() *keypair.Full {\n\tpair, err := keypair.Random()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"Seed:\", pair.Seed())\n\tlog.Println(\"Address:\", pair.Address())\n\n\treturn pair\n}" ]
[ "0.7982938", "0.783545", "0.77949226", "0.77779335", "0.7758787", "0.76775175", "0.76755846", "0.760864", "0.7564112", "0.7452798", "0.7405781", "0.73792243", "0.73792243", "0.73213327", "0.72448134", "0.7242817", "0.71996576", "0.7087019", "0.7071567", "0.7037876", "0.6998725", "0.6997272", "0.69693685", "0.6914743", "0.6907646", "0.6877842", "0.68733734", "0.6869478", "0.6828843", "0.6790937", "0.678122", "0.6777774", "0.676183", "0.676183", "0.6641808", "0.6620773", "0.6603025", "0.65515184", "0.6505021", "0.64978975", "0.64716333", "0.64554256", "0.6414679", "0.63790715", "0.63727105", "0.63719434", "0.6346613", "0.63417166", "0.63417166", "0.63312", "0.6328094", "0.63246584", "0.63139933", "0.6301394", "0.63009286", "0.62970495", "0.6287675", "0.62744856", "0.6264683", "0.62632966", "0.62393916", "0.62300247", "0.6215896", "0.62125874", "0.62027586", "0.6190416", "0.6178209", "0.61685205", "0.6167022", "0.61467695", "0.6125431", "0.6119023", "0.6114127", "0.6086334", "0.606664", "0.6059402", "0.6059226", "0.60587883", "0.6050727", "0.6038048", "0.60376805", "0.60364854", "0.60363597", "0.6024204", "0.60239667", "0.6015091", "0.60095304", "0.5997264", "0.59907806", "0.5988816", "0.59787357", "0.5975086", "0.59696114", "0.59675276", "0.5956084", "0.5940783", "0.5929775", "0.5929737", "0.59290457", "0.5912092" ]
0.76324284
7
Create creates a new registry.
func (service ServiceTx) Create(registry *portainer.Registry) error { return service.Tx.CreateObject( BucketName, func(id uint64) (int, interface{}) { registry.ID = portainer.RegistryID(id) return int(registry.ID), registry }, ) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Create(name string) *Registry {\n\treturn &Registry{name: name, registrants: map[string]Registrant{}}\n}", "func (cmd *createRegistryCommand) CreateRegistry(cfg *config.Config, arguments []string) error {\n\tdatabase, err := cfg.OpenDatabase()\n\tif database != nil {\n\t\tdefer cfg.CloseDatabase()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// detect type\n\tfactory, found := registry.Types[cmd.Type]\n\tif !found {\n\t\treturn ErrorRegistryTypeNotSupported\n\t}\n\n\treg, err := factory.Create(registry.Data{\n\t\tName: cmd.Name,\n\t}, arguments)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// create path for registry\n\tpath, err := filepath.Abs(filepath.Join(cfg.ConfigDir, \"registries\", reg.Data().Name))\n\tif err != nil {\n\t\treturn err\n\t}\n\treg.Data().Path = path\n\n\tregistries := registry.New(config.Database{DB: database})\n\n\texists, err := registries.Exists(reg.Data().Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif exists && cmd.Force {\n\t\tregistries.Remove(reg.Data().Name)\n\t}\n\n\terr = reg.Initialize()\n\tif err != nil {\n\t\t// remove the content there\n\t\tos.RemoveAll(path)\n\t\tlogrus.Warningln(\"Could not initialize registry\")\n\t\treturn err\n\t}\n\n\terr = registries.Add(reg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn GetRegistries(cfg.WithDatabase(database))\n}", "func (g *GitFactory) Create(d Data, args []string) (Registry, error) {\n\tif len(args) != 1 {\n\t\treturn nil, ErrorNoValidRepositoryGiven\n\t}\n\td.Type = RegTypeGit\n\tif len(d.Name) == 0 {\n\t\td.Name = strings.Replace(filepath.Base(args[0]), filepath.Ext(args[0]), \"\", 1)\n\t}\n\treg := &GitRegistry{\n\t\tCore: d,\n\t\tRepository: args[0],\n\t}\n\n\treturn reg, nil\n}", "func (c *client) CreateRegistry(registryPort string, args []string) (string, error) {\n\tregistryName := fmt.Sprintf(defaultRegistryNamePattern, c.clusterName)\n\n\tcmd := append([]string{\"registry\", \"create\", registryName, \"--port\", registryPort}, args...)\n\tout, err := c.runCmd(cmd...)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tregistryNameMatch := registryNameRegexp.FindStringSubmatch(out)\n\tif len(registryNameMatch) > 0 {\n\t\treturn fmt.Sprintf(\"%s:%s\", registryNameMatch[1], registryPort), nil\n\t}\n\n\t//fallback to k3d convention if the regexp fails\n\treturn fmt.Sprintf(\"%s:%s\", registryName, registryPort), nil\n}", "func New(reg *api.Registry, store ApiObjectProvider) *Registry {\n\treturn &Registry{\n\t\tapiProvider: store,\n\t\tapiRegistry: reg,\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(ctx *pulumi.Context,\n\tname string, args *RegistryArgs, opts ...pulumi.ResourceOption) (*Registry, error) {\n\tif args == nil {\n\t\targs = &RegistryArgs{}\n\t}\n\tvar resource Registry\n\terr := ctx.RegisterResource(\"gcp:kms/registry:Registry\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func New() *Registry {\n\treturn &Registry{\n\t\tdb: make(map[string]*task.Task),\n\t}\n}", "func New() *Registry {\n\tr := &Registry{\n\t\tstore: make(map[string]template.Template),\n\t}\n\n\treturn r\n}", "func (app *fetchRegistryBuilder) Create() FetchRegistryBuilder {\n\treturn createFetchRegistryBuilder()\n}", "func (c *ImageRegistryCollection) Create(r *ImageRegistryResource) error {\n\treturn c.core.db.create(c, r.Name, r)\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 NewRegistry() *Registry {\n\treturn &Registry{\n\t\tServicesMap: make(map[string]ServiceList),\n\t}\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 NewRegistry(\n\trepoRegistry domain.RepositoryRegistry,\n) domain.Registry {\n\n\tr := registry{\n\t\trepoRegistry: repoRegistry,\n\t\taccountService: NewAccountService(\n\t\t\trepoRegistry,\n\t\t\tvalidator.NewAccountCreation(),\n\t\t\tvalidator.NewAccountBalanceUpdate(),\n\t\t),\n\t\ttransferService: NewTransferService(\n\t\t\trepoRegistry,\n\t\t\tvalidator.NewTransferCreation(),\n\t\t),\n\t\taccessService: NewAccessService(\n\t\t\trepoRegistry,\n\t\t),\n\t}\n\tr.checkDependencies()\n\n\treturn &r\n}", "func ExampleRegistriesClient_BeginCreate_registryCreate() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armcontainerregistry.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := clientFactory.NewRegistriesClient().BeginCreate(ctx, \"myResourceGroup\", \"myRegistry\", armcontainerregistry.Registry{\n\t\tLocation: to.Ptr(\"westus\"),\n\t\tTags: map[string]*string{\n\t\t\t\"key\": to.Ptr(\"value\"),\n\t\t},\n\t\tProperties: &armcontainerregistry.RegistryProperties{\n\t\t\tAdminUserEnabled: to.Ptr(true),\n\t\t},\n\t\tSKU: &armcontainerregistry.SKU{\n\t\t\tName: to.Ptr(armcontainerregistry.SKUNameStandard),\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\tres, err := poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Registry = armcontainerregistry.Registry{\n\t// \tName: to.Ptr(\"myRegistry\"),\n\t// \tType: to.Ptr(\"Microsoft.ContainerRegistry/registries\"),\n\t// \tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.ContainerRegistry/registries/myRegistry\"),\n\t// \tLocation: to.Ptr(\"westus\"),\n\t// \tTags: map[string]*string{\n\t// \t\t\"key\": to.Ptr(\"value\"),\n\t// \t},\n\t// \tProperties: &armcontainerregistry.RegistryProperties{\n\t// \t\tAdminUserEnabled: to.Ptr(true),\n\t// \t\tAnonymousPullEnabled: to.Ptr(false),\n\t// \t\tCreationDate: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2021-06-15T21:38:26.1537861Z\"); return t}()),\n\t// \t\tDataEndpointEnabled: to.Ptr(false),\n\t// \t\tDataEndpointHostNames: []*string{\n\t// \t\t},\n\t// \t\tEncryption: &armcontainerregistry.EncryptionProperty{\n\t// \t\t\tStatus: to.Ptr(armcontainerregistry.EncryptionStatusDisabled),\n\t// \t\t},\n\t// \t\tLoginServer: to.Ptr(\"myRegistry.azurecr-test.io\"),\n\t// \t\tNetworkRuleBypassOptions: to.Ptr(armcontainerregistry.NetworkRuleBypassOptionsAzureServices),\n\t// \t\tNetworkRuleSet: &armcontainerregistry.NetworkRuleSet{\n\t// \t\t\tDefaultAction: to.Ptr(armcontainerregistry.DefaultActionAllow),\n\t// \t\t\tIPRules: []*armcontainerregistry.IPRule{\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\tPolicies: &armcontainerregistry.Policies{\n\t// \t\t\tExportPolicy: &armcontainerregistry.ExportPolicy{\n\t// \t\t\t\tStatus: to.Ptr(armcontainerregistry.ExportPolicyStatusEnabled),\n\t// \t\t\t},\n\t// \t\t\tQuarantinePolicy: &armcontainerregistry.QuarantinePolicy{\n\t// \t\t\t\tStatus: to.Ptr(armcontainerregistry.PolicyStatusDisabled),\n\t// \t\t\t},\n\t// \t\t\tRetentionPolicy: &armcontainerregistry.RetentionPolicy{\n\t// \t\t\t\tDays: to.Ptr[int32](7),\n\t// \t\t\t\tLastUpdatedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2021-06-15T21:40:12.8506835+00:00\"); return t}()),\n\t// \t\t\t\tStatus: to.Ptr(armcontainerregistry.PolicyStatusDisabled),\n\t// \t\t\t},\n\t// \t\t\tTrustPolicy: &armcontainerregistry.TrustPolicy{\n\t// \t\t\t\tType: to.Ptr(armcontainerregistry.TrustPolicyTypeNotary),\n\t// \t\t\t\tStatus: to.Ptr(armcontainerregistry.PolicyStatusDisabled),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\tPrivateEndpointConnections: []*armcontainerregistry.PrivateEndpointConnection{\n\t// \t\t},\n\t// \t\tProvisioningState: to.Ptr(armcontainerregistry.ProvisioningStateSucceeded),\n\t// \t\tPublicNetworkAccess: to.Ptr(armcontainerregistry.PublicNetworkAccessEnabled),\n\t// \t\tZoneRedundancy: to.Ptr(armcontainerregistry.ZoneRedundancyDisabled),\n\t// \t},\n\t// \tSKU: &armcontainerregistry.SKU{\n\t// \t\tName: to.Ptr(armcontainerregistry.SKUNameStandard),\n\t// \t\tTier: to.Ptr(armcontainerregistry.SKUTierStandard),\n\t// \t},\n\t// }\n}", "func Create(ns walletdb.ReadWriteBucket) er.R {\n\treturn createStore(ns)\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 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\ttypeForTag: typeForTag{},\n\t\ttagForType: tagForType{},\n\t\tfactoryForType: factoryForType{},\n\t}\n}", "func Create() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"create\",\n\t\tShort: \"Create a forensicstore\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tstoreName := cmd.Flags().Args()[0]\n\t\t\tstore, err := goforensicstore.NewJSONLite(storeName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn store.Close()\n\t\t},\n\t}\n}", "func NewRegistry() *Registry {\n\treturn new(Registry)\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\ttypes: make(map[string]reflect.Type),\n\t\tmu: sync.Mutex{},\n\t}\n}", "func NewRegistry() *Registry {\n\tt := Registry{}\n\tt.Reset()\n\n\treturn &t\n}", "func NewRegistry() Registry {\n\treturn make(Registry)\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\tnodesView: make(map[identity.ID]*View),\n\t}\n}", "func New(store model.RegistryStore) model.RegistryService {\n\treturn &db{store}\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\tentries: make(map[datatransfer.TypeIdentifier]Processor),\n\t}\n}", "func New(endpoint, username, password string, tls, insecure bool) (hub *registry.Registry, err error) {\n\tvar url = fmt.Sprintf(\"http://%s\", endpoint)\n\tif tls {\n\t\turl = fmt.Sprintf(\"https://%s\", endpoint)\n\t}\n\n\tif insecure || !tls {\n\t\thub, err = registry.NewInsecure(url, username, password)\n\t} else {\n\t\thub, err = registry.New(url, username, password)\n\t}\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"hub failed\")\n\t\treturn\n\t}\n\thub.Logf = func(format string, args ...interface{}) {\n\t\tlogrus.Infof(format, args...)\n\t}\n\treturn\n}", "func NewRegistry(scheme *runtime.Scheme, codec serializer.CodecFactory, serializer *json.Serializer) *Registry {\n\tvar groupVersions []schema.GroupVersion\n\tfor k := range scheme.AllKnownTypes() {\n\t\tgroupVersions = append(groupVersions, k.GroupVersion())\n\t}\n\n\treturn &Registry{\n\t\tscheme: scheme,\n\t\tcodec: codec.CodecForVersions(serializer, serializer, schema.GroupVersions(groupVersions), schema.GroupVersions(groupVersions)),\n\t\tnameToObject: make(map[string]*object),\n\t}\n}", "func NewRegistry(s rest.StandardStorage) Registry {\n\treturn &storage{s}\n}", "func NewRegistry(s Storage) Registry {\n\treturn &storage{s}\n}", "func NewRegistry(s Storage) Registry {\n\treturn &storage{s}\n}", "func NewRegistry() *Registry {\n\tregistry := Registry{}\n\tregistry.lock = &sync.Mutex{}\n\treturn &registry\n}", "func (o *Service) Create() (*restapi.StringResponse, error) {\n\terr := o.resolveIDs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar queryArg = make(map[string]interface{})\n\tqueryArg, err = generateRequestMap(o)\n\tif err != nil {\n\t\tlogger.Errorf(err.Error())\n\t\treturn nil, err\n\t}\n\n\tlogger.Debugf(\"Generated Map for Create(): %+v\", queryArg)\n\tresp, err := o.client.CallStringAPI(o.apiCreate, queryArg)\n\tif err != nil {\n\t\tlogger.Errorf(err.Error())\n\t\treturn nil, err\n\t}\n\tif !resp.Success {\n\t\terrmsg := fmt.Sprintf(\"%s %s\", resp.Message, resp.Exception)\n\t\tlogger.Errorf(errmsg)\n\t\treturn nil, fmt.Errorf(errmsg)\n\t}\n\n\t// Assign ID after successful creation so that the same object can be used for subsequent update operation\n\to.ID = resp.Result\n\n\treturn resp, nil\n}", "func NewRegistry() *Registry {\n\tr := &Registry{}\n\tr.functions = make(map[string]*function)\n\treturn r\n}", "func (s *ImagesByRepositoryRegistryStorage) Create(obj interface{}) (<-chan interface{}, error) {\n\tmapping, ok := obj.(*imageapi.ImageRepositoryMapping)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"not an image repository mapping: %#v\", obj)\n\t}\n\n\tif mapping.Image.ID == \"\" {\n\t\treturn nil, fmt.Errorf(\"no image ID defined: %#v\", mapping)\n\t}\n\n\treturn apiserver.MakeAsync(func() (interface{}, error) {\n\t\t_, err := s.registry.GetImageRepository(mapping.RepositoryName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := s.imageRegistry.CreateImage(mapping.Image); err != nil && !apiserver.IsAlreadyExists(err) {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := s.registry.AddImageToRepository(mapping.RepositoryName, mapping.Image.ID); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn mapping, nil\n\t}), 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 (c *resourceDefinitions) Create(rd *ResourceDefinition) (result *ResourceDefinition, err error) {\n\tresult = &ResourceDefinition{}\n\terr = c.rc.Post().\n\t\tResource(\"definitions\").\n\t\tNamespace(c.namespace).\n\t\tBody(rd).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}", "func NewReg(ctx app.Ctx) *Reg {\n\treturn &Reg{\n\t\tctx: ctx,\n\t\tl: map[string]H{},\n\t}\n}", "func Create(ns walletdb.ReadWriteBucket) error {\n\treturn createStore(ns)\n}", "func New(configType string) *registry.Registry {\n\tGOPATH := os.Getenv(\"GOPATH\")\n\tif GOPATH == \"\" {\n\t\tGOPATH = defaultGOPATH()\n\t}\n\tr, err := os.Open(GOPATH + \"/src/github.com/snagles/docker-registry-manager/test/registrytest/configs/\" + configType)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Failed to open %v configuration file: %v\", configType, err)\n\t}\n\tc, err := configuration.Parse(r)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Failed to parse %v configuration file: %v\", c, err)\n\t}\n\n\tregistry, err := registry.NewRegistry(context.Background(), c)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\treturn registry\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\tall: make(map[string]*Job),\n\t}\n}", "func (f *Factory) Create(componentName string) (interface{}, error) {\n\tif info, exists := f.registry[componentName]; exists {\n\t\treturn info.Constructor()\n\t}\n\treturn nil, fmt.Errorf(\"Factory error: component '%s' does not exist\", componentName)\n}", "func CreateRegistrySecret() {\n\tif RegistryUsername() != \"\" && RegistryPassword() != \"\" {\n\t\tfmt.Printf(\"Creating image pull secret for Dockerhub on node %d\\n\", GinkgoParallelProcess())\n\t\t_, _ = proc.Kubectl(\"create\", \"secret\", \"docker-registry\", \"regcred\",\n\t\t\t\"--docker-server\", \"https://index.docker.io/v1/\",\n\t\t\t\"--docker-username\", RegistryUsername(),\n\t\t\t\"--docker-password\", RegistryPassword(),\n\t\t)\n\t}\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(userNS *auth.UserNamespace) *Registry {\n\treturn &Registry{\n\t\treg: ipc.NewRegistry(userNS),\n\t}\n}", "func (n *namespaceClient) Create(namespaceName string) error {\n\turl := fmt.Sprintf(\"%s%s\", n.url, nsh.AddURL)\n\tdata, err := json.Marshal(defaultNamespaceRequest(namespaceName))\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = n.client.DoHTTPRequest(\"POST\", url, bytes.NewBuffer(data))\n\tif err != nil {\n\t\treturn err\n\t}\n\tn.logger.Info(\"successfully created namespace\", zap.String(\"namespace\", namespaceName))\n\treturn nil\n}", "func NewRegistry(url *url.URL) *Registry {\n\tclient := Client{BaseURL: url}\n\treturn &Registry{client: &client}\n}", "func Open(name string, syscallService *bridge.SyscallService, db db.Database) (InstanceCreator, error) {\n\treturn defaultRegistry.Open(name, syscallService, db)\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 Create(name string, parameters map[string]interface{}) (StorageDriver, error) {\n\treturn factory.Create(name, parameters)\n}", "func (reg *registrar) Make(name string) (interface{}, error) {\n\treg.lock.Lock()\n\tdefer reg.lock.Unlock()\n\treturn reg.Registry.Make(name)\n}", "func Create() *dht {\n\treturn &dht{}\n}", "func New(config *Config, disco *xep0030.DiscoInfo, router router.Router, userRep repository.User) *Register {\n\tr := &Register{\n\t\tcfg: config,\n\t\trouter: router,\n\t\trunQueue: runqueue.New(\"xep0077\"),\n\t\trep: userRep,\n\t}\n\tif disco != nil {\n\t\tdisco.RegisterServerFeature(registerNamespace)\n\n\t}\n\treturn r\n}", "func Register(name string, port int) (err error) {\n\tr := RegistryRequest{name, port}\n\n\tbyt, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresp, err := http.Post(\"http://127.0.0.1\" + _LOCAL_PORT, \"text/json\", bytes.NewBuffer(byt))\n\tif err != nil {\n\t\treturn\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\terr = fmt.Errorf(\"non 200 response %d: %s\", resp.StatusCode, resp.Status)\n\t\treturn\n\t}\n\n\tbyt, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (t *Type) Create(data interface{}) error {\n\tcpy := reflect.Indirect(reflect.ValueOf(deepcopy.Copy(data))).Interface()\n\treturn t.registry.storage.Create(t, cpy)\n}", "func NewRegistrator() *Registrator {\n\treturn &Registrator{\n\t\tJobs: make(map[string]string),\n\t}\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 NewRegistry() *Registry {\n\treturn &Registry{\n\t\tmodules: make([]bar.Module, 0),\n\t}\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\tplugins: make(map[string]interface{}),\n\t\tproviders: make(map[string]interface{}),\n\t}\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToRegionCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(createURL(client), &b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\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 (s *Service) Create(ctx context.Context, req *CreateRequest) (*CreateReply, error) {\n\tid, token, err := s.m.Create(ctx)\n\tif err != nil {\n\t\tlog.Errorf(\"creating instance: %s\", err)\n\t\treturn nil, err\n\t}\n\treturn &CreateReply{\n\t\tID: id.String(),\n\t\tToken: token,\n\t}, nil\n}", "func NewRegistry(opts ...registry.Option) registry.Registry {\r\n\treturn registry.NewRegistry(opts...)\r\n}", "func NewRegistry(c *rest.Config) error {\n\tvar err error\n\tdefaultGenericClient, err = newForConfig(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfgCopy := *c\n\tcfg = &cfgCopy\n\treturn nil\n}", "func Create() *Router {\n\tconfig := cors.DefaultConfig()\n\tconfig.AllowOrigins = []string{\"http://localhost:3000\"}\n\tr := Router{Router: gin.New()}\n\tr.Router.Use(gin.Recovery())\n\tr.Router.Use(cors.New(config))\n\t// SetUserGroup set user group in the router\n\tr.UserGroup = r.Router.Group(\"/users\")\n\tr.RadioGroup = r.Router.Group(\"/radios\")\n\tr.ActionGroup = r.Router.Group(\"/recommendations\")\n\treturn &r\n}", "func (c *NurseClient) Create() *NurseCreate {\n\tmutation := newNurseMutation(c.config, OpCreate)\n\treturn &NurseCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func NewRegistry() ObjectRegistry {\n\timpl := &registry{actionChannel: make(actionChannel)}\n\tgo impl.run()\n\n\treturn impl\n}", "func (r *SoftwareResource) Create(item SoftwareConfig) error {\n\tif err := r.c.ModQuery(\"POST\", BasePath+SoftwareEndpoint, item); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\trateLimiters: make(map[string]*rate.Limiter),\n\t}\n}", "func (r *Releaser) Create(name string) (*Release, error) {\n\trelease, _, err := r.client.Repositories.CreateRelease(context.Background(), r.owner, r.repository, &gogithub.RepositoryRelease{Name: gogithub.String(name), TagName: gogithub.String(name)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"created release ID: %v, tag: %v\", *release.ID, *release.TagName)\n\treturn &Release{ID: *release.ID, TagName: *release.TagName, Releaser: r}, nil\n}", "func Create(name string, configPath string) error {\n\treturn <-create(name, configPath)\n}", "func (svc *SSHKeysService) Create(ctx context.Context, prj string, params *SSHKey) (*SSHKey, *http.Response, error) {\n\tret := new(SSHKey)\n\tresp, err := svc.client.resourceCreate(ctx, projectSSHKeysPath(prj), params, ret)\n\treturn ret, resp, err\n}", "func (t *FakeObjectTracker) Create(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error {\n\treturn nil\n}", "func NewRegistrar() Registry {\n\treturn &registrar{\n\t\tRegistry: NewRegistry(),\n\t}\n}", "func NewRegistry() Registry {\n\tfr := make(Registry)\n\tfr.mustRegister(BuiltIns...)\n\treturn fr\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 NewRegistry(name string) *Registry {\n\treturn &Registry{\n\t\tname: name,\n\t\tmetricNames: make(map[string]struct{}),\n\t\tcounters: make(map[string]*Counter),\n\t\tgauges: make(map[string]*Gauge),\n\t\ttimers: make(map[string]*Timer),\n\t}\n}", "func Create(c *golangsdk.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToNamespaceCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\treqOpt := &golangsdk.RequestOpts{OkCodes: []int{201}}\n\t_, r.Err = c.Post(rootURL(c), b, &r.Body, reqOpt)\n\treturn\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 NewRegistry() *bsoncodec.Registry {\n\treturn NewRegistryBuilder().Build()\n}", "func (factory) Create(cfg config.NodeHostConfig,\n\tcb config.LogDBCallback, dirs []string, wals []string) (raftio.ILogDB, error) {\n\treturn CreateTan(cfg, cb, dirs, wals)\n}", "func NewRegistryCmd(client dynamic.Interface) (cmd *cobra.Command) {\n\tctx := context.TODO()\n\n\tcmd = &cobra.Command{\n\t\tUse: \"registry\",\n\t\tAliases: []string{\"reg\"},\n\t\tShort: \"start a registry locally\",\n\t\tExample: `Before you get started, please sudo vim /etc/docker/daemon.json, then add the following config:\n\t\"insecure-registries\": [\n\t\t\"139.198.3.176:32678\"\n\t],\nAfter that, please restart docker daemon via: systemctl restart docker\n`,\n\t\tRunE: func(cmd *cobra.Command, args []string) (err error) {\n\t\t\t_ = client.Resource(types.GetDeploySchema()).Namespace(\"default\").Delete(ctx, \"registry\", metav1.DeleteOptions{})\n\t\t\t_ = client.Resource(types.GetServiceSchema()).Namespace(\"default\").Delete(ctx, \"registry\", metav1.DeleteOptions{})\n\n\t\t\tobj := &unstructured.Unstructured{}\n\t\t\tcontent := getRegistryDeploy()\n\t\t\tif err = yaml.Unmarshal([]byte(content), obj); err == nil {\n\t\t\t\tif _, err = client.Resource(types.GetDeploySchema()).Namespace(\"default\").Create(ctx, obj, metav1.CreateOptions{}); err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"failed when create deploy, %#v\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcmd.Println(\"registry deploy installed\")\n\t\t\t}\n\n\t\t\tobj = &unstructured.Unstructured{}\n\t\t\tsvcContent := getService()\n\t\t\tif err = yaml.Unmarshal([]byte(svcContent), obj); err == nil {\n\t\t\t\tif _, err = client.Resource(types.GetServiceSchema()).Namespace(\"default\").Create(ctx, obj, metav1.CreateOptions{}); err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"failed when create service, %#v\", err)\n\t\t\t\t} else {\n\t\t\t\t\tcmd.Println(\"registry service installed\")\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t},\n\t}\n\treturn\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 NewRegistry(settings ...Settings) *Registry {\n\treturn NewSwarmRegistry(nil, nil, settings...)\n}", "func NewRegistry(s Storage) WatchingRegistry {\n\treturn &storage{s}\n}", "func NewRegistry(s Storage) WatchingRegistry {\n\treturn &storage{s}\n}", "func NewRegistry(c RemoteClientFactory, l log.Logger) Registry {\n\treturn &registry{\n\t\tfactory: c,\n\t\tLogger: l,\n\t}\n}", "func (a *API) Create(s *funkmasta.Service) error {\n\tv := url.Values{}\n\tv.Set(\"name\", s.Name)\n\tv.Set(\"endpoint\", s.Endpoint)\n\tv.Set(\"payload\", s.Payload)\n\tv.Set(\"env\", s.EnvSetup)\n\n\t_, err := a.PostForm(CREATE, v)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Register(ctx context.Context, args RegisterArgs) (*Client, error) {\n\tid, err := uuid.NewRandom()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"rmapi.Register: unable to generate uuid: %w\", err)\n\t}\n\tdata := registerPayload{\n\t\tToken: args.Token,\n\t\tDescription: args.Description,\n\t\tID: id.String(),\n\t}\n\tpayload := new(bytes.Buffer)\n\tif err := json.NewEncoder(payload).Encode(data); err != nil {\n\t\treturn nil, fmt.Errorf(\"rmapi.Register: unable to encode json payload: %w\", err)\n\t}\n\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPost, registerURL, payload)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"rmapi.Register: unable to create http request: %w\", err)\n\t}\n\trefresh, err := readToken(req, 1024)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"rmapi.Register: %w\", err)\n\t}\n\treturn &Client{\n\t\tRefreshToken: refresh,\n\t}, nil\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 New(logger *zap.SugaredLogger, ports config.Ports, nodes ...*ipfs.NodeInfo) *NodeRegistry {\n\t// parse nodes\n\tm := make(map[string]*ipfs.NodeInfo)\n\tif nodes != nil {\n\t\tfor _, n := range nodes {\n\t\t\tm[n.NetworkID] = n\n\t\t}\n\t}\n\n\t// build registry\n\treturn &NodeRegistry{\n\t\tl: logger.Named(\"registry\"),\n\t\tnodes: m,\n\n\t\t// See documentation regarding public/private-ness of IPFS ports in package\n\t\t// ipfs\n\t\tswarmPorts: network.NewRegistry(logger, network.Public, ports.Swarm),\n\t\tapiPorts: network.NewRegistry(logger, network.Private, ports.API),\n\t\tgatewayPorts: network.NewRegistry(logger, network.Private, ports.Gateway),\n\t}\n}", "func (c *PharmacistClient) Create() *PharmacistCreate {\n\tmutation := newPharmacistMutation(c.config, OpCreate)\n\treturn &PharmacistCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func Create() *mux.Router {\n\tr := mux.NewRouter()\n\treturn routes.SetRouter(r)\n}", "func (rm *RsrcManager) Create(item reconciler.Object) error {\n\to := item.Obj.(*Object)\n\t_, err := rm.service.Buckets.Insert(o.ProjectID, o.Bucket).Do()\n\treturn err\n}", "func New(registry Registry, name string) *Repository {\n\treturn &Repository{\n\t\tname: name,\n\t\tregistry: registry,\n\t}\n}", "func (client *NamespacesClient) Create(data *schema.CreateNamespaceData) (*schema.Namespace, error) {\n\tresponse, err := client.http.execute(\"POST\", endpointNamespaces, data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnamespace := new(schema.Namespace)\n\tif err := json.Unmarshal(response, namespace); err != nil {\n\t\treturn nil, err\n\t}\n\treturn namespace, nil\n}", "func (td *OsmTestData) CreateDockerRegistrySecret(ns string) {\n\tsecret := &corev1.Secret{}\n\tsecret.Name = RegistrySecretName\n\tsecret.Type = corev1.SecretTypeDockerConfigJson\n\tsecret.Data = map[string][]byte{}\n\n\tdockercfgAuth := DockerConfigEntry{\n\t\tUsername: td.CtrRegistryUser,\n\t\tPassword: td.CtrRegistryPassword,\n\t\tEmail: \"[email protected]\",\n\t\tAuth: base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(\"%s:%s\", td.CtrRegistryUser, td.CtrRegistryPassword))),\n\t}\n\n\tdockerCfgJSON := DockerConfigJSON{\n\t\tAuths: map[string]DockerConfigEntry{td.CtrRegistryServer: dockercfgAuth},\n\t}\n\n\tif jsonConfig, err := json.Marshal(dockerCfgJSON); err != nil {\n\t\ttd.T.Fatalf(\"Error marshaling Docker config\", err)\n\t} else {\n\t\tsecret.Data[corev1.DockerConfigJsonKey] = jsonConfig\n\t}\n\n\ttd.T.Logf(\"Pushing Registry secret '%s' for namespace %s... \", RegistrySecretName, ns)\n\t_, err := td.Client.CoreV1().Secrets(ns).Create(context.Background(), secret, metav1.CreateOptions{})\n\tif err != nil {\n\t\ttd.T.Fatalf(\"Could not add registry secret\")\n\t}\n}", "func (nc *NodeController) Create(r types.Resource) (err error) {\n\tn, err := assertNode(r)\n\tif err != nil {\n\t\treturn\n\t}\n\targs := make(map[string]interface{})\n\tq := \"WITH \" + nc.newNode(n, args) + \",\" + nc.newLinks(n, args) + \",\" + nc.newNodeMetric(n, args) + \" \" + selectNode(\"new_node\", nc.db.table(\"nodes\"), \"new_links\", \"new_node_metric\", \"\")\n\tstmt, err := nc.db.PrepareNamed(q)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = stmt.Get(n, args)\n\treturn\n}" ]
[ "0.82440567", "0.71896267", "0.6660126", "0.66595465", "0.65610474", "0.6396036", "0.637547", "0.6353766", "0.63506126", "0.62829024", "0.6184734", "0.6160968", "0.6154092", "0.6126337", "0.6102998", "0.6073001", "0.60332346", "0.60317767", "0.60232884", "0.6013441", "0.60006934", "0.5990776", "0.59828746", "0.59820485", "0.5973762", "0.59690005", "0.59086245", "0.58928764", "0.5886399", "0.5848303", "0.584741", "0.5829853", "0.5829853", "0.5826116", "0.58146226", "0.5813457", "0.57994366", "0.5779846", "0.5772435", "0.5765687", "0.5745317", "0.5740154", "0.5713817", "0.5706987", "0.5681254", "0.5661727", "0.56319344", "0.56317526", "0.5629419", "0.5626518", "0.56236535", "0.5619009", "0.5610455", "0.5607523", "0.5596496", "0.55841434", "0.55816275", "0.5578605", "0.55756265", "0.5575447", "0.5562928", "0.5560727", "0.55537736", "0.5552968", "0.55288965", "0.5520077", "0.55044436", "0.5500688", "0.5492711", "0.5482292", "0.5473321", "0.54474896", "0.543607", "0.5435344", "0.54334646", "0.5432438", "0.5429607", "0.54256165", "0.5423507", "0.542001", "0.5417287", "0.5416662", "0.54158956", "0.5414646", "0.5410744", "0.5409033", "0.54090065", "0.54090065", "0.540549", "0.5402519", "0.5396747", "0.539108", "0.5380519", "0.5379119", "0.5372684", "0.5364567", "0.5362096", "0.5359779", "0.5357728", "0.5344629" ]
0.69471276
2
Asset loads and returns the asset for the given name. It returns an error if the asset could not be found or could not be loaded.
func Asset(name string) ([]byte, error) { cannonicalName := strings.Replace(name, "\\", "/", -1) if f, ok := _bindata[cannonicalName]; ok { a, err := f() if err != nil { return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) } return a.bytes, nil } return nil, fmt.Errorf("Asset %s not found", name) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Asset(name string) ([]byte, error) {\n cannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n if f, ok := _bindata[cannonicalName]; ok {\n a, err := f()\n if err != nil {\n return nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n }\n return a.bytes, nil\n }\n return nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func (model *GrogModel) GetAsset(name string) (*Asset, error) {\n\tvar foundAsset *Asset\n\tvar mimeType string\n\tvar content = make([]byte, 0)\n\tvar serveExternal int64\n\tvar rendered int64\n\tvar added int64\n\tvar modified int64\n\tvar err error\n\n\trow := model.db.DB.QueryRow(`select mimeType, content, serve_external, rendered,\n\t\tadded, modified from Assets where name = ?`, name)\n\tif row.Scan(&mimeType, &content, &serveExternal, &rendered, &added, &modified) != sql.ErrNoRows {\n\t\tfoundAsset = model.NewAsset(name, mimeType)\n\t\tfoundAsset.Content = content\n\t\tif serveExternal == 1 {\n\t\t\tfoundAsset.ServeExternal = true\n\t\t} else {\n\t\t\tfoundAsset.ServeExternal = false\n\t\t}\n\n\t\tif rendered == 1 {\n\t\t\tfoundAsset.Rendered = true\n\t\t} else {\n\t\t\tfoundAsset.Rendered = false\n\t\t}\n\n\t\tfoundAsset.Added.Set(time.Unix(added, 0))\n\t\tfoundAsset.Modified.Set(time.Unix(modified, 0))\n\t} else {\n\t\terr = fmt.Errorf(\"No asset with name %s\", name)\n\t}\n\n\treturn foundAsset, err\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}" ]
[ "0.73466825", "0.72669834", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.71033317", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885", "0.70938885" ]
0.0
-1
MustAsset is like Asset but panics when Asset would return an error. It simplifies safe initialization of global variables.
func MustAsset(name string) []byte { a, err := Asset(name) if err != nil { panic("asset: Asset(" + name + "): " + err.Error()) } return a }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}" ]
[ "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886", "0.749886" ]
0.0
-1
AssetInfo loads and returns the asset info for the given name. It returns an error if the asset could not be found or could not be loaded.
func AssetInfo(name string) (os.FileInfo, error) { cannonicalName := strings.Replace(name, "\\", "/", -1) if f, ok := _bindata[cannonicalName]; ok { a, err := f() if err != nil { return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) } return a.info, nil } return nil, fmt.Errorf("AssetInfo %s not found", name) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}" ]
[ "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143", "0.81351143" ]
0.0
-1
AssetNames returns the names of the assets.
func AssetNames() []string { names := make([]string, 0, len(_bindata)) for name := range _bindata { names = append(names, name) } return names }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[]
[]
0.0
-1
RestoreAsset restores an asset under the given directory
func RestoreAsset(dir, name string) error { data, err := Asset(name) if err != nil { return err } info, err := AssetInfo(name) if err != nil { return err } err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755)) if err != nil { return err } err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode()) if err != nil { return err } err = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime()) if err != nil { return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RestoreAsset(dir, name string) error {\n\tdata, err := Asset(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := AssetInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.MkdirAll(_filePath(dir, path.Dir(name)), os.FileMode(0755))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func RestoreAsset(dir, name string) error {\n\tdata, err := Asset(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := AssetInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.MkdirAll(_filePath(dir, path.Dir(name)), os.FileMode(0755))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func RestoreAsset(dir, name string) error {\n\tdata, err := Asset(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := AssetInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.MkdirAll(_filePath(dir, path.Dir(name)), os.FileMode(0755))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func RestoreAsset(dir, name string) error {\n\tdata, err := Asset(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := AssetInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.MkdirAll(_filePath(dir, path.Dir(name)), os.FileMode(0755))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}" ]
[ "0.80596304", "0.80596304", "0.80596304", "0.80596304" ]
0.0
-1
RestoreAssets restores an asset under the given directory recursively
func RestoreAssets(dir, name string) error { children, err := AssetDir(name) // File if err != nil { return RestoreAsset(dir, name) } // Dir for _, child := range children { err = RestoreAssets(dir, filepath.Join(name, child)) if err != nil { return err } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n\tchildren, err := AssetDir(name)\n\tif err != nil { // File\n\t\treturn RestoreAsset(dir, name)\n\t} else { // Dir\n\t\tfor _, child := range children {\n\t\t\terr = RestoreAssets(dir, path.Join(name, child))\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 RestoreAssets(dir, name string) error {\n\tchildren, err := AssetDir(name)\n\tif err != nil { // File\n\t\treturn RestoreAsset(dir, name)\n\t} else { // Dir\n\t\tfor _, child := range children {\n\t\t\terr = RestoreAssets(dir, path.Join(name, child))\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 RestoreAssets(dir, name string) error {\n\tchildren, err := AssetDir(name)\n\tif err != nil { // File\n\t\treturn RestoreAsset(dir, name)\n\t} else { // Dir\n\t\tfor _, child := range children {\n\t\t\terr = RestoreAssets(dir, path.Join(name, child))\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 RestoreAssets(dir, name string) error {\n\tchildren, err := AssetDir(name)\n\tif err != nil { // File\n\t\treturn RestoreAsset(dir, name)\n\t} else { // Dir\n\t\tfor _, child := range children {\n\t\t\terr = RestoreAssets(dir, path.Join(name, child))\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}" ]
[ "0.79875094", "0.79875094", "0.79875094", "0.79875094", "0.79875094", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.78383785", "0.78383785", "0.78383785", "0.78383785" ]
0.0
-1
SyncCompanies : Sync the company data to DB Delete all DB data Insert JSON data to DB
func SyncCompanies(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") res := models.APIRes{} // - Get the size of companies data var companiesIdx int rows, err := glob.DB.Query("SELECT COUNT(1) FROM `companies`") if err != nil { logs.Error(err) res.Error = err.Error() js, err := json.Marshal(res) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write(js) return } defer rows.Close() for rows.Next() { err := rows.Scan(&companiesIdx) if err != nil { logs.Error(err) res.Error = err.Error() js, err := json.Marshal(res) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write(js) return } } err = rows.Err() if err != nil { logs.Error(err) res.Error = err.Error() js, err := json.Marshal(res) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write(js) return } logs.Debug("Will skip %v rows.", companiesIdx) // - Open Data File file, err := os.Open(config.CfgData.Data.Companies) if err != nil { logs.Error(err) res.Error = err.Error() js, err := json.Marshal(res) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write(js) return } defer file.Close() // - Scan Data Line By Line var wg sync.WaitGroup scanner := bufio.NewScanner(file) v := reflect.ValueOf(models.CompaniesJSONItem{}) size := glob.MySQLUpperPlaceholders / v.NumField() skipCount := 0 totalCount := 0 guard := make(chan struct{}, 2) // Max goroutines limit. errChan := make(chan bool) items := []models.CompaniesJSONItem{} for scanner.Scan() { // - Skip existing data. if skipCount < companiesIdx { skipCount++ continue } // - Parse JSON to Item itemJSON := scanner.Text() item := models.CompaniesJSONItem{} json.Unmarshal([]byte(itemJSON), &item) // logs.Debug("JSON = %+v", item) items = append(items, item) totalCount++ // break if len(items) >= size { // - Send items to channel and clear items, skipCount. guard <- struct{}{} wg.Add(1) go syncCompaniesInsertData(&wg, guard, errChan, items) logs.Debug("Send to insert %v data.", size) items = []models.CompaniesJSONItem{} } } if len(items) > 0 { // - Send the last data that not reach the size. guard <- struct{}{} wg.Add(1) go syncCompaniesInsertData(&wg, guard, errChan, items) logs.Debug("Last time send to insert %v data.", len(items)) } // - Check Error of Scanner if err := scanner.Err(); err != nil { res.Error = err.Error() js, err := json.Marshal(res) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write(js) return } logs.Debug("Waiting all goroutine") wg.Wait() // - Rev Err select { case <-errChan: res.Error = fmt.Sprintf("Something wrong !") default: res.Message = fmt.Sprintf("Skip %v data and insert %v data", skipCount, totalCount) } js, err := json.Marshal(res) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write(js) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *CompanyController) Put() {\n\n\tcompany := models.Company{}\n\tcompany.UpdateAt = time.Now().Unix()\n\tif err := json.Unmarshal(c.Ctx.Input.RequestBody, &company); err != nil {\n\t\tlogs.Error(err)\n\t\tc.Data[\"json\"] = utils.ResponseError(c.Ctx, \"参数错误!\", nil)\n\t\tc.ServeJSON()\n\t\treturn\n\t}\n\n\t// validation\n\tvalid := validation.Validation{}\n\tvalid.Required(company.Logo, \"logo\").Message(\"公司LOGO不能为空!\")\n\tvalid.Required(company.Title, \"title\").Message(\"公司名称不能为空!\")\n\tvalid.MaxSize(company.Title, 50, \"title\").Message(\"公司名称不能超过50个字符!\")\n\tvalid.Required(company.Service, \"service\").Message(\"在线客服时间不能为空!\")\n\tvalid.MaxSize(company.Service, 50, \"service\").Message(\"在线客服时间长度不能超过50个字符!\")\n\tvalid.MaxSize(company.Email, 50, \"service\").Message(\"Email长度不能超过50个字符!\")\n\tvalid.MaxSize(company.Tel, 50, \"tel\").Message(\"公司电话长度不能超过50个字符!\")\n\tif valid.HasErrors() {\n\t\tfor _, err := range valid.Errors {\n\t\t\tlogs.Error(err)\n\t\t\tc.Data[\"json\"] = &models.Response{Code: 400, Message: err.Message, Data: nil}\n\t\t\tbreak\n\t\t}\n\t\tc.ServeJSON()\n\t\treturn\n\t}\n\n\t// orm\n\to := orm.NewOrm()\n\tcompany.ID = 1\n\tcompany.UpdateAt = time.Now().Unix()\n\tif _, err := o.Update(&company); err != nil {\n\t\tlogs.Error(err)\n\t\tc.Data[\"json\"] = utils.ResponseError(c.Ctx, \"更新失败!\", err)\n\t} else {\n\t\tc.Data[\"json\"] = utils.ResponseSuccess(c.Ctx, \"更新成功!\", &company)\n\t}\n\tc.ServeJSON()\n}", "func PutCompany(c *gin.Context) {\n\tixorm, _ := c.Get(\"xorm\")\n\txormEngine, _ := ixorm.(*xorm.Engine)\n\n\tc.Header(\"Content-Type\", \"application/json\")\n\tvar company models.Company\n\tc.Bind(&company)\n\n\tif id, err := strconv.Atoi(c.Params.ByName(\"id\")); err == nil {\n\t\tif companyUpdated, err := db.UpdateCompanyByID(xormEngine, id, company); err == nil && companyUpdated.ID > 0 {\n\t\t\tc.JSON(http.StatusOK, companyUpdated)\n\t\t} else {\n\t\t\tif err == nil {\n\t\t\t\tc.AbortWithStatus(http.StatusNotModified)\n\t\t\t} else {\n\t\t\t\tc.JSON(http.StatusInternalServerError,\n\t\t\t\t\tgin.H{\"code\": \"ERROR\", \"message\": \"Internal Server Error \"})\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tc.JSON(http.StatusNoContent, gin.H{\"code\": \"ERROR\", \"message\": \"Invalid param\"})\n\t}\n}", "func (dao CompanyDAOPsql) Update(obj *models.Company) error {\n\tquery := `UPDATE companies SET identification_type_id = $2, identification_number = $3, verification_digit = $4, company = upper($5), address = upper($6), phone = $7, department_id = $8, city_id = $9, web = lower($10), email = lower($11), activity = $12, autorretenedor = $13, person_type_id = $14, regime_type_id = $15, taxpayer_type_id = $16, logo = lower($17), updated_at = now() WHERE id = $1\n\t\t\t\tRETURNING id, identification_type_id, identification_number, verification_digit, company, address, phone, departments_id, cities_id, web, email, activity, autorretenedor, person_type_id, regime_type_id, taxpayer_type_id, logo, created_at, updated_at`\n\tdb := get()\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(query)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer stmt.Close()\n\n\trow := stmt.QueryRow(obj.ID, obj.IdentificationType.ID, obj.IdentificationNumber, obj.VerificationDigit, obj.Company, obj.Address, obj.Phone, obj.Department.ID, obj.City.ID, obj.Web, obj.Email, obj.Activity, obj.AutoRretenedor, obj.PersonType.ID, obj.RegimeType.ID, obj.TaxpayerType.ID, obj.Logo)\n\treturn dao.rowToObject(row, obj)\n}", "func (c *Company) Update() {\n\tinitdb.DbInstance.Save(&c)\n\tlog.Println(\"Updated -> \", c)\n}", "func (dao CompanyDAOPsql) Insert(obj *models.Company) error {\n\tquery := `INSERT INTO companies (identification_type, identification_number, verification_digit, company, address, phone, departments_id, cities_id, web, email, activity, autorretenedor, person_type_id, regime_type_id, taxpayer_type_id, logo)\n\t\t\t\tVALUES ($1, $2, $3, upper($4), upper($5), $6, $7, $8, lower($9), lower($10), $11, $12, $13, $14, $15, lower($16))\n\t\t\t\tRETURNING id, identification_type_id, identification_number, verification_digit, company, address, phone, departments_id, cities_id, web, email, activity, autorretenedor, person_type_id, regime_type_id, taxpayer_type_id, logo, created_at, updated_at`\n\tdb := get()\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(query)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer stmt.Close()\n\n\trow := stmt.QueryRow(obj.IdentificationType.ID, obj.IdentificationNumber, obj.VerificationDigit, obj.Company, obj.Address, obj.Phone, obj.Department.ID, obj.City.ID, obj.Web, obj.Email, obj.Activity, obj.AutoRretenedor, obj.PersonType.ID, obj.RegimeType.ID, obj.TaxpayerType.ID, obj.Logo)\n\treturn dao.rowToObject(row, obj)\n}", "func (d UserData) SetCompanies(value m.CompanySet) m.UserData {\n\td.ModelData.Set(models.NewFieldName(\"Companies\", \"company_ids\"), value)\n\treturn d\n}", "func (d UserData) CreateCompanies(related m.CompanyData) m.UserData {\n\td.ModelData.Create(models.NewFieldName(\"Companies\", \"company_ids\"), related.Underlying())\n\treturn d\n}", "func SyncToSMdb() {\n\n\tdbName := c.DBConfig.DBName.StockMarketRawD1\n\tnames, _ := h.GetCollectionNames(dbName)\n\tcCount := len(names)\n\n\tfor i, name := range names {\n\t\tMergeDMtoMM(name)\n\t\tfmt.Printf(\"Synchronizing daily-bar to monthly-bar. Stock code:%s (%d/%d) \\r\", name, i+1, cCount)\n\t}\n\tfmt.Println()\n}", "func (ccb *CompanyCreateBulk) Save(ctx context.Context) ([]*Company, error) {\n\tspecs := make([]*sqlgraph.CreateSpec, len(ccb.builders))\n\tnodes := make([]*Company, len(ccb.builders))\n\tmutators := make([]Mutator, len(ccb.builders))\n\tfor i := range ccb.builders {\n\t\tfunc(i int, root context.Context) {\n\t\t\tbuilder := ccb.builders[i]\n\t\t\tbuilder.defaults()\n\t\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\t\tmutation, ok := m.(*CompanyMutation)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t\t}\n\t\t\t\tif err := builder.check(); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tbuilder.mutation = mutation\n\t\t\t\tnodes[i], specs[i] = builder.createSpec()\n\t\t\t\tvar err error\n\t\t\t\tif i < len(mutators)-1 {\n\t\t\t\t\t_, err = mutators[i+1].Mutate(root, ccb.builders[i+1].mutation)\n\t\t\t\t} else {\n\t\t\t\t\t// Invoke the actual operation on the latest mutation in the chain.\n\t\t\t\t\tif err = sqlgraph.BatchCreate(ctx, ccb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {\n\t\t\t\t\t\tif sqlgraph.IsConstraintError(err) {\n\t\t\t\t\t\t\terr = &ConstraintError{err.Error(), err}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tmutation.id = &nodes[i].ID\n\t\t\t\tmutation.done = true\n\t\t\t\tid := specs[i].ID.Value.(int64)\n\t\t\t\tnodes[i].ID = int(id)\n\t\t\t\treturn nodes[i], nil\n\t\t\t})\n\t\t\tfor i := len(builder.hooks) - 1; i >= 0; i-- {\n\t\t\t\tmut = builder.hooks[i](mut)\n\t\t\t}\n\t\t\tmutators[i] = mut\n\t\t}(i, ctx)\n\t}\n\tif len(mutators) > 0 {\n\t\tif _, err := mutators[0].Mutate(ctx, ccb.builders[0].mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn nodes, nil\n}", "func API_UPDATE() {\n\n \n client := &http.Client{}\n\n ApiUrl := bmgObj.ApiUrl + \"products?deleted=true\" \n \n fmt.Println(ApiUrl)\n\n req, _ := http.NewRequest(\"GET\", ApiUrl, nil)\n req.Header.Add(\"X-Authorization\", bmgObj.ApiKey)\n\n resp, err := client.Do(req)\n\n if err != nil {\n fmt.Println(err)\n fmt.Println(\"Errored when sending request to the server\")\n return\n }\n\n defer resp.Body.Close()\n\n resp_body, _ := ioutil.ReadAll(resp.Body)\n\n // DB Insert, temporary method \n\n\n db, errdb := sql.Open(\"mysql\", mysqlObj.MySqlUsername+\":\"+mysqlObj.MySqlPassword+\"@tcp(\"+mysqlObj.MySqlHost+\":\"+mysqlObj.MysqlPort+\")/\"+mysqlObj.MysqlDb)\n if errdb != nil {\n panic(errdb.Error()) \n }\n\n\n\n stmt7, _ := db.Prepare(\"INSERT INTO deals_deleted(deal_uuid, title, deleted_date) values(?,?,?)\") \n \n \n var buffer bytes.Buffer\n var DealsFlatStruct FlatData\n\n json.Unmarshal(resp_body, &DealsFlatStruct)\n \n buffer.WriteString(\"(\")\n for i := range DealsFlatStruct.Data {\n\n item_flat := DealsFlatStruct.Data[i]\n\n fmt.Println(item_flat.Uuid)\n\n stmt7.Exec(item_flat.Uuid, item_flat.Title, item_flat.DeletedDate) \n \n buffer.WriteString(\"'\" + item_flat.Uuid + \"',\")\n\n \n } \n \n buffer.WriteString(\"'0')\")\n \n fmt.Println(buffer.String())\n \n stmtDelete, _ := db.Prepare(\"UPDATE deals_flat_data SET published = 2 WHERE deal_uuid IN \" + buffer.String()) \n \n stmtDelete.Exec()\n \n defer stmt7.Close() \n defer stmtDelete.Close() \n\n defer db.Close()\n\n\n}", "func (dao CompanyDAOPsql) GetAll() ([]models.Company, error) {\n\tquery := `SELECT id, identification_type_id, identification_number, verification_digit, company, address, phone, departments_id, cities_id, web, email, activity, autorretenedor, person_type_id, regime_type_id, taxpayer_type_id, logo, created_at, updated_at\n\t\t\t\tFROM companies ORDER BY id`\n\tobjs := make([]models.Company, 0)\n\tdb := get()\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer stmt.Close()\n\n\trows, err := stmt.Query()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar o models.Company\n\t\terr = rows.Scan(&o.ID, &o.IdentificationType.ID, &o.IdentificationNumber, &o.VerificationDigit, &o.Company, &o.Address, &o.Phone, &o.Department.ID, &o.City.ID, &o.Web, &o.Email, &o.Activity, &o.AutoRretenedor, &o.PersonType.ID, &o.RegimeType.ID, &o.TaxpayerType.ID, &o.Logo, &o.CreatedAt, &o.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn objs, err\n\t\t}\n\t\tobjs = append(objs, o)\n\t}\n\treturn objs, nil\n}", "func (s *Store) sync() {\n\tresult, err := logger.GetAll(local)\n\tif err != nil {\n\t\tlogs.CRITICAL.Println(\"Panic for get all objects\")\n\t}\n\ttotal := len(result)\n\tif total != 0 {\n\t\tlogs.INFO.Println(\"Total of records: \", total)\n\t}\n\tif total == 0 {\n\t\tlog.Println(\"Nothing to sync\")\n\t\tif store.getFile() != \"\" {\n\t\t\tlogs.INFO.Println(\"Initiating clearing....\")\n\t\t\tremoveLines(store.getFile(), 1, -1)\n\t\t}\n\t\tstore.Transaction = nil\n\t\treturn\n\t}\n\tfor i := 0; i < total; i++ {\n\t\tlogs.INFO.Println(\"PUSH -> UserName: \" +\n\t\t\tresult[i].UserName + \" :: DataBase: \" +\n\t\t\tresult[i].DatabaseName + \" :: VirtualTransactionID: \" +\n\t\t\tresult[i].VirtualTransactionID)\n\n\t\tstore.Transaction = append(store.Transaction, result[i].VirtualTransactionID)\n\t\tlogger.Persist(prod, result[i])\n\t\t// Depending on the amount of data and traffic, goroutines that were\n\t\t// first run have already removed the registry, not identifying the\n\t\t// registry in the database at the current execution.\n\t\terr := logger.DeletePerObjectId(local, result[i].ID)\n\t\tif err != nil {\n\t\t\tlogs.INFO.Println(\"ObjectId -> \" + result[i].ID.Hex() + \" removed on the last goroutine\")\n\t\t}\n\t}\n}", "func (c *Company) Delete() {\n\tinitdb.DbInstance.Delete(&c)\n\tlog.Println(\"Deleted -> \", c)\n}", "func UploadCompanysWithCSV(c *gin.Context) {\n\tixorm, _ := c.Get(\"xorm\")\n\txormEngine, _ := ixorm.(*xorm.Engine)\n\n\tfile, _ := c.FormFile(\"file\")\n\tlog.Println(file.Filename)\n\n\tfileTemp := \"./temp/\" + file.Filename\n\tc.SaveUploadedFile(file, fileTemp)\n\n\tRegisterCompanyFromCSV(xormEngine, fileTemp)\n\n\tos.Remove(fileTemp)\n\n\tc.String(http.StatusOK, fmt.Sprintf(\"'%s' uploaded!\", file.Filename))\n}", "func (ct *CompanyTestSuite) TestUpdate(c *C) {\n\ttoken := getTestDefaultAuthToken()\n\n\t// create new company\n\tcompanyName := fmt.Sprintf(\"companyName_%v\", time.Now().UnixNano())\n\n\tcompany, err := createTestCompany(companyName, token)\n\tc.Assert(err, IsNil)\n\n\tanotherCompanyName := fmt.Sprintf(\"anotherCompanyName_%v\", time.Now().UnixNano())\n\n\tcompany.Name = anotherCompanyName\n\tcompany.IsEnabled = false\n\n\tcompanyTxt, _ := json.Marshal(company)\n\n\t// try to update company\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"http://127.0.0.1:8080/v1/company/%v\", company.Id), bytes.NewReader(companyTxt))\n\tc.Assert(err, IsNil)\n\n\treq.Header.Add(\"Authorization\", token)\n\n\tclient := server.GetHTTPClient()\n\n\tresp, err := client.Do(req)\n\tdefer resp.Body.Close()\n\tc.Assert(err, IsNil)\n\n\tmess := server.NewCommonResponse()\n\terr = jsonpb.Unmarshal(resp.Body, mess)\n\tc.Assert(err, IsNil)\n\n\tc.Assert(mess.Meta.StatusCode, Equals, HttpStatusOK)\n\tc.Assert(mess.Meta.Ok, Equals, true)\n\tc.Assert(mess.Meta.Error, Equals, \"\")\n\n\t// try get updated company\n\treq, err = http.NewRequest(\"GET\", fmt.Sprintf(\"http://127.0.0.1:8080/v1/company/%v\", company.Id), nil)\n\tc.Assert(err, IsNil)\n\n\treq.Header.Add(\"Authorization\", token)\n\n\tresp, err = client.Do(req)\n\tdefer resp.Body.Close()\n\tc.Assert(err, IsNil)\n\n\tretrievedCompany := server.NewCompanyResponse()\n\terr = jsonpb.Unmarshal(resp.Body, retrievedCompany)\n\tc.Assert(err, IsNil)\n\n\tc.Assert(retrievedCompany.Meta.StatusCode, Equals, HttpStatusOK)\n\tc.Assert(retrievedCompany.Data.Name, Equals, company.Name)\n\tc.Assert(retrievedCompany.Data.IsEnabled, Not(Equals), company.IsEnabled)\n}", "func (s UserSet) SetCompanies(value m.CompanySet) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Companies\", \"company_ids\"), value)\n}", "func syncDatabase() {\n\tadapter := adapters[db.DriverName()]\n\tdbTables := adapter.tables()\n\t// Create or update existing tables\n\tfor tableName, mi := range modelRegistry.registryByTableName {\n\t\tif _, ok := dbTables[tableName]; !ok {\n\t\t\tcreateDBTable(mi.tableName)\n\t\t}\n\t\tupdateDBColumns(mi)\n\t\tupdateDBIndexes(mi)\n\t}\n\t// Drop DB tables that are not in the models\n\tfor dbTable := range adapter.tables() {\n\t\tvar modelExists bool\n\t\tfor tableName := range modelRegistry.registryByTableName {\n\t\t\tif dbTable != tableName {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmodelExists = true\n\t\t\tbreak\n\t\t}\n\t\tif !modelExists {\n\t\t\tdropDBTable(dbTable)\n\t\t}\n\t}\n}", "func (c Companion) GetAllCompanions() []Companion {\n\tdb := db.GetDb()\n\tcompanions := []Companion{}\n\tdb.Find(&companions)\n\treturn companions\n}", "func (m *CompanyMutation) ResetCompanys() {\n\tm.companys = nil\n\tm.removedcompanys = nil\n}", "func (e *elephant) getCompanies() ([]string, error) {\n\tresult := make([]string, 0, 16)\n\treturn result, db.Model(&Company{}).\n\t\tPluck(\"name\", &result).\n\t\tError\n}", "func (userAuthorizationServerObject *userAuthorizationEngineServerObjectStruct) sqlListUsersAuthorizedCompanies(userAuthorizedCompaniesRequest *userAuthorizationEngine_grpc_api.UserAuthorizedCompaniesRequest) *userAuthorizationEngine_grpc_api.UserAuthorizedCompaniesResponse {\n\tvar err error\n\tvar returnMessage *userAuthorizationEngine_grpc_api.UserAuthorizedCompaniesResponse\n\n\t// SQl for 'List users authorized accounts'\n\tsqlText := \"SELECT Company \"\n\tsqlText += \"FROM AuthorizedCompany \"\n\tsqlText += \"WHERE \"\n\tsqlText += \"UserName = '\" + userAuthorizedCompaniesRequest.UserId + \"' AND \"\n\tsqlText += \"ORDER BY Company \"\n\n\t// Execute a sql quesry\n\tsqlResponseRows, err := userAuthorizationServerObject.sqlDbObject.Query(sqlText)\n\tif err != nil {\n\t\tuserAuthorizationServerObject.logger.WithFields(logrus.Fields{\n\t\t\t\"Id\": \"6c93ed23-02a0-454c-8975-49906677b83c\",\n\t\t\t\"err.Error()\": err.Error(),\n\t\t\t\"sqlText\": sqlText,\n\t\t}).Warning(\"Couldn't execute sql-query\")\n\n\t\t// Create return message\n\t\treturnMessage = &userAuthorizationEngine_grpc_api.UserAuthorizedCompaniesResponse{\n\t\t\tUserId: userAuthorizedCompaniesRequest.UserId,\n\t\t\tAcknack: false,\n\t\t\tComments: \"Error While executing SQL\",\n\t\t\tCompanies: nil,\n\t\t}\n\t\treturn returnMessage\n\n\t} else {\n\n\t\t// Success in executing sqlStatement\n\t\tuserAuthorizationServerObject.logger.WithFields(logrus.Fields{\n\t\t\t\"Id\": \"0d3417ef-c952-4ffd-aed4-e7bb2fd4066a\",\n\t\t\t\"sqlResponseRows\": sqlResponseRows,\n\t\t}).Debug(\"Success in executing sql for 'List users authorized companies'\")\n\n\t\t// Extract data from SQL results and create response object\n\t\tvar companiesList []*userAuthorizationEngine_grpc_api.Company\n\t\tvar Company string\n\n\t\t// Iterate and fetch the records from result cursor\n\t\tfor sqlResponseRows.Next() {\n\t\t\tsqlResponseRows.Scan(&Company)\n\t\t\tconvertedCompany := &userAuthorizationEngine_grpc_api.Company{Company: Company}\n\t\t\tcompaniesList = append(companiesList, convertedCompany)\n\t\t}\n\n\t\t// Create return message\n\t\treturnMessage = &userAuthorizationEngine_grpc_api.UserAuthorizedCompaniesResponse{\n\t\t\tUserId: userAuthorizedCompaniesRequest.UserId,\n\t\t\tAcknack: true,\n\t\t\tComments: \"\",\n\t\t\tCompanies: companiesList,\n\t\t}\n\t}\n\n\treturn returnMessage\n}", "func (d UserData) UnsetCompanies() m.UserData {\n\td.ModelData.Unset(models.NewFieldName(\"Companies\", \"company_ids\"))\n\treturn d\n}", "func (a *App) GetCompanies(w http.ResponseWriter, r *http.Request) {\n\thandler.GetCompanies(a.DB, w, r)\n}", "func (company *Company) Save() {\n\tDB.Set(\"Company\", company.ID, company)\n}", "func NewCompany(c *gin.Context) {\n\tixorm, _ := c.Get(\"xorm\")\n\txormEngine, _ := ixorm.(*xorm.Engine)\n\n\tc.Header(\"Content-Type\", \"application/json\")\n\n\tvar company models.Company\n\tc.Bind(&company)\n\n\tif companyInserted, err := db.InsertCompany(xormEngine, company); err == nil && companyInserted.ID > 0 {\n\t\tc.JSON(http.StatusCreated, companyInserted)\n\n\t} else {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"code\": \"ERROR\", \"message\": \"Internal Server Error\"})\n\t}\n}", "func (s *servicecenter) FlushData() {\n\tdata, err := s.servicecenter.GetAll(context.Background())\n\tif err != nil {\n\t\tlog.Error(\"Syncer discover instances failed\", err)\n\t\treturn\n\t}\n\n\tmaps := s.storage.GetMaps()\n\n\tdata, maps = s.exclude(data, maps)\n\ts.storage.UpdateData(data)\n\ts.storage.UpdateMaps(maps)\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 SyncTransactions(\n\tctx context.Context,\n\tcompany *Company,\n\tsubscription *braintree.Subscription,\n) error {\n\n\tcompanyKey := company.Key(ctx)\n\n\t// TODO: Add 6-month cutoff.\n\tfor _, btTransaction := range subscription.Transactions.Transaction {\n\t\tvar transaction Transaction\n\n\t\tkey := datastore.NewKey(ctx, transactionKind, btTransaction.Id, 0, companyKey)\n\t\tif err := nds.Get(ctx, key, &transaction); err == datastore.ErrNoSuchEntity {\n\t\t\ttransaction.Company = companyKey\n\t\t\ttransaction.SubscriptionID = subscription.Id\n\t\t\ttransaction.SubscriptionPlanID = subscription.PlanId\n\t\t\ttransaction.SubscriptionCountry = company.SubscriptionCountry\n\t\t\ttransaction.SubscriptionVATID = company.SubscriptionVATID\n\t\t\tif company.SubscriptionVATID == \"\" {\n\t\t\t\ttransaction.SubscriptionVATPercent = utils.LookupVAT(company.SubscriptionCountry)\n\t\t\t}\n\t\t}\n\n\t\ttransaction.TransactionID = btTransaction.Id\n\t\ttransaction.TransactionType = btTransaction.Type\n\t\ttransaction.TransactionStatus = btTransaction.Status\n\t\ttransaction.TransactionAmount = btTransaction.Amount.Unscaled\n\n\t\ttransaction.CreatedAt = *btTransaction.CreatedAt\n\t\ttransaction.UpdatedAt = *btTransaction.UpdatedAt\n\t\tif _, err := nds.Put(ctx, key, &transaction); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func RegisterCompanyFromCSV(xormEngine *xorm.Engine, file string) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tdefer f.Close()\n\n\treader := csv.NewReader(f)\n\treader.Comma = ';'\n\treader.FieldsPerRecord = -1\n\n\tlines, err := reader.ReadAll()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\tfor i, line := range lines {\n\n\t\tif i != 0 {\n\n\t\t\tname := line[0]\n\t\t\tzipcode := line[1]\n\t\t\twebsite := \"\"\n\n\t\t\tif len(line) > 2 {\n\t\t\t\twebsite = line[2]\n\t\t\t}\n\n\t\t\tcompany := models.Company{\n\t\t\t\tName: name,\n\t\t\t\tZipcode: zipcode,\n\t\t\t\tWebsite: website,\n\t\t\t}\n\n\t\t\tif companiesFinded, err := db.FindCompany(xormEngine, 0, name, \"\", false, 1); len(companiesFinded) > 0 && err == nil {\n\t\t\t\tcompany.ID = companiesFinded[0].ID\n\t\t\t\tcompany.Version = companiesFinded[0].Version\n\t\t\t\tdb.UpdateCompanyByID(xormEngine, company.ID, company)\n\t\t\t} else {\n\t\t\t\tdb.InsertCompany(xormEngine, company)\n\t\t\t}\n\t\t}\n\n\t}\n}", "func Company_get_multiple_by_project () {\n\n // GET /projects/{project_id}/companies.json\n\n }", "func updateCovidData() {\n\tlog.Instance.Debug(\"updateCovidData is hit\")\n\tlog.Instance.Info(\"State cron job periodic call, updating data of all states\")\n\n\tvar covidStatesData []schema.TCovidState\n\n\tallStatesData, allStatesDataErr := services.GetAllStateCovidDataGovtApi()\n\tif allStatesDataErr.Err != nil {\n\t\tlog.Instance.Err(\"Error while fetching all states data from 3rd party API, err: %v\", allStatesDataErr.Message())\n\t\treturn\n\t}\n\n\tjson.Unmarshal(allStatesData, &covidStatesData)\n\n\tmongoDriverInstance, mongoDriverInstanceErr := drivers.GetMongoDriver()\n\tif mongoDriverInstanceErr != nil {\n\t\treturn\n\t}\n\n\tfor i := 0; i < len(covidStatesData); i++ {\n\t\tgo updateStateData(&covidStatesData[i], mongoDriverInstance)\n\t}\n}", "func (s *Syncable) Sync(ctx context.Context, entry *types.AcceptedProposal) error {\n\tbytes := []byte(entry.Data)\n\tvar jsonData interface{}\n\tjson.Marshal(string(bytes))\n\terr := json.Unmarshal(bytes, &jsonData)\n\tif err != nil {\n\t\tlog.Printf(\"Error Unmarshalling json: %v\", err)\n\t\treturn err\n\t}\n\n\tvar values []interface{}\n\tfor _, path := range s.insert.jsonPath {\n\t\tres, err := jsonpath.JsonPathLookup(jsonData, path)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error while parsing [%v] in [%v]: %v\\n\", path, jsonData, err)\n\t\t\treturn err\n\t\t}\n\t\tvalues = append(values, res)\n\t}\n\n\ttx, err := s.DB.BeginTx(context.Background(), &sql.TxOptions{Isolation: 0, ReadOnly: false})\n\n\tif err != nil {\n\t\tlog.Printf(\"Error while creating transaction: %v\", err)\n\t\treturn err\n\t}\n\t_, err = tx.Stmt(s.insert.stmt).ExecContext(ctx, values...)\n\tif err != nil {\n\t\tlog.Printf(\"Error while executing statement: %v\", err)\n\t\treturn err\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Printf(\"Error while executing commit: %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (g *Gateway) Sync() {\n\tg.lock.RLock()\n\tdefer g.lock.RUnlock()\n\n\tif g.server == nil || g.info.Role != db.RaftVoter {\n\t\treturn\n\t}\n\n\tclient, err := g.getClient()\n\tif err != nil {\n\t\tlogger.Warnf(\"Failed to get client: %v\", err)\n\t\treturn\n\t}\n\n\tdefer func() { _ = client.Close() }()\n\n\tfiles, err := client.Dump(context.Background(), \"db.bin\")\n\tif err != nil {\n\t\t// Just log a warning, since this is not fatal.\n\t\tlogger.Warnf(\"Failed get database dump: %v\", err)\n\t\treturn\n\t}\n\n\tdir := filepath.Join(g.db.Dir(), \"global\")\n\tfor _, file := range files {\n\t\tpath := filepath.Join(dir, file.Name)\n\t\terr := os.WriteFile(path, file.Data, 0600)\n\t\tif err != nil {\n\t\t\tlogger.Warnf(\"Failed to dump database file %s: %v\", file.Name, err)\n\t\t}\n\t}\n}", "func PutBatch(db *dynamo.DB, c []CompanyRaw) error {\n\tbw := db.Table(\"Test\").Batch(\"CompanyId\").Write().Put(c)\n\t_, err := bw.Run()\n\treturn err\n}", "func Company_get() {\n\n // GET /companies/{company_id}.json\n\n }", "func (cpr *CompanyGormRepositoryImpl) UpdateCompany(cmp *entity.Company) (*entity.Company, error) {\n\tcompany := cmp\n\terrs := cpr.conn.Save(&company).GetErrors()\n\tif len(errs) > 0 {\n\t\treturn company, errs[0]\n\t}\n\treturn company, nil\n}", "func (c *Contractor) saveSync() error {\n\treturn c.persist.saveSync(c.persistData())\n}", "func (v *Deputy) GetCompanies(token string) (Companies, error) {\n\tclient := &http.Client{}\n\tclient.CheckRedirect = checkRedirectFunc\n\n\tu, _ := url.ParseRequestURI(\"https://\" + v.EndPoint + \"/\")\n\tu.Path = \"api/v1/resource/Company/\"\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\tfmt.Println(\"rawResBody\", string(rawResBody))\n\n\tif res.StatusCode == 200 {\n\t\tvar resp Companies\n\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 Deputy Company %s\", res.Status)\n\n}", "func (cl ContactList) SaveContacts() {\n\toutput, _ := json.Marshal(cl.directory)\n\terr := ioutil.WriteFile(\"contacts.json\", output, 0755)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func Sync(cmd *cobra.Command, args []string) {\n\n\tfdbURL, err := cmd.Flags().GetString(\"doclayer-url\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfDB, err := cmd.Flags().GetString(\"doclayer-database\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdebug, err := cmd.Flags().GetBool(\"debug\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif debug {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\n\tlog.Debugf(\"Creating client for FDB: %v, %v, %v\", fdbURL, fDB, debug)\n\tclientOptions := options.Client().ApplyURI(fdbURL).SetMinPoolSize(10).SetMaxPoolSize(100)\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tclient, err := NewDocLayerClient(ctx, clientOptions)\n\tif err != nil {\n\t\tlog.Fatalf(\"Can't create client for FoundationDB document layer: %v. URL provided was: %v\", err, fdbURL)\n\t\treturn\n\t}\n\n\tlog.Debugf(\"Client created.\")\n\n\tstartTime := time.Now()\n\t//Close db client after serving request\n\tvar clientKeepAlive = false\n\tauthorizationHeader := os.Getenv(\"AUTHORIZATION_HEADER\")\n\tif err = SyncRepo(client, fDB, args[0], args[1], authorizationHeader, clientKeepAlive); err != nil {\n\t\tlog.Fatalf(\"Can't add chart repository to database: %v\", err)\n\t\treturn\n\t}\n\ttimeTaken := time.Since(startTime).Seconds()\n\tlog.Infof(\"Successfully added the chart repository %s to database in %v seconds\", args[0], timeTaken)\n}", "func (company *Company) Delete() error {\n\tif company.IsDraft {\n\t\tdraftIndex := company.Creator().DraftIndex()\n\t\tdraftIndex.CompanyID = \"\"\n\t\tdraftIndex.Save()\n\t}\n\n\t// Remove company ID from all anime\n\tfor anime := range StreamAnime() {\n\t\tfor index, id := range anime.StudioIDs {\n\t\t\tif id == company.ID {\n\t\t\t\tanime.StudioIDs = append(anime.StudioIDs[:index], anime.StudioIDs[index+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tfor index, id := range anime.ProducerIDs {\n\t\t\tif id == company.ID {\n\t\t\t\tanime.ProducerIDs = append(anime.ProducerIDs[:index], anime.ProducerIDs[index+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tfor index, id := range anime.LicensorIDs {\n\t\t\tif id == company.ID {\n\t\t\t\tanime.LicensorIDs = append(anime.LicensorIDs[:index], anime.LicensorIDs[index+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tDB.Delete(\"Company\", company.ID)\n\treturn nil\n}", "func syncRepos(c *gin.Context) {\n\to := c.Param(\"org\")\n\tif strings.Contains(o, \"not-found\") {\n\t\tmsg := fmt.Sprintf(\"Repo %s does not exist\", o)\n\n\t\tc.AbortWithStatusJSON(http.StatusNotFound, types.Error{Message: &msg})\n\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, fmt.Sprintf(\"Org %s repos have been synced\", o))\n}", "func (s *Syncer) Sync(localObjects []uploader.Object, saveRoot string) error {\n\tremoteObjects, err := s.uploader.ListObjects(saveRoot)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"find %d local objects\", len(localObjects))\n\tlog.Printf(\"find %d remote objects\", len(remoteObjects))\n\tlog.Printf(\"compare the local files and the remote objects...\")\n\ts.compareObjects(localObjects, remoteObjects)\n\n\tlog.Printf(\"found %d files to be uploaded, uploading...\", len(s.tobeUploadedObjects))\n\tfor _, obj := range s.tobeUploadedObjects {\n\t\tlog.Printf(\"[%s] %s => %s\", obj.Type, obj.FilePath, obj.Key)\n\t\tif err := s.uploader.Upload(obj.Key, obj.FilePath); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Printf(\"found %d files to be deleted, cleaning...\", len(s.tobeDeletedObjects))\n\tfor _, obj := range s.tobeDeletedObjects {\n\t\tlog.Printf(\"[deleted] %s\", obj.Key)\n\t\tif err := s.uploader.Delete(obj.Key); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Printf(\"files sync done.\")\n\treturn nil\n}", "func (rb Rebuild) UploadDataSources() error {\n\tdb := rb.NewDbGorm()\n\tdefer db.Close()\n\tlog.Println(\"Populating data_sources table\")\n\tds, err := rb.loadDataSources()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, v := range ds {\n\t\tdb.Create(&v)\n\t}\n\treturn nil\n}", "func (d UserData) SetCompany(value m.CompanySet) m.UserData {\n\td.ModelData.Set(models.NewFieldName(\"Company\", \"company_id\"), value)\n\treturn d\n}", "func (ct *CompanyTestSuite) TestUpdateByNonAdmin(c *C) {\n\ttoken := getTestDefaultAuthToken()\n\n\t// create new another company\n\tcompanyName := fmt.Sprintf(\"companyName_%v\", time.Now().UnixNano())\n\n\tcompany, err := createTestCompany(companyName, token)\n\tc.Assert(err, IsNil)\n\n\temail := fmt.Sprintf(\"test_%[email protected]\", time.Now().UnixNano())\n\t_, err = createTestUser(email, token, \"\", false)\n\tcreatedUserToken := getTestLoginToken(fmt.Sprintf(`{\"email\":\"%s\", \"password\": \"12345\"}`, email))\n\n\t// try to update company\n\tcompanyTxt, _ := json.Marshal(company)\n\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"http://127.0.0.1:8080/v1/company/%v\", company.Id), bytes.NewReader(companyTxt))\n\tc.Assert(err, IsNil)\n\n\treq.Header.Add(\"Authorization\", createdUserToken)\n\n\tclient := server.GetHTTPClient()\n\tresp, err := client.Do(req)\n\tdefer resp.Body.Close()\n\tc.Assert(err, IsNil)\n\n\tidResp := server.NewIDResponse()\n\terr = jsonpb.Unmarshal(resp.Body, idResp)\n\tc.Assert(err, IsNil)\n\tc.Assert(idResp.Meta.StatusCode, Equals, HttpStatusForbidden)\n}", "func UpdateCSVContacts(db *sql.DB) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tfile, _, err := r.FormFile(\"contacts\")\n\t\tnewFile, _ := ioutil.ReadAll(file)\n\t\ttempFile, _ := ioutil.TempFile(\"\", \"contacts\")\n\t\tif err != nil {\n\t\t\trespond.With(w, r, http.StatusBadRequest, nil, err)\n\t\t\treturn\n\t\t}\n\n\t\tif err = ioutil.WriteFile(tempFile.Name(), newFile, 0644); err != nil {\n\t\t\trespond.With(w, r, http.StatusBadRequest, nil, err)\n\t\t\treturn\n\t\t}\n\t\tquery := fmt.Sprintf(\"COPY contacts_imports FROM '%s' DELIMITER ',' CSV HEADER;\", tempFile.Name())\n\n\t\ttempTable := `DROP TABLE IF EXISTS contacts_imports; CREATE TEMP TABLE contacts_imports\n\t\t\t\t(\n\t\t\t\tid VARCHAR(64),\n\t\t\t\tfirst_name VARCHAR(50),\n\t\t\t\tlast_name VARCHAR(50),\n\t\t\t\temail VARCHAR(50),\n\t\t\t\tphone VARCHAR(50)\n\t\t\t\t);`\n\t\tif _, err := db.Exec(tempTable); err != nil {\n\t\t\trespond.With(w, r, http.StatusBadRequest, nil, err)\n\t\t\treturn\n\t\t}\n\t\tif _, err := db.Exec(query); err != nil {\n\t\t\trespond.With(w, r, http.StatusBadRequest, nil, err)\n\t\t\treturn\n\t\t}\n\n\t\tif _, err := db.Exec(`insert into contacts(id, first_name, last_name, email, phone)\n\t\t\tselect id, first_name, last_name, email, phone\n\t\t\tfrom contacts_imports\n\t\t\ton conflict(id) do update set\n \t\tfirst_name = EXCLUDED.first_name,\n \t\tlast_name = EXCLUDED.last_name,\n \t\temail = EXCLUDED.email,\n \t\tphone = EXCLUDED.phone;\n\t\t\t`); err != nil {\n\t\t\trespond.With(w, r, http.StatusBadRequest, nil, err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func main() {\n\tdb, err := sqlx.Connect(\"mysql\", user+\":\"+password+\"@/\"+dbname+\"?charset=\"+charset)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(\"connected\")\n\tdefer db.Close()\n\n\turlCity := \"https://myfave.com/api/mobile/cities\"\n\n\tspaceClient := http.Client{\n\t\tTimeout: time.Second * 2, // Maximum of 2 secs\n\t}\n\n\treq, err := http.NewRequest(http.MethodGet, urlCity, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treq.Header.Set(\"User-Agent\", \"fave-testcoding\")\n\n\tres, getErr := spaceClient.Do(req)\n\tif getErr != nil {\n\t\tlog.Fatal(getErr)\n\t}\n\n\tbody, readErr := ioutil.ReadAll(res.Body)\n\tif readErr != nil {\n\t\tlog.Fatal(readErr)\n\t}\n\n\tvar cities []extract.Cities\n\n\tjson.Unmarshal([]byte(body), &cities)\n\tfor _, city := range cities {\n\t\tsqlStatement := `\n\t\tINSERT INTO city (country, currency, city_id, lat, lon, city_name, slug)\n\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?)`\n\n\t\tdb.MustExec(sqlStatement, city.Country, city.Currency, city.ID, city.Lat, city.Lng, city.Name, city.Slug)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n}", "func UpdateCompanyBranchHyCompanybranchOKIdname(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) (http.ResponseWriter, *app.CompanyIdname) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil, nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected parameter validation error: %+v\", _e)\n\t\treturn nil, nil\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 200 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 200\", rw.Code)\n\t}\n\tvar mt *app.CompanyIdname\n\tif resp != nil {\n\t\tvar __ok bool\n\t\tmt, __ok = resp.(*app.CompanyIdname)\n\t\tif !__ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of app.CompanyIdname\", resp, resp)\n\t\t}\n\t\t__err = mt.Validate()\n\t\tif __err != nil {\n\t\t\tt.Errorf(\"invalid response media type: %s\", __err)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func (dao CompanyDAOPsql) Delete(obj *models.Company) error {\n\tquery := \"DELETE FROM companies WHERE id = $1\"\n\tdb := get()\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(query)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer stmt.Close()\n\n\tresult, err := stmt.Exec(obj.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif rowsAffected, _ := result.RowsAffected(); rowsAffected == 0 {\n\t\t\treturn errors.New(\"No se eliminó ningún registro\")\n\t}\n\tobj = new(models.Company)\n\treturn nil\n}", "func (o *BudgetProjectBudgetsResponseIncluded) SetCompanies(v map[string]ViewCompany) {\n\to.Companies = &v\n}", "func (d UserData) Companies() m.CompanySet {\n\tval := d.ModelData.Get(models.NewFieldName(\"Companies\", \"company_ids\"))\n\tif !d.Has(models.NewFieldName(\"Companies\", \"company_ids\")) || val == nil || val == (*interface{})(nil) {\n\t\tval = models.InvalidRecordCollection(\"Company\")\n\t}\n\treturn val.(models.RecordSet).Collection().Wrap().(m.CompanySet)\n}", "func (uc *Userclient) Sync() error {\r\n\treturn uc.iSync()\r\n}", "func (db *DB) Sync() error { return fdatasync(db) }", "func (d UserData) Company() m.CompanySet {\n\tval := d.ModelData.Get(models.NewFieldName(\"Company\", \"company_id\"))\n\tif !d.Has(models.NewFieldName(\"Company\", \"company_id\")) || val == nil || val == (*interface{})(nil) {\n\t\tval = models.InvalidRecordCollection(\"Company\")\n\t}\n\treturn val.(models.RecordSet).Collection().Wrap().(m.CompanySet)\n}", "func (s *grpcServer) LocalUpdateCompany(ctx context.Context, req *pb.UpdateJobCompanyRequest) (*pb.JobCompany, error) {\n\t_, rep, err := s.localUpdateCompany.ServeGRPC(ctx, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rep.(*pb.JobCompany), nil\n}", "func (s *grpcServer) GetAllCompanies(ctx context.Context, req *pb.GetAllJobCompaniesRequest) (*pb.GetAllJobCompaniesResponse, error) {\n\t_, rep, err := s.getAllCompanies.ServeGRPC(ctx, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rep.(*pb.GetAllJobCompaniesResponse), nil\n}", "func (s *Store) SetCompany(stu string, c schema.Company) error {\n\treturn s.singleUpdate(updateCompany, schema.ErrUnknownInternship, c.WWW, c.Name, c.Title, stu)\n}", "func (db *DB) Sync() error {\n\t// 刷到 DB\n\treturn fdatasync(db)\n}", "func (mp *SQLProvider) performFirstSync(sync func(string, string)) error {\n\tperPage := mp.perPage\n\ttables, err := getAllTables(mp.db, mp.dbName)\n\tif err != nil {\n\t\tlog.Printf(\"unable to get dataBases. Error: %+v\", err.Error())\n\t\treturn err\n\t}\n\n\tfor _, table := range tables {\n\n\t\tif table == meta_changelog_table || table == meta_data_table || contains(mp.excludedTables, table) {\n\t\t\tcontinue\n\t\t}\n\n\t\tprimaryKeysList, err := getAllPrimaryKeysInTable(mp.db, table)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tprimaryKeysCSV := strings.Join(primaryKeysList, \",\")\n\n\t\tcountRow := mp.db.QueryRow(\"select count(*) from \" + table)\n\n\t\tvar count int\n\t\terr = countRow.Scan(&count)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tpages := count / perPage\n\t\tfor i := 0; i < pages; i++ {\n\t\t\tstartInt := i * perPage\n\t\t\tstart := strconv.Itoa(startInt)\n\t\t\tend := strconv.Itoa(startInt + perPage)\n\n\t\t\tquery := fmt.Sprintf(`SELECT * FROM (\n \t\t\t\tSELECT *, ROW_NUMBER() OVER (ORDER BY %[4]s) as row FROM %[1]s\n \t\t\t\t\t) a WHERE row > %[2]s and row <= %[3]s`, table, start, end, primaryKeysCSV)\n\n\t\t\ttableJSON, err := getJSON(mp.db, query)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"unable to convert table data to json. Error: %+v\", err)\n\t\t\t}\n\t\t\tsync(tableJSON, table)\n\t\t}\n\t}\n\treturn nil\n}", "func toSyncData(cache *model.Cache, schemas []*scpb.Schema) (data *pb.SyncData) {\n\tdata = &pb.SyncData{\n\t\tServices: make([]*pb.SyncService, 0, len(cache.Microservices)),\n\t\tInstances: make([]*pb.SyncInstance, 0, len(cache.Instances)),\n\t}\n\n\tfor _, service := range cache.Microservices {\n\t\tdomain, project := getDomainProjectFromServiceKey(service.Key)\n\t\tif domain == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tsyncService := toSyncService(service.Value)\n\t\tsyncService.DomainProject = domain + \"/\" + project\n\t\tsyncService.Expansions = append(syncService.Expansions, schemaExpansions(service.Value, schemas)...)\n\n\t\tsyncInstances := toSyncInstances(syncService.ServiceId, cache.Instances)\n\t\tif len(syncInstances) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdata.Services = append(data.Services, syncService)\n\t\tdata.Instances = append(data.Instances, syncInstances...)\n\t}\n\treturn\n}", "func (a *ApiDB) DeleteAllContract(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\ttype arrcontractId struct {\n\t\tContractsId []int `json:\"contractsId\"`\n\t}\n\tp := arrcontractId{}\n\terr := json.NewDecoder(r.Body).Decode(&p)\n\tif err != nil {\n\t\tio.WriteString(w, `{\"message\": \"wrong format!\"}`)\n\t\treturn\n\t}\n\n\tres, _ := BUSINESS.DeleteAllContract(a.Db, p.ContractsId)\n\n\tif res {\n\t\tio.WriteString(w, `{\n\t\t\t\t\t\t\"status\": 200,\n\t\t\t\t\t\t\"message\": \"Delete contract success\",\n\t\t\t\t\t\t\"data\": {\n\t\t\t\t\t\t\t\"status\": 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}`)\n\t\treturn\n\t}\n\tio.WriteString(w, `{\"message\" : \"Can’t delete contract\"}`)\n}", "func GenerateCompanyInformation() []Company {\n\n\tvar listOfTop10BlueChipCompanies []Company\n\n\t//Get the latest stock price\n\tstockPrice := generateLatestStockPrice()\n\n\t//#1 DBS Group Holdings Ltd\n\n\tvar dbs Company\n\tdbs.companyName = \"DBS Group Holdings Ltd\"\n\tdbs.companyCurrentStockPrice = stockPrice[0]\n\tdbs.companyFinancialResults = append(dbs.companyFinancialResults, FinancialResults{2018, 2559460000, 13183000000, 5653000000, 1.20, 49045000000})\n\n\tlistOfTop10BlueChipCompanies = append(listOfTop10BlueChipCompanies, dbs)\n\n\t//#2 Oversea-Chinese Banking Corporation Limited\n\n\tvar ocbc Company\n\tocbc.companyName = \"Oversea-Chinese Banking Corporation Limited\"\n\tocbc.companyCurrentStockPrice = stockPrice[1]\n\tocbc.companyFinancialResults = append(ocbc.companyFinancialResults, FinancialResults{2018, 4211140000, 9701901000, 4675226000, 0.43, 42136870000})\n\n\tlistOfTop10BlueChipCompanies = append(listOfTop10BlueChipCompanies, ocbc)\n\n\t//#3 United Overseas Bank Limited (Singapore)\n\n\tvar uob Company\n\tuob.companyName = \"United Overseas Bank Limited (Singapore)\"\n\tuob.companyCurrentStockPrice = stockPrice[2]\n\tuob.companyFinancialResults = append(uob.companyFinancialResults, FinancialResults{2018, 1671350000, 9116000000, 4008000000, 1.20, 37812792000})\n\n\tlistOfTop10BlueChipCompanies = append(listOfTop10BlueChipCompanies, uob)\n\n\t//#4 Singapore Telecommunications Limited\n\n\tvar singtel Company\n\tsingtel.companyName = \"Singapore Telecommunications Limited\"\n\tsingtel.companyCurrentStockPrice = stockPrice[3]\n\tsingtel.companyFinancialResults = append(singtel.companyFinancialResults, FinancialResults{2018, 16344330000, 17531800000, 5430300000, 0.175, 29256800000})\n\n\tlistOfTop10BlueChipCompanies = append(listOfTop10BlueChipCompanies, singtel)\n\n\t//#5 Jardine Matheson Holdings Limited\n\n\tvar Jardine1 Company\n\tJardine1.companyName = \"Jardine Matheson Holdings Limited\"\n\tJardine1.companyCurrentStockPrice = stockPrice[4]\n\tJardine1.companyFinancialResults = append(Jardine1.companyFinancialResults, FinancialResults{2018, 376000000, 58661744452.44, 6211438269.08, 2.34, 36336549669.29})\n\n\tlistOfTop10BlueChipCompanies = append(listOfTop10BlueChipCompanies, Jardine1)\n\n\t//#6 Hongkong Land Holdings Limited\n\n\tvar hongkong Company\n\thongkong.companyName = \"Hongkong Land Holdings Limited\"\n\thongkong.companyCurrentStockPrice = stockPrice[5]\n\thongkong.companyFinancialResults = append(hongkong.companyFinancialResults, FinancialResults{2018, 2341800000, 3676692714.62, 3389360572.18, 30.35, 52888150135.53})\n\n\tlistOfTop10BlueChipCompanies = append(listOfTop10BlueChipCompanies, hongkong)\n\n\t//#7 Keppel Corporation Limited\n\n\tvar keppel Company\n\tkeppel.companyName = \"Keppel Corporation Limited\"\n\tkeppel.companyCurrentStockPrice = stockPrice[6]\n\tkeppel.companyFinancialResults = append(keppel.companyFinancialResults, FinancialResults{2018, 1824890000, 5964780000, 943830000, 0.30, 11278210000})\n\n\tlistOfTop10BlueChipCompanies = append(listOfTop10BlueChipCompanies, keppel)\n\n\t//#8 Jardine Strategic Holdings Limited\n\n\tvar Jardine2 Company\n\tJardine2.companyName = \"Jardine Strategic Holdings Limited\"\n\tJardine2.companyCurrentStockPrice = stockPrice[7]\n\tJardine2.companyFinancialResults = append(Jardine2.companyFinancialResults, FinancialResults{2018, 1108000000, 47029774672.56, 5994937546.99, 0.47, 43480539903.03})\n\n\tlistOfTop10BlueChipCompanies = append(listOfTop10BlueChipCompanies, Jardine2)\n\n\t//#9 Global Logistic Properties Limited\n\n\tvar global Company\n\tglobal.companyName = \" Global Logistic Properties Limited\"\n\tglobal.companyCurrentStockPrice = stockPrice[8]\n\tglobal.companyFinancialResults = append(global.companyFinancialResults, FinancialResults{})\n\n\tlistOfTop10BlueChipCompanies = append(listOfTop10BlueChipCompanies, global)\n\n\t//#10 Thai Beverage Public Company Limited\n\n\tvar thai Company\n\tthai.companyName = \"Thai Beverage Public Company Limited\"\n\tthai.companyCurrentStockPrice = stockPrice[9]\n\tthai.companyFinancialResults = append(thai.companyFinancialResults, FinancialResults{2018, 25116000000, 9906040555.35, 799129222.74, 0.017, 5217106430.45})\n\n\tlistOfTop10BlueChipCompanies = append(listOfTop10BlueChipCompanies, thai)\n\n\treturn listOfTop10BlueChipCompanies\n\n}", "func (c *Company) Insert() error {\n\tresult := initdb.DbInstance.Create(c)\n\tlog.Println(\"Created -> \", result)\n\treturn result.Error\n}", "func (s *grpcServer) UpdateCompany(ctx context.Context, req *pb.UpdateJobCompanyRequest) (*pb.JobCompany, error) {\n\t_, rep, err := s.updateCompany.ServeGRPC(ctx, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rep.(*pb.JobCompany), nil\n}", "func main() {\n\n\tdb, err := gorm.Open(\"mysql\", \"root:root@tcp(127.0.0.1:3377)/Company?charset=utf8&parseTime=True\")\n\tfmt.Println(\"db:\", db)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t} else {\n\t\tfmt.Println(\"Database connection established\")\n\t}\n\n\t//Empty table Employee creation.\n\tdb.AutoMigrate(&Employee{})\n\n\t//Employee table row insert if row does not exist\n\temp := Employee{FirstName: \"Jacob\", DeptId: 202}\n\tres := db.FirstOrCreate(&emp)\n\tif res.Error != nil {\n\t\tfmt.Println(\"Error while creating the employee\")\n\t} else {\n\t\tfmt.Println(\"Successfully created the employee\")\n\t}\n\n\t//Searching for Jacob and\n\tupdatedEmpOnName := Employee{FirstName: \"George\", DeptId: 302}\n\tres = db.Model(&Employee{}).Where(Employee{FirstName: \"Jacob\"}).Update(&updatedEmpOnName)\n\tif res.Error != nil {\n\t\tfmt.Println(\"Error while updating the employee based on FirstName\")\n\t} else {\n\t\tfmt.Println(\"Successfully updated the employee based on FirstName\")\n\t}\n\n\tupdateEmpOnDeptId := Employee{FirstName: \"John\", DeptId: 402}\n\tres = db.Model(&Employee{}).Where(Employee{DeptId: 302}).Update(&updateEmpOnDeptId)\n\tif res.Error != nil {\n\t\tfmt.Println(\"Error while updating the employee based on DeptId\")\n\t} else {\n\t\tfmt.Println(\"Successfully updated the employee based on DeptId\")\n\t}\n\n\t//delete employee based on FirstName - deleted_at gets updated.\n\tvar rowsToDelete int\n\tres = db.Model(&Employee{}).Where(Employee{FirstName: \"John\"}).Count(&rowsToDelete)\n\tif rowsToDelete > 0 {\n\t\tres = db.Model(&Employee{}).Where(Employee{FirstName: \"John\"}).Delete(emp)\n\t\tif res.Error != nil {\n\t\t\tfmt.Println(\"Error while deleting the employee\")\n\t\t} else {\n\t\t\tfmt.Println(\"Successfully deleted the employee\")\n\t\t}\n\t}\n\n\t//HardDelete employee based on FirstName\n\tres = db.Model(&Employee{}).Where(Employee{FirstName: \"George\"}).Unscoped().Delete(emp)\n\tif res.Error != nil {\n\t\tfmt.Println(\"Error while hard deleting the employee\")\n\t} else {\n\t\tfmt.Println(\"Successfully hard deleted the employee\")\n\t}\n}", "func (r *Remote) SyncBranches(branchName string) error {\n\tif err := r.switchRemoteBranch(r.Name + \"/\" + branchName); err != nil {\n\t\t// probably couldn't find, but its ok.\n\t}\n\treturn nil\n}", "func (db *DB) SyncFromMing(serverURL, company, user, password string) error {\n\t// New a session\n\ts, err := ming800.NewSession(serverURL, company, user, password)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewSession() error: %v\", err)\n\t}\n\n\t// Login\n\tif err = s.Login(); err != nil {\n\t\treturn fmt.Errorf(\"Login() error: %v\", err)\n\t}\n\n\t// Clear all data before sync.\n\tif err = db.Clear(); err != nil {\n\t\treturn err\n\t}\n\n\t// Walk\n\t// Write your own class and student handler functions.\n\t// Class and student handler will be called while walking ming800.\n\tif err = s.Walk(db); err != nil {\n\t\treturn fmt.Errorf(\"Walk() error: %v\", err)\n\t}\n\n\t// Logout\n\tif err = s.Logout(); err != nil {\n\t\treturn fmt.Errorf(\"Logout() error: %v\", err)\n\t}\n\n\treturn nil\n}", "func (cpr *CompanyGormRepositoryImpl) StoreCompany(cmp *entity.Company) (*entity.Company, error) {\n\tcompany := cmp\n\terrs := cpr.conn.Create(&company).GetErrors()\n\tif len(errs) > 0 {\n\t\treturn company, errs[0]\n\t}\n\treturn company, nil\n}", "func (s UserSet) SetCompany(value m.CompanySet) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Company\", \"company_id\"), value)\n}", "func (cpr *CompanyGormRepositoryImpl) Companies() ([]entity.Company, error) {\n\tvar companies []entity.Company\n\terrs := cpr.conn.Find(&companies).GetErrors()\n\tif len(errs) > 0 {\n\t\treturn companies, errs[0]\n\t}\n\treturn companies, nil\n}", "func (api *bucketAPI) SyncDelete(obj *objstore.Bucket) error {\n\tvar writeErr error\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, writeErr = apicl.ObjstoreV1().Bucket().Delete(context.Background(), &obj.ObjectMeta)\n\t}\n\n\tif writeErr == nil {\n\t\tapi.ct.handleBucketEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\t}\n\n\treturn writeErr\n}", "func All( w http.ResponseWriter, r *http.Request ,basic_name string ,copy_file string ,new_file string )( err error) {\n\n// IN w   : response-writer\n// IN r   : request-parameter\n// IN basic_name : d.s. name of basic\n// IN copy_file : d.s. name which is cpied\n// IN new_file : new d.s. name\n\n// OUT err : error inf.\n\n// fmt.Fprintf( w, \"copy3.all start \\n\" )\n// fmt.Fprintf( w, \"copy3.all basic_name %v\\n\" ,basic_name)\n\n c := appengine.NewContext(r)\n\n\tq := datastore.NewQuery(copy_file)\n\n\tcount, err := q.Count(c)\n\tif err != nil {\n//\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn err\n\n\t}\n // allocate work area for records\n ds_data := make([]type2.Deliver, 0, count)\n\n\tif _, err := q.GetAll(c, &ds_data); err != nil { // get d.s. inf.\n\n//\t http.Error(w, err.Error(), http.StatusInternalServerError)\n\t return err\n\n\t} else{\n for _, ds_dataw := range ds_data { // put copy inf. for d.s.\n\n\t if _, err := datastore.Put(c, datastore.NewIncompleteKey(c, new_file, nil), &ds_dataw); err != nil {\n\n//\t\t http.Error(w,err.Error(), http.StatusInternalServerError)\n\t\t return err\n\n\t }\n\n\t }\n\t}\n\n//\tfmt.Fprintf( w, \"copy3.all normal end \\n\" )\n\n return nil\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 StartAddDataForProjects() {\n\tvar projects []Project\n\tdata, err := ioutil.ReadFile(\"../dump_data/projects.json\")\n\tcheckErr(err)\n\terr = json.Unmarshal(data, &projects)\n\tcheckErr(err)\n\tfmt.Println(\"data extracted from file\")\n\tfmt.Println(\"# Inserting values\")\n\tvar lastInsertID int\n\tfor _, value := range projects {\n\t\terr := DB.QueryRow(\"INSERT INTO projects(name,created_by) VALUES($1,$2) returning id;\", value.Name, value.CreatedBy).Scan(&lastInsertID)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(\"last inserted id =\", lastInsertID)\n\t}\n\n}", "func (a *Client) SharedCatalogCompanyManagementV1UnassignCompaniesPost(params *SharedCatalogCompanyManagementV1UnassignCompaniesPostParams) (*SharedCatalogCompanyManagementV1UnassignCompaniesPostOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewSharedCatalogCompanyManagementV1UnassignCompaniesPostParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"sharedCatalogCompanyManagementV1UnassignCompaniesPost\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/V1/sharedCatalog/{sharedCatalogId}/unassignCompanies\",\n\t\tProducesMediaTypes: []string{\"\"},\n\t\tConsumesMediaTypes: []string{\"\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &SharedCatalogCompanyManagementV1UnassignCompaniesPostReader{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.(*SharedCatalogCompanyManagementV1UnassignCompaniesPostOK), nil\n\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 (ct *CompanyTestSuite) TestDelete(c *C) {\n\ttoken := getTestDefaultAuthToken()\n\n\t// create new another company\n\tcompanyName := fmt.Sprintf(\"companyName_%v\", time.Now().UnixNano())\n\n\tcompany, err := createTestCompany(companyName, token)\n\tc.Assert(err, IsNil)\n\n\t// try to remove company\n\treq, err := http.NewRequest(\"DELETE\", fmt.Sprintf(\"http://127.0.0.1:8080/v1/company/%v\", company.Id), nil)\n\tc.Assert(err, IsNil)\n\n\treq.Header.Add(\"Authorization\", token)\n\n\tclient := server.GetHTTPClient()\n\n\tresp, err := client.Do(req)\n\tdefer resp.Body.Close()\n\tc.Assert(err, IsNil)\n\n\tmess := server.NewCommonResponse()\n\terr = jsonpb.Unmarshal(resp.Body, mess)\n\tc.Assert(err, IsNil)\n\n\tc.Assert(mess.Meta.StatusCode, Equals, HttpStatusOK)\n\tc.Assert(mess.Meta.Ok, Equals, true)\n\tc.Assert(mess.Meta.Error, Equals, \"\")\n\n\t// try get removed company\n\treq, err = http.NewRequest(\"GET\", fmt.Sprintf(\"http://127.0.0.1:8080/v1/company/%v\", company.Id), nil)\n\tc.Assert(err, IsNil)\n\n\treq.Header.Add(\"Authorization\", token)\n\n\tresp, err = client.Do(req)\n\tdefer resp.Body.Close()\n\tc.Assert(err, IsNil)\n\n\tcompanyResponse := server.NewCompanyResponse()\n\terr = jsonpb.Unmarshal(resp.Body, companyResponse)\n\tc.Assert(err, IsNil)\n\tc.Assert(companyResponse.Meta.StatusCode, Equals, HttpStatusNotFound)\n\n\t// try get removed company\n\treq, err = http.NewRequest(\"GET\", fmt.Sprintf(\"http://127.0.0.1:8080/v1/company\"), nil)\n\tc.Assert(err, IsNil)\n\n\treq.Header.Add(\"Authorization\", token)\n\n\tresp, err = client.Do(req)\n\tdefer resp.Body.Close()\n\tc.Assert(err, IsNil)\n\n\tcompanyListResponse := server.NewCompanyListResponse()\n\terr = jsonpb.Unmarshal(resp.Body, companyListResponse)\n\tc.Assert(err, IsNil)\n\n\tc.Assert(companyListResponse.Meta.StatusCode, Equals, HttpStatusOK)\n\n\tisFound := false\n\tfor _, comp := range companyListResponse.Data {\n\t\tif comp.Id == company.Id {\n\t\t\tisFound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tc.Assert(isFound, Equals, false)\n}", "func (a *Client) SharedCatalogCompanyManagementV1AssignCompaniesPost(params *SharedCatalogCompanyManagementV1AssignCompaniesPostParams) (*SharedCatalogCompanyManagementV1AssignCompaniesPostOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewSharedCatalogCompanyManagementV1AssignCompaniesPostParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"sharedCatalogCompanyManagementV1AssignCompaniesPost\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/V1/sharedCatalog/{sharedCatalogId}/assignCompanies\",\n\t\tProducesMediaTypes: []string{\"\"},\n\t\tConsumesMediaTypes: []string{\"\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &SharedCatalogCompanyManagementV1AssignCompaniesPostReader{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.(*SharedCatalogCompanyManagementV1AssignCompaniesPostOK), nil\n\n}", "func (s UserSet) CheckCompany() {\n\ts.Collection().Call(\"CheckCompany\")\n}", "func (r Repository) InsertTHalls(townhalls TownHalls) error {\n\tsession, err := noSslConnect()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer session.Close()\n\tlog.Println(\"Inserting new record of Cities..\")\n\tfor _, key := range []string{\"comunity\"} {\n\t\tindex := mgo.Index{\n\t\t\tKey: []string{key},\n\t\t\tUnique: true,\n\t\t}\n\t\tif err := session.DB(DBNAME).C(APIKCOLL).EnsureIndex(index); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = session.DB(DBNAME).C(APIKCOLL).Insert(&townhalls)\n\n\treturn err\n}", "func UpdateCompanyBranchHyCompanybranchOK(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) (http.ResponseWriter, *app.Company) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil, nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected parameter validation error: %+v\", _e)\n\t\treturn nil, nil\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 200 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 200\", rw.Code)\n\t}\n\tvar mt *app.Company\n\tif resp != nil {\n\t\tvar __ok bool\n\t\tmt, __ok = resp.(*app.Company)\n\t\tif !__ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of app.Company\", resp, resp)\n\t\t}\n\t\t__err = mt.Validate()\n\t\tif __err != nil {\n\t\t\tt.Errorf(\"invalid response media type: %s\", __err)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func (ct *CompanyTestSuite) TestGetCompaniesByNonAdmin(c *C) {\n\ttoken := getTestDefaultAuthToken()\n\n\temail := fmt.Sprintf(\"test_%[email protected]\", time.Now().UnixNano())\n\t_, err := createTestUser(email, token, \"\", false)\n\tcreatedUserToken := getTestLoginToken(fmt.Sprintf(`{\"email\":\"%s\", \"password\": \"12345\"}`, email))\n\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"http://127.0.0.1:8080/v1/company\"), nil)\n\tc.Assert(err, IsNil)\n\n\treq.Header.Add(\"Authorization\", createdUserToken)\n\n\tclient := server.GetHTTPClient()\n\n\tresp, err := client.Do(req)\n\tdefer resp.Body.Close()\n\tc.Assert(err, IsNil)\n\n\tcompanyListResponse := server.NewCompanyListResponse()\n\terr = jsonpb.Unmarshal(resp.Body, companyListResponse)\n\tc.Assert(err, IsNil)\n\n\tc.Assert(companyListResponse.Meta.StatusCode, Equals, HttpStatusForbidden)\n}", "func (mb *metadataBackend) sync() error {\n\treturn mb.db.Sync()\n}", "func (d UserData) UnsetCompany() m.UserData {\n\td.ModelData.Unset(models.NewFieldName(\"Company\", \"company_id\"))\n\treturn d\n}", "func (*elephant) createCompany(name string) (*Company, error) {\n\tres := &Company{Name: name}\n\treturn res, db.Create(res).Error\n}", "func (sm Semester) InsertToDB() {\n\ts, c, err := mongo.GetSemester(sm.Semester)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer s.Close()\n\n\tfor _, cr := range sm.CourseList {\n\t\t_, err := c.UpsertId(cr.CallNumber, cr)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}", "func SyncCapabilityCenter(capabilityCenterName string) error {\n\trepos, err := plugins.LoadRepos()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(repos) == 0 {\n\t\treturn fmt.Errorf(\"no capability center configured\")\n\t}\n\tfind := false\n\tif capabilityCenterName != \"\" {\n\t\tfor idx, r := range repos {\n\t\t\tif r.Name == capabilityCenterName {\n\t\t\t\trepos = []plugins.CapCenterConfig{repos[idx]}\n\t\t\t\tfind = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !find {\n\t\t\treturn fmt.Errorf(\"%s center not exist\", capabilityCenterName)\n\t\t}\n\t}\n\tctx := context.Background()\n\tfor _, d := range repos {\n\t\tclient, err := plugins.NewCenterClient(ctx, d.Name, d.Address, d.Token)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = client.SyncCapabilityFromCenter()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func testSyncerWithData(data []asSync, initialDbState, finalDbState []libovsdbtest.TestData, controllerName string,\n\tdisableBatching bool) {\n\t// create initial db setup\n\tdbSetup := libovsdbtest.TestSetup{NBData: initialDbState}\n\tfor _, asSync := range data {\n\t\tdbSetup.NBData = append(dbSetup.NBData, asSync.before)\n\t}\n\tlibovsdbOvnNBClient, _, libovsdbCleanup, err := libovsdbtest.NewNBSBTestHarness(dbSetup)\n\tdefer libovsdbCleanup.Cleanup()\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t// create expected data using addressSetFactory\n\texpectedDbState := initialDbState\n\tif finalDbState != nil {\n\t\texpectedDbState = finalDbState\n\t}\n\tfor _, asSync := range data {\n\t\tif asSync.remove {\n\t\t\tcontinue\n\t\t}\n\t\tif asSync.leave {\n\t\t\texpectedDbState = append(expectedDbState, asSync.before)\n\t\t} else if asSync.after != nil {\n\t\t\tupdatedAS := getUpdatedAS(asSync.before, asSync.after, asSync.addressSetFactoryIPID)\n\t\t\tif asSync.afterTweak != nil {\n\t\t\t\tasSync.afterTweak(updatedAS)\n\t\t\t}\n\t\t\texpectedDbState = append(expectedDbState, updatedAS)\n\t\t\tif finalDbState == nil {\n\t\t\t\tfor _, dbObj := range expectedDbState {\n\t\t\t\t\tif lrp, ok := dbObj.(*nbdb.LogicalRouterPolicy); ok {\n\t\t\t\t\t\tlrp.Match = strings.ReplaceAll(lrp.Match, \"$\"+asSync.before.Name, \"$\"+updatedAS.Name)\n\t\t\t\t\t}\n\t\t\t\t\tif acl, ok := dbObj.(*nbdb.ACL); ok {\n\t\t\t\t\t\tacl.Match = strings.ReplaceAll(acl.Match, \"$\"+asSync.before.Name, \"$\"+updatedAS.Name)\n\t\t\t\t\t}\n\t\t\t\t\tif qos, ok := dbObj.(*nbdb.QoS); ok {\n\t\t\t\t\t\tqos.Match = strings.ReplaceAll(qos.Match, \"$\"+asSync.before.Name, \"$\"+updatedAS.Name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// run sync\n\tsyncer := NewAddressSetSyncer(libovsdbOvnNBClient, controllerName)\n\t// to make sure batching works, set it to 2 to cover number of batches = 0,1,>1\n\tsyncer.txnBatchSize = 2\n\tif disableBatching {\n\t\tsyncer.txnBatchSize = 0\n\t}\n\terr = syncer.SyncAddressSets()\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t// check results\n\tgomega.Eventually(libovsdbOvnNBClient).Should(libovsdbtest.HaveData(expectedDbState))\n}", "func (a *BulkApiService) CreateBulkMoCloner(ctx context.Context) ApiCreateBulkMoClonerRequest {\n\treturn ApiCreateBulkMoClonerRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func sendJobsToDB(jobs [] *types.GithubJob) {\n\tclient, err := aws.CreateDynamoClient()\n\n\tif err != nil {\n\t\tloggly.Error(err)\n\t\treturn\n\t}\n\n\tfor _, j := range jobs {\n\t\terr := aws.PutItem(client, TableName, *j)\n\t\tif err != nil {\n\t\t\tloggly.Error(err)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (p *Placements) Save(db *sql.DB) error {\n\tfor i, r := range p.Lines {\n\t\tif r.IrisCode == \"\" {\n\t\t\treturn fmt.Errorf(\"Ligne %d, iris_code vide\", i+1)\n\t\t}\n\t}\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"tx begin %v\", err)\n\t}\n\tstmt, err := tx.Prepare(pq.CopyIn(\"temp_placement\", \"iris_code\", \"count\",\n\t\t\"contract_year\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"copy in %v\", err)\n\t}\n\tdefer stmt.Close()\n\tfor _, r := range p.Lines {\n\t\tif _, err = stmt.Exec(r.IrisCode, r.Count, r.ContractYear); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn fmt.Errorf(\"insertion de %+v : %s\", r, err.Error())\n\t\t}\n\t}\n\tif _, err = stmt.Exec(); err != nil {\n\t\ttx.Rollback()\n\t\treturn fmt.Errorf(\"statement exec flush %v\", err)\n\t}\n\tqueries := []string{`INSERT INTO placement(iris_code,count,contract_year,\n\t\tcommitment_id) \n\tSELECT t.iris_code,t.count,t.contract_year,MIN(c.id) FROM temp_placement t\n\tLEFT OUTER JOIN commitment c ON t.iris_code=c.iris_code\n\tWHERE t.iris_code NOT IN (SELECT DISTINCT iris_code FROM placement)\n GROUP BY 1,2,3`,\n\t\t`UPDATE placement SET count=t.count,contract_year=t.contract_year,\n\t\tcommitment_id=t.id FROM\n\t\t(SELECT t.iris_code,t.count,t.contract_year,MIN(c.id) id FROM temp_placement t\n\t\t\tLEFT OUTER JOIN commitment c ON t.iris_code=c.iris_code\n\t\t\tWHERE t.iris_code IN (SELECT DISTINCT iris_code FROM placement)\n\t\t\tGROUP BY 1,2,3) t\n\t\tWHERE placement.iris_code=t.iris_code`,\n\t\t`DELETE FROM temp_placement`,\n\t}\n\tfor i, q := range queries {\n\t\t_, err = tx.Exec(q)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn fmt.Errorf(\"requête %d : %s\", i, err.Error())\n\t\t}\n\t}\n\treturn tx.Commit()\n}", "func syncRelatedFieldInfo() {\n\tfor _, mi := range modelRegistry.registryByName {\n\t\tfor _, fi := range mi.fields.registryByName {\n\t\t\tif !fi.related() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnewFI := *mi.getRelatedFieldInfo(fi.relatedPath)\n\t\t\tnewFI.name = fi.name\n\t\t\tnewFI.json = fi.json\n\t\t\tnewFI.relatedPath = fi.relatedPath\n\t\t\tnewFI.stored = fi.stored\n\t\t\tnewFI.mi = mi\n\t\t\tnewFI.noCopy = true\n\t\t\t*fi = newFI\n\t\t}\n\t}\n}", "func (m *OrderproductMutation) ResetCompany() {\n\tm.company = nil\n\tm.clearedcompany = false\n}", "func (c *PlanController) PlanUpdate() {\n\tlog.Println(\"haiiiii\")\n\tw := c.Ctx.ResponseWriter\n\tr := c.Ctx.Request\n\tstoredSession,_ := SessionForPlan(w,r)\n\tcompanyId := storedSession.CompanyId\n\tselectedCompanyPlan := c.GetString(\"companyPlan\")\n\tcompany := models.Company{}\n\tcompany.Plan = selectedCompanyPlan\n\tdbStatus, _ := company.ChangeCompanyPlan(c.AppEngineCtx,companyId)\n\tswitch dbStatus {\n\tcase true :\n\n\t\tClearSession(w)\n\t\tsessionValues := SessionValues{}\n\t\tsessionValues.AdminId = storedSession.AdminId\n\t\tsessionValues.AdminFirstName = storedSession.AdminFirstName\n\t\tsessionValues.AdminLastName = storedSession.AdminLastName\n\t\tsessionValues.AdminEmail = storedSession.AdminEmail\n\t\tsessionValues.CompanyId = storedSession.CompanyId\n\t\tsessionValues.CompanyName = storedSession.CompanyName\n\t\tsessionValues.CompanyTeamName = storedSession.CompanyTeamName\n\t\tsessionValues.CompanyPlan = selectedCompanyPlan\n\n\t\tSetSession(w, sessionValues)\n\t\tslices := []interface{}{\"true\", sessionValues.CompanyTeamName,sessionValues.CompanyPlan}\n\t\tsliceToClient, _ := json.Marshal(slices)\n\t\tw.Write(sliceToClient)\n\n\tcase false:\n\t\tw.Write([]byte(\"false\"))\n\n\n\t}\n\n\n\n}", "func (cd *Connection) InsertContributions(Coc model.ContributionAPI) error {\n\n\tsession, err := cd.connect()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer session.Close()\n\n\tc := session.DB(\"jigsaw-gateway\").C(\"Contributions\")\n\terr1 := c.Insert(Coc)\n\tif err1 != nil {\n\t\tfmt.Println(err1)\n\t}\n\n\treturn err\n}", "func SyncGitLabConnections(ctx context.Context) {\n\tt := time.NewTicker(configWatchInterval)\n\tvar lastConfig []*schema.GitLabConnection\n\tfor range t.C {\n\t\tgitlabConf, err := conf.GitLabConfigs(ctx)\n\t\tif err != nil {\n\t\t\tlog15.Error(\"unable to fetch Gitlab configs\", \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar hasGitLabDotComConnection bool\n\t\tfor _, c := range gitlabConf {\n\t\t\tu, _ := url.Parse(c.Url)\n\t\t\tif u != nil && (u.Hostname() == \"gitlab.com\" || u.Hostname() == \"www.gitlab.com\") {\n\t\t\t\thasGitLabDotComConnection = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !hasGitLabDotComConnection {\n\t\t\t// Add a GitLab.com entry by default, to support navigating to URL paths like\n\t\t\t// /gitlab.com/foo/bar to auto-add that project.\n\t\t\tgitlabConf = append(gitlabConf, &schema.GitLabConnection{\n\t\t\t\tProjectQuery: []string{\"none\"}, // don't try to list all repositories during syncs\n\t\t\t\tUrl: \"https://gitlab.com\",\n\t\t\t\tInitialRepositoryEnablement: true,\n\t\t\t})\n\t\t}\n\n\t\tif reflect.DeepEqual(gitlabConf, lastConfig) {\n\t\t\tcontinue\n\t\t}\n\t\tlastConfig = gitlabConf\n\n\t\tvar conns []*gitlabConnection\n\t\tfor _, c := range gitlabConf {\n\t\t\tconn, err := newGitLabConnection(c, nil)\n\t\t\tif err != nil {\n\t\t\t\tlog15.Error(\"Error processing configured GitLab connection. Skipping it.\", \"url\", c.Url, \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconns = append(conns, conn)\n\t\t}\n\n\t\tgitlabConnections.Set(func() interface{} {\n\t\t\treturn conns\n\t\t})\n\n\t\tgitLabRepositorySyncWorker.restart()\n\t}\n}", "func UpdateHCNMongo(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, \"(USER) %v\", err.Error())\n\t\treturn\n\t}\n\t// Prepare the data for insert\n\tvar newHCN mymodels.HCNmongo\n\tvar newGeneralData *mymodels.GeneralData\n\tvar newPatientData *mymodels.PatientData\n\tvar newConsultationReason *string\n\tvar newAnthropometry *mymodels.Anthropometry\n\n\tvar newGeneralInterpretation *string\n\tvar newGeneralFeedback *string\n\n\t// All json assessment data\n\tjson.Unmarshal(reqBody, &newHCN)\n\n\t// General nutritional assessment data\n\tgeneralData := gjson.Get(string(reqBody), \"GeneralData\")\n\tjson.Unmarshal([]byte(generalData.Raw), &newGeneralData)\n\n\t// Patient data\n\tpatientData := gjson.Get(string(reqBody), \"PatientData\")\n\tjson.Unmarshal([]byte(patientData.Raw), &newPatientData)\n\n\t// Consultation reason nutritional assessment data\n\tconsultationReason := gjson.Get(string(reqBody), \"ConsultationReason\")\n\tjson.Unmarshal([]byte(consultationReason.Raw), &newConsultationReason)\n\n\t// Anthropometry data\n\tAnthropometry := gjson.Get(string(reqBody), \"Anthropometry\")\n\tjson.Unmarshal([]byte(Anthropometry.Raw), &newAnthropometry)\n\n\t// Biochemistry data\n\tvar newAllBiochemistryParameters mymodels.AllBiochemistryParameters\n\tvar interpretation *string\n\tvar feedback *string\n\t// Look for the array of parameters\n\tbiochemistryParameters := gjson.Get(string(reqBody), \"Biochemistry.Parameters\")\n\t// Loop the array of parameters\n\tfor _, parameter := range biochemistryParameters.Array() {\n\t\tvar newParameter mymodels.BiochemistryParameters\n\t\tjson.Unmarshal([]byte(parameter.Raw), &newParameter)\n\t\tnewAllBiochemistryParameters = append(newAllBiochemistryParameters, newParameter)\n\t}\n\n\tbiochemistryInterpretation := gjson.Get(string(reqBody), \"Biochemistry.Interpretation\")\n\tbiochemistryFeedback := gjson.Get(string(reqBody), \"Biochemistry.Feedback\")\n\tjson.Unmarshal([]byte(biochemistryInterpretation.Raw), &interpretation)\n\tjson.Unmarshal([]byte(biochemistryFeedback.Raw), &feedback)\n\n\t// We have to create the biochemistry struct like this\n\t// because it has an array of structs\n\tnewBiochemistry := mymodels.Biochemistry{\n\t\tParameters: &newAllBiochemistryParameters,\n\t\tInterpretation: interpretation,\n\t\tFeedback: feedback,\n\t}\n\n\t// General interpretation data\n\tgeneralInterpretation := gjson.Get(string(reqBody), \"Interpretation\")\n\tjson.Unmarshal([]byte(generalInterpretation.Raw), &newGeneralInterpretation)\n\n\t// General feedback data\n\tgeneralFeedback := gjson.Get(string(reqBody), \"Feedback\")\n\tjson.Unmarshal([]byte(generalFeedback.Raw), &newGeneralFeedback)\n\n\tclient, ctx := config.MongoConnection()\n\tcollection := client.Database(\"HCNProject\").Collection(\"HCN\")\n\n\tid, _ := primitive.ObjectIDFromHex(*newHCN.ID)\n\tresult, err := collection.UpdateOne(\n\t\tctx,\n\t\tbson.M{\"_id\": id},\n\t\tbson.D{\n\t\t\t{\"$set\", bson.D{\n\t\t\t\t{\"GeneralData\", newGeneralData},\n\t\t\t\t{\"PatientData\", newPatientData},\n\t\t\t\t{\"ConsultationReason\", newConsultationReason},\n\t\t\t\t{\"Anthropometry\", newAnthropometry},\n\t\t\t\t{\"Biochemistry\", newBiochemistry},\n\t\t\t\t{\"Interpretation\", newGeneralInterpretation},\n\t\t\t\t{\"Feedback\", newGeneralFeedback}}},\n\t\t},\n\t)\n\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(result)\n}", "func TestSync(t *testing.T) {\n\t// Same as TestReorganize() w/r/t no return value, etc.\n\tdb, _ := Open(db_filename, \"c\")\n\tdefer db.Close()\n\tdefer os.Remove(db_filename)\n\n\tdb.Sync()\n}", "func (cp *CsPlugins) Sync() error {\n\tplugins, err := cp.cloud.API().Plugins(cp.organizationID, cp.clusterID).List()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := json.Marshal(plugins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjson.Unmarshal(data, &cp.cache)\n\n\treturn nil\n}" ]
[ "0.58223844", "0.56305516", "0.5416946", "0.5339815", "0.5296623", "0.5262525", "0.5246168", "0.5221587", "0.5201021", "0.5123006", "0.51011467", "0.5084826", "0.5080166", "0.5061221", "0.5054014", "0.5026091", "0.5018993", "0.49539638", "0.49169976", "0.49040416", "0.49003574", "0.4898075", "0.4887501", "0.48772496", "0.48591697", "0.48431087", "0.48237458", "0.4821197", "0.47929728", "0.47613925", "0.475784", "0.47498995", "0.4739636", "0.4738049", "0.47175533", "0.4707775", "0.47075793", "0.47066048", "0.470118", "0.46914032", "0.46900514", "0.46519712", "0.46519172", "0.46346122", "0.46306184", "0.46296883", "0.4610247", "0.46083313", "0.45948562", "0.4581615", "0.4578792", "0.45733452", "0.4571846", "0.4551963", "0.454469", "0.45405033", "0.45354852", "0.45276666", "0.452685", "0.45201328", "0.45130333", "0.4506482", "0.4506268", "0.4504792", "0.44961795", "0.4495205", "0.44949114", "0.44942468", "0.44933844", "0.4489507", "0.44877923", "0.44831312", "0.44795662", "0.44777307", "0.4475055", "0.44668692", "0.44508514", "0.44464743", "0.44461286", "0.44411427", "0.44288412", "0.44185612", "0.4413373", "0.4411923", "0.44066882", "0.4395728", "0.4394696", "0.43944165", "0.43919864", "0.43839252", "0.43810865", "0.43785363", "0.43742916", "0.437173", "0.43693063", "0.43673822", "0.43648", "0.43567258", "0.43437535", "0.43436408" ]
0.73131657
0
convert number < 10k to chinese maybeZero: has higher number, can be zero lastZero: last one contains zero, ignore here
func kiloToChinese(number int, maybeZero, lastZero bool) (string, bool, bool) { var buffer bytes.Buffer for i, str := range Reverse(Number2) { n := int(math.Pow10(3 - i)) switch { case number >= n: buffer.WriteString(Number1[number/n] + str) number = number % n maybeZero = true lastZero = false case maybeZero: if !lastZero && number != 0 { buffer.WriteString("零") lastZero = true } } } return buffer.String(), maybeZero, lastZero }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func prefix0(needle int) (zstr string) {\n\tvar str string = strconv.Itoa(needle)\n\tif len(str) < 2 {\n\t\tzstr = \"0\" + str\n\t} else {\n\t\tzstr = str\n\t}\n\treturn zstr\n}", "func main() {\n\ttrailingZeroes(125)\n}", "func countTrailingZeroes(i int, word int32) int {\n\ttrace_util_0.Count(_mydecimal_00000, 28)\n\ttrailing := 0\n\tfor word%powers10[i] == 0 {\n\t\ttrace_util_0.Count(_mydecimal_00000, 30)\n\t\ti++\n\t\ttrailing++\n\t}\n\ttrace_util_0.Count(_mydecimal_00000, 29)\n\treturn trailing\n}", "func Solution(N int) int {\n result := 0\n binaryRepresentation := strconv.FormatInt(int64(N), 2)\n currentGap := 0\n \n for _,value := range binaryRepresentation{\n //Converts the current rune to ASCII representation of the digit\n val := int(value -'0')\n if val == 1{\n if currentGap > result{\n result = currentGap\n currentGap = 0\n }\n }else{\n currentGap ++\n }\n }\n \n return result\n}", "func parse0To999(s string) (n int, ok bool) {\n\tif len(s) < 1 || 3 < len(s) {\n\t\treturn 0, false\n\t}\n\tif len(s) > 1 && s[0] == '0' {\n\t\t// Leading zeros are rejected.\n\t\treturn 0, false\n\t}\n\tfor _, c := range []byte(s) {\n\t\tif c < '0' || '9' < c {\n\t\t\treturn 0, false\n\t\t}\n\t\tn = n*10 + int(c-'0')\n\t}\n\treturn n, true\n}", "func (b Bits) ZeroFrom(num int) int {\n\t// code much like OneFrom except words are negated before testing\n\tif num >= b.Num {\n\t\treturn -1\n\t}\n\tx := num >> 6\n\t// negate word to test for 0 at or after n\n\tif wx := ^b.Bits[x] >> uint(num&63); wx != 0 {\n\t\tnum += mb.TrailingZeros64(wx)\n\t\tif num >= b.Num {\n\t\t\treturn -1\n\t\t}\n\t\treturn num\n\t}\n\tx++\n\tfor y, wy := range b.Bits[x:] {\n\t\twy = ^wy\n\t\tif wy != 0 {\n\t\t\tnum = (x+y)<<6 | mb.TrailingZeros64(wy)\n\t\t\tif num >= b.Num {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\treturn num\n\t\t}\n\t}\n\treturn -1\n}", "func SelectLastDigits(in *big.Int, depth uint64) (*big.Int, error) {\n\ta := ZeroBigInt()\n\ts := in.String()\n\tif s == \"0\" {\n\t\treturn nil, fmt.Errorf(\"%s\", \"string has value of 0? something is not ok\")\n\t}\n\tfs := strings.TrimRight(s, \"0\")\n\tindex := int(depth)\n\tfx := fs[len(fs)-index:]\n\ta.SetString(fx, 10)\n\treturn a, nil\n}", "func ToIndexZero(numString string) (string, error) {\n\tnum, err := strconv.Atoi(numString)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnum--\n\n\treturn strconv.Itoa(num), nil\n}", "func LeadingZeros(x uint) int { return UintSize - Len(x) }", "func addLeadingZero(value int) string {\n\tresult := strconv.Itoa(value)\n\tif value < 10 {\n\t\tresult = \"0\" + result\n\t}\n\treturn result\n}", "func trailingZeroBits(x Word) int {\n\t// x & -x leaves only the right-most bit set in the word. Let k be the\n\t// index of that bit. Since only a single bit is set, the value is two\n\t// to the power of k. Multiplying by a power of two is equivalent to\n\t// left shifting, in this case by k bits. The de Bruijn constant is\n\t// such that all six bit, consecutive substrings are distinct.\n\t// Therefore, if we have a left shifted version of this constant we can\n\t// find by how many bits it was shifted by looking at which six bit\n\t// substring ended up at the top of the word.\n\tswitch _W {\n\tcase 32:\n\t\treturn int(deBruijn32Lookup[((x&-x)*deBruijn32)>>27])\n\tcase 64:\n\t\treturn int(deBruijn64Lookup[((x&-x)*(deBruijn64&_M))>>58])\n\tdefault:\n\t\tpanic(\"Unknown word size\")\n\t}\n\n\treturn 0\n}", "func getPositiveNumber(data []byte, cursor int) (int, error) {\r\n\tif cursor >= len(data)-1 {\r\n\t\treturn 0, errors.New(\"Index out of range.\")\r\n\t}\r\n\r\n\taux := string(data[cursor : cursor+2])\r\n\tresult, err := strconv.Atoi(aux)\r\n\tif result <= 0 || err != nil {\r\n\t\treturn 0, errors.New(fmt.Sprintf(\"Invalid number %s.\", aux))\r\n\t}\r\n\treturn result, nil\r\n}", "func (z ZLine) MaxZeroVal() float64 {\n\tvar maxZero float64\n\tfor _, zero := range z.Zeros {\n\t\tif zero.Values[len(zero.Values)-1] > maxZero {\n\t\t\tmaxZero = zero.Values[len(zero.Values)-1]\n\t\t}\n\t}\n\treturn maxZero\n}", "func isZero(text, code []byte) ([]byte, bool) {\n\t// Handle different forms of zero.\n\tif (len(text) == 1) && (text[0] == ZERO) {\n\t\tcode = append(code, ZERO)\n\t\treturn code, true\n\n\t} else if (len(text) == 2) && ((text[0] == PLUS) || (text[0] == MINUS)) &&\n\t\t(text[1] == ZERO) {\n\n\t\tcode = append(code, ZERO)\n\t\treturn code, true\n\t}\n\treturn code, false\n}", "func removeK(a string, k int) string {\n\tdefer tools.FuncTime()()\n\ttmp := 0\n\n\tfor i := 0; i < k; i++ {\n\t\tfor j := tmp; j < len(a); {\n\t\t\t// it is the end of a, remove the last character\n\t\t\tif j == len(a)-1 {\n\t\t\t\ta = a[:j]\n\t\t\t\ttmp = j - 1\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif a[j] > a[j+1] {\n\t\t\t\ta = a[:j] + a[j+1:]\n\t\t\t\ttmp = 0\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tj++\n\t\t}\n\n\t}\n\n\t// remove the prefix 0\n\tfor i := 0; i < len(a); {\n\t\tif '0' != a[i] {\n\t\t\tbreak\n\t\t}\n\n\t\ta = a[i+1:]\n\t}\n\n\tif 0 == len(a) {\n\t\ta = \"0\"\n\t}\n\n\treturn a\n}", "func LeadingZeros8(x uint8) int { return 8 - Len8(x) }", "func LeadingZeros8(x uint8) int { return 8 - Len8(x) }", "func LeadingZeros(x uint) int { return int(benchmarks.SizeOfUintInBits) - Len(x) }", "func countLeadingZeroes(i int, word int32) int {\n\ttrace_util_0.Count(_mydecimal_00000, 25)\n\tleading := 0\n\tfor word < powers10[i] {\n\t\ttrace_util_0.Count(_mydecimal_00000, 27)\n\t\ti--\n\t\tleading++\n\t}\n\ttrace_util_0.Count(_mydecimal_00000, 26)\n\treturn leading\n}", "func countTrailingZeroes(i int, word int32) int {\n\ttrailing := 0\n\tfor word%powers10[i] == 0 {\n\t\ti++\n\t\ttrailing++\n\t}\n\treturn trailing\n}", "func removeZeroAtTail(str string) string {\n\ti := len(str) - 1\n\tfor ; i >= 0; i-- {\n\t\tif str[i] != '0' {\n\t\t\tbreak\n\t\t}\n\t}\n\tstr = str[:i+1]\n\t// delete \".\" at last of result\n\tif str[len(str)-1] == '.' {\n\t\tstr = str[:len(str)-1]\n\t}\n\treturn str\n}", "func removeZeroAtTail(str string) string {\n\ti := len(str) - 1\n\tfor ; i >= 0; i-- {\n\t\tif str[i] != '0' {\n\t\t\tbreak\n\t\t}\n\t}\n\tstr = str[:i+1]\n\t// delete \".\" at last of result\n\tif str[len(str)-1] == '.' {\n\t\tstr = str[:len(str)-1]\n\t}\n\treturn str\n}", "func Convert(number int64) (string, error) {\n\n\tif number > maxValue {\n\t\tmsg := fmt.Sprintf(\"input parameters exceed the maximum limit. Max = %d\", maxValue)\n\t\terr := errors.New(msg)\n\t\treturn \"\", err\n\t}\n\n\tvar isMinus bool = false\n\n\tif number == 0 {\n\t\treturn smallNumbers[number], nil\n\t} else if number < 0 {\n\t\tisMinus = true\n\t\tnumber = number * -1\n\t}\n\n\tdigitGroups := splitIntoThreeDigitGroups(number)\n\n\tvar groupText []Words\n\tfor _, digit := range digitGroups {\n\t\tgroupText = append(groupText, threeDigitGroupsToWords(digit))\n\t}\n\n\tcombinedWords := combineWords(groupText)\n\tif isMinus {\n\t\tcombinedWords = append(Words{\"negatif\"}, combinedWords...)\n\t}\n\n\treturn strings.Join(combinedWords, \" \"), nil\n}", "func main() {\n\tpp.Println(\"=========================================\")\n\tpp.Println(removeKdigits(\"1432219\", 3))\n\tpp.Println(\"1219\")\n\tpp.Println(\"=========================================\")\n\tpp.Println(removeKdigits(\"10200\", 1))\n\tpp.Println(\"200\")\n\tpp.Println(\"=========================================\")\n\tpp.Println(removeKdigits(\"10\", 2))\n\tpp.Println(\"0\")\n\tpp.Println(\"=========================================\")\n\tpp.Println(removeKdigits(\"9\", 1))\n\tpp.Println(\"0\")\n\tpp.Println(\"=========================================\")\n\tpp.Println(removeKdigits(\"112\", 1))\n\tpp.Println(\"11\")\n\tpp.Println(\"=========================================\")\n\tpp.Println(removeKdigits(\"1107\", 1))\n\tpp.Println(\"107\")\n\tpp.Println(\"=========================================\")\n}", "func countLeadingZeroes(i int, word int32) int {\n\tleading := 0\n\tfor word < powers10[i] {\n\t\ti--\n\t\tleading++\n\t}\n\treturn leading\n}", "func dtoi(s string, i0 int) (n int, i int, ok bool) {\n\tn = 0\n\tfor i = i0; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {\n\t\tn = n*10 + int(s[i]-'0')\n\t\tif n >= big {\n\t\t\treturn 0, i, false\n\t\t}\n\t}\n\tif i == i0 {\n\t\treturn 0, i, false\n\t}\n\treturn n, i, true\n}", "func IntTrailingZeroBits(x *big.Int,) uint", "func superDigit(n string, k int32) int32 {\n\n\tif len(n) == 1 {\n\n\t\tfinalSuperDigit, err := strconv.Atoi(n)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn int32(finalSuperDigit)\n\t}\n\tvar sum uint64\n\tfor _, ch := range n {\n\t\tsum += uint64(ch) - uint64('0')\n\t}\n\tsum *= uint64(k)\n\n\treturn superDigit(strconv.FormatUint(sum, 10), 1)\n\n}", "func humanReadableCountSI(bytes int64) string {\n\tif -1000 < bytes && bytes < 1000 {\n\t\treturn fmt.Sprintf(\"%d \", bytes)\n\t}\n\tci := \"kMGTPE\"\n\tidx := 0\n\tfor bytes <= -999950 || bytes >= 999950 {\n\t\tbytes /= 1000\n\t\tidx++\n\t}\n\treturn fmt.Sprintf(\"%.1f %c\", float64(bytes)/1000.0, ci[idx])\n}", "func main() {\n\tnum := \"0.00035485293981043127901785714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714\"\n\tsteps := 5120\n\tdelta := \"0.00000000000000000001089913504464285714285714285714285714285714285714285714285714285714285714285714285714285714285714286\"\n\tfinal := \"0.0003548529398104870825892857142857142857142857142857142857142857142857142857142857142857142857142857143\"\n\tfinalNeg := \"-0.0003548529398104870825892857142857142857142857142857142857142857142857142857142857142857142857142857143\"\n\n\tbits := uint(96)\n\n\t{ // big float\n\t\tx, _, err := big.ParseFloat(num, 10, bits, big.ToNearestEven)\n\t\tg.Die(err)\n\t\tdelta_, _, err := big.ParseFloat(delta, 10, bits, big.ToNearestEven)\n\t\tg.Die(err)\n\t\tfinal_, _, err := big.ParseFloat(final, 10, bits, big.ToNearestEven)\n\t\tg.Die(err)\n\n\t\tfor i := 0; i < steps; i++ {\n\t\t\tx.Add(x, delta_)\n\t\t}\n\t\tx.Sub(x, final_)\n\t\tfmt.Println(x.Text('f', int(bits)))\n\t}\n\n\t{ // fixnum\n\t\tx, err := naive_fixnum.FromString(num)\n\t\tg.Die(err)\n\t\tdelta_, err := naive_fixnum.FromString(delta)\n\t\tg.Die(err)\n\t\t//final_, err := fixnum.FromString(final)\n\t\t//g.Die(err)\n\t\tfinalNeg_, err := naive_fixnum.FromString(finalNeg)\n\t\tg.Die(err)\n\n\t\tfor i := 0; i < steps; i++ {\n\t\t\tx.Add(x, delta_)\n\t\t}\n\t\tx.Add(x, finalNeg_)\n\t\tfmt.Println(x)\n\t}\n}", "func TrailingZeros8(x uint8) int {\n\treturn int(ntz8tab[x])\n}", "func LeadingZeros(x uint) int {\n\t_x := int(x)\n\tn := int(0)\n\ty := _x\nL:\n\tif _x < 0 {\n\t\treturn n\n\t}\n\tif y == 0 {\n\t\treturn benchmarks.SizeOfUintInBits - n\n\t}\n\tn = n + 1\n\tx = x << 1\n\ty = y >> 1\n\tgoto L\n}", "func (this *unsignedFixed) zero() bool {\n\tm := this.mantissa\n\tresult := m == 0\n\treturn result\n}", "func zeroUpTo(tr *Struct, stayBelow int, out []byte, k, numFieldsSeen int) (newOut []byte, newNextFieldExpected int, newFieldsSeen int) {\n\t//p(\"zeroUpTo called with k = %v, stayBelow = %v, tr = %#v\", k, stayBelow, tr)\n\tfor k < stayBelow {\n\t\t//p(\"k is now %v\", k)\n\t\tif tr.Fields[k].Skip {\n\t\t\t//p(\"skipping field k=%v\", k)\n\t\t\tk++\n\t\t\tcontinue\n\t\t}\n\t\t//p(\"tr.Fields[k] = '%#v'\", tr.Fields[k])\n\t\t// fill in missing fields that are showzero\n\t\tif tr.Fields[k].ShowZero {\n\t\t\tnumFieldsSeen++\n\t\t\t//p(\"found showzero field at k = %v\", k)\n\t\t\tout = msgp.AppendString(out, tr.Fields[k].FieldTagName)\n\t\t\tout = writeZeroMsgpValueFor(&(tr.Fields[k]), out)\n\t\t}\n\t\tk++\n\t}\n\treturn out, k, numFieldsSeen\n}", "func ToInteger(value string) (int, error) {\n value = strings.ToUpper(value)\n value = strings.TrimSpace(value)\n max := len(value)\n\n if max == 0 {\n return 0, errors.New(\"empty value\")\n }\n\n roman := map[string]int{\n \"I\": 1, \"V\": 5, \"X\": 10,\n \"L\": 50, \"C\": 100, \"D\": 500, \"M\": 1000,\n }\n\n output := 0\n rpkey := 0\n last := max - 1\n lastkey := string(value[last])\n lnumber, _ := roman[lastkey]\n \n for i := last; i >= 0; i-- {\n key := string(value[i])\n number, found := roman[key]\n if !found {\n return 0, errors.New(\"invalid value\")\n }\n\n if number >= lnumber { \n output += number\n } else {\n output += -number\n }\n\n if i < last {\n if lastkey == key {\n rpkey++\n } else {\n rpkey = 0\n }\n if rpkey >= 3 {\n return 0, errors.New(\"invalid value\")\n }\n\n lastkey = string(value[i])\n lnumber, _ = roman[lastkey]\n }\n }\n\n return output, nil\n}", "func numberLtKToWords(num int) string {\n if num < 20 {\n return LESS_THAN_20[num]\n }\n if num < 100 {\n if num % 10 != 0 {\n return TENS[num/10] + \" \" + LESS_THAN_20[num%10] \n } else {\n return TENS[num/10]\n }\n }\n if num%100 != 0 {\n return LESS_THAN_20[num/100] + \" Hundred \" + numberLtKToWords(num%100)\n } else {\n return LESS_THAN_20[num/100] + \" Hundred\"\n } \n}", "func CheckGreaterThanZero(value string) error {\r\n\tn, err := strconv.ParseFloat(value, 64)\r\n\tif n < 0 {\r\n\t\treturn fmt.Errorf(\"parsed version of %v, should be >= 0\", value)\r\n\t}\r\n\treturn err\r\n}", "func TrailingZeros(x uint) int {\n\tif UintSize == 32 {\n\t\treturn TrailingZeros32(uint32(x))\n\t}\n\treturn TrailingZeros64(uint64(x))\n}", "func LeadingZeros8(x uint8) int {\n\t_x := int8(x)\n\tn := int8(0)\n\ty := _x\nL:\n\tif _x < 0 {\n\t\treturn int(n)\n\t}\n\tif y == 0 {\n\t\treturn int(8 - n)\n\t}\n\tn = n + 1\n\tx = x << 1\n\ty = y >> 1\n\tgoto L\n}", "func ryuDigits32(d *decimalSlice, lower, central, upper uint32,\n\tc0, cup bool, endindex int) {\n\tif upper == 0 {\n\t\td.dp = endindex + 1\n\t\treturn\n\t}\n\ttrimmed := 0\n\t// Remember last trimmed digit to check for round-up.\n\t// c0 will be used to remember zeroness of following digits.\n\tcNextDigit := 0\n\tfor upper > 0 {\n\t\t// Repeatedly compute:\n\t\t// l = Ceil(lower / 10^k)\n\t\t// c = Round(central / 10^k)\n\t\t// u = Floor(upper / 10^k)\n\t\t// and stop when c goes out of the (l, u) interval.\n\t\tl := (lower + 9) / 10\n\t\tc, cdigit := central/10, central%10\n\t\tu := upper / 10\n\t\tif l > u {\n\t\t\t// don't trim the last digit as it is forbidden to go below l\n\t\t\t// other, trim and exit now.\n\t\t\tbreak\n\t\t}\n\t\t// Check that we didn't cross the lower boundary.\n\t\t// The case where l < u but c == l-1 is essentially impossible,\n\t\t// but may happen if:\n\t\t// lower = ..11\n\t\t// central = ..19\n\t\t// upper = ..31\n\t\t// and means that 'central' is very close but less than\n\t\t// an integer ending with many zeros, and usually\n\t\t// the \"round-up\" logic hides the problem.\n\t\tif l == c+1 && c < u {\n\t\t\tc++\n\t\t\tcdigit = 0\n\t\t\tcup = false\n\t\t}\n\t\ttrimmed++\n\t\t// Remember trimmed digits of c\n\t\tc0 = c0 && cNextDigit == 0\n\t\tcNextDigit = int(cdigit)\n\t\tlower, central, upper = l, c, u\n\t}\n\t// should we round up?\n\tif trimmed > 0 {\n\t\tcup = cNextDigit > 5 ||\n\t\t\t(cNextDigit == 5 && !c0) ||\n\t\t\t(cNextDigit == 5 && c0 && central&1 == 1)\n\t}\n\tif central < upper && cup {\n\t\tcentral++\n\t}\n\t// We know where the number ends, fill directly\n\tendindex -= trimmed\n\tv := central\n\tn := endindex\n\tfor n > d.nd {\n\t\tv1, v2 := v/100, v%100\n\t\td.d[n] = smallsString[2*v2+1]\n\t\td.d[n-1] = smallsString[2*v2+0]\n\t\tn -= 2\n\t\tv = v1\n\t}\n\tif n == d.nd {\n\t\td.d[n] = byte(v + '0')\n\t}\n\td.nd = endindex + 1\n\td.dp = d.nd + trimmed\n}", "func tzsetNum(s string, min, max int) (num int, rest string, ok bool) {\n\tif len(s) == 0 {\n\t\treturn 0, \"\", false\n\t}\n\tnum = 0\n\tfor i, r := range s {\n\t\tif r < '0' || r > '9' {\n\t\t\tif i == 0 || num < min {\n\t\t\t\treturn 0, \"\", false\n\t\t\t}\n\t\t\treturn num, s[i:], true\n\t\t}\n\t\tnum *= 10\n\t\tnum += int(r) - '0'\n\t\tif num > max {\n\t\t\treturn 0, \"\", false\n\t\t}\n\t}\n\tif num < min {\n\t\treturn 0, \"\", false\n\t}\n\treturn num, \"\", true\n}", "func (util *stringUtil) FillZero(num string, digit int) string {\n\tfor fillNum := len(num) - digit; fillNum > 0; fillNum-- {\n\t\tnum = \"0\" + num\n\t}\n\treturn num\n}", "func removeZeroPadding(str string) string {\n\tvar buffer bytes.Buffer\n\tfoundNonZeroChar := false\n\tfor _, ch := range str {\n\t\tif string(ch) == \"0\" && !foundNonZeroChar {\n\t\t\tcontinue\n\t\t}\n\t\tfoundNonZeroChar = true\n\t\tbuffer.WriteString(string(ch))\n\t}\n\treturn buffer.String()\n}", "func _0012(num int) string {\n\tvar ans []rune\n\tfor num >= 1000 {\n\t\tnum -= 1000\n\t\tans = append(ans, 'M')\n\t}\n\tif num >= 900 {\n\t\tnum -= 900\n\t\tans = append(ans, 'C', 'M')\n\t}\n\tif num >= 500 {\n\t\tnum -= 500\n\t\tans = append(ans, 'D')\n\t}\n\tif num >= 400 {\n\t\tnum -= 400\n\t\tans = append(ans, 'C', 'D')\n\t}\n\tfor num >= 100 {\n\t\tnum -= 100\n\t\tans = append(ans, 'C')\n\t}\n\tif num >= 90 {\n\t\tnum -= 90\n\t\tans = append(ans, 'X', 'C')\n\t}\n\tif num >= 50 {\n\t\tnum -= 50\n\t\tans = append(ans, 'L')\n\t}\n\tif num >= 40 {\n\t\tnum -= 40\n\t\tans = append(ans, 'X', 'L')\n\t}\n\tfor num >= 10 {\n\t\tnum -= 10\n\t\tans = append(ans, 'X')\n\t}\n\tif num >= 9 {\n\t\tnum -= 9\n\t\tans = append(ans, 'I', 'X')\n\t}\n\tif num >= 5 {\n\t\tnum -= 5\n\t\tans = append(ans, 'V')\n\t}\n\tif num >= 4 {\n\t\tnum -= 4\n\t\tans = append(ans, 'I', 'V')\n\t}\n\tfor num != 0 {\n\t\tnum -= 1\n\t\tans = append(ans, 'I')\n\t}\n\treturn string(ans)\n}", "func CheckNumber(index int, inputText []string) (int, string, error) {\r\n\tvar c string = inputText[index]\r\n\tvar Shift int\r\n\tvar findOctal bool\r\n\tfor i, v := range inputText[index+1:] {\r\n\t\tif IsNumber([]rune(v)[0]) || v == \".\" || v == \"o\" || v == \"O\" {\r\n\t\t\tif v == \"o\" || v == \"O\" {\r\n\t\t\t\tfindOctal = true\r\n\t\t\t}\r\n\t\t\tc += v\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tShift = i\r\n\t\tbreak\r\n\t}\r\n\r\n\tsplittedNumber := strings.Split(c, \"\")\r\n\r\n\tif findOctal { //Make checks if number is Octal\r\n\t\tif splittedNumber[0] == \"0\" && (splittedNumber[1] == \"o\" || splittedNumber[1] == \"O\") {\r\n\t\t\tcountOs := 0\r\n\t\t\tfor _, v := range splittedNumber {\r\n\t\t\t\tif v == \"o\" || v == \"O\" {\r\n\t\t\t\t\tcountOs++\r\n\t\t\t\t} else if !(v >= \"0\" && v <= \"7\") {\r\n\t\t\t\t\treturn index + Shift, c, errors.New(\"Bad octal number\")\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif countOs > 1 {\r\n\t\t\t\treturn index + Shift, c, errors.New(\"Bad octal number\")\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn index + Shift, c, errors.New(\"Bad octal number\")\r\n\t\t}\r\n\r\n\t}\r\n\tcountDots := 0\r\n\tfor _, v := range splittedNumber {\r\n\t\tif v == \".\" {\r\n\t\t\tcountDots++\r\n\t\t}\r\n\t}\r\n\tif countDots > 1 {\r\n\t\treturn index + Shift, c, errors.New(\"Bad float number\")\r\n\t}\r\n\r\n\treturn index + Shift, c, nil\r\n}", "func dtoi(s string) (n int, i int, ok bool) {\n\tn = 0\n\tfor i = 0; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {\n\t\tn = n*10 + int(s[i]-'0')\n\t\tif n >= bigInt {\n\t\t\treturn bigInt, i, false\n\t\t}\n\t}\n\tif i == 0 {\n\t\treturn 0, 0, false\n\t}\n\treturn n, i, true\n}", "func zeroInt(s string) string {\n\tn, _ := strconv.Atoi(s)\n\treturn strconv.FormatInt(int64(n), 10)\n}", "func numscan_e0(c byte) (numscanStep, error) {\n\tif '0' <= c && c <= '9' {\n\t\treturn numscan_e0, nil\n\t}\n\treturn nil, nil\n}", "func LessThanZero(numString string) bool {\n\tdefer color.Unset()\n\tnum, err := strconv.Atoi(numString)\n\tif err != nil {\n\t\tcolor.Set(color.FgRed)\n\t\tlog.L.Infof(\"Error converting %s to a number: %s\", numString, err.Error())\n\t\treturn false\n\t}\n\n\treturn num < 0\n}", "func ZeroTruncate(t BlockType, buf []byte) []byte {\n\tif t.depth() > 0 {\n\t\t// ignore slop at end of block\n\t\ti := (len(buf) / ScoreSize) * ScoreSize\n\t\tzero := ZeroScore()\n\t\tzeroBytes := zero.Bytes()\n\t\tfor i >= ScoreSize {\n\t\t\tif bytes.Equal(buf[i-ScoreSize:i], zeroBytes) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti -= ScoreSize\n\t\t}\n\t\treturn buf[:i]\n\t} else if t == RootType {\n\t\tif len(buf) < RootSize {\n\t\t\treturn buf\n\t\t}\n\t\treturn buf[:RootSize]\n\t} else {\n\t\tvar i int\n\t\tfor i = len(buf); i > 0; i-- {\n\t\t\tif buf[i-1] != 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn buf[:i]\n\t}\n}", "func reducePalindrome(n int) int {\n numberString := strconv.Itoa(n)\n length := len(numberString)\n midlen := length / 2\n reduceValueString := \"\"\n\n if length % 2 == 1 {\n reduceValueString += \"1\"\n for i := midlen + 1; i < length; i++ {\n reduceValueString += \"0\"\n }\n } else {\n reduceValueString += \"11\"\n for i := midlen + 1; i < length; i++ {\n reduceValueString += \"0\"\n }\n }\n reduceValue, _ := strconv.Atoi(reduceValueString)\n\n // if length % 2 == 1 {\n // carryString := \"\"\n // if string(numberString[midlen]) == \"0\" {\n // string(numberString[midlen]) = \"9\"\n // }\n // } else {\n\n // }\n\n return reduceValue\n}", "func formatNano(nanosec uint, n int, trim bool) []byte {\n\tu := nanosec\n\tvar buf [9]byte\n\tfor start := len(buf); start > 0; {\n\t\tstart--\n\t\tbuf[start] = byte(u%10 + '0')\n\t\tu /= 10\n\t}\n\n\tif n > 9 {\n\t\tn = 9\n\t}\n\tif trim {\n\t\tfor n > 0 && buf[n-1] == '0' {\n\t\t\tn--\n\t\t}\n\t\tif n == 0 {\n\t\t\treturn buf[:0]\n\t\t}\n\t}\n\treturn buf[:n]\n}", "func isHappy(n int) bool {\n\tmemo := make(map[int]bool)\n\n\tfor n != 1 && !memo[n] {\n\t\tmemo[n] = true\n\t\ttmp := n\n\t\tfor n != 0 {\n\t\t\ttmp += (n % 10) * (n % 10)\n\t\t\tn /= 10\n\t\t}\n\t\tn = tmp\n\t}\n\n\tif n == 1 {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func (this *BigInteger) ToString(b int64) string {\n\tif this.S < 0 {\n\t\treturn \"-\" + this.Negate().ToString(b)\n\t}\n\tvar k int64\n\tif b == 16 {\n\t\tk = 4\n\t} else if b == 8 {\n\t\tk = 3\n\t} else if b == 2 {\n\t\tk = 1\n\t} else if b == 32 {\n\t\tk = 5\n\t} else if b == 4 {\n\t\tk = 2\n\t} else {\n\t\treturn this.ToRadix(b)\n\t}\n\tvar km int64 = (1 << uint(k)) - 1\n\tvar d int64\n\tvar m bool = false\n\tvar r string = \"\"\n\tvar i int64 = this.T\n\tvar p int64 = DB - (i*DB)%k\n\tif i > 0 {\n\t\ti--\n\t\tif p < DB {\n\t\t\td = this.V[i] >> uint(p)\n\t\t\tif d > 0 {\n\t\t\t\tm = true\n\t\t\t\tr = Int2char(int(d))\n\t\t\t}\n\t\t}\n\t\tfor i >= 0 {\n\t\t\tif p < k {\n\t\t\t\td = this.V[i] & ((1 << uint(p)) - 1) << uint(k-p)\n\t\t\t\ti--\n\t\t\t\tp += DB - k\n\t\t\t\td |= this.V[i] >> uint(p)\n\t\t\t} else {\n\t\t\t\tp -= k\n\t\t\t\td = (this.V[i] >> uint(p)) & km\n\t\t\t\tif p <= 0 {\n\t\t\t\t\tp += DB\n\t\t\t\t\ti--\n\t\t\t\t}\n\t\t\t}\n\t\t\tif d > 0 {\n\t\t\t\tm = true\n\t\t\t}\n\t\t\tif m {\n\t\t\t\tr += Int2char(int(d))\n\t\t\t}\n\t\t}\n\t}\n\tif m {\n\t\treturn r\n\t} else {\n\t\treturn \"0\"\n\t}\n}", "func (n *Number) Zero() bool {\n\tif n.isInteger {\n\t\treturn n.integer.Cmp(&big.Int{}) == 0\n\t} else {\n\t\treturn n.floating == 0\n\t}\n}", "func isLeadingNumZeroes(hash []byte) bool {\n\tif numLeadingZeroes == 0 {\n\t\treturn true\n\t} else {\n\t\ti := 0\n\t\tnumZeroes := numLeadingZeroes\n\t\tfor {\n\t\t\t// numZeroes <= 8, byte at hash[i] will determine validity\n\t\t\tif numZeroes-8 <= 0 {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\t// numZeroes is greater than 8, byte at hash[i] must be zero\n\t\t\t\tif hash[i] != 0 {\n\t\t\t\t\treturn false\n\t\t\t\t} else {\n\t\t\t\t\ti++\n\t\t\t\t\tnumZeroes -= 8\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// returns true if byte at hash[i] has the the minimum number of leading zeroes\n\t\t// if numZeroes is 8: hash[i] < 2^(8-8) == hash[1] < 1 == hash[i] must be (0000 0000)b.\n\t\t// if numZeroes is 1: hash[i] < 2^(8-1) == hash[1] < (1000 0000)b == hash[i] <= (0111 1111)b\n\t\treturn float64(hash[i]) < math.Pow(2, float64(8-numZeroes))\n\t}\n}", "func NumStrToChineseStr(numStr string) string {\n\tvar b bytes.Buffer\n\tfor _, c := range numStr {\n\t\tdigitChar := string(c)\n\t\tdigit, ok := gDigitCharDigit[digitChar]\n\n\t\tif ok {\n\t\t\tb.WriteString(fmt.Sprintf(\"[%d[\", digit))\n\t\t\tpinyinList := DigitToConsonant(digit)\n\n\t\t\tfor i, py := range pinyinList {\n\n\t\t\t\tchStr := pinyinToChineseStr(py)\n\t\t\t\tif i == 0 {\n\t\t\t\t\tb.WriteString(\"\\n\")\n\t\t\t\t}\n\t\t\t\tb.WriteString(fmt.Sprintf(\" %s -> %s\\n\", py, chStr))\n\t\t\t}\n\t\t\tb.WriteString(fmt.Sprintf(\"]]\\n\\n\"))\n\t\t} else {\n\t\t\tb.WriteString(fmt.Sprintf(\"[[%s]]\\n\\n\", digitChar))\n\t\t}\n\n\t}\n\treturn b.String()\n}", "func isZero(buffer []byte) bool {\n\tfor i := range buffer {\n\t\tif buffer[i] != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func trim(a *decimal) {\n\tfor a.nd > 0 && a.d[a.nd-1] == '0' {\n\t\ta.nd--\n\t}\n\tif a.nd == 0 {\n\t\ta.dp = 0\n\t}\n}", "func isPossible2(x int) int {\n\ts := strconv.Itoa(x)\n\tvar (\n\t\tlastC rune\n\t\tgs [10]int\n\t\tnotIncreasing bool\n\t\thasDouble bool\n\t)\n\tfor pos, c := range s {\n\t\tif pos > 0 {\n\t\t\tif lastC == c {\n\t\t\t\tgs[c - '0']++\n\t\t\t}\n\t\t\tif c < lastC {\n\t\t\t\tnotIncreasing = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tlastC = c\n\t}\n\tfor i := range gs {\n\t\tif gs[i] == 1 {\n\t\t\thasDouble = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif hasDouble && !notIncreasing {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func RemoveDecFromFloat(in *big.Float) (*big.Int, error) {\n\t// fmt.Println(\"REMOVEDECFROMFLOAT -> this is the incoming float\", in)\n\ts := fmt.Sprintf(\"%.128f\", in)\n\t// fmt.Println(\"REMOVEDECFROMFLOAT -> this is the string\", s)\n\tif len(s) == 0 {\n\t\treturn nil, fmt.Errorf(\"%s\", \"string has 0 zero length\")\n\t}\n\tx := strings.Replace(s, \".\", \"\", -1)\n\t// fmt.Println(\"REMOVEDECFROMFLOAT -> this is the string result : \", x)\n\ta := big.NewInt(0)\n\ta.SetString(x, 0)\n\t// fmt.Println(\"REMOVEDECFROMFLOAT -> this is the final big int : \", a)\n\treturn a, nil\n}", "func TrailingZeroBits(x *big.Int) uint {\n\treturn x.TrailingZeroBits()\n}", "func SomenteNumeros(cnpj string) string {\n\tr := regexp.MustCompile(\"[0-9]+\")\n\treturn strings.Join(r.FindAllString(cnpj, -1), \"\")\n}", "func parseNumber(cur *GoJSON, input []byte) ([]byte, error) {\n\tvar n, sign, scale float64\n\tvar subscale, signsubscale, offset int\n\tvar isDouble bool = false\n\n\tsign = 1\n\tsubscale = 0\n\tsignsubscale = 1\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Byte slice is empty\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tif input[offset] == '-' {\n\t\tsign = -1\n\t\toffset++\n\t}\n\n\tif unicode.IsDigit(rune(input[offset])) == false {\n\t\terrorStr := fmt.Sprintf(\"%s: Not a valid number in input %s\", funcName(), string(input))\n\t\treturn nil, errors.New(errorStr)\n\t}\n\n\tfor {\n\t\tif input[offset] == '0' {\n\t\t\toffset++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor {\n\t\tif unicode.IsDigit(rune(input[offset])) == true {\n\t\t\tn = (n * 10.0) + float64(input[offset]-'0')\n\t\t\toffset++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif input[offset] == '.' && unicode.IsDigit(rune(input[offset+1])) == true {\n\t\toffset++\n\t\tisDouble = true\n\n\t\tfor {\n\t\t\tif unicode.IsDigit(rune(input[offset])) == true {\n\t\t\t\tn = (n * 10.0) + float64(input[offset]-'0')\n\t\t\t\toffset++\n\t\t\t\tscale--\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif input[offset] == 'e' || input[offset] == 'E' {\n\t\toffset++\n\t\tisDouble = true\n\n\t\tif input[offset] == '-' {\n\t\t\tsignsubscale = -1\n\t\t}\n\t\toffset++\n\n\t\tfor {\n\t\t\tif unicode.IsDigit(rune(input[offset])) == true {\n\t\t\t\tsubscale = (subscale * 10) + int(input[offset]-'0')\n\t\t\t\toffset++\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tn = sign * n * math.Pow(10.0, scale+float64(subscale)*float64(signsubscale))\n\n\tif isDouble == true {\n\t\tcur.Valdouble = n\n\t\tcur.Jsontype = JSON_DOUBLE\n\t} else if sign == -1 {\n\t\tcur.Valint = int64(n)\n\t\tcur.Jsontype = JSON_INT\n\t} else {\n\t\tcur.Valuint = uint64(n)\n\t\tcur.Jsontype = JSON_UINT\n\t}\n\n\treturn input[offset:], nil\n}", "func trailingZeroes(n int) int {\n\tif n < 5 {\n\t\treturn 0\n\t}\n\tfives := n / 5\n\n\treturn fives + trailingZeroes(n/5)\n}", "func leadingZeros(x uint32) (n int) {\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\tn += int(len8tab[x])\n\treturn 32 - n\n}", "func asciiToNumber(c byte) (uint8, error) {\n\tif c < one || c > nine {\n\t\treturn uint8(c), ErrParseInvalidNumber\n\t}\n\treturn uint8(c) - zero, nil\n}", "func LeadingZeros16(x uint16) int { return 16 - Len16(x) }", "func LeadingZeros16(x uint16) int { return 16 - Len16(x) }", "func ConvertFromDec(numS string, toBase int) (string, error) {\n\tif toBase < 2 {\n\t\treturn \"\", fmt.Errorf(\"Invalid base: %v\", toBase)\n\t}\n\tif numS == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Nothing to convert\")\n\t}\n\t// Converting string to the number bigger than int64.\n\tbNum := big.NewInt(0)\n\tbNum, ok := bNum.SetString(numS, 10)\n\tif ok != true {\n\t\treturn \"\", fmt.Errorf(\"Invalid number: %v\", numS)\n\t}\n\tbZero := big.NewInt(0)\n\t// If original number is equal to \"0...0\".\n\tif bNum.Cmp(bZero) == 0 {\n\t\treturn \"0\", nil\n\t}\n\t// If the number is negativ: flagNeg = 1 and \"saving\" the negative sign.\n\tif bNum.Cmp(bZero) == -1 {\n\t\tflagNeg = 1\n\t\tbNum.Neg(bNum)\n\t}\n\t// Converting the number to needed base (toBase).\n\tvar newNum string\n\tbToBase := big.NewInt(int64(toBase))\n\tbReminder := big.NewInt(0)\n\tfor bNum.Cmp(bZero) != 0 {\n\t\tbNum.DivMod(bNum, bToBase, bReminder)\n\t\treminderHex := numToLetter(bReminder.Int64(), toBase)\n\t\tnewNum += reminderHex\n\t}\n\n\tif flagNeg != 0 {\n\t\t// If original number was negative - making new one negative too.\n\t\tnewNum += \"-\"\n\t\tflagNeg = 0\n\t}\n\t// Reversing the number.\n\tnumRunes := []rune(newNum)\n\tleft := 0\n\tright := len(numRunes) - 1\n\tfor left < len(numRunes)/2 {\n\t\tnumRunes[left], numRunes[right] = numRunes[right], numRunes[left]\n\t\tleft++\n\t\tright--\n\t}\n\n\treturn string(numRunes), nil\n}", "func Humanize(n uint64) string {\n\t// -1 precision removes trailing zeros\n\treturn HumanizeWithPrecision(n, -1)\n}", "func (v *Version) intOrZero(input string) (value int) {\n\tif input != \"\" {\n\t\tvalue, _ = strconv.Atoi(input)\n\t}\n\treturn value\n}", "func removeDigit(number string, digit byte) string {\n\tbs := []byte(number)\n\trem := 0\n\tafter := false\n\tfor i, d := range bs {\n\t\tif after {\n\t\t\tif d > digit {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tafter = false\n\t\t}\n\t\tif d == digit {\n\t\t\trem = i\n\t\t\tafter = true\n\t\t}\n\t}\n\n\treturn number[:rem] + number[rem+1:]\n}", "func duplicateZeros(n int) string {\n\tvar zero string\n\tfor i := 0; i < n; i++ {\n\t\tzero += \"f0\"\n\t}\n\n\treturn zero\n}", "func numscan_neg(c byte) (numscanStep, error) {\n\tif c == '0' {\n\t\treturn numscan_0, nil\n\t}\n\tif '1' <= c && c <= '9' {\n\t\treturn numscan_1, nil\n\t}\n\treturn nil, fmt.Errorf(\"invalid byte in numeric literal: 0x%x\", c)\n}", "func TakeNumberFromString(chTextString string, opt ...interface{}) interface{} {\n\n\t//默认参数设置\n\tif len(opt) > 2 {\n\t\tpanic(\"too many arguments\")\n\t}\n\n\tvar percentConvert bool\n\tvar traditionalConvert bool\n\t// digitsNumberSwitch := false\n\n\tswitch len(opt) {\n\tcase 1:\n\t\tpercentConvert = opt[0].(bool)\n\t\ttraditionalConvert = true\n\t\t// digitsNumberSwitch = false\n\tcase 2:\n\t\tpercentConvert = opt[0].(bool)\n\t\ttraditionalConvert = opt[1].(bool)\n\t\t// digitsNumberSwitch = false\n\t// case 3:\n\t// \tpercentConvert = opt[0].(bool)\n\t// \ttraditionalConvert = opt[1].(bool)\n\t// digitsNumberSwitch = opt[2].(bool)\n\tdefault:\n\t\tpercentConvert = true\n\t\ttraditionalConvert = true\n\t}\n\tfinalResult := TakeChineseNumberFromString(chTextString, percentConvert, traditionalConvert)\n\treturn finalResult\n}", "func ToNepaliDigitString(digit int, str *string) {\n\tif digit == 0 {\n\t\treturn\n\t}\n\tToNepaliDigitString(digit/10, str)\n\t*str += NepaliDigit[digit%10]\n}", "func LeadingZeros32(x uint32) int { return 32 - Len32(x) }", "func LeadingZeros32(x uint32) int { return 32 - Len32(x) }", "func LeadingZeros16(x uint16) int {\n\t_x := int16(x)\n\tn := int16(0)\n\ty := _x\nL:\n\tif _x < 0 {\n\t\treturn int(n)\n\t}\n\tif y == 0 {\n\t\treturn int(16 - n)\n\t}\n\tn = n + 1\n\tx = x << 1\n\ty = y >> 1\n\tgoto L\n}", "func nonZeroToAllOnes(x uint32) uint32 {\n\treturn ((x - 1) >> 31) - 1\n}", "func nonZeroToAllOnes(x uint32) uint32 {\n\treturn ((x - 1) >> 31) - 1\n}", "func (conn *ConnWithParameters) checkZero(coord []string) []string {\n\t//compare the decimals of the \"-0.\" case to the zeroTest\n\t//if they are equal, remove the \"-\"\n\tzeroTest := conn.zeroTest\n\tif strings.Compare(coord[1], zeroTest) == 0 {\n\t\tcoord[0] = \"0.\"\n\t\treturn coord\n\t}\n\treturn coord\n}", "func TestWordToKoKo_number_inside(t *testing.T) {\r\n\tconst src3 string = \"he11o05ty\"\r\n\r\n\tsrc3_2 := wordToKoKo(src3)\r\n\tif src3_2 != Ko+Ko+Ko+Koo {\r\n\t\tt.Error(\"word_with_num_inside src -> ordinary koko's output\")\r\n\t}\r\n}", "func (b Bits) String() string {\n\tif b == 0 {\n\t\treturn \"0\"\n\t}\n\t// Largest value is \"-123.150EB\"\n\tvar buf [10]byte\n\tw := len(buf) - 1\n\tu := uint64(b)\n\tneg := b < 0\n\tif neg {\n\t\tu = -u\n\t}\n\tif u < uint64(Byte) {\n\t\tw -= 2\n\t\tcopy(buf[w:], \"Bit\")\n\t\tw = fmtInt(buf[:w], u)\n\t} else {\n\t\tswitch {\n\t\tcase u < uint64(KB):\n\t\t\tw -= 0\n\t\t\tbuf[w] = 'B'\n\t\t\tu = (u * 1e3 / 8)\n\t\tcase u < uint64(MB):\n\t\t\tw -= 1\n\t\t\tcopy(buf[w:], \"kB\")\n\t\t\tu /= 8\n\t\tcase u < uint64(GB):\n\t\t\tw -= 1\n\t\t\tcopy(buf[w:], \"MB\")\n\t\t\tu /= 8 * 1e3\n\t\tcase u < uint64(TB):\n\t\t\tw -= 1\n\t\t\tcopy(buf[w:], \"GB\")\n\t\t\tu /= 8 * 1e6\n\t\tcase u < uint64(PB):\n\t\t\tw -= 1\n\t\t\tcopy(buf[w:], \"TB\")\n\t\t\tu /= 8 * 1e9\n\t\tcase u < uint64(EB):\n\t\t\tw -= 1\n\t\t\tcopy(buf[w:], \"PB\")\n\t\t\tu /= 8 * 1e12\n\t\tcase u >= uint64(EB):\n\t\t\tw -= 1\n\t\t\tcopy(buf[w:], \"EB\")\n\t\t\tu /= 8 * 1e15\n\t\t}\n\t\tw, u = fmtFrac(buf[:w], u, 3)\n\t\tw = fmtInt(buf[:w], u)\n\t}\n\tif neg {\n\t\tw--\n\t\tbuf[w] = '-'\n\t}\n\treturn string(buf[w:])\n}", "func validateKeyNotZero(key *big.Int) error {\n\t// Check if key = 0\n\tif len(key.Bits()) == 0 {\n\t\treturn errors.New(\"validateKeyNotZero: key is 0\")\n\t}\n\treturn nil\n}", "func byteCountToHuman(b int64) string {\n\tconst unit = 1000\n\tif b < unit {\n\t\treturn fmt.Sprintf(\"%dB\", b)\n\t}\n\tdiv, exp := int64(unit), 0\n\tfor n := b / unit; n >= unit; n /= unit {\n\t\tdiv *= unit\n\t\texp++\n\t}\n\treturn fmt.Sprintf(\"%.1f%cB\", float64(b)/float64(div), \"kMGTPE\"[exp])\n}", "func (t Token) IsZero() bool {\n\t// as each number is already minified, starting with a zero means it is zero\n\treturn (t.TokenType == css.DimensionToken || t.TokenType == css.PercentageToken || t.TokenType == css.NumberToken) && t.Data[0] == '0'\n}", "func ParseUint(s string) (uint64, error) {\n\tn := len(s)\n\tif n == 0 {\n\t\treturn 0, ErrEmpty\n\t}\n\tsum := uint64(0)\n\tsegment := uint64(0)\n\tlastValue := uint64(0)\n\tminSegmentValue := uint64(math.MaxUint64)\n\tminSegmentEnd := uint64(math.MaxUint64)\n\ti := 0\nloop:\n\tfor ; i < n-2; i += 3 {\n\t\tr := decodeUtf8Kanji(i, s)\n\t\tvalue, ok := ValueOf(r)\n\t\tif value > 0 && ok {\n\t\t\tif value < 10 { // 1 to 9\n\t\t\t\t// last number must not be < 10 as well\n\t\t\t\tif 0 < lastValue && lastValue < 10 {\n\t\t\t\t\treturn 0, ErrInvalidSequence\n\t\t\t\t}\n\t\t\t\tlastValue = value\n\t\t\t} else if value < 10_000 { // 10, 100, 1000\n\t\t\t\t// check if we already encountered this number in the current segment\n\t\t\t\tif value >= minSegmentValue {\n\t\t\t\t\treturn 0, ErrInvalidSequence\n\t\t\t\t}\n\t\t\t\tminSegmentValue = value\n\t\t\t\t// multiply with last number if allowed and possible\n\t\t\t\tif 0 < lastValue && lastValue < 10 {\n\t\t\t\t\tsegment += lastValue * value\n\t\t\t\t} else {\n\t\t\t\t\tsegment += value\n\t\t\t\t}\n\t\t\t\tlastValue = value\n\t\t\t} else { // >= 1_0000\n\t\t\t\t// check if we already encountered this number\n\t\t\t\tif value >= minSegmentEnd {\n\t\t\t\t\treturn 0, ErrInvalidSequence\n\t\t\t\t}\n\t\t\t\tminSegmentEnd = value\n\t\t\t\t// create sum of current segment and add to sum\n\t\t\t\tif 0 < lastValue && lastValue < 10 {\n\t\t\t\t\tsegment += lastValue\n\t\t\t\t}\n\t\t\t\tif segment == 0 {\n\t\t\t\t\treturn 0, ErrInvalidSequence\n\t\t\t\t}\n\n\t\t\t\tvar carry uint64\n\t\t\t\toverflow, segmentSum := bits.Mul64(segment, value)\n\t\t\t\tsum, carry = bits.Add64(sum, segmentSum, 0)\n\t\t\t\tif carry > 0 || overflow > 0 {\n\t\t\t\t\treturn 0, ErrOverflow\n\t\t\t\t}\n\t\t\t\t// prepare for new segment\n\t\t\t\tminSegmentValue = uint64(math.MaxUint64)\n\t\t\t\tsegment = 0\n\t\t\t\tlastValue = 0\n\t\t\t}\n\t\t} else {\n\t\t\tswitch r {\n\t\t\tcase '零', '〇':\n\t\t\t\tif i == 0 {\n\t\t\t\t\ti += 3\n\t\t\t\t\tbreak loop\n\t\t\t\t}\n\t\t\t\treturn 0, ErrInvalidSequence\n\t\t\t// 10^20 - 10^68 overflows uint64\n\t\t\t// only the first kanji for multi kanji numbers\n\t\t\tcase '垓', '秭', '穣', '溝',\n\t\t\t\t'澗', '正', '載', '極',\n\t\t\t\t'恒', '阿', '那', '不',\n\t\t\t\t'無':\n\t\t\t\treturn 0, ErrOverflow\n\t\t\tdefault:\n\t\t\t\treturn 0, checkUnexpectedRune(s[i:])\n\t\t\t}\n\t\t}\n\t}\n\tif i < n {\n\t\treturn 0, checkUnexpectedRune(s[i:])\n\t}\n\t// add last segment to sum if there is one\n\tif 0 < lastValue && lastValue < 10 {\n\t\tsegment += lastValue\n\t}\n\tif segment > 0 {\n\t\tvar carry uint64\n\t\tsum, carry = bits.Add64(sum, segment, 0)\n\t\tif carry > 0 {\n\t\t\treturn 0, ErrOverflow\n\t\t}\n\t}\n\treturn sum, nil\n}", "func TokenValueToString(input *big.Int, decimals uint8, _ bool) string {\n\toutput := \"\"\n\n\t// Take a string version of the input.\n\tvalue := input.String()\n\n\t// Input sanity checks.\n\tif input.Cmp(zero) == 0 {\n\t\treturn \"0\"\n\t}\n\n\tnonDecimalLength := len(value) - int(decimals)\n\tswitch {\n\tcase nonDecimalLength <= 0:\n\t\t// We need to add leading decimal 0s.\n\t\toutput = \"0.\" + strings.Repeat(\"0\", int(decimals)-len(value)) + value\n\t\toutput = strings.TrimRight(output, \"0\")\n\tcase nonDecimalLength == len(value):\n\t\toutput = value\n\tdefault:\n\t\t// We might need to add decimal point.\n\t\tpostDecimalsAllZero, _ := regexp.MatchString(\"^0+$\", value[nonDecimalLength:])\n\t\tif postDecimalsAllZero {\n\t\t\t// Nope; just take the leading figures.\n\t\t\toutput = value[:nonDecimalLength]\n\t\t} else {\n\t\t\t// Yep; add the zeros.\n\t\t\toutput = value[:nonDecimalLength] + \".\" + value[nonDecimalLength:]\n\t\t\toutput = strings.TrimRight(output, \"0\")\n\t\t}\n\t}\n\treturn output\n}", "func _(n int) int {\n\tif n > 1 {\n\t\tn *= 10\n\t} else if n > 10 {\n\t\tn *= 100\n\n\t} else if n > 1100 {\n\t\tn *= 110\n\t}\n\treturn n\n}", "func formatZeroValue(T types.Type, qf types.Qualifier) string {\n\tswitch u := T.Underlying().(type) {\n\tcase *types.Basic:\n\t\tswitch {\n\t\tcase u.Info()&types.IsNumeric > 0:\n\t\t\treturn \"0\"\n\t\tcase u.Info()&types.IsString > 0:\n\t\t\treturn `\"\"`\n\t\tcase u.Info()&types.IsBoolean > 0:\n\t\t\treturn \"false\"\n\t\tdefault:\n\t\t\treturn \"\"\n\t\t}\n\tcase *types.Pointer, *types.Interface, *types.Chan, *types.Map, *types.Slice, *types.Signature:\n\t\treturn \"nil\"\n\tdefault:\n\t\treturn types.TypeString(T, qf) + \"{}\"\n\t}\n}", "func superDigit(n string, k int32) int32 {\n\tvar s int64\n\tfor _, d := range n {\n\t\ts += int64(d - 0x30)\n\t}\n\treturn int32(sum(s * int64(k)))\n}", "func isPossible(x int) int {\n\ts := strconv.Itoa(x)\n\tvar (\n\t\tlastC rune\n\t\thasDouble bool\n\t\tnotIncreasing bool\n\t)\n\tfor pos, c := range s {\n\t\tif pos > 0 {\n\t\t\tif lastC == c {\n\t\t\t\thasDouble = true\n\t\t\t}\n\t\t\tif c < lastC {\n\t\t\t\tnotIncreasing = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tlastC = c\n\t}\n\tif hasDouble && !notIncreasing {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func IsZeroToThree(r rune) bool {\n\treturn (r == '0' || r == '1' || r == '2' || r == '3')\n}", "func checkLastDigit(cISBN []int) bool {\n\tvar sum int\n\tfor i, v := range cISBN {\n\t\tsum += int(math.Abs(float64(i)-10)) * v\n\t}\n\tres := sum % 11\n\treturn res == 0\n}", "func noasm_countTrailingZeros(x uint64) int {\n\t// x & -x leaves only the right-most bit set in the word. Let k be the\n\t// index of that bit. Since only a single bit is set, the value is two\n\t// to the power of k. Multiplying by a power of two is equivalent to\n\t// left shifting, in this case by k bits. The de Bruijn constant is\n\t// such that all six bit, consecutive substrings are distinct.\n\t// Therefore, if we have a left shifted version of this constant we can\n\t// find by how many bits it was shifted by looking at which six bit\n\t// substring ended up at the top of the word.\n\t// (Knuth, volume 4, section 7.3.1)\n\treturn int(noasm_deBruijn64Lookup[((x&-x)*(noasm_deBruijn64))>>58])\n}", "func LeadingZeros64(x uint64) int { return 64 - Len64(x) }", "func LeadingZeros64(x uint64) int { return 64 - Len64(x) }", "func convertToBase7(num int) string {\n\tif num == 0 {\n\t\treturn \"0\"\n\t}\n\tarr := []byte{}\n\tneg := false\n\tif num < 0 {\n\t\tneg = true\n\t\tnum *= -1\n\t}\n\tfor num != 0 {\n\t\tarr = append(arr, byte(num%7)+'0')\n\t\tnum /= 7\n\t}\n\tif neg {\n\t\tarr = append(arr, '-')\n\t}\n\tfor i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {\n\t\tarr[i], arr[j] = arr[j], arr[i]\n\t}\n\treturn string(arr)\n}" ]
[ "0.56443095", "0.55608016", "0.55232406", "0.5510075", "0.550407", "0.54581755", "0.5450317", "0.5422908", "0.53383005", "0.5303034", "0.52828276", "0.52789444", "0.52776885", "0.5268197", "0.52392256", "0.52033955", "0.52033955", "0.5184833", "0.5183813", "0.51807237", "0.50908285", "0.50908285", "0.50889266", "0.5064498", "0.5052907", "0.5029578", "0.5028016", "0.50201935", "0.5003205", "0.49869996", "0.49862492", "0.49718165", "0.49684447", "0.49670866", "0.49583083", "0.4952059", "0.4945541", "0.4944261", "0.49391642", "0.49368507", "0.49367493", "0.49264225", "0.4908674", "0.48946682", "0.4891051", "0.4885914", "0.48711365", "0.48677126", "0.48555174", "0.48517263", "0.48422983", "0.4823581", "0.48210248", "0.48209086", "0.48180136", "0.4813078", "0.48083362", "0.47956264", "0.47858784", "0.47851354", "0.47750565", "0.47732735", "0.47723386", "0.47690907", "0.4766767", "0.47626182", "0.47602725", "0.47537243", "0.47537243", "0.4726964", "0.47218823", "0.47185087", "0.47152194", "0.47088388", "0.47084263", "0.47064307", "0.47062206", "0.46918923", "0.46918923", "0.46895218", "0.46869415", "0.46869415", "0.46861514", "0.46851185", "0.46837932", "0.467558", "0.46750414", "0.46739697", "0.46540314", "0.4651012", "0.4646855", "0.46434167", "0.46370918", "0.4624054", "0.4618397", "0.46172997", "0.46159422", "0.46134117", "0.46134117", "0.46121216" ]
0.68486977
0
NewMockUserRepositoryInterface creates a new mock instance
func NewMockUserRepositoryInterface(ctrl *gomock.Controller) *MockUserRepositoryInterface { mock := &MockUserRepositoryInterface{ctrl: ctrl} mock.recorder = &MockUserRepositoryInterfaceMockRecorder{mock} return mock }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewMockRepository() Repository {\n\treturn mockRepository{\n\t\tUser{\n\t\t\tEmail: \"[email protected]\",\n\t\t\tName: \"User Friendly\",\n\t\t\tRole: \"user\",\n\t\t\tID: 42,\n\t\t\tPassword: \"user1\",\n\t\t},\n\t\tUser{\n\t\t\tEmail: \"[email protected]\",\n\t\t\tName: \"John Walker\",\n\t\t\tRole: \"user\",\n\t\t\tID: 45,\n\t\t\tPassword: \"12345qwerty\",\n\t\t},\n\t}\n}", "func NewMockUser() sqlmock.Sqlmock {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tlog.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\n\tdbMockUsers = db\n\tconnMockUser = &database.Data{\n\t\tDB: dbMockUsers,\n\t}\n\n\tuserRepositoryMock = repo.NewPostgresUserRepo(connMockUser)\n\n\t/*userRepositoryMock = &repo.UserRepository{\n\t\tData: &connMockUser,\n\t}*/\n\n\treturn mock\n}", "func newUserRepo(db *sql.DB) *userRepo {\n\treturn &userRepo{\n\t\tdb: db,\n\t}\n}", "func NewTestRepository() user.IRepository {\n\tlog.Println(\"Create users table...\")\n\n\trep := &testRepo{\n\t\tusers: make([]*user.User, 0),\n\t}\n\n\treturn rep\n}", "func NewMockUserGormRepo(dbConn *gorm.DB) user.UserRepository {\n\treturn &MockUserGormRepo{conn: dbConn}\n}", "func (m *MockIUserRepository) CreateNewUser() *model.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateNewUser\")\n\tret0, _ := ret[0].(*model.User)\n\treturn ret0\n}", "func (m_2 *MockUserRepository) Create(m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Create\", m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockUserRepositoryProvider) Create(user *model.User) (int, error) {\n\tret := _m.Called(user)\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func(*model.User) int); ok {\n\t\tr0 = rf(user)\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*model.User) error); ok {\n\t\tr1 = rf(user)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockHandler) UserCreate(username, email, password string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserCreate\", username, email, password)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func NewMockUsersRepoInterface(ctrl *gomock.Controller) *MockUsersRepoInterface {\n\tmock := &MockUsersRepoInterface{ctrl: ctrl}\n\tmock.recorder = &MockUsersRepoInterfaceMockRecorder{mock}\n\treturn mock\n}", "func (_m *UserRepository) Create(user domain.User) (domain.User, error) {\n\tret := _m.Called(user)\n\n\tvar r0 domain.User\n\tif rf, ok := ret.Get(0).(func(domain.User) domain.User); ok {\n\t\tr0 = rf(user)\n\t} else {\n\t\tr0 = ret.Get(0).(domain.User)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(domain.User) error); ok {\n\t\tr1 = rf(user)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockUserProvider) Create(username string, password []byte, FirstName string, LastName string, confirmationToken []byte, isSuperuser bool, IsStaff bool, isActive bool, isConfirmed bool) (*UserEntity, error) {\n\tret := _m.Called(username, password, FirstName, LastName, confirmationToken, isSuperuser, IsStaff, isActive, isConfirmed)\n\n\tvar r0 *UserEntity\n\tif rf, ok := ret.Get(0).(func(string, []byte, string, string, []byte, bool, bool, bool, bool) *UserEntity); ok {\n\t\tr0 = rf(username, password, FirstName, LastName, confirmationToken, isSuperuser, IsStaff, isActive, isConfirmed)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*UserEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, []byte, string, string, []byte, bool, bool, bool, bool) error); ok {\n\t\tr1 = rf(username, password, FirstName, LastName, confirmationToken, isSuperuser, IsStaff, isActive, isConfirmed)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUsersRepo) Create(arg0 auth.User) (auth.User, error) {\n\tret := m.ctrl.Call(m, \"Create\", arg0)\n\tret0, _ := ret[0].(auth.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserPGRepository) Create(ctx context.Context, user *models.User) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, user)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserLogic) UserCreate(username, email, password string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserCreate\", username, email, password)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockRepository) Create(ctx context.Context, u *models.User) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, u)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func New(repo rel.Repository) UserRepository {\n\treturn userRepository{\n\t\trepository: repo,\n\t}\n}", "func NewMockUserInterface(ctrl *gomock.Controller) *MockUserInterface {\n\tmock := &MockUserInterface{ctrl: ctrl}\n\tmock.recorder = &MockUserInterfaceMockRecorder{mock}\n\treturn mock\n}", "func (_m *MockUserProvider) CreateSuperuser(username string, password []byte, FirstName string, LastName string) (*UserEntity, error) {\n\tret := _m.Called(username, password, FirstName, LastName)\n\n\tvar r0 *UserEntity\n\tif rf, ok := ret.Get(0).(func(string, []byte, string, string) *UserEntity); ok {\n\t\tr0 = rf(username, password, FirstName, LastName)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*UserEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, []byte, string, string) error); ok {\n\t\tr1 = rf(username, password, FirstName, LastName)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *UserRepositoryI) Create(tx database.TransactionI, user *models.UserPrivateInfo) (int, error) {\n\tret := _m.Called(tx, user)\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func(database.TransactionI, *models.UserPrivateInfo) int); ok {\n\t\tr0 = rf(tx, user)\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(database.TransactionI, *models.UserPrivateInfo) error); ok {\n\t\tr1 = rf(tx, user)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func createRepo(repoConstructorFunc interface{}, convMock interface{}) interface{} {\n\tv := reflect.ValueOf(repoConstructorFunc)\n\tif v.Kind() != reflect.Func {\n\t\tpanic(\"Repo constructor should be a function\")\n\t}\n\tt := v.Type()\n\n\tif t.NumOut() != 1 {\n\t\tpanic(\"Repo constructor should return only one argument\")\n\t}\n\n\tif t.NumIn() == 0 {\n\t\treturn v.Call(nil)[0].Interface()\n\t}\n\n\tif t.NumIn() != 1 {\n\t\tpanic(\"Repo constructor should accept zero or one arguments\")\n\t}\n\n\tmockVal := reflect.ValueOf(convMock)\n\treturn v.Call([]reflect.Value{mockVal})[0].Interface()\n}", "func (m *MockUserRepo) Create(ctx context.Context, input CreateUserInput) (User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, input)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewAdminRepoMock(up, nem, jwt string) *AdminRepoMock {\n\treturn &AdminRepoMock{\n\t\tUniversalPassword: up,\n\t\tNonExistentEmail: nem,\n\t\tFakeJWT: jwt,\n\t}\n}", "func NewMockUsersRepository(ctrl *gomock.Controller) *MockUsersRepository {\n\tmock := &MockUsersRepository{ctrl: ctrl}\n\tmock.recorder = &MockUsersRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockUsersRepo(ctrl *gomock.Controller) *MockUsersRepo {\n\tmock := &MockUsersRepo{ctrl: ctrl}\n\tmock.recorder = &MockUsersRepoMockRecorder{mock}\n\treturn mock\n}", "func (m *MockUserRepo) Create(arg0 *app.User) (*app.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", arg0)\n\tret0, _ := ret[0].(*app.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func CreateUserRepositoryForTests() stored_users.UserRepository {\n\tfileRepository := concrete_files.CreateFileRepositoryForTests()\n\tuserBuilderFactory := CreateUserBuilderFactoryForTests()\n\tout := CreateUserRepository(fileRepository, userBuilderFactory)\n\treturn out\n}", "func (m *MockUserRepository) Create(user *auth.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func NewMockIUserRepository(ctrl *gomock.Controller) *MockIUserRepository {\n\tmock := &MockIUserRepository{ctrl: ctrl}\n\tmock.recorder = &MockIUserRepositoryMockRecorder{mock}\n\treturn mock\n}", "func (m *MockGitUseCaseI) Create(userID int64, repos *git.Repository) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", userID, repos)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockrepoProvider) Create(ctx context.Context, user *types.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUser) Create(ctx context.Context, db repo.DB, username string, hashedPassword []byte, now time.Time) (int, *internal.E) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, db, username, hashedPassword, now)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(*internal.E)\n\treturn ret0, ret1\n}", "func makeTestRepo() *TestRepo {\n\ttestRepo := &TestRepo{\n\t\tArgsIn: make(map[string][]interface{}),\n\t\tArgsOut: make(map[string][]interface{}),\n\t\tSpecialFuncs: make(map[string]interface{}),\n\t}\n\ttestRepo.ArgsIn[GetUserByExternalIDMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[AddUserMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[UpdateUserMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[GetUsersFilteredMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[GetGroupsByUserIDMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[RemoveUserMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[GetGroupByNameMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[IsMemberOfGroupMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[GetGroupMembersMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[IsAttachedToGroupMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[GetAttachedPoliciesMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[GetGroupsFilteredMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[RemoveGroupMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[AddGroupMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[AddMemberMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[RemoveMemberMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[UpdateGroupMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[AttachPolicyMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[DetachPolicyMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[GetPolicyByNameMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[AddPolicyMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[UpdatePolicyMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[RemovePolicyMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[GetPoliciesFilteredMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[GetAttachedGroupsMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[OrderByValidColumnsMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[GetProxyResourcesMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[RemoveProxyResourceMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[AddProxyResourceMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[UpdateProxyResourceMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[GetProxyResourceByNameMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsIn[AddOidcProviderMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[GetOidcProviderByNameMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[GetOidcProvidersFilteredMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[UpdateOidcProviderMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsIn[RemoveOidcProviderMethod] = make([]interface{}, 1)\n\n\ttestRepo.ArgsOut[GetUserByExternalIDMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[AddUserMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[UpdateUserMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[GetUsersFilteredMethod] = make([]interface{}, 3)\n\ttestRepo.ArgsOut[GetGroupsByUserIDMethod] = make([]interface{}, 3)\n\ttestRepo.ArgsOut[RemoveUserMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsOut[GetGroupByNameMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[IsMemberOfGroupMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[GetGroupMembersMethod] = make([]interface{}, 3)\n\ttestRepo.ArgsOut[IsAttachedToGroupMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[GetAttachedPoliciesMethod] = make([]interface{}, 3)\n\ttestRepo.ArgsOut[GetGroupsFilteredMethod] = make([]interface{}, 3)\n\ttestRepo.ArgsOut[RemoveGroupMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsOut[AddGroupMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[AddMemberMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsOut[RemoveMemberMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsOut[UpdateGroupMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[AttachPolicyMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsOut[DetachPolicyMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsOut[GetPolicyByNameMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[AddPolicyMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[UpdatePolicyMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[RemovePolicyMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsOut[GetPoliciesFilteredMethod] = make([]interface{}, 3)\n\ttestRepo.ArgsOut[GetAttachedGroupsMethod] = make([]interface{}, 3)\n\ttestRepo.ArgsOut[OrderByValidColumnsMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsOut[GetProxyResourcesMethod] = make([]interface{}, 3)\n\ttestRepo.ArgsOut[RemoveProxyResourceMethod] = make([]interface{}, 1)\n\ttestRepo.ArgsOut[AddProxyResourceMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[UpdateProxyResourceMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[GetProxyResourceByNameMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[AddOidcProviderMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[GetOidcProviderByNameMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[GetOidcProvidersFilteredMethod] = make([]interface{}, 3)\n\ttestRepo.ArgsOut[UpdateOidcProviderMethod] = make([]interface{}, 2)\n\ttestRepo.ArgsOut[RemoveOidcProviderMethod] = make([]interface{}, 1)\n\n\treturn testRepo\n}", "func (m_2 *MockUserUsecaser) Create(c context.Context, m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Create\", c, m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) Create(attr UserAttributes) (UserUUID, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", attr)\n\tret0, _ := ret[0].(UserUUID)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) Create(ctx context.Context, user *domain.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func NewUserTeamwork()(*UserTeamwork) {\n m := &UserTeamwork{\n Entity: *NewEntity(),\n }\n return m\n}", "func (m *MockUser) Create(user api.User) (api.User, error) {\n\tret := m.ctrl.Call(m, \"Create\", user)\n\tret0, _ := ret[0].(api.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (userRepo *mockUserRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func NewMockObject(uid, name, ns string, res api.Resource) api.Object {\n\treturn NewObject(uuid.NewFromString(uid), name, ns, res)\n}", "func (_m *Repository) Create(_a0 *entities.User) (uint, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 uint\n\tif rf, ok := ret.Get(0).(func(*entities.User) uint); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(uint)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*entities.User) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func New() UsersRepository {\n\treturn &usersRepository{}\n}", "func CreateUserRepoImpl(db *gorm.DB) user.UserRepository {\n\treturn &UserRepoImpl{db}\n}", "func NewMapDBMock() Repository {\n\t// our MapDB already woks as mock;) well, let's just use it for tests\n\t// if we will changed realization of Repository using real DB,\n\t// current MapDB will be moved here\n\trepo := NewMapDB()\n\n\t// fill repo with data\n\tfor _, item := range testItems {\n\t\trepo.CreateItem(item)\n\t}\n\n\treturn repo\n}", "func New(db *mgo.Database) *UserRepository {\n\treturn &UserRepository{\n\t\tdb: db,\n\t\tcollection: db.C(collectionName),\n\t}\n}", "func NewMockInterface(t mockConstructorTestingTNewMockInterface) *MockInterface {\n\tmock := &MockInterface{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func newUser(userID interface{}) *User {\n\treturn &User{connMap: newConnMap(), id: userID}\n}", "func (m *MockFunctionsPlatformFactory) Create(projectName, applicationType string) (applications.PlatformRepository, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", projectName, applicationType)\n\tret0, _ := ret[0].(applications.PlatformRepository)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewPaymentRepositoryMock(t minimock.Tester) *PaymentRepositoryMock {\n\tm := &PaymentRepositoryMock{t: t}\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.CreateMock = mPaymentRepositoryMockCreate{mock: m}\n\tm.CreateMock.callArgs = []*PaymentRepositoryMockCreateParams{}\n\n\tm.GetByIDMock = mPaymentRepositoryMockGetByID{mock: m}\n\tm.GetByIDMock.callArgs = []*PaymentRepositoryMockGetByIDParams{}\n\n\tm.ListMock = mPaymentRepositoryMockList{mock: m}\n\tm.ListMock.callArgs = []*PaymentRepositoryMockListParams{}\n\n\treturn m\n}", "func (m *MockManager) Create(ctx context.Context, user *model.User) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, user)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUseCase) CreateUser(ctx context.Context, username, password, firstName, lastName string, age uint8, location, sex, about string) (uint64, uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateUser\", ctx, username, password, firstName, lastName, age, location, sex, about)\n\tret0, _ := ret[0].(uint64)\n\tret1, _ := ret[1].(uint64)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (_m *Service) CreateUser(ctx context.Context, username string, password string, firstName *string, lastName *string) (*users.User, error) {\n\tret := _m.Called(ctx, username, password, firstName, lastName)\n\n\tvar r0 *users.User\n\tif rf, ok := ret.Get(0).(func(context.Context, string, string, *string, *string) *users.User); ok {\n\t\tr0 = rf(ctx, username, password, firstName, lastName)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*users.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string, string, *string, *string) error); ok {\n\t\tr1 = rf(ctx, username, password, firstName, lastName)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockIUser) GetOrCreateUser(arg0 *User, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetOrCreateUser\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestCreateRepoNoError_MockingLayer(t *testing.T) {\n\tservices.RepoService = &repoServiceMock{}\n\n\tfuncCreateRepo = func(request repositories.CreateRepoRequest) (*repositories.CreateRepoResponse, utils.ApiError) {\n\t\treturn &repositories.CreateRepoResponse{\n\t\t\tId: 777,\n\t\t\tName: \"repotest\",\n\t\t\tOwner: \"marcelo\",\n\t\t}, nil\n\t}\n\n\tresponse := httptest.NewRecorder()\n\trequest := httptest.NewRequest(http.MethodPost, \"/repositories\", strings.NewReader(`{ \"name\" : \"repotest\" }`))\n\n\n\tc := test_utils.GetMockedContext(request, response)\n\n\tCreateRepo(c)\n\n\tvar result repositories.CreateRepoResponse\n\terr := json.Unmarshal(response.Body.Bytes(), &result)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, result)\n\tassert.Equal(t, http.StatusCreated, response.Code)\n\tassert.Equal(t, \"repotest\", result.Name)\n\tassert.Equal(t, int64(777), result.Id)\n}", "func (m *MockUserStore) Create(arg0 context.Context, arg1 *sql.Tx, arg2 proto.User) error {\n\tret := m.ctrl.Call(m, \"Create\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func NewUserRepository(db *sql.DB) *Users {\n\n\treturn &Users{db}\n}", "func NewMock(t *testing.T) *MockT { return &MockT{t: t} }", "func testRepo() *library.Repo {\n\treturn &library.Repo{\n\t\tID: new(int64),\n\t\tUserID: new(int64),\n\t\tBuildLimit: new(int64),\n\t\tTimeout: new(int64),\n\t\tCounter: new(int),\n\t\tPipelineType: new(string),\n\t\tHash: new(string),\n\t\tOrg: new(string),\n\t\tName: new(string),\n\t\tFullName: new(string),\n\t\tLink: new(string),\n\t\tClone: new(string),\n\t\tBranch: new(string),\n\t\tVisibility: new(string),\n\t\tPreviousName: new(string),\n\t\tPrivate: new(bool),\n\t\tTrusted: new(bool),\n\t\tActive: new(bool),\n\t\tAllowPull: new(bool),\n\t\tAllowPush: new(bool),\n\t\tAllowDeploy: new(bool),\n\t\tAllowTag: new(bool),\n\t\tAllowComment: new(bool),\n\t}\n}", "func (c *UserRepositoriesClient) Create(ctx context.Context,\n\tref gitprovider.UserRepositoryRef,\n\treq gitprovider.RepositoryInfo,\n\topts ...gitprovider.RepositoryCreateOption) (gitprovider.UserRepository, error) {\n\t// Make sure the RepositoryRef is valid\n\tif err := validateUserRepositoryRef(ref, c.host); err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiObj, err := createRepository(ctx, c.client, addTilde(ref.UserLogin), ref, req, opts...)\n\tif err != nil {\n\t\tif errors.Is(err, ErrAlreadyExists) {\n\t\t\treturn nil, gitprovider.ErrAlreadyExists\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to create repository %s/%s: %w\", addTilde(ref.UserLogin), ref.RepositoryName, err)\n\t}\n\n\tref.SetSlug(apiObj.Slug)\n\n\treturn newUserRepository(c.clientContext, apiObj, ref), nil\n}", "func (m *MockUserRepository) CreateUser(user easyalert.User) (easyalert.User, error) {\n\tret := m.ctrl.Call(m, \"CreateUser\", user)\n\tret0, _ := ret[0].(easyalert.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUnitOfWork) GetUserRepository() repositories.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserRepository\")\n\tret0, _ := ret[0].(repositories.User)\n\treturn ret0\n}", "func (m MockRepositoryStore) CreateRepository(ctx context.Context, repositoryID int64, virtualStorage, relativePath, replicaPath, primary string, updatedSecondaries, outdatedSecondaries []string, storePrimary, storeAssignments bool) error {\n\tif m.CreateRepositoryFunc == nil {\n\t\treturn nil\n\t}\n\n\treturn m.CreateRepositoryFunc(ctx, repositoryID, virtualStorage, relativePath, replicaPath, primary, updatedSecondaries, outdatedSecondaries, storePrimary, storeAssignments)\n}", "func MockUserItemStorage() *mongoDB.UserItemStorage {\n\treturn &mongoDB.UserItemStorage{\n\t\tUserID: \"Test\",\n\t\tPrices: make(map[string]models.UserPrices),\n\t\tProfits: make(map[string]models.UserProfits),\n\t}\n}", "func NewMockIMutantRepository(ctrl *gomock.Controller) *MockIMutantRepository {\n\tmock := &MockIMutantRepository{ctrl: ctrl}\n\tmock.recorder = &MockIMutantRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepository(ctrl *gomock.Controller) *MockUserRepository {\n\tmock := &MockUserRepository{ctrl: ctrl}\n\tmock.recorder = &MockUserRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepository(ctrl *gomock.Controller) *MockUserRepository {\n\tmock := &MockUserRepository{ctrl: ctrl}\n\tmock.recorder = &MockUserRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepository(ctrl *gomock.Controller) *MockUserRepository {\n\tmock := &MockUserRepository{ctrl: ctrl}\n\tmock.recorder = &MockUserRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepository(ctrl *gomock.Controller) *MockUserRepository {\n\tmock := &MockUserRepository{ctrl: ctrl}\n\tmock.recorder = &MockUserRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepository(ctrl *gomock.Controller) *MockUserRepository {\n\tmock := &MockUserRepository{ctrl: ctrl}\n\tmock.recorder = &MockUserRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepository(ctrl *gomock.Controller) *MockUserRepository {\n\tmock := &MockUserRepository{ctrl: ctrl}\n\tmock.recorder = &MockUserRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepository(ctrl *gomock.Controller) *MockUserRepository {\n\tmock := &MockUserRepository{ctrl: ctrl}\n\tmock.recorder = &MockUserRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepository(ctrl *gomock.Controller) *MockUserRepository {\n\tmock := &MockUserRepository{ctrl: ctrl}\n\tmock.recorder = &MockUserRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepository(ctrl *gomock.Controller) *MockUserRepository {\n\tmock := &MockUserRepository{ctrl: ctrl}\n\tmock.recorder = &MockUserRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepo(ctrl *gomock.Controller) *MockUserRepo {\n\tmock := &MockUserRepo{ctrl: ctrl}\n\tmock.recorder = &MockUserRepoMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepo(ctrl *gomock.Controller) *MockUserRepo {\n\tmock := &MockUserRepo{ctrl: ctrl}\n\tmock.recorder = &MockUserRepoMockRecorder{mock}\n\treturn mock\n}", "func NewMockUserRepo(ctrl *gomock.Controller) *MockUserRepo {\n\tmock := &MockUserRepo{ctrl: ctrl}\n\tmock.recorder = &MockUserRepoMockRecorder{mock}\n\treturn mock\n}", "func (_m *MockRepository) Create(scope *jsonapi.Scope) *unidb.Error {\n\tret := _m.Called(scope)\n\n\tvar r0 *unidb.Error\n\tif rf, ok := ret.Get(0).(func(*jsonapi.Scope) *unidb.Error); ok {\n\t\tr0 = rf(scope)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*unidb.Error)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (mock *RepositoryMock) UserCreateCalls() []struct {\n\tData gqlmeetup.User\n} {\n\tvar calls []struct {\n\t\tData gqlmeetup.User\n\t}\n\tlockRepositoryMockUserCreate.RLock()\n\tcalls = mock.calls.UserCreate\n\tlockRepositoryMockUserCreate.RUnlock()\n\treturn calls\n}", "func (u *UserRepository) Create(user *domain.User) (uint, error) {\n\targs := u.Called(user)\n\treturn uint(args.Int(0)), args.Error(1)\n}", "func HelpTestMockRepo(t *testing.T, cfg *config.Config) *core.IpfsNode {\n\tmc := config.Config{}\n\tif cfg != nil {\n\t\tmc = *cfg\n\t}\n\tmc.Identity = config.Identity{\n\t\tPeerID: testPeerID, // required by offline node\n\t}\n\tr := &repo.Mock{\n\t\tC: mc,\n\t\tD: syncds.MutexWrap(datastore.NewMapDatastore()),\n\t}\n\tnode, err := core.NewNode(context.Background(), &core.BuildCfg{Repo: r})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn node\n}", "func (m *MockDB) GetOrCreateUser(arg0 *User, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetOrCreateUser\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRemotes) Create(arg0, arg1 string) (*git.Remote, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", arg0, arg1)\n\tret0, _ := ret[0].(*git.Remote)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockHerokuPlatformFactory) Create(projectName, applicationType string) (applications.PlatformRepository, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", projectName, applicationType)\n\tret0, _ := ret[0].(applications.PlatformRepository)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewRepository(canQuery bool, failingMethods ...string) repository.Repository {\n\treturn &TestRepository{\n\t\tuser: NewUserRepository(canQuery, failingMethods...),\n\t\tsession: NewSessionRepository(canQuery, failingMethods...),\n\t\tproject: NewProjectRepository(canQuery, failingMethods...),\n\t\tcluster: NewClusterRepository(canQuery),\n\t\thelmRepo: NewHelmRepoRepository(canQuery),\n\t\tregistry: NewRegistryRepository(canQuery),\n\t\tgitRepo: NewGitRepoRepository(canQuery),\n\t\tgitActionConfig: NewGitActionConfigRepository(canQuery),\n\t\tinvite: NewInviteRepository(canQuery),\n\t\trelease: NewReleaseRepository(canQuery),\n\t\tauthCode: NewAuthCodeRepository(canQuery),\n\t\tdnsRecord: NewDNSRecordRepository(canQuery),\n\t\tpwResetToken: NewPWResetTokenRepository(canQuery),\n\t\tinfra: NewInfraRepository(canQuery),\n\t\tkubeIntegration: NewKubeIntegrationRepository(canQuery),\n\t\tbasicIntegration: NewBasicIntegrationRepository(canQuery),\n\t\toidcIntegration: NewOIDCIntegrationRepository(canQuery),\n\t\toauthIntegration: NewOAuthIntegrationRepository(canQuery),\n\t\tgcpIntegration: NewGCPIntegrationRepository(canQuery),\n\t\tawsIntegration: NewAWSIntegrationRepository(canQuery),\n\t\tgithubAppInstallation: NewGithubAppInstallationRepository(canQuery),\n\t\tgithubAppOAuthIntegration: NewGithubAppOAuthIntegrationRepository(canQuery),\n\t\tslackIntegration: NewSlackIntegrationRepository(canQuery),\n\t\tnotificationConfig: NewNotificationConfigRepository(canQuery),\n\t\tevent: NewEventRepository(canQuery),\n\t}\n}", "func NewTwinRepository() twins.TwinRepository {\n\treturn &twinRepositoryMock{\n\t\ttwins: make(map[string]twins.Twin),\n\t}\n}", "func NewRepo() contact.UserRepo {\n\treturn &userRepo{}\n}", "func (_m *UserRepo) CreateUser(_a0 *models.User) (*models.User, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *models.User\n\tif rf, ok := ret.Get(0).(func(*models.User) *models.User); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*models.User) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockSessionManager) Create(userId string) (*session.Session, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", userId)\n\tret0, _ := ret[0].(*session.Session)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) Store(arg0 *sweeper.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mock *Mock) CreateUser(newUser entities.User) (uint, error) {\n\tinputHash := toHash(getInputForCreateUser(newUser))\n\tarrOutputForCreateUser, exists := mock.patchCreateUserMap[inputHash]\n\tif !exists || len(arrOutputForCreateUser) == 0 {\n\t\tpanic(\"Mock not available for CreateUser\")\n\t}\n\n\toutput := arrOutputForCreateUser[0]\n\tarrOutputForCreateUser = arrOutputForCreateUser[1:]\n\tmock.patchCreateUserMap[inputHash] = arrOutputForCreateUser\n\n\treturn output.newUserID, output.error\n}", "func NewAdminDBRepositoryMock() *AdminDBRepositoryMock {\n\treturn &AdminDBRepositoryMock{}\n}", "func NewFakeUser() *FakeUser {\n\tdata := make(map[int]user.User)\n\treturn &FakeUser{data}\n}", "func (mock *HarborRepositoryInterfaceMock) CreateCalls() []struct {\n\tIn1 *v3.HarborRepository\n} {\n\tvar calls []struct {\n\t\tIn1 *v3.HarborRepository\n\t}\n\tlockHarborRepositoryInterfaceMockCreate.RLock()\n\tcalls = mock.calls.Create\n\tlockHarborRepositoryInterfaceMockCreate.RUnlock()\n\treturn calls\n}", "func NewUserRepositoryImpl(Conn *sql.DB) *UserRepositoryImpl {\n\treturn &UserRepositoryImpl{conn: Conn}\n}", "func (m *MockUserUsecase) Create(email, passwordHash, name string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", email, passwordHash, name)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockStore) CreateUser(arg0 context.Context, arg1 db.CreateUserParams) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateUser\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMockUserPGRepository(ctrl *gomock.Controller) *MockUserPGRepository {\n\tmock := &MockUserPGRepository{ctrl: ctrl}\n\tmock.recorder = &MockUserPGRepositoryMockRecorder{mock}\n\treturn mock\n}", "func NewMockStore() *MockStore {\n\treturn &MockStore{\n\t\tid: map[int]User{},\n\t\tname: map[string]User{},\n\t\temail: map[string]User{},\n\t\tconfirm: map[string]ConfirmToken{},\n\t\trecover: map[string]RecoverToken{},\n\t}\n}", "func (m *MockUserStorage) CreateUser(ctx context.Context, user model.User) (model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateUser\", ctx, user)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewRepository() UsersRepository {\n\treturn &usersRepository{}\n}" ]
[ "0.7291781", "0.68338925", "0.6270238", "0.62460506", "0.6210891", "0.6192462", "0.5999379", "0.59820676", "0.5960797", "0.5911187", "0.59106743", "0.5903829", "0.5894814", "0.5846043", "0.5838952", "0.5830972", "0.5784427", "0.5781261", "0.5780247", "0.5776818", "0.57508534", "0.57312965", "0.57220453", "0.571612", "0.5716053", "0.5703916", "0.56949097", "0.56486815", "0.5645771", "0.56054103", "0.5595755", "0.557251", "0.5559212", "0.55527604", "0.5536277", "0.55302733", "0.5506355", "0.55020285", "0.549495", "0.54919654", "0.54475975", "0.54417706", "0.5426418", "0.5410325", "0.5403908", "0.53680736", "0.53555554", "0.53536576", "0.5344089", "0.53374064", "0.5335223", "0.5334693", "0.5332547", "0.5329015", "0.5324183", "0.53239334", "0.5318833", "0.5295476", "0.5293546", "0.5283238", "0.5283166", "0.52828366", "0.52813506", "0.5277343", "0.5274931", "0.5274931", "0.5274931", "0.5274931", "0.5274931", "0.5274931", "0.5274931", "0.5274931", "0.5274931", "0.52725935", "0.52725935", "0.52725935", "0.5271555", "0.52645075", "0.5246201", "0.52433157", "0.523843", "0.52331156", "0.52305573", "0.5229431", "0.5213687", "0.5213197", "0.5200085", "0.5187753", "0.5177323", "0.51695806", "0.51663166", "0.5162868", "0.51621765", "0.5162023", "0.5153271", "0.5144235", "0.51393723", "0.5125961", "0.5099605", "0.5097325" ]
0.57597727
20
EXPECT returns an object that allows the caller to indicate expected use
func (m *MockUserRepositoryInterface) EXPECT() *MockUserRepositoryInterfaceMockRecorder { return m.recorder }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mmGetObject *mClientMockGetObject) Expect(ctx context.Context, head insolar.Reference) *mClientMockGetObject {\n\tif mmGetObject.mock.funcGetObject != nil {\n\t\tmmGetObject.mock.t.Fatalf(\"ClientMock.GetObject mock is already set by Set\")\n\t}\n\n\tif mmGetObject.defaultExpectation == nil {\n\t\tmmGetObject.defaultExpectation = &ClientMockGetObjectExpectation{}\n\t}\n\n\tmmGetObject.defaultExpectation.params = &ClientMockGetObjectParams{ctx, head}\n\tfor _, e := range mmGetObject.expectations {\n\t\tif minimock.Equal(e.params, mmGetObject.defaultExpectation.params) {\n\t\t\tmmGetObject.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetObject.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetObject\n}", "func (r Requester) Assert(actual, expected interface{}) Requester {\n\t//r.actualResponse = actual\n\t//r.expectedResponse = expected\n\treturn r\n}", "func (r *Request) Expect(t *testing.T) *Response {\n\tr.apiTest.t = t\n\treturn r.apiTest.response\n}", "func (m *MockNotary) Notarize(arg0 string) (map[string]interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Notarize\", arg0)\n\tret0, _ := ret[0].(map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (tc TestCases) expect() {\n\tfmt.Println(cnt)\n\tcnt++\n\tif !reflect.DeepEqual(tc.resp, tc.respExp) {\n\t\ttc.t.Error(fmt.Sprintf(\"\\nRequested: \", tc.req, \"\\nExpected: \", tc.respExp, \"\\nFound: \", tc.resp))\n\t}\n}", "func (r *Request) Expect(t TestingT) *Response {\n\tr.apiTest.t = t\n\treturn r.apiTest.response\n}", "func Expect(t cbtest.T, actual interface{}, matcher matcher.Matcher, labelAndArgs ...interface{}) {\n\tt.Helper()\n\tres := ExpectE(t, actual, matcher, labelAndArgs...)\n\tif !res {\n\t\tt.FailNow()\n\t}\n}", "func (m *MockisObject_Obj) EXPECT() *MockisObject_ObjMockRecorder {\n\treturn m.recorder\n}", "func Expect(t *testing.T, v, m interface{}) {\n\tvt, vok := v.(Equaler)\n\tmt, mok := m.(Equaler)\n\n\tvar state bool\n\tif vok && mok {\n\t\tstate = vt.Equal(mt)\n\t} else {\n\t\tstate = reflect.DeepEqual(v, m)\n\t}\n\n\tif state {\n\t\tflux.FatalFailed(t, \"Value %+v and %+v are not a match\", v, m)\n\t\treturn\n\t}\n\tflux.LogPassed(t, \"Value %+v and %+v are a match\", v, m)\n}", "func (mmState *mClientMockState) Expect() *mClientMockState {\n\tif mmState.mock.funcState != nil {\n\t\tmmState.mock.t.Fatalf(\"ClientMock.State mock is already set by Set\")\n\t}\n\n\tif mmState.defaultExpectation == nil {\n\t\tmmState.defaultExpectation = &ClientMockStateExpectation{}\n\t}\n\n\treturn mmState\n}", "func (mmProvide *mContainerMockProvide) Expect(constructor interface{}) *mContainerMockProvide {\n\tif mmProvide.mock.funcProvide != nil {\n\t\tmmProvide.mock.t.Fatalf(\"ContainerMock.Provide mock is already set by Set\")\n\t}\n\n\tif mmProvide.defaultExpectation == nil {\n\t\tmmProvide.defaultExpectation = &ContainerMockProvideExpectation{}\n\t}\n\n\tmmProvide.defaultExpectation.params = &ContainerMockProvideParams{constructor}\n\tfor _, e := range mmProvide.expectations {\n\t\tif minimock.Equal(e.params, mmProvide.defaultExpectation.params) {\n\t\t\tmmProvide.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmProvide.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmProvide\n}", "func Mock() Env {\n\treturn mock.New()\n}", "func (mmGetCode *mClientMockGetCode) Expect(ctx context.Context, ref insolar.Reference) *mClientMockGetCode {\n\tif mmGetCode.mock.funcGetCode != nil {\n\t\tmmGetCode.mock.t.Fatalf(\"ClientMock.GetCode mock is already set by Set\")\n\t}\n\n\tif mmGetCode.defaultExpectation == nil {\n\t\tmmGetCode.defaultExpectation = &ClientMockGetCodeExpectation{}\n\t}\n\n\tmmGetCode.defaultExpectation.params = &ClientMockGetCodeParams{ctx, ref}\n\tfor _, e := range mmGetCode.expectations {\n\t\tif minimock.Equal(e.params, mmGetCode.defaultExpectation.params) {\n\t\t\tmmGetCode.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetCode.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetCode\n}", "func expect(t *testing.T, method, url string, testieOptions ...func(*http.Request)) *testie {\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor _, opt := range testieOptions {\n\t\topt(req)\n\t}\n\n\treturn testReq(t, req)\n}", "func (_m *MockOStream) EXPECT() *MockOStreamMockRecorder {\n\treturn _m.recorder\n}", "func (mmGetUser *mStorageMockGetUser) Expect(ctx context.Context, userID int64) *mStorageMockGetUser {\n\tif mmGetUser.mock.funcGetUser != nil {\n\t\tmmGetUser.mock.t.Fatalf(\"StorageMock.GetUser mock is already set by Set\")\n\t}\n\n\tif mmGetUser.defaultExpectation == nil {\n\t\tmmGetUser.defaultExpectation = &StorageMockGetUserExpectation{}\n\t}\n\n\tmmGetUser.defaultExpectation.params = &StorageMockGetUserParams{ctx, userID}\n\tfor _, e := range mmGetUser.expectations {\n\t\tif minimock.Equal(e.params, mmGetUser.defaultExpectation.params) {\n\t\t\tmmGetUser.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetUser.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetUser\n}", "func (mmGetObject *mClientMockGetObject) Return(o1 ObjectDescriptor, err error) *ClientMock {\n\tif mmGetObject.mock.funcGetObject != nil {\n\t\tmmGetObject.mock.t.Fatalf(\"ClientMock.GetObject mock is already set by Set\")\n\t}\n\n\tif mmGetObject.defaultExpectation == nil {\n\t\tmmGetObject.defaultExpectation = &ClientMockGetObjectExpectation{mock: mmGetObject.mock}\n\t}\n\tmmGetObject.defaultExpectation.results = &ClientMockGetObjectResults{o1, err}\n\treturn mmGetObject.mock\n}", "func (mmGather *mGathererMockGather) Expect() *mGathererMockGather {\n\tif mmGather.mock.funcGather != nil {\n\t\tmmGather.mock.t.Fatalf(\"GathererMock.Gather mock is already set by Set\")\n\t}\n\n\tif mmGather.defaultExpectation == nil {\n\t\tmmGather.defaultExpectation = &GathererMockGatherExpectation{}\n\t}\n\n\treturn mmGather\n}", "func (m *MockParser) EXPECT() *MockParserMockRecorder {\n\treturn m.recorder\n}", "func (m *MockParser) EXPECT() *MockParserMockRecorder {\n\treturn m.recorder\n}", "func (mmWriteTo *mDigestHolderMockWriteTo) Expect(w io.Writer) *mDigestHolderMockWriteTo {\n\tif mmWriteTo.mock.funcWriteTo != nil {\n\t\tmmWriteTo.mock.t.Fatalf(\"DigestHolderMock.WriteTo mock is already set by Set\")\n\t}\n\n\tif mmWriteTo.defaultExpectation == nil {\n\t\tmmWriteTo.defaultExpectation = &DigestHolderMockWriteToExpectation{}\n\t}\n\n\tmmWriteTo.defaultExpectation.params = &DigestHolderMockWriteToParams{w}\n\tfor _, e := range mmWriteTo.expectations {\n\t\tif minimock.Equal(e.params, mmWriteTo.defaultExpectation.params) {\n\t\t\tmmWriteTo.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmWriteTo.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmWriteTo\n}", "func (rb *RequestBuilder) EXPECT() *ResponseAsserter {\n\treq := httptest.NewRequest(rb.method, rb.path, rb.body)\n\tfor k, v := range rb.hdr {\n\t\treq.Header[k] = v\n\t}\n\n\trec := httptest.NewRecorder()\n\trb.cas.h.ServeHTTP(rec, req)\n\n\treturn &ResponseAsserter{\n\t\trec: rec,\n\t\treq: req,\n\t\tb: rb,\n\t\tfail: rb.fail.\n\t\t\tCopy().\n\t\t\tWithRequest(req).\n\t\t\tWithResponse(rec),\n\t}\n}", "func (mmGetState *mGatewayMockGetState) Expect() *mGatewayMockGetState {\n\tif mmGetState.mock.funcGetState != nil {\n\t\tmmGetState.mock.t.Fatalf(\"GatewayMock.GetState mock is already set by Set\")\n\t}\n\n\tif mmGetState.defaultExpectation == nil {\n\t\tmmGetState.defaultExpectation = &GatewayMockGetStateExpectation{}\n\t}\n\n\treturn mmGetState\n}", "func (m *mParcelMockGetSign) Expect() *mParcelMockGetSign {\n\tm.mock.GetSignFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetSignExpectation{}\n\t}\n\n\treturn m\n}", "func (mmCreateTag *mTagCreatorMockCreateTag) Expect(t1 semantic.Tag) *mTagCreatorMockCreateTag {\n\tif mmCreateTag.mock.funcCreateTag != nil {\n\t\tmmCreateTag.mock.t.Fatalf(\"TagCreatorMock.CreateTag mock is already set by Set\")\n\t}\n\n\tif mmCreateTag.defaultExpectation == nil {\n\t\tmmCreateTag.defaultExpectation = &TagCreatorMockCreateTagExpectation{}\n\t}\n\n\tmmCreateTag.defaultExpectation.params = &TagCreatorMockCreateTagParams{t1}\n\tfor _, e := range mmCreateTag.expectations {\n\t\tif minimock.Equal(e.params, mmCreateTag.defaultExpectation.params) {\n\t\t\tmmCreateTag.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmCreateTag.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmCreateTag\n}", "func (m *MockActorUsecase) EXPECT() *MockActorUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *mParcelMockGetCaller) Expect() *mParcelMockGetCaller {\n\tm.mock.GetCallerFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetCallerExpectation{}\n\t}\n\n\treturn m\n}", "func mockAlwaysRun() bool { return true }", "func (m *MockArg) EXPECT() *MockArgMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (st *SDKTester) Test(resp interface{}) {\n\tif resp == nil || st.respWant == nil {\n\t\tst.t.Logf(\"response want/got is nil, abort\\n\")\n\t\treturn\n\t}\n\n\trespMap := st.getFieldMap(resp)\n\tfor i, v := range st.respWant {\n\t\tif reflect.DeepEqual(v, respMap[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tswitch x := respMap[i].(type) {\n\t\tcase Stringer:\n\t\t\tif !assert.Equal(st.t, v, x.String()) {\n\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t}\n\t\tcase map[string]interface{}:\n\t\t\tif value, ok := x[\"Value\"]; ok {\n\t\t\t\tif !assert.Equal(st.t, v, value) {\n\t\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t\t}\n\t\t\t}\n\t\tcase Inter:\n\t\t\tif !assert.Equal(st.t, v, x.Int()) {\n\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t}\n\t\tdefault:\n\t\t\tif !assert.Equal(st.t, v, respMap[i]) {\n\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *MockCreator) EXPECT() *MockCreatorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockCreator) EXPECT() *MockCreatorMockRecorder {\n\treturn m.recorder\n}", "func TestCallFunc_arguments(t *testing.T) {\n\n}", "func (m *mParcelMockGetSender) Expect() *mParcelMockGetSender {\n\tm.mock.GetSenderFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetSenderExpectation{}\n\t}\n\n\treturn m\n}", "func TestGetNone4A(t *testing.T) {\n}", "func expectEqual(value, expected interface{}) {\n\tif value != expected {\n\t\tfmt.Printf(\"Fehler: %v bekommen, erwartet war aber %v.\\n\", value, expected)\n\t} else {\n\t\tfmt.Printf(\"OK: %v bekommen, erwartet war aber %v.\\n\", value, expected)\n\t}\n}", "func (mmHasPendings *mClientMockHasPendings) Expect(ctx context.Context, object insolar.Reference) *mClientMockHasPendings {\n\tif mmHasPendings.mock.funcHasPendings != nil {\n\t\tmmHasPendings.mock.t.Fatalf(\"ClientMock.HasPendings mock is already set by Set\")\n\t}\n\n\tif mmHasPendings.defaultExpectation == nil {\n\t\tmmHasPendings.defaultExpectation = &ClientMockHasPendingsExpectation{}\n\t}\n\n\tmmHasPendings.defaultExpectation.params = &ClientMockHasPendingsParams{ctx, object}\n\tfor _, e := range mmHasPendings.expectations {\n\t\tif minimock.Equal(e.params, mmHasPendings.defaultExpectation.params) {\n\t\t\tmmHasPendings.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmHasPendings.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmHasPendings\n}", "func (mmGetPacketSignature *mPacketParserMockGetPacketSignature) Expect() *mPacketParserMockGetPacketSignature {\n\tif mmGetPacketSignature.mock.funcGetPacketSignature != nil {\n\t\tmmGetPacketSignature.mock.t.Fatalf(\"PacketParserMock.GetPacketSignature mock is already set by Set\")\n\t}\n\n\tif mmGetPacketSignature.defaultExpectation == nil {\n\t\tmmGetPacketSignature.defaultExpectation = &PacketParserMockGetPacketSignatureExpectation{}\n\t}\n\n\treturn mmGetPacketSignature\n}", "func Run(t testing.TB, cloud cloud.Client, src string, opts ...RunOption) {\n\n\tif cloud == nil {\n\t\tcloud = mockcloud.Client(nil)\n\t}\n\n\tvm := otto.New()\n\n\tpkg, err := godotto.Apply(context.Background(), vm, cloud)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvm.Set(\"cloud\", pkg)\n\tvm.Set(\"equals\", func(call otto.FunctionCall) otto.Value {\n\t\tvm := call.Otto\n\t\tgot, err := call.Argument(0).Export()\n\t\tif err != nil {\n\t\t\tottoutil.Throw(vm, err.Error())\n\t\t}\n\t\twant, err := call.Argument(1).Export()\n\t\tif err != nil {\n\t\t\tottoutil.Throw(vm, err.Error())\n\t\t}\n\t\tok, cause := deepEqual(got, want)\n\t\tif ok {\n\t\t\treturn otto.UndefinedValue()\n\t\t}\n\t\tmsg := \"assertion failed!\\n\" + cause\n\n\t\tif len(call.ArgumentList) > 2 {\n\t\t\tformat, err := call.ArgumentList[2].ToString()\n\t\t\tif err != nil {\n\t\t\t\tottoutil.Throw(vm, err.Error())\n\t\t\t}\n\t\t\tmsg += \"\\n\" + format\n\t\t}\n\t\tottoutil.Throw(vm, msg)\n\t\treturn otto.UndefinedValue()\n\t})\n\tvm.Set(\"assert\", func(call otto.FunctionCall) otto.Value {\n\t\tvm := call.Otto\n\t\tv, err := call.Argument(0).ToBoolean()\n\t\tif err != nil {\n\t\t\tottoutil.Throw(vm, err.Error())\n\t\t}\n\t\tif v {\n\t\t\treturn otto.UndefinedValue()\n\t\t}\n\t\tmsg := \"assertion failed!\"\n\t\tif len(call.ArgumentList) > 1 {\n\t\t\tformat, err := call.ArgumentList[1].ToString()\n\t\t\tif err != nil {\n\t\t\t\tottoutil.Throw(vm, err.Error())\n\t\t\t}\n\t\t\tmsg += \"\\n\" + format\n\t\t}\n\t\tottoutil.Throw(vm, msg)\n\t\treturn otto.UndefinedValue()\n\t})\n\tscript, err := vm.Compile(\"\", src)\n\tif err != nil {\n\t\tt.Fatalf(\"invalid code: %v\", err)\n\t}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(vm); err != nil {\n\t\t\tt.Fatalf(\"can't apply option: %v\", err)\n\t\t}\n\t}\n\n\tif _, err := vm.Run(script); err != nil {\n\t\tif oe, ok := err.(*otto.Error); ok {\n\t\t\tt.Fatal(oe.String())\n\t\t} else {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}", "func TestSetGoodArgs(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetGoodArgs\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\n\t// Testing the init. It always return true. No parameters in init. \n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\"),\n\t[]byte(\"agentInfo.atype\"),[]byte(\"1.2.3.4\"),\n\t[]byte(\"agentInfo.id\"),[]byte(\"agentidentifier\"),\n\t[]byte(\"agentinfo.name\"),[]byte(\"7.8.9\"),\n\t[]byte(\"agentinfo.idp\"),[]byte(\"urn:tiani-spirit:sts\"),\n\t[]byte(\"locationInfo.id\"),[]byte(\"urn:oid:1.2.3\"),\n\t[]byte(\"locationInfo.name\"),[]byte(\"General Hospital\"),\n\t[]byte(\"locationInfo.locality\"),[]byte(\"Nashville, TN\"),\n\t[]byte(\"locationInfo.docid\"),[]byte(\"1.2.3\"),\n\t[]byte(\"action\"),[]byte(\"ex:CREATE\"),\n\t[]byte(\"date\"),[]byte(\"2018-11-10T12:15:55.028Z\")})\n\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n}", "func (mmRegisterResult *mClientMockRegisterResult) Expect(ctx context.Context, request insolar.Reference, result RequestResult) *mClientMockRegisterResult {\n\tif mmRegisterResult.mock.funcRegisterResult != nil {\n\t\tmmRegisterResult.mock.t.Fatalf(\"ClientMock.RegisterResult mock is already set by Set\")\n\t}\n\n\tif mmRegisterResult.defaultExpectation == nil {\n\t\tmmRegisterResult.defaultExpectation = &ClientMockRegisterResultExpectation{}\n\t}\n\n\tmmRegisterResult.defaultExpectation.params = &ClientMockRegisterResultParams{ctx, request, result}\n\tfor _, e := range mmRegisterResult.expectations {\n\t\tif minimock.Equal(e.params, mmRegisterResult.defaultExpectation.params) {\n\t\t\tmmRegisterResult.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmRegisterResult.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmRegisterResult\n}", "func Mock() Cluster { return mockCluster{} }", "func (m *MockS3API) EXPECT() *MockS3APIMockRecorder {\n\treturn m.recorder\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (mmGetPendings *mClientMockGetPendings) Expect(ctx context.Context, objectRef insolar.Reference) *mClientMockGetPendings {\n\tif mmGetPendings.mock.funcGetPendings != nil {\n\t\tmmGetPendings.mock.t.Fatalf(\"ClientMock.GetPendings mock is already set by Set\")\n\t}\n\n\tif mmGetPendings.defaultExpectation == nil {\n\t\tmmGetPendings.defaultExpectation = &ClientMockGetPendingsExpectation{}\n\t}\n\n\tmmGetPendings.defaultExpectation.params = &ClientMockGetPendingsParams{ctx, objectRef}\n\tfor _, e := range mmGetPendings.expectations {\n\t\tif minimock.Equal(e.params, mmGetPendings.defaultExpectation.params) {\n\t\t\tmmGetPendings.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetPendings.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetPendings\n}", "func (m *MockOrg) EXPECT() *MockOrgMockRecorder {\n\treturn m.recorder\n}", "func (mmGetUserLocation *mStorageMockGetUserLocation) Expect(ctx context.Context, userID int64) *mStorageMockGetUserLocation {\n\tif mmGetUserLocation.mock.funcGetUserLocation != nil {\n\t\tmmGetUserLocation.mock.t.Fatalf(\"StorageMock.GetUserLocation mock is already set by Set\")\n\t}\n\n\tif mmGetUserLocation.defaultExpectation == nil {\n\t\tmmGetUserLocation.defaultExpectation = &StorageMockGetUserLocationExpectation{}\n\t}\n\n\tmmGetUserLocation.defaultExpectation.params = &StorageMockGetUserLocationParams{ctx, userID}\n\tfor _, e := range mmGetUserLocation.expectations {\n\t\tif minimock.Equal(e.params, mmGetUserLocation.defaultExpectation.params) {\n\t\t\tmmGetUserLocation.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetUserLocation.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetUserLocation\n}", "func (mmCreate *mPaymentRepositoryMockCreate) Expect(ctx context.Context, from int64, to int64, amount int64) *mPaymentRepositoryMockCreate {\n\tif mmCreate.mock.funcCreate != nil {\n\t\tmmCreate.mock.t.Fatalf(\"PaymentRepositoryMock.Create mock is already set by Set\")\n\t}\n\n\tif mmCreate.defaultExpectation == nil {\n\t\tmmCreate.defaultExpectation = &PaymentRepositoryMockCreateExpectation{}\n\t}\n\n\tmmCreate.defaultExpectation.params = &PaymentRepositoryMockCreateParams{ctx, from, to, amount}\n\tfor _, e := range mmCreate.expectations {\n\t\tif minimock.Equal(e.params, mmCreate.defaultExpectation.params) {\n\t\t\tmmCreate.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmCreate.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmCreate\n}", "func (mmAuther *mGatewayMockAuther) Expect() *mGatewayMockAuther {\n\tif mmAuther.mock.funcAuther != nil {\n\t\tmmAuther.mock.t.Fatalf(\"GatewayMock.Auther mock is already set by Set\")\n\t}\n\n\tif mmAuther.defaultExpectation == nil {\n\t\tmmAuther.defaultExpectation = &GatewayMockAutherExpectation{}\n\t}\n\n\treturn mmAuther\n}", "func TestObjectsMeetReq(t *testing.T) {\n\tvar kr verifiable.StorageReader\n\tvar kw verifiable.StorageWriter\n\n\tvar m verifiable.MutatorService\n\n\tvar o verifiable.AuthorizationOracle\n\n\tkr = &memory.TransientStorage{}\n\tkw = &memory.TransientStorage{}\n\n\tkr = &bolt.Storage{}\n\tkw = &bolt.Storage{}\n\n\tkr = &badger.Storage{}\n\tkw = &badger.Storage{}\n\n\tm = &instant.Mutator{}\n\tm = (&batch.Mutator{}).MustCreate()\n\n\to = policy.Open\n\to = &policy.Static{}\n\n\tlog.Println(kr, kw, m, o) // \"use\" these so that go compiler will be quiet\n}", "func (mmInvoke *mContainerMockInvoke) Expect(function interface{}) *mContainerMockInvoke {\n\tif mmInvoke.mock.funcInvoke != nil {\n\t\tmmInvoke.mock.t.Fatalf(\"ContainerMock.Invoke mock is already set by Set\")\n\t}\n\n\tif mmInvoke.defaultExpectation == nil {\n\t\tmmInvoke.defaultExpectation = &ContainerMockInvokeExpectation{}\n\t}\n\n\tmmInvoke.defaultExpectation.params = &ContainerMockInvokeParams{function}\n\tfor _, e := range mmInvoke.expectations {\n\t\tif minimock.Equal(e.params, mmInvoke.defaultExpectation.params) {\n\t\t\tmmInvoke.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmInvoke.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmInvoke\n}", "func (mmGetPosition *mStoreMockGetPosition) Expect(account string, contractID string) *mStoreMockGetPosition {\n\tif mmGetPosition.mock.funcGetPosition != nil {\n\t\tmmGetPosition.mock.t.Fatalf(\"StoreMock.GetPosition mock is already set by Set\")\n\t}\n\n\tif mmGetPosition.defaultExpectation == nil {\n\t\tmmGetPosition.defaultExpectation = &StoreMockGetPositionExpectation{}\n\t}\n\n\tmmGetPosition.defaultExpectation.params = &StoreMockGetPositionParams{account, contractID}\n\tfor _, e := range mmGetPosition.expectations {\n\t\tif minimock.Equal(e.params, mmGetPosition.defaultExpectation.params) {\n\t\t\tmmGetPosition.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetPosition.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetPosition\n}", "func (mmGetAbandonedRequest *mClientMockGetAbandonedRequest) Expect(ctx context.Context, objectRef insolar.Reference, reqRef insolar.Reference) *mClientMockGetAbandonedRequest {\n\tif mmGetAbandonedRequest.mock.funcGetAbandonedRequest != nil {\n\t\tmmGetAbandonedRequest.mock.t.Fatalf(\"ClientMock.GetAbandonedRequest mock is already set by Set\")\n\t}\n\n\tif mmGetAbandonedRequest.defaultExpectation == nil {\n\t\tmmGetAbandonedRequest.defaultExpectation = &ClientMockGetAbandonedRequestExpectation{}\n\t}\n\n\tmmGetAbandonedRequest.defaultExpectation.params = &ClientMockGetAbandonedRequestParams{ctx, objectRef, reqRef}\n\tfor _, e := range mmGetAbandonedRequest.expectations {\n\t\tif minimock.Equal(e.params, mmGetAbandonedRequest.defaultExpectation.params) {\n\t\t\tmmGetAbandonedRequest.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetAbandonedRequest.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetAbandonedRequest\n}", "func (mmSend *mSenderMockSend) Expect(ctx context.Context, email Email) *mSenderMockSend {\n\tif mmSend.mock.funcSend != nil {\n\t\tmmSend.mock.t.Fatalf(\"SenderMock.Send mock is already set by Set\")\n\t}\n\n\tif mmSend.defaultExpectation == nil {\n\t\tmmSend.defaultExpectation = &SenderMockSendExpectation{}\n\t}\n\n\tmmSend.defaultExpectation.params = &SenderMockSendParams{ctx, email}\n\tfor _, e := range mmSend.expectations {\n\t\tif minimock.Equal(e.params, mmSend.defaultExpectation.params) {\n\t\t\tmmSend.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmSend.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmSend\n}", "func callAndVerify(msg string, client pb.GreeterClient, shouldFail bool) error {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\t_, err := client.SayHello(ctx, &pb.HelloRequest{Name: msg})\n\tif want, got := shouldFail == true, err != nil; got != want {\n\t\treturn fmt.Errorf(\"want and got mismatch, want shouldFail=%v, got fail=%v, rpc error: %v\", want, got, err)\n\t}\n\treturn nil\n}", "func (m *Mockrequester) EXPECT() *MockrequesterMockRecorder {\n\treturn m.recorder\n}", "func expectEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)\n}", "func (m *MockstackDescriber) EXPECT() *MockstackDescriberMockRecorder {\n\treturn m.recorder\n}", "func (req *outgoingRequest) Assert(t *testing.T, fixture *fixture) {\n\tassert.Equal(t, req.path, fixture.calledPath, \"called path not as expected\")\n\tassert.Equal(t, req.method, fixture.calledMethod, \"called path not as expected\")\n\tassert.Equal(t, req.body, fixture.requestBody, \"call body no as expected\")\n}", "func (mmVerify *mDelegationTokenFactoryMockVerify) Expect(parcel mm_insolar.Parcel) *mDelegationTokenFactoryMockVerify {\n\tif mmVerify.mock.funcVerify != nil {\n\t\tmmVerify.mock.t.Fatalf(\"DelegationTokenFactoryMock.Verify mock is already set by Set\")\n\t}\n\n\tif mmVerify.defaultExpectation == nil {\n\t\tmmVerify.defaultExpectation = &DelegationTokenFactoryMockVerifyExpectation{}\n\t}\n\n\tmmVerify.defaultExpectation.params = &DelegationTokenFactoryMockVerifyParams{parcel}\n\tfor _, e := range mmVerify.expectations {\n\t\tif minimock.Equal(e.params, mmVerify.defaultExpectation.params) {\n\t\t\tmmVerify.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmVerify.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmVerify\n}", "func (mmRead *mDigestHolderMockRead) Expect(p []byte) *mDigestHolderMockRead {\n\tif mmRead.mock.funcRead != nil {\n\t\tmmRead.mock.t.Fatalf(\"DigestHolderMock.Read mock is already set by Set\")\n\t}\n\n\tif mmRead.defaultExpectation == nil {\n\t\tmmRead.defaultExpectation = &DigestHolderMockReadExpectation{}\n\t}\n\n\tmmRead.defaultExpectation.params = &DigestHolderMockReadParams{p}\n\tfor _, e := range mmRead.expectations {\n\t\tif minimock.Equal(e.params, mmRead.defaultExpectation.params) {\n\t\t\tmmRead.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmRead.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmRead\n}", "func (mmSend *mClientMockSend) Expect(ctx context.Context, n *Notification) *mClientMockSend {\n\tif mmSend.mock.funcSend != nil {\n\t\tmmSend.mock.t.Fatalf(\"ClientMock.Send mock is already set by Set\")\n\t}\n\n\tif mmSend.defaultExpectation == nil {\n\t\tmmSend.defaultExpectation = &ClientMockSendExpectation{}\n\t}\n\n\tmmSend.defaultExpectation.params = &ClientMockSendParams{ctx, n}\n\tfor _, e := range mmSend.expectations {\n\t\tif minimock.Equal(e.params, mmSend.defaultExpectation.params) {\n\t\t\tmmSend.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmSend.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmSend\n}", "func (mmAsByteString *mDigestHolderMockAsByteString) Expect() *mDigestHolderMockAsByteString {\n\tif mmAsByteString.mock.funcAsByteString != nil {\n\t\tmmAsByteString.mock.t.Fatalf(\"DigestHolderMock.AsByteString mock is already set by Set\")\n\t}\n\n\tif mmAsByteString.defaultExpectation == nil {\n\t\tmmAsByteString.defaultExpectation = &DigestHolderMockAsByteStringExpectation{}\n\t}\n\n\treturn mmAsByteString\n}", "func Expect(msg string) error {\n\tif msg != \"\" {\n\t\treturn errors.New(msg)\n\t} else {\n\t\treturn nil\n\t}\n}", "func (mmEncrypt *mRingMockEncrypt) Expect(t1 secrets.Text) *mRingMockEncrypt {\n\tif mmEncrypt.mock.funcEncrypt != nil {\n\t\tmmEncrypt.mock.t.Fatalf(\"RingMock.Encrypt mock is already set by Set\")\n\t}\n\n\tif mmEncrypt.defaultExpectation == nil {\n\t\tmmEncrypt.defaultExpectation = &RingMockEncryptExpectation{}\n\t}\n\n\tmmEncrypt.defaultExpectation.params = &RingMockEncryptParams{t1}\n\tfor _, e := range mmEncrypt.expectations {\n\t\tif minimock.Equal(e.params, mmEncrypt.defaultExpectation.params) {\n\t\t\tmmEncrypt.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmEncrypt.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmEncrypt\n}", "func (mmBootstrapper *mGatewayMockBootstrapper) Expect() *mGatewayMockBootstrapper {\n\tif mmBootstrapper.mock.funcBootstrapper != nil {\n\t\tmmBootstrapper.mock.t.Fatalf(\"GatewayMock.Bootstrapper mock is already set by Set\")\n\t}\n\n\tif mmBootstrapper.defaultExpectation == nil {\n\t\tmmBootstrapper.defaultExpectation = &GatewayMockBootstrapperExpectation{}\n\t}\n\n\treturn mmBootstrapper\n}", "func (m *MockNotary) EXPECT() *MockNotaryMockRecorder {\n\treturn m.recorder\n}", "func (m *mParcelMockSetSender) Expect(p insolar.Reference) *mParcelMockSetSender {\n\tm.mock.SetSenderFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockSetSenderExpectation{}\n\t}\n\tm.mainExpectation.input = &ParcelMockSetSenderInput{p}\n\treturn m\n}", "func (mmGetPacketType *mPacketParserMockGetPacketType) Expect() *mPacketParserMockGetPacketType {\n\tif mmGetPacketType.mock.funcGetPacketType != nil {\n\t\tmmGetPacketType.mock.t.Fatalf(\"PacketParserMock.GetPacketType mock is already set by Set\")\n\t}\n\n\tif mmGetPacketType.defaultExpectation == nil {\n\t\tmmGetPacketType.defaultExpectation = &PacketParserMockGetPacketTypeExpectation{}\n\t}\n\n\treturn mmGetPacketType\n}", "func (mmParsePacketBody *mPacketParserMockParsePacketBody) Expect() *mPacketParserMockParsePacketBody {\n\tif mmParsePacketBody.mock.funcParsePacketBody != nil {\n\t\tmmParsePacketBody.mock.t.Fatalf(\"PacketParserMock.ParsePacketBody mock is already set by Set\")\n\t}\n\n\tif mmParsePacketBody.defaultExpectation == nil {\n\t\tmmParsePacketBody.defaultExpectation = &PacketParserMockParsePacketBodyExpectation{}\n\t}\n\n\treturn mmParsePacketBody\n}", "func (mmAsBytes *mDigestHolderMockAsBytes) Expect() *mDigestHolderMockAsBytes {\n\tif mmAsBytes.mock.funcAsBytes != nil {\n\t\tmmAsBytes.mock.t.Fatalf(\"DigestHolderMock.AsBytes mock is already set by Set\")\n\t}\n\n\tif mmAsBytes.defaultExpectation == nil {\n\t\tmmAsBytes.defaultExpectation = &DigestHolderMockAsBytesExpectation{}\n\t}\n\n\treturn mmAsBytes\n}", "func (m *MockArticleLogic) EXPECT() *MockArticleLogicMockRecorder {\n\treturn m.recorder\n}", "func (mmKey *mIteratorMockKey) Expect() *mIteratorMockKey {\n\tif mmKey.mock.funcKey != nil {\n\t\tmmKey.mock.t.Fatalf(\"IteratorMock.Key mock is already set by Set\")\n\t}\n\n\tif mmKey.defaultExpectation == nil {\n\t\tmmKey.defaultExpectation = &IteratorMockKeyExpectation{}\n\t}\n\n\treturn mmKey\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *mOutboundMockCanAccept) Expect(p Inbound) *mOutboundMockCanAccept {\n\tm.mock.CanAcceptFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &OutboundMockCanAcceptExpectation{}\n\t}\n\tm.mainExpectation.input = &OutboundMockCanAcceptInput{p}\n\treturn m\n}", "func (m *MockLoaderFactory) EXPECT() *MockLoaderFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockPKG) EXPECT() *MockPKGMockRecorder {\n\treturn m.recorder\n}", "func (m *MockbucketDescriber) EXPECT() *MockbucketDescriberMockRecorder {\n\treturn m.recorder\n}", "func (m *mParcelMockType) Expect() *mParcelMockType {\n\tm.mock.TypeFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockTypeExpectation{}\n\t}\n\n\treturn m\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func (mmExchange *mMDNSClientMockExchange) Expect(msg *mdns.Msg, address string) *mMDNSClientMockExchange {\n\tif mmExchange.mock.funcExchange != nil {\n\t\tmmExchange.mock.t.Fatalf(\"MDNSClientMock.Exchange mock is already set by Set\")\n\t}\n\n\tif mmExchange.defaultExpectation == nil {\n\t\tmmExchange.defaultExpectation = &MDNSClientMockExchangeExpectation{}\n\t}\n\n\tmmExchange.defaultExpectation.params = &MDNSClientMockExchangeParams{msg, address}\n\tfor _, e := range mmExchange.expectations {\n\t\tif minimock.Equal(e.params, mmExchange.defaultExpectation.params) {\n\t\t\tmmExchange.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmExchange.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmExchange\n}", "func (m *MockStream) EXPECT() *MockStreamMockRecorder {\n\treturn m.recorder\n}", "func (c Chkr) Expect(v validator, args ...interface{}) {\n\tif c.runTest(v, args...) {\n\t\tc.Fail()\n\t}\n}", "func (mmClone *mStorageMockClone) Expect(ctx context.Context, from insolar.PulseNumber, to insolar.PulseNumber, keepActual bool) *mStorageMockClone {\n\tif mmClone.mock.funcClone != nil {\n\t\tmmClone.mock.t.Fatalf(\"StorageMock.Clone mock is already set by Set\")\n\t}\n\n\tif mmClone.defaultExpectation == nil {\n\t\tmmClone.defaultExpectation = &StorageMockCloneExpectation{}\n\t}\n\n\tmmClone.defaultExpectation.params = &StorageMockCloneParams{ctx, from, to, keepActual}\n\tfor _, e := range mmClone.expectations {\n\t\tif minimock.Equal(e.params, mmClone.defaultExpectation.params) {\n\t\t\tmmClone.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmClone.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmClone\n}", "func (m *MockCodeGenerator) EXPECT() *MockCodeGeneratorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockNodeAttestor) EXPECT() *MockNodeAttestorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockNodeAttestor) EXPECT() *MockNodeAttestorMockRecorder {\n\treturn m.recorder\n}", "func (_m *MockIStream) EXPECT() *MockIStreamMockRecorder {\n\treturn _m.recorder\n}", "func (m *mOutboundMockGetEndpointType) Expect() *mOutboundMockGetEndpointType {\n\tm.mock.GetEndpointTypeFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &OutboundMockGetEndpointTypeExpectation{}\n\t}\n\n\treturn m\n}", "func (m *MockAZInfoProvider) EXPECT() *MockAZInfoProviderMockRecorder {\n\treturn m.recorder\n}" ]
[ "0.58157563", "0.5714918", "0.5672776", "0.5639812", "0.56273276", "0.5573085", "0.5567367", "0.5529613", "0.55066866", "0.5486919", "0.54729885", "0.54647803", "0.5460882", "0.54414886", "0.5440682", "0.5405729", "0.54035264", "0.53890616", "0.53831995", "0.53831995", "0.5369224", "0.53682834", "0.5358863", "0.5340405", "0.5338385", "0.5327707", "0.53230935", "0.53132576", "0.5307127", "0.5306891", "0.5306891", "0.5306891", "0.5306891", "0.5306891", "0.5306891", "0.5306891", "0.5306891", "0.53035146", "0.5295391", "0.5295391", "0.5291368", "0.52822006", "0.52821374", "0.52767164", "0.5273333", "0.5273239", "0.5265769", "0.52593946", "0.52572596", "0.5256972", "0.52545565", "0.5249454", "0.52421427", "0.52410823", "0.5238541", "0.52360845", "0.5235068", "0.5227199", "0.5227038", "0.52227145", "0.52144563", "0.5212412", "0.52120364", "0.5211835", "0.5211705", "0.5208191", "0.5194654", "0.5190334", "0.51877177", "0.5187148", "0.5185659", "0.51827794", "0.51817787", "0.5175451", "0.51730126", "0.5169131", "0.5167294", "0.5162394", "0.51599216", "0.51597583", "0.5159494", "0.51442164", "0.51442164", "0.51442164", "0.5143891", "0.51437116", "0.51395434", "0.51341194", "0.5133995", "0.51337904", "0.51337904", "0.51298875", "0.5129523", "0.5128482", "0.5123544", "0.51224196", "0.51162475", "0.51162475", "0.51148367", "0.51146877", "0.51091874" ]
0.0
-1
InsertUser mocks base method
func (m *MockUserRepositoryInterface) InsertUser(arg0 *db.User) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InsertUser", arg0) ret0, _ := ret[0].(error) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockUserService) Insert(tx *sqlx.Tx, username, password string) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Insert\", tx, username, password)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDatabase) InsertUser(ID, Email string) error {\n\targs := m.Called(ID, Email)\n\treturn args.Error(0)\n}", "func TestInsertNewUserService (t *testing.T){\n\terr := PostNewUserService(user_01)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_02)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_03)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_04)\n\tassert.Equal(t, 200, err.HTTPStatus)\n}", "func (m *MockPersister) AddUser(username, email, password string, isSysAdmin, overwrite bool) error {\n\tret := m.ctrl.Call(m, \"AddUser\", username, email, password, isSysAdmin, overwrite)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockStudentRepository) Insert(arg0 *domain.Student) (*domain.Student, *exception.AppError) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Insert\", arg0)\n\tret0, _ := ret[0].(*domain.Student)\n\tret1, _ := ret[1].(*exception.AppError)\n\treturn ret0, ret1\n}", "func (m *MockProduct) InsertNominativeUserFileUploadDetails(arg0 context.Context, arg1 db.InsertNominativeUserFileUploadDetailsParams) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InsertNominativeUserFileUploadDetails\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestMySQLStore(t *testing.T) {\n\t//create a new sql mock\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"error creating sql mock: %v\", err)\n\t}\n\t//ensure it's closed at the end of the test\n\tdefer db.Close()\n\n\tnewUser := CreateNewUser()\n\n\texpectedUser, _ := newUser.ToUser()\n\t//construct a new MySQLStore using the mock db\n\tstore := NewMySQLStore(db)\n\n\trows := sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"username\", \"firstname\", \"lastname\", \"photourl\"})\n\trows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL)\n\n\t// test insert function\n\tmock.ExpectExec(regexp.QuoteMeta(sqlInsertUser)).\n\t\tWithArgs(expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\t_, err = store.Insert(expectedUser)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when inserting new user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlInsertUser)).\n\t\tWithArgs(expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.Insert(expectedUser)\n\tif err == nil {\n\t\tt.Errorf(\"expected error does not occurs when inserting new user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// test get function\n\t// test get by id\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByID)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnRows(rows)\n\n\t_, err = store.GetByID(expectedUser.ID)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when get user by ID: %v\", err)\n\t}\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByID)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.GetByID(expectedUser.ID)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when getting user by id: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// test get by email\n\trows = sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"username\", \"firstname\", \"lastname\", \"photourl\"})\n\trows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL)\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByEmail)).\n\t\tWithArgs(expectedUser.Email).\n\t\tWillReturnRows(rows)\n\n\t_, err = store.GetByEmail(expectedUser.Email)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when get user by email: %v\", err)\n\t}\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByEmail)).\n\t\tWithArgs(expectedUser.Email).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.GetByEmail(expectedUser.Email)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when getting user by email: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// test get by user name\n\trows = sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"username\", \"firstname\", \"lastname\", \"photourl\"})\n\trows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL)\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByUserName)).\n\t\tWithArgs(expectedUser.UserName).\n\t\tWillReturnRows(rows)\n\n\t_, err = store.GetByUserName(expectedUser.UserName)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when get user by UserName: %v\", err)\n\t}\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByUserName)).\n\t\tWithArgs(expectedUser.UserName).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.GetByUserName(expectedUser.UserName)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when getting user by UserName: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// Test update\n\tupdate := &Updates{\n\t\tFirstName: \"updatedFirstName\",\n\t\tLastName: \"updatedLastName\",\n\t}\n\t// updatedRows := sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"UserName\", \"FirstName\", \"LastName\", \"photourl\"})\n\t// rows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, update.FirstName, update.LastName, expectedUser.PhotoURL)\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlUpdate)).\n\t\tWithArgs(update.FirstName, update.LastName, expectedUser.ID).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\terr = store.Update(expectedUser.ID, update)\n\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when update user: %v\", err)\n\t}\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlUpdate)).\n\t\tWithArgs(update.FirstName, update.LastName, expectedUser.ID).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\terr = store.Update(expectedUser.ID, update)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when update user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t//Test delete\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlDelete)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\terr = store.Delete(expectedUser.ID)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when deleting user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlDelete)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\terr = store.Delete(expectedUser.ID)\n\tif err == nil {\n\t\tt.Errorf(\"expected error does not occurs when deleting user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n}", "func (m *MockHandler) UserCreate(username, email, password string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserCreate\", username, email, password)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func TestCreateTablePutUser(t *testing.T) {\n\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\terr = db.PutUser(12312)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (m *MockRepositorer) Insert(arg0 post.Post) error {\n\tret := m.ctrl.Call(m, \"Insert\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockFamilyRepo) Insert(arg0 models.Family) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Insert\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockController) Insert(model postgres.Model) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Insert\", model)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUser) Create(ctx context.Context, db repo.DB, username string, hashedPassword []byte, now time.Time) (int, *internal.E) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, db, username, hashedPassword, now)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(*internal.E)\n\treturn ret0, ret1\n}", "func (m *MockSessionRep) Insert(arg0 *models.Session) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Insert\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestDbInterfaceMethods(t *testing.T) {\n\ttestUser := models.User{\n\t\tAccount: models.Account{\n\t\t\tType: \"email\",\n\t\t\tAccountID: \"[email protected]\",\n\t\t\tPassword: \"testhashedpassword-youcantreadme\",\n\t\t},\n\t\tRoles: []string{\"TEST\"},\n\t\tTimestamps: models.Timestamps{\n\t\t\tCreatedAt: time.Now().Unix(),\n\t\t},\n\t}\n\n\tt.Run(\"Testing create user\", func(t *testing.T) {\n\t\tid, err := testDBService.AddUser(testInstanceID, testUser)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif len(id) == 0 {\n\t\t\tt.Errorf(\"id is missing\")\n\t\t\treturn\n\t\t}\n\t\t_id, _ := primitive.ObjectIDFromHex(id)\n\t\ttestUser.ID = _id\n\t})\n\n\tt.Run(\"Testing creating existing user\", func(t *testing.T) {\n\t\ttestUser2 := testUser\n\t\ttestUser2.Roles = []string{\"TEST2\"}\n\t\t_, err := testDBService.AddUser(testInstanceID, testUser2)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user already existed, but created again\")\n\t\t\treturn\n\t\t}\n\t\tu, e := testDBService.GetUserByAccountID(testInstanceID, testUser2.Account.AccountID)\n\t\tif e != nil {\n\t\t\tt.Errorf(e.Error())\n\t\t\treturn\n\t\t}\n\t\tif len(u.Roles) > 0 && u.Roles[0] == \"TEST2\" {\n\t\t\tt.Error(\"user should not be updated\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing find existing user by id\", func(t *testing.T) {\n\t\tuser, err := testDBService.GetUserByID(testInstanceID, testUser.ID.Hex())\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif user.Account.AccountID != testUser.Account.AccountID {\n\t\t\tt.Errorf(\"found user is not matching test user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find not existing user by id\", func(t *testing.T) {\n\t\t_, err := testDBService.GetUserByID(testInstanceID, testUser.ID.Hex()+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find existing user by email\", func(t *testing.T) {\n\t\tuser, err := testDBService.GetUserByAccountID(testInstanceID, testUser.Account.AccountID)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif user.Account.AccountID != testUser.Account.AccountID {\n\t\t\tt.Errorf(\"found user is not matching test user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find not existing user by email\", func(t *testing.T) {\n\t\t_, err := testDBService.GetUserByAccountID(testInstanceID, testUser.Account.AccountID+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing updating existing user's attributes\", func(t *testing.T) {\n\t\ttestUser.Account.AccountConfirmedAt = time.Now().Unix()\n\t\t_, err := testDBService.UpdateUser(testInstanceID, testUser)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing updating not existing user's attributes\", func(t *testing.T) {\n\t\ttestUser.Account.AccountConfirmedAt = time.Now().Unix()\n\t\tcurrentUser := testUser\n\t\twrongID := testUser.ID.Hex()[:len(testUser.ID.Hex())-2] + \"00\"\n\t\tid, err := primitive.ObjectIDFromHex(wrongID)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tcurrentUser.ID = id\n\t\t_, err = testDBService.UpdateUser(testInstanceID, currentUser)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"cannot update not existing user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing counting recently added users\", func(t *testing.T) {\n\t\tcount, err := testDBService.CountRecentlyCreatedUsers(testInstanceID, 20)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"unexpected error: %v\", err)\n\t\t\treturn\n\n\t\t}\n\t\tlogger.Debug.Println(count)\n\t\tif count < 1 {\n\t\t\tt.Error(\"at least one user should be found\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing deleting existing user\", func(t *testing.T) {\n\t\terr := testDBService.DeleteUser(testInstanceID, testUser.ID.Hex())\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing deleting not existing user\", func(t *testing.T) {\n\t\terr := testDBService.DeleteUser(testInstanceID, testUser.ID.Hex()+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found - error expected\")\n\t\t\treturn\n\t\t}\n\t})\n}", "func TestCreateUser(t *testing.T) {\n user := User{\n Name: \"Mohammd Osama\",\n Password: \"helloworld\",\n Email: \"[email protected]\",\n }\n if user.ID == 0 {\n t.Errorf(\"Expected ID > 0, Received %d\", user.ID)\n }\n}", "func (m *MockUserLogic) UserCreate(username, email, password string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserCreate\", username, email, password)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (_m *MockService) AddUser(ctx context.Context, name string) (string, error) {\n\tret := _m.ctrl.Call(_m, \"AddUser\", ctx, name)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (x *UserStore) Create(uuid, firstName, lastName, email, password string) (string, error) {\n\tif x.mock != nil && x.mock.Enabled() {\n\t\treturn x.mock.String(), x.mock.Error()\n\t}\n\n\t_, err := x.db.Exec(`\n\t\tINSERT INTO user\n\t\t(id, first_name, last_name, email, password, status_id)\n\t\tVALUES\n\t\t(?,?,?,?,?,?)\n\t\t`,\n\t\tuuid, firstName, lastName, email, password, 1)\n\n\treturn uuid, err\n}", "func (u *UserTest) Insert(user User) (int, error) {\n\treturn 2, nil\n}", "func (m *MockUserStore) Create(arg0 context.Context, arg1 *sql.Tx, arg2 proto.User) error {\n\tret := m.ctrl.Call(m, \"Create\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserPGRepository) Create(ctx context.Context, user *models.User) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, user)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestUserstorage(t *testing.T) {\n t.Log(\"*** User data storage and retrieval test ***\")\n\n // initialize user\n u, err := InitUser(\"alice\",\"fubar\")\n if err != nil {\n t.Error(\"Failed to initialize user (\", err, \")\")\n } else {\n t.Log(\"Successfully stored user\", u)\n }\n\n // retrieve user \n v, err := GetUser(\"alice\", \"fubar\")\n if err != nil {\n t.Error(\"Failed to reload user\", err)\n } else {\n t.Log(\"Correctly retrieved user\", v)\n }\n}", "func TestContactAddCreateUser(t *testing.T) {\n\tdb := database.Connect()\n\tu := models.User{\n\t\tEmail: \"[email protected]\",\n\t}\n\tu.Create(db)\n\tut, _ := u.AddToken(db)\n\n\ttype Data struct {\n\t\tName string\n\t\tEmail string\n\t}\n\td := Data{Name: \"test\", Email: \"[email protected]\"}\n\tj, _ := json.Marshal(d)\n\tb := bytes.NewBuffer(j)\n\n\tr, err := http.NewRequest(\"POST\", \"/\", b)\n\tr.Header.Add(\"Content-Type\", \"application/json\")\n\tr.Header.Add(\"X-Access-Token\", ut.Token)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error\", err)\n\t}\n\n\tw := httptest.NewRecorder()\n\tc := SetupWebContext()\n\tContactAdd(c, w, r)\n\tif w.Code != http.StatusAccepted {\n\t\tt.Errorf(\"%v expected, got %v instead\", http.StatusAccepted, w.Code)\n\t}\n}", "func (_m *Repository) Insert(ctx context.Context, a *models.User) error {\n\tret := _m.Called(ctx, a)\n\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *models.User) error); ok {\n\t\tr1 = rf(ctx, a)\n\t} else {\n\t\tr1 = ret.Error(0)\n\t}\n\n\treturn r1\n}", "func (m *MockFavouriteRepository) Insert(favourite *models.Favourite) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Insert\", favourite)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockDatabase) SaveUser(user *model.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SaveUser\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserService) Save(ctx context.Context, user model.UserCreationDto) error {\n\tret := m.ctrl.Call(m, \"Save\", ctx, user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockDB) GetOrCreateUser(arg0 *User, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetOrCreateUser\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserDB) AddUser(user *UserModel.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddUser\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserRepository) Add(nationality string, birth int, gender string) string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", nationality, birth, gender)\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *MockUserProvider) Insert(_a0 *UserEntity) (*UserEntity, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *UserEntity\n\tif rf, ok := ret.Get(0).(func(*UserEntity) *UserEntity); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*UserEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*UserEntity) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUser) Create(user api.User) (api.User, error) {\n\tret := m.ctrl.Call(m, \"Create\", user)\n\tret0, _ := ret[0].(api.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIRepository) Insert(arg0 aggregates.Question) (aggregates.Id, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Insert\", arg0)\n\tret0, _ := ret[0].(aggregates.Id)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestInsertNewUserServiceAlreadyExists (t *testing.T){\n\terr := PostNewUserService(user_01)\n\tassert.Equal(t, 409, err.HTTPStatus)\n}", "func (m_2 *MockUserRepository) Create(m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Create\", m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIRepository) Insert(arg0 aggregates.Topic) (aggregates.Id, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Insert\", arg0)\n\tret0, _ := ret[0].(aggregates.Id)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) CreateUser(arg0 context.Context, arg1 db.CreateUserParams) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateUser\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestCreateUser(t *testing.T) {\n\tt.Log(\"testing user creation\")\n\tvar createUser = func() {\n\t\trec = httptest.NewRecorder()\n\t\treq, err := http.NewRequest(\"POST\", \"/v0/users\", strings.NewReader(`\n\t\t{\n\t\t\t\"data\": {\n\t\t\t\t\"type\": \"users\",\n\t\t\t\t\"attributes\": {\n\t\t\t\t\t\"username\": \"Holygarian\",\n\t\t\t\t\t\"password\": \"pass6\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t`))\n\t\t// Expect(err).ToNot(HaveOccurred())\n\t\tapi.Handler().ServeHTTP(rec, req)\n\t\tExpect(rec.Code).To(Equal(http.StatusCreated))\n\t\tExpect(rec.Body.String()).To(MatchJSON(`\n\t\t{\n\t\t\t\"meta\": {\n\t\t\t\t\"author\": \"The api2go examples crew\",\n\t\t\t\t\"license\": \"wtfpl\",\n\t\t\t\t\"license-url\": \"http://www.wtfpl.net\"\n\t\t\t},\n\t\t\t\"data\": {\n\t\t\t\t\"id\": \"1\",\n\t\t\t\t\"type\": \"users\",\n\t\t\t\t\"attributes\": {\n\t\t\t\t\t\"user-name\": \"marvin\"\n\t\t\t\t},\n\t\t\t\t\"relationships\": {\n\t\t\t\t\t\"sweets\": {\n\t\t\t\t\t\t\"data\": [],\n\t\t\t\t\t\t\"links\": {\n\t\t\t\t\t\t\t\"related\": \"http://localhost:31415/v0/users/1/sweets\",\n\t\t\t\t\t\t\t\"self\": \"http://localhost:31415/v0/users/1/relationships/sweets\"\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`))\n\t}\n\t\n}", "func (m *MockRepository) Create(ctx context.Context, u *models.User) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, u)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m_2 *MockUserUsecaser) Create(c context.Context, m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Create\", c, m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) Store(arg0 *sweeper.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUsersRepo) Create(arg0 auth.User) (auth.User, error) {\n\tret := m.ctrl.Call(m, \"Create\", arg0)\n\tret0, _ := ret[0].(auth.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) Create(user *auth.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockInfluxDB) InsertToInflux(MyDB, measurement, columnName string, value int, roundedTime time.Time) {\n\tm.ctrl.Call(m, \"InsertToInflux\", MyDB, measurement, columnName, value, roundedTime)\n}", "func insertUser(id int) result {\n\tr := result{\n\t\tid: id,\n\t\top: fmt.Sprintf(\"insert USERS value (%d)\", id),\n\t}\n\n\t// Randomize if the insert fails or not.\n\tif rand.Intn(10) == 0 {\n\t\tr.err = fmt.Errorf(\"Unable to insert %d into USER table\", id)\n\t}\n\n\treturn r\n}", "func (r *Repository) UsersInsert(o *User) error {\n\n\tif hash, err := crypto.HashPassword(o.Password); err != nil {\n\t\treturn err\n\t} else {\n\t\to.PasswordHash = hash\n\t\to.Password = \"\"\n\t}\n\n\to.CreatedAt = now()\n\to.UpdatedAt = o.CreatedAt\n\n\tstmt, err := r.db.PrepareNamed(\n\t\t\"INSERT INTO users (name, email, password_hash, extra, is_activated, created_at, updated_at) \" +\n\t\t\t\"VALUES(:name, :email, :password_hash, :extra, :is_activated, :created_at, :updated_at) \" +\n\t\t\t\"RETURNING id\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn stmt.QueryRowx(o).Scan(&o.ID)\n}", "func (m *MockDatabase) InsertUserList(ID string, listID int) error {\n\targs := m.Called(ID, listID)\n\treturn args.Error(0)\n}", "func (m *MockIUserRepository) CreateNewUser() *model.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateNewUser\")\n\tret0, _ := ret[0].(*model.User)\n\treturn ret0\n}", "func (m *MockInterface) AddUser(arg0 *userService.User) (*userService.Nothing, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddUser\", arg0)\n\tret0, _ := ret[0].(*userService.Nothing)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUseCase) CreateUser(ctx context.Context, username, password, firstName, lastName string, age uint8, location, sex, about string) (uint64, uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateUser\", ctx, username, password, firstName, lastName, age, location, sex, about)\n\tret0, _ := ret[0].(uint64)\n\tret1, _ := ret[1].(uint64)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockUserRepo) Create(arg0 *app.User) (*app.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", arg0)\n\tret0, _ := ret[0].(*app.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockMessageRepository) InsertRemind(ctx context.Context, entity *model.Message, ExecuteAt time.Time) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InsertRemind\", ctx, entity, ExecuteAt)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (userRepo *mockUserRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (m *MockStorage) Insert(arg0 *model.Car) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Insert\", arg0)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUsersRepository) Save(arg0 context.Context, arg1 *entities.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Save\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUCAuth) Register(ctx context.Context, user *models.User) (*models.UserWithToken, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Register\", ctx, user)\n\tret0, _ := ret[0].(*models.UserWithToken)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepo) Create(ctx context.Context, input CreateUserInput) (User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, input)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockUserGroupsProvider) Insert(entity *UserGroupsEntity) (*UserGroupsEntity, error) {\n\tret := _m.Called(entity)\n\n\tvar r0 *UserGroupsEntity\n\tif rf, ok := ret.Get(0).(func(*UserGroupsEntity) *UserGroupsEntity); ok {\n\t\tr0 = rf(entity)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*UserGroupsEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*UserGroupsEntity) error); ok {\n\t\tr1 = rf(entity)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockAccount) Register(arg0, arg1 string) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Register\", arg0, arg1)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestStore_CreateUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create user.\n\tif ui, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if ui.Name != \"susy\" || ui.Hash == \"\" || ui.Admin != true {\n\t\tt.Fatalf(\"unexpected user: %#v\", ui)\n\t}\n}", "func (m *MockUser) Put(ctx context.Context, e entity.User) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Put\", ctx, e)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIUserStore) Save(user *dto.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Save\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Test_DeviceService_AddOrUpdate_Success(t *testing.T) {\n\th := TestHelper{}\n\trep := new(mocks.IDeviceRepository)\n\trepAuth := new(mocks.IDeviceAuthRepository)\n\ts := h.CreateTestDeviceService(rep, repAuth)\n\n\tip := \"192.168.11.4\"\n\tport := 37777\n\n\tauths := make([]models.DeviceAuth, 1)\n\tauths[0] = models.DeviceAuth {\n\t\tLogin: \"admin1234\",\n\t\tPassword: \"admin4321\",\n\t}\n\n\tdev := models.Device{\n\t\tIP: ip,\n\t\tPort: port,\n\t\tLogin: auths[0].Login,\n\t\tPassword: auths[0].Password,\n\t\tChannels: make([]models.Channel, 0),\n\t}\n\n\trepAuth.On(\"GetAll\").Return(auths, nil)\n\trep.On(\"AddOrUpdate\", dev).Return(dev, nil)\n\n\treal, err := s.AddOrUpdate(ip, port)\n\n\tassert.NoError(t, err)\n\tassert.Equal(t, dev, real)\n}", "func Insert() error {\n\tuser := &TbUser{\n\t\tName: \"viney\",\n\t\tEmail: \"[email protected]\",\n\t\tCreated: time.Now().Format(\"2006-01-02 15:04:05\"),\n\t}\n\treturn orm.Save(user)\n}", "func (_m *MockUserProvider) Create(username string, password []byte, FirstName string, LastName string, confirmationToken []byte, isSuperuser bool, IsStaff bool, isActive bool, isConfirmed bool) (*UserEntity, error) {\n\tret := _m.Called(username, password, FirstName, LastName, confirmationToken, isSuperuser, IsStaff, isActive, isConfirmed)\n\n\tvar r0 *UserEntity\n\tif rf, ok := ret.Get(0).(func(string, []byte, string, string, []byte, bool, bool, bool, bool) *UserEntity); ok {\n\t\tr0 = rf(username, password, FirstName, LastName, confirmationToken, isSuperuser, IsStaff, isActive, isConfirmed)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*UserEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, []byte, string, string, []byte, bool, bool, bool, bool) error); ok {\n\t\tr1 = rf(username, password, FirstName, LastName, confirmationToken, isSuperuser, IsStaff, isActive, isConfirmed)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (s *MockStore) Create(u User) (User, error) {\n\t// name unique\n\t_, err := s.GetByName(u.Name)\n\tif err == nil { // successful query, err != ErrNoRows\n\t\treturn u, errors.New(\"That name is taken.\")\n\t}\n\n\t// email address exists and is unique\n\tif !(strings.Contains(u.Email, \"@\") && strings.Contains(u.Email, \".\")) {\n\t\treturn u, errors.New(\"Please enter a valid email address.\")\n\t}\n\t_, err = s.GetByName(u.Email)\n\tif err == nil {\n\t\treturn u, errors.New(\"That email address is already being used.\")\n\t}\n\n\t// password > 6 char\n\tif len(u.Password) < 6 {\n\t\treturn u, errors.New(\"Password must have 6 or more characters.\")\n\t}\n\n\t// securely hash the password\n\thash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcryptCost)\n\tif err != nil {\n\t\treturn u, errors.New(\"Error hashing password.\")\n\t}\n\tu.Password = string(hash)\n\n\tu.Created = time.Now()\n\n\tu.ID = s.idSerial\n\ts.idSerial++\n\n\t// insert into db\n\ts.Put(u)\n\n\treturn u, err\n}", "func (m *MockUserRepository) Persist(arg0 *entities.User) (*entities.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Persist\", arg0)\n\tret0, _ := ret[0].(*entities.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserStorage) CreateUser(ctx context.Context, user model.User) (model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateUser\", ctx, user)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s MockStore) Put(u User) error {\n\ts.id[u.ID] = u\n\ts.name[u.Name] = u\n\ts.email[u.Email] = u\n\n\treturn nil\n}", "func (_m *MockUserPermissionsProvider) Insert(entity *UserPermissionsEntity) (*UserPermissionsEntity, error) {\n\tret := _m.Called(entity)\n\n\tvar r0 *UserPermissionsEntity\n\tif rf, ok := ret.Get(0).(func(*UserPermissionsEntity) *UserPermissionsEntity); ok {\n\t\tr0 = rf(entity)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*UserPermissionsEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*UserPermissionsEntity) error); ok {\n\t\tr1 = rf(entity)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserRepository) Create(ctx context.Context, user *domain.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (sqlMock *SQLMock) ExpectInsert(models ...interface{}) *SQLMock {\n\tsqlMock.lock.Lock()\n\tdefer sqlMock.lock.Unlock()\n\n\tvar inserts []string\n\tfor _, v := range models {\n\t\tinserts = append(inserts, strings.ToLower(manager.GetType(v)))\n\t}\n\tcurrentInsert := strings.Join(inserts, \",\")\n\n\tsqlMock.currentInsert = currentInsert\n\treturn sqlMock\n}", "func (m *MockManager) CreateExternalUser(arg0, arg1, arg2, arg3 string) error {\n\tret := m.ctrl.Call(m, \"CreateExternalUser\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func insertUser(db *sql.DB, u *User) {\n\n\t// name := u.name\n\t// rollno := u.rollno\n\tinsertUserSQL := `INSERT INTO User( name, rollno) VALUES (?, ?)`\n\tstatement, err := db.Prepare(insertUserSQL) \n\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n\t_, err = statement.Exec(u.name, u.rollno)\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n}", "func (m *MockPageTable) Insert(arg0 vm.Page) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Insert\", arg0)\n}", "func (u *UserModel) Insert(uid uuid.UUID, firstName models.NullString, lastName models.NullString, email models.NullString, phone string, statusID int, password string) (*models.User, error) {\n\tcreated := time.Now()\n\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), PW_HASH_COST)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstmt := `INSERT INTO user (\n uuid,\n\t\tfirst_name,\n\t\tlast_name,\n\t\temail,\n\t\tphone,\n\t\tstatus_id,\n\t\thashed_password,\n\t\tcreated\n\t) VALUES (\n\t ?,\n\t\t?,\n\t\t?,\n\t\t?,\n\t\t?,\n\t\t?,\n\t\t?,\n\t\t?\n\t)`\n\n\tresult, err := u.DB.Exec(stmt, uid.String(), firstName.String, lastName.String, email.String, NormalizePhone(phone), statusID, hashedPassword, created)\n\tif err != nil {\n\t\tif mysqlErr, ok := err.(*mysql.MySQLError); ok {\n\t\t\tif mysqlErr.Number == 1062 && strings.Contains(mysqlErr.Message, \"uk_user_email\") {\n\t\t\t\treturn nil, models.ErrDuplicateEmail\n\t\t\t}\n\t\t\tif mysqlErr.Number == 1062 && strings.Contains(mysqlErr.Message, \"uk_user_phone\") {\n\t\t\t\treturn nil, models.ErrDuplicatePhone\n\t\t\t}\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuserStatus := models.UserStatus(statusID)\n\n\tuser := &models.User{\n\t\tID: id,\n\t\tUUID: uid,\n\t\tFirstName: firstName,\n\t\tLastName: lastName,\n\t\tEmail: email,\n\t\tPhone: phone,\n\t\tStatus: userStatus.Slug(),\n\t\tCreated: created,\n\t}\n\n\treturn user, nil\n}", "func (suite *StoreTestSuite) Test001_User() {\n\tusername := \"foo\"\n\temail := \"bar\"\n\tpw := \"baz\"\n\trole := 1337\n\n\t// Test CreateUser\n\tnewUser := &schema.User{\n\t\tUsername: &username,\n\t\tEmail: &email,\n\t\tPassword: &pw,\n\t\tRole: &role,\n\t}\n\terr := suite.store.CreateUser(newUser)\n\tsuite.Nil(err)\n\n\t// Test GetUserByUsername\n\tuser, err := suite.store.GetUserByUsername(username)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\tid := user.ID.Hex()\n\n\t// Test GetUserByEmail\n\tuser, err = suite.store.GetUserByEmail(email)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\t// Test GetUserByPassword\n\tuser, err = suite.store.GetUserByCreds(username, pw)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\t// Test CreateUser with conflict\n\terr = suite.store.CreateUser(newUser)\n\tsuite.NotNil(err)\n\tsuite.Equal(\"user with username as foo already exists\", err.Error())\n\n\t// Test UpdateUser\n\tnewUsername := \"foobar\"\n\tuserPatch := &schema.User{Username: &newUsername}\n\tuser, err = suite.store.UpdateUser(id, userPatch)\n\tsuite.Nil(err)\n\tsuite.Equal(newUsername, user.Username)\n\tsuite.Equal(email, user.Email)\n\tsuite.Equal(role, user.Role)\n\n\t// Add second user\n\terr = suite.store.CreateUser(newUser)\n\tsuite.Nil(err)\n\n\t// Try to update second user\n\tu, err := suite.store.GetUserByUsername(*newUser.Username)\n\tsuite.Nil(err)\n\n\tuser, err = suite.store.UpdateUser(u.ID.Hex(), userPatch)\n\tsuite.Nil(user)\n\tsuite.True(mgo.IsDup(err))\n\n\t// Test GetAllUsers\n\tusers, err := suite.store.GetAllUsers()\n\tsuite.Nil(err)\n\tsuite.Equal(len(users), 2)\n\n\t// Test DeleteUser\n\tuser, err = suite.store.DeleteUser(id)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(newUsername, user.Username)\n\tsuite.Equal(email, user.Email)\n}", "func createTestUser(ts *Server) (string, string) {\n\tuser := new(Models.User)\n\terr := ts.insertUser(\"[email protected]\", nil, user)\n\tSo(err, ShouldEqual, nil)\n\n\ttoken := generateToken(user.ID, 10*time.Minute, false)\n\ttStr, err := token.SignedString(SigningKey)\n\tSo(err, ShouldEqual, nil)\n\n\terr = ts.storeToken(tStr, 10*time.Minute)\n\tSo(err, ShouldEqual, nil)\n\treturn user.ID, tStr\n}", "func TestReadUser(t *testing.T) {\r\n/////////////////////////////////// MOCKING ////////////////////////////////////////////\r\n\tvar batches = []string{\r\n\t\t`CREATE TABLE Users (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Name TEXT NOT NULL UNIQUE);`,\r\n\t\t`INSERT INTO Users (Id,Name) VALUES (1,'anonymous');`,\r\n\t}\r\n\t//open pseudo database for function\r\n\tdb, err := sql.Open(\"ramsql\", \"TestReadUser\")\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Error creating mock sql : %s\\n\", err)\r\n\t}\r\n\tdefer db.Close()\r\n\r\n\t// Exec every line of batch and create database\r\n\tfor _, b := range batches {\r\n\t\t_, err = db.Exec(b)\r\n\t\tif err != nil {\r\n\t\t\tt.Fatalf(\"Error exec query in query: %s\\n Error:%s\", b, err)\r\n\t\t}\r\n\t}\r\n/////////////////////////////////// MOCKING ////////////////////////////////////////////\r\n\r\n\t// Specify test variables and expected results.\r\n\ttests := []struct {\r\n\t\tid int\r\n\t\t// we need to use models.User for passing to object.This is different with \"database.User\".\r\n\t\tresult models.User\r\n\t\terr error\r\n\t}{\r\n\t\t// When give to first parameter(id) 1 , We expect result :1 error nil\r\n\t\t{id: 1, result: models.User{Id: 1, Name: \"anonymous\"}, err: nil},\r\n\t\t// When give to first parameter(id) 1 , We expect result :1 error nil\r\n\t\t//{id: 2, result: models.User{Id: 2, Name: \"test\"}, err: nil},\r\n\t}\r\n\r\n\t// test all of the variables.\r\n\tfor _, test := range tests {\r\n\t\t//get result after test.\r\n\t\ts, err := u.ReadUser(db, test.id)\r\n\t\t// if expected error type nil we need to compare with actual error different way.\r\n\t\tif test.err == nil {\r\n\t\t\t// If test fails give error.It checks expected result and expected error\r\n\t\t\tif err != test.err || s != test.result {\r\n\t\t\t\t// Compare expected error and actual error\r\n\t\t\t\tt.Errorf(\"Error is: %v . Expected: %v\", err, test.err)\r\n\t\t\t\t// Compare expected result and actual result\r\n\t\t\t\tt.Errorf(\"Result is: %v . Expected: %v\", s, test.result)\r\n\t\t\t}\r\n\t\t\t// if expected error type is not nil we need to compare with actual error different way.\r\n\t\t} else {\r\n\t\t\tif err.Error() != test.err.Error() || s != test.result {\r\n\t\t\t\t// Compare expected error and actual error\r\n\t\t\t\tt.Errorf(\"Error is: %v . Expected: %v\", err, test.err)\r\n\t\t\t\t// Compare expected result and actual result\r\n\t\t\t\tt.Errorf(\"Result is: %v . Expected: %v\", s, test.result)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func (m *MockCache) InsertOrderBookRow(arg0 *models.OrderBookRow) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"InsertOrderBookRow\", arg0)\n}", "func (m *MockManager) Create(ctx context.Context, user *model.User) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, user)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestFindUserById(t *testing.T) {\n\t_, mock, err := NewMock()\n\tif err != nil {\n\t\tfmt.Printf(\"error mock: \" + err.Error())\n\t}\n\n\t// simulate any sql driver behavior in tests, without needing a real database connection\n\tquery := \"select id, user_name, password from m_user where id = \\\\?\"\n\n\trows := sqlmock.NewRows([]string{\"id\", \"user_name\", \"password\"}).\n\t\tAddRow(user.ID, user.UserName, user.Password)\n\n\tmock.ExpectQuery(query).WithArgs(user.ID).WillReturnRows(rows)\n\t// ------------ end of mock ---------------\n\n\tassert.NotNil(t, user)\n}", "func (m *MockUserRepository) Create(attr UserAttributes) (UserUUID, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", attr)\n\tret0, _ := ret[0].(UserUUID)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mss *MySQLStore) Insert(user *User) (*User, error) {\n\tinsq := \"insert into users(email, pass_hash, user_name, first_name, last_name) values (?, ?, ?, ?, ?)\"\n\tres, err := mss.Client.Exec(insq, user.Email, user.PassHash, user.UserName, user.FirstName, user.LastName)\n\tif err != nil {\n\t\tlog.Printf(\"Issue executing sql statement: %v\", err)\n\t\treturn nil, err\n\t}\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\tlog.Print(\"Error retrieving last insert id\")\n\t\treturn nil, err\n\t}\n\tuser.ID = id\n\treturn user, nil\n}", "func (m *MockUserUsecase) Create(email, passwordHash, name string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", email, passwordHash, name)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *MockUserProvider) CreateSuperuser(username string, password []byte, FirstName string, LastName string) (*UserEntity, error) {\n\tret := _m.Called(username, password, FirstName, LastName)\n\n\tvar r0 *UserEntity\n\tif rf, ok := ret.Get(0).(func(string, []byte, string, string) *UserEntity); ok {\n\t\tr0 = rf(username, password, FirstName, LastName)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*UserEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, []byte, string, string) error); ok {\n\t\tr1 = rf(username, password, FirstName, LastName)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUsersRepoInterface) Register(arg0 *user.User) (*user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Register\", arg0)\n\tret0, _ := ret[0].(*user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) Save(arg0 entity.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Save\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestAddUser(t *testing.T) {\n\taddUserWithArgs(t, []string{\n\t\t\"--user\", \"someuser\",\n\t})\n}", "func (_obj *WebApiAuth) SysUser_Insert(req *SysUser, id *int32, _opt ...map[string]string) (err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = req.WriteBlock(_os, 1)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = _os.Write_int32((*id), 2)\n\tif err != nil {\n\t\treturn 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, \"SysUser_Insert\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = _is.Read_int32(&(*id), 2, true)\n\tif err != nil {\n\t\treturn 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 nil\n}", "func (r *Repository) create(user *domain.UserInfoModel) error {\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tquery := \"INSERT INTO users (namee, email, password) VALUES ($1, $2, $3)\"\n\tstmt, err := r.db.PrepareContext(ctx, query)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\tqueryStart := time.Now().Nanosecond() / 1000\n\t_, err = stmt.ExecContext(ctx, user.Name, user.Email, user.PassWord)\n\tif err != nil {\n\t\treturn err\n\t}\n\tqueryEnd := time.Now().Nanosecond() / 1000\n\texecutionTime := queryEnd - queryStart\n\terr = r.insertTimeSpent(\"Create\", executionTime)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn nil\n}", "func InsertIntoDB(userinfo types.ThirdPartyResponse) error {\n\tmeta, err := json.Marshal(userinfo.MetaData)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\tif userinfo.Name == \"\" {\n\t\tfmt.Println(\"Name is not issued from third party\")\n\t} else if userinfo.Id == 0 {\n\t\tfmt.Println(\"Email is not issued from third party\")\n\t}\n\n\tinsertQuery := `INSERT INTO loggedinuser (id, name, email, meta) VALUES ($1, $2, $3, $4)`\n\t_, err = db.Exec(insertQuery, userinfo.Id, userinfo.Name, userinfo.Email, string(meta))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *MockDataSourceRepo) Insert(arg0 context.Context, arg1 repository.DataSource) (int64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Insert\", arg0, arg1)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIUser) GetOrCreateUser(arg0 *User, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetOrCreateUser\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockAuthorization) CreateUser(user domain.User) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateUser\", user)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func insertUser(user User) {\n\tcollection := client.Database(\"Go_task\").Collection(\"users\")\n\tinsertResult, err := collection.InsertOne(context.TODO(), user)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Inserted user with ID:\", insertResult.InsertedID)\n}", "func (mock *Mock) CreateUser(newUser entities.User) (uint, error) {\n\tinputHash := toHash(getInputForCreateUser(newUser))\n\tarrOutputForCreateUser, exists := mock.patchCreateUserMap[inputHash]\n\tif !exists || len(arrOutputForCreateUser) == 0 {\n\t\tpanic(\"Mock not available for CreateUser\")\n\t}\n\n\toutput := arrOutputForCreateUser[0]\n\tarrOutputForCreateUser = arrOutputForCreateUser[1:]\n\tmock.patchCreateUserMap[inputHash] = arrOutputForCreateUser\n\n\treturn output.newUserID, output.error\n}", "func (_m *MockTx) AddUser(_a0 *model.User) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*model.User) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *RepositoryMock) Insert(args db_models.DbDTO) error {\n\tret := _m.Called(args)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(db_models.DbDTO) error); ok {\n\t\tr0 = rf(args)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}" ]
[ "0.737739", "0.6988573", "0.67998195", "0.6665167", "0.63610375", "0.6327294", "0.6291074", "0.62281567", "0.62146413", "0.6182508", "0.61761326", "0.617257", "0.6166692", "0.6157793", "0.6155977", "0.6132569", "0.61202914", "0.61003804", "0.6093564", "0.60906214", "0.6062177", "0.60193425", "0.601491", "0.6008972", "0.59884274", "0.5973492", "0.59639555", "0.59514177", "0.5941858", "0.59370285", "0.5934149", "0.5932733", "0.5924189", "0.5914747", "0.59099925", "0.59082353", "0.59067917", "0.59029514", "0.58908015", "0.58828884", "0.5871917", "0.5860584", "0.5855877", "0.5844123", "0.58360267", "0.58351165", "0.5826783", "0.5823677", "0.58198357", "0.5810562", "0.5804736", "0.57986355", "0.5795127", "0.5794694", "0.5790624", "0.57896096", "0.5771904", "0.576557", "0.57442987", "0.57437986", "0.5726168", "0.572571", "0.572211", "0.5719703", "0.5718454", "0.57147545", "0.5711882", "0.57117105", "0.57111067", "0.571079", "0.57010114", "0.5698849", "0.56963503", "0.5695853", "0.56955624", "0.5691438", "0.568807", "0.5686617", "0.56832945", "0.56750154", "0.5668994", "0.56685257", "0.5667826", "0.56583434", "0.5654715", "0.56424105", "0.5642211", "0.5640904", "0.5640483", "0.5640473", "0.5636637", "0.5623624", "0.5621319", "0.5618033", "0.5608868", "0.5598904", "0.5598674", "0.5592884", "0.5586622", "0.55822945" ]
0.73504555
1
InsertUser indicates an expected call of InsertUser
func (mr *MockUserRepositoryInterfaceMockRecorder) InsertUser(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InsertUser", reflect.TypeOf((*MockUserRepositoryInterface)(nil).InsertUser), arg0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockDatabase) InsertUser(ID, Email string) error {\n\targs := m.Called(ID, Email)\n\treturn args.Error(0)\n}", "func (u *UserTest) Insert(user User) (int, error) {\n\treturn 2, nil\n}", "func (usr *User) Insert() error {\n\tif _, err := orm.NewOrm().Insert(usr); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Insert() error {\n\tuser := &TbUser{\n\t\tName: \"viney\",\n\t\tEmail: \"[email protected]\",\n\t\tCreated: time.Now().Format(\"2006-01-02 15:04:05\"),\n\t}\n\treturn orm.Save(user)\n}", "func TestInsertNewUserService (t *testing.T){\n\terr := PostNewUserService(user_01)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_02)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_03)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_04)\n\tassert.Equal(t, 200, err.HTTPStatus)\n}", "func (r *RepoImp) InsertUser(user models.Users) (int, error) {\n\tif err := r.db.Create(&user).Error; err != nil {\n\t\treturn -1, err\n\t}\n\treturn user.ID, nil\n}", "func insertUser(username string, password string, kind int) bool {\n\tresult, err := mysql_client.Exec(\"INSERT INTO User(username, password, kind) VALUES(?,?,?)\", username, password, kind)\n\tif err != nil {\n\t\t// insert failed\n\t\treturn false\n\t}\n\t_, err = result.LastInsertId()\n\tif err != nil {\n\t\treturn false\n\t}\n\t_, err = result.RowsAffected()\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func insertUser(id int) result {\n\tr := result{\n\t\tid: id,\n\t\top: fmt.Sprintf(\"insert USERS value (%d)\", id),\n\t}\n\n\t// Randomize if the insert fails or not.\n\tif rand.Intn(10) == 0 {\n\t\tr.err = fmt.Errorf(\"Unable to insert %d into USER table\", id)\n\t}\n\n\treturn r\n}", "func (r User) Insert() error {\n\tr.ID = bson.NewObjectId()\n\terr := db.C(\"user\").Insert(&r)\n\treturn err\n}", "func (u *User) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif u._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tconst sqlstr = `INSERT INTO test_database.users (` +\n\t\t`username, created_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, u.Username, u.CreatedAt)\n\tres, err := db.Exec(sqlstr, u.Username, u.CreatedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tu.UserID = uint64(id)\n\tu._exists = true\n\n\treturn nil\n}", "func (mr *MockUserServiceMockRecorder) Insert(tx, username, password interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Insert\", reflect.TypeOf((*MockUserService)(nil).Insert), tx, username, password)\n}", "func (_UserCrud *UserCrudTransactor) InsertUser(opts *bind.TransactOpts, userAddress common.Address, userEmail string, userAge *big.Int) (*types.Transaction, error) {\n\treturn _UserCrud.contract.Transact(opts, \"insertUser\", userAddress, userEmail, userAge)\n}", "func (u *User) Insert() error {\n\treturn db.Create(&u).Error\n}", "func (s *Database) InsertUser(user UserPartner) error {\n\tc, err := s.Engine.Insert(user)\n\tif c == 0 {\n\t\treturn errors.New(\"Loi insert\")\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (d Data) InsertUser(ctx context.Context, user userEntity.User) error {\n\t_, err := d.stmt[insertUser].ExecContext(ctx,\n\t\tuser.ID,\n\t\tuser.Nip,\n\t\tuser.Nama,\n\t\tuser.TanggalLahir,\n\t\tuser.Jabatan,\n\t\tuser.Email)\n\treturn err\n}", "func (r *Repository) InsertUser(data *User) (err error) {\n\n\thp, err := hashString(data.Password)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdata.HashPassword = hp\n\n\terr = r.db.Create(data).Error\n\n\treturn\n}", "func insertUser(user User) {\n\tcollection := client.Database(\"Go_task\").Collection(\"users\")\n\tinsertResult, err := collection.InsertOne(context.TODO(), user)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Inserted user with ID:\", insertResult.InsertedID)\n}", "func (u *userService) InsertUser(user dto.UserRequest) (*string, resterr.APIError) {\n\t// cek ketersediaan id\n\t_, err := u.dao.CheckIDAvailable(user.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// END cek ketersediaan id\n\n\thashPassword, err := u.crypto.GenerateHash(user.Password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser.Password = hashPassword\n\tuser.Timestamp = time.Now().Unix()\n\n\tinsertedID, err := u.dao.InsertUser(user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn insertedID, nil\n}", "func Insert() error {\n\tuser := &Users{\n\t\tUid: 1,\n\t\tName: \"viney\",\n\t\tEmail: \"[email protected]\",\n\t\tCreated: time.Now(),\n\t}\n\n\tid, err := engine.InsertOne(user)\n\tif err != nil {\n\t\treturn err\n\t} else if id <= 0 {\n\t\treturn errors.New(\"插入失败\")\n\t}\n\n\treturn nil\n}", "func (user User) Insert() (User, error) {\n\tdigest, err := GenerateHash(user.Password)\n\tif err != nil {\n\t\treturn user, err\n\t}\n\t_, err = time.LoadLocation(user.Location)\n\tif err != nil {\n\t\treturn user, errors.New(\"user location invalid\")\n\t}\n\tuser.Digest = digest\n\t_, err = db.NamedExec(\"INSERT INTO users (name, digest, email, location) VALUES (:name, :digest, :email, :location)\", user)\n\tif err != nil {\n\t\tif err.Error() == \"UNIQUE constraint failed: users.email\" || err.Error() == `pq: duplicate key value violates unique constraint \"users_email_key\"` {\n\t\t\treturn user, errors.New(\"user email exists\")\n\t\t}\n\t\treturn user, err\n\t}\n\treturn user, nil\n}", "func (ur *UserRepo) Insert(u models.User) error {\n\t_, err := ur.db.InsertOne(userColNmae, u)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *GodrorStorage) InsertUser(db XODB, u *User) error {\n\tvar err error\n\n\t// sql insert query, primary key provided by sequence\n\tconst sqlstr = `INSERT INTO \"AC\".\"user\" (` +\n\t\t`\"subject\", \"name\", \"created_date\", \"changed_date\", \"deleted_date\"` +\n\t\t`) VALUES (` +\n\t\t`:1, :2, :3, :4, :5` +\n\t\t`) RETURNING \"id\" INTO :6`\n\n\t// run query\n\ts.Logger.Info(sqlstr, u.Subject, u.Name, u.CreatedDate, u.ChangedDate, u.DeletedDate)\n\t_, err = db.Exec(sqlstr, RealOracleEmptyString(u.Subject), RealOracleNullString(u.Name), u.CreatedDate, u.ChangedDate, u.DeletedDate, sql.Out{Dest: &u.ID})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *Repository) UsersInsert(o *User) error {\n\n\tif hash, err := crypto.HashPassword(o.Password); err != nil {\n\t\treturn err\n\t} else {\n\t\to.PasswordHash = hash\n\t\to.Password = \"\"\n\t}\n\n\to.CreatedAt = now()\n\to.UpdatedAt = o.CreatedAt\n\n\tstmt, err := r.db.PrepareNamed(\n\t\t\"INSERT INTO users (name, email, password_hash, extra, is_activated, created_at, updated_at) \" +\n\t\t\t\"VALUES(:name, :email, :password_hash, :extra, :is_activated, :created_at, :updated_at) \" +\n\t\t\t\"RETURNING id\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn stmt.QueryRowx(o).Scan(&o.ID)\n}", "func (u *User) BeforeInsert(db orm.DB) error {\n\tnow := time.Now()\n\tif u.CreatedAt.IsZero() {\n\t\tu.CreatedAt = now\n\t\tu.UpdatedAt = now\n\t}\n\n\terr := u.validatePin()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn u.Validate()\n}", "func (u *UserFunctions) Insert(username, firstname, lastname, email, password string) error {\n\n\t//Insert user to the database\n\tnewUser := u.CLIENT.Database(\"queue\")\n\tuserCollection := newUser.Collection(\"user\")\n\tvar user models.User\n\n\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 12)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser.UserName = username\n\tuser.FirstName = firstname\n\tuser.LastName = lastname\n\tuser.Email = email\n\tuser.Password = hashedPassword\n\tuser.Created = time.Now().UTC()\n\tuser.Active = true\n\n\t//Insert the user into the database\n\tresult, err := userCollection.InsertOne(context.TODO(), user)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\t//Check ID of the inserted document\n\tinsertedID := result.InsertedID.(primitive.ObjectID)\n\tfmt.Println(insertedID)\n\n\treturn nil\n}", "func (ua *UserAuth) Insert(ctx context.Context, db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif ua._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key must be provided\n\tconst sqlstr = `INSERT INTO user_auths (` +\n\t\t`user_id, email, password_hash, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, ua.UserID, ua.Email, ua.PasswordHash, ua.CreatedAt, ua.UpdatedAt)\n\t_, err = db.ExecContext(ctx, sqlstr, ua.UserID, ua.Email, ua.PasswordHash, ua.CreatedAt, ua.UpdatedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\tua._exists = true\n\n\treturn nil\n}", "func (h *Handler) InsertUser(user models.User) (error){\n\n\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), 8)\n\n\tquery := fmt.Sprintf(\"insert into users (first_name, last_name, email, password) values ('%s', '%s', '%s', '%s');\", user.FirstName, user.LastName, user.Email, hashedPassword)\n\n\t_, err = h.DB.Exec(query)\n\tif err != nil {\n\t\tfmt.Printf(\"user_service-InsertUser-Exec: %s\\n\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (dao *DAO) InsertUser(user model.User) error {\r\n\terr := db.C(dao.UserCollection).Insert(&user)\r\n\r\n\treturn err\r\n}", "func TestInsertNewUserServiceAlreadyExists (t *testing.T){\n\terr := PostNewUserService(user_01)\n\tassert.Equal(t, 409, err.HTTPStatus)\n}", "func insertUser(db *sql.DB, u *User) {\n\n\t// name := u.name\n\t// rollno := u.rollno\n\tinsertUserSQL := `INSERT INTO User( name, rollno) VALUES (?, ?)`\n\tstatement, err := db.Prepare(insertUserSQL) \n\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n\t_, err = statement.Exec(u.name, u.rollno)\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n}", "func (u *userService) Insert(user *domain.User) (*domain.User, error) {\n\tif err := user.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn u.storage.Insert(user)\n}", "func InsertUser(u User, t string) {\n\t// Begin transaction\n\ttx, err := globals.Db.Begin()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer tx.Rollback()\n\n\t// Prepare user insertion and execute\n\tstmt, err := tx.Prepare(\"INSERT INTO tblUsers(fldFirstName, fldLastName, fldEmail, fldPassword) VALUES (?, ?, ?, ?)\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer stmt.Close()\n\n\tres, err := stmt.Exec(u.FirstName, u.LastName, u.Email, u.Password)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Get the last inserted row's ID\n\tlastID, err := res.LastInsertId()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Prepare token insertion and execute\n\tstmt, err = tx.Prepare(\"INSERT INTO tblActivationTokens (fldToken,fldFKUserID) VALUES (?, ?)\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tres, err = stmt.Exec(t, lastID)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Commit query\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (ctl *controller) APIUserInsertPostAction(ctx *gin.Context) {\n\tctl.logger.Debug(\"[POST] UserPostAction\")\n\n\tvar userRequest UserRequest\n\tif err := validateUserRequest(ctx, &userRequest); err != nil {\n\t\tctx.AbortWithError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tid, err := ctl.insertUser(&userRequest)\n\tif err != nil {\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\t// json response\n\tctx.JSON(http.StatusOK, jsonresp.CreateUserJSON(id))\n}", "func (u *User) Insert(tx *sql.Tx, password string) (sql.Result, error) {\n\tstmt, err := tx.Prepare(`\n\tinsert into users (name, email, salt, salted)\n\tvalues(?, ?, ?, ?)\n\t`)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer stmt.Close()\n\tsalt := Salt(100)\n\treturn stmt.Exec(u.Name, u.Email, salt, Stretch(password, salt))\n}", "func insertUser(data User) (int64, error) {\n\t// perform a db.Query insert\n\tinsert, err := db.Exec(\"INSERT INTO users (username, email, created_at) VALUES (?, ?, ?)\", data.Username, data.Email, data.CreatedAt)\n\n\t// if there is an error inserting, handle it\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tid, err := insert.LastInsertId()\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\treturn id, err\n}", "func (mss *MySQLStore) Insert(user *User) (*User, error) {\n\tinsq := \"insert into users(email, pass_hash, user_name, first_name, last_name) values (?, ?, ?, ?, ?)\"\n\tres, err := mss.Client.Exec(insq, user.Email, user.PassHash, user.UserName, user.FirstName, user.LastName)\n\tif err != nil {\n\t\tlog.Printf(\"Issue executing sql statement: %v\", err)\n\t\treturn nil, err\n\t}\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\tlog.Print(\"Error retrieving last insert id\")\n\t\treturn nil, err\n\t}\n\tuser.ID = id\n\treturn user, nil\n}", "func (db *BlabDb) InsertUser(user User) {\n\taddUserStatement := `INSERT INTO users (id, name, email) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`\n\n\tdb.QueryRow(addUserStatement, user.ID, user.Name, user.Email)\n}", "func (m *MockUserRepositoryInterface) InsertUser(arg0 *db.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InsertUser\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_UserCrud *UserCrudTransactorSession) InsertUser(userAddress common.Address, userEmail string, userAge *big.Int) (*types.Transaction, error) {\n\treturn _UserCrud.Contract.InsertUser(&_UserCrud.TransactOpts, userAddress, userEmail, userAge)\n}", "func (s *UserStore) Insert(record *User) error {\n\trecord.SetSaving(true)\n\tdefer record.SetSaving(false)\n\n\trecord.CreatedAt = record.CreatedAt.Truncate(time.Microsecond)\n\trecord.UpdatedAt = record.UpdatedAt.Truncate(time.Microsecond)\n\n\tif err := record.BeforeSave(); err != nil {\n\t\treturn err\n\t}\n\n\treturn s.Store.Insert(Schema.User.BaseSchema, record)\n}", "func (m *MockDatabase) InsertUserFavorite(ID string, ArticleID int, ArticleTitle, ArticleURL string) error {\n\targs := m.Called(ID, ArticleID, ArticleTitle, ArticleURL)\n\treturn args.Error(0)\n}", "func (m *MgoUserManager) insertUser(u *auth.User) error {\n\terr := m.UserColl.Insert(u)\n\tif err != nil {\n\t\tif mgo.IsDup(err) {\n\t\t\treturn auth.ErrDuplicateEmail\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (mgr *UserMgr) InsertUser(user *User) {\n\tuser.Password = HashPassword(user.Password)\n\tsql := \"INSERT INTO users (username, email, password, role) VALUES (:username, :email, :password, :role)\"\n\t_, err := mgr.db.NamedExec(sql, user)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Insert(u *User) error {\n\tdb, err := sql.Open(\"mysql\", os.Getenv(\"MYSQL_CONNECT_STR\"))\n\tif err != nil {\n\t\tpanic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic\n\t}\n\tdefer db.Close()\n\thash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := db.Prepare(\"INSERT INTO user(fullname, email, password) values(?,?,?)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tres, err := stmt.Exec(u.Fullname, u.Email, hash)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (ss *SQLStore) Insert(user *User) (*User, error) {\n\tinsq := \"insert into USERS(Email, PassHash, UserName, FirstName, LastName, PhotoURL) values(?,?,?,?,?,?)\"\n\tres, err := ss.db.Exec(insq, user.Email, user.PassHash, user.UserName, user.FirstName, user.LastName, user.PhotoURL)\n\tif err != nil {\n\t\tfmt.Printf(\"error inserting row: %v\\n\", err)\n\t\treturn user, errors.New(\"Error inserting row: \" + err.Error())\n\t} else {\n\t\tid, err := res.LastInsertId()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error getting new id: %v\\n\", err)\n\t\t\treturn user, errors.New(\"Error getting new ID\")\n\t\t} else {\n\t\t\tuser.ID = id\n\t\t\treturn user, nil\n\t\t}\n\t}\n}", "func (srv *Service) InsertUser(email string, hash string, name string) (*models.User, error) {\n\t//check if the email already exists\n\t_, err := srv.mongoRepository.GetUserByEmail(email)\n\n\tif err != nil {\n\t\tif mongoError := err.(*pkg.Error); mongoError.Code != http.StatusNotFound {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t//check if the email already exists\n\t_, err = srv.mongoRepository.GetUserFromWhitelistByEmail(email)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar user *models.User\n\n\t//call driven adapter responsible for inserting a user inside the database\n\tuser, err = srv.mongoRepository.InsertUser(email, hash, name, \"member\")\n\n\tif err != nil {\n\t\t//return the error sent by the repository\n\t\treturn nil, err\n\t}\n\n\t//remove user from whitelist\n\t_, err = srv.mongoRepository.DeleteUserFromWhitelistByEmail(email)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn user, nil\n}", "func (dbh *DBHandler) InsertUser(user api.User) {\n\t//User structure is described in the api package file user.go\n\t_, err := dbh.Connection.Exec(`INSERT INTO users (telegram_id, nickname) VALUES (?, ?);`, user.ID, user.Username)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (m *UserModel) Insert(email, password string) error {\n\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 12)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstmt := `INSERT INTO users (email, password, created_at) VALUES(?, ?, datetime('now'))`\n\n\t_, err = m.DB.Exec(stmt, email, string(hashedPassword))\n\tif err != nil {\n\t\tif errors.Is(err, sqlite3.ErrConstraintUnique) {\n\t\t\treturn models.ErrDuplicateEmail\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func InsertUser(email string, lName string, first string, last string, active bool, superadmin bool, password string) {\n\t/*\n\t\temail varchar(30),\n\t\tloginName varchar(30),\n\t\tfirstname varchar(30),\n\t\tlastname varchar(30),\n\t\tactive boolean,\n\t\tsuperadmin boolean,\n\t\tpassword varchar(30)\n\t*/\n\tquery := \"INSERT INTO coyoUser VALUES (NULL, '\" + email + \"' , '\" + lName + \"' , '\" + first + \"' , '\" + last + \"' ,\" + strconv.FormatBool(active) + \" ,\" + strconv.FormatBool(superadmin) + \" , '\" + password + \"')\"\n\tinsert, err := DB.Query(query)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tdefer insert.Close()\n}", "func (_UserCrud *UserCrudSession) InsertUser(userAddress common.Address, userEmail string, userAge *big.Int) (*types.Transaction, error) {\n\treturn _UserCrud.Contract.InsertUser(&_UserCrud.TransactOpts, userAddress, userEmail, userAge)\n}", "func (u *UserCtr) InsertUser(c *gin.Context) {\n\tvar newuser model.User\n\tc.BindJSON(&newuser)\n\tuser, err := model.InsertUser(u.DB,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 (this *Queries_UServ) InsertUsers(ctx context.Context, db persist.Runnable) *Query_UServ_InsertUsers {\n\treturn &Query_UServ_InsertUsers{\n\t\topts: this.opts,\n\t\tctx: ctx,\n\t\tdb: db,\n\t}\n}", "func (u *UserModel) Insert(name, email, password string) error {\n\t// Create a bcrypt hash of the plain-text password.\n\thashedPw, err := bcrypt.GenerateFromPassword([]byte(password), 12)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstmt := `INSERT INTO users (name, email, hashed_password, created)\n\tVALUES(?, ?, ?, UTC_TIMESTAMP())`\n\n\t// Use the Exec(0 method to insert the user details and hashed password\n\t// into the users table.\n\t_, err = u.DB.Exec(stmt, name, email, string(hashedPw))\n\tif err != nil {\n\t\t// If this returns an error, we use the errors.As() function to check\n\t\t// whether the error has the type *mysql.MySQLError. If it does, the\n\t\t// error will be assigned to the mySQLError variable. We can then check\n\t\t// whether or not the error relates to our users_uc_email key by checking\n\t\t// the contents of the message string. If it does, we return an\n\t\t// ErrDuplicateEmail error.\n\t\tvar mySQLError *mysql.MySQLError\n\t\tif errors.As(err, &mySQLError) {\n\t\t\tif mySQLError.Number == 1062 && strings.Contains(mySQLError.Message,\n\t\t\t\t\"users_uc_email\") {\n\t\t\t\treturn models.ErrDuplicateEmail\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n\n}", "func (mr *MockPersisterMockRecorder) AddUser(username, email, password, isSysAdmin, overwrite interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddUser\", reflect.TypeOf((*MockPersister)(nil).AddUser), username, email, password, isSysAdmin, overwrite)\n}", "func Create(user User) error {\n\t\n}", "func (model *UserModel) Insert(name, email, password string) error {\n\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 12)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstmt := `INSERT INTO users (name, email, hashed_password, created) VALUES(?, ?, ?, UTC_TIMESTAMP())`\n\n\t_, err = model.DB.Exec(stmt, name, email, string(hashedPassword))\n\tif err != nil {\n\t\tvar mySQLError *mysql.MySQLError\n\t\tif errors.As(err, &mySQLError) {\n\t\t\tif mySQLError.Number == 1062 && strings.Contains(mySQLError.Message, \"users_uc_email\") {\n\t\t\t\treturn models.ErrDuplicateEmail\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *MockDatabase) InsertUserList(ID string, listID int) error {\n\targs := m.Called(ID, listID)\n\treturn args.Error(0)\n}", "func (m *MockUserService) Insert(tx *sqlx.Tx, username, password string) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Insert\", tx, username, password)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (ln *LnDatabase) InsertUser(user *models.User) (*models.User, error) {\n\t// Specifies the order in which to return results.\n\tlog.Println(\"binsert:\", user.Passwd)\n\tresult, err := ln.DB.Collection(\"test\").InsertOne(\n\t\tcontext.Background(),\n\t\tuser,\n\t)\n\tfmt.Println(\"InserData: \", result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func (s *ConnSession) InsertUser(collConf storage.UserCollConfig, insUserData storage.InsertUserData) (storage.JSONCollResult, error) {\n\tsql := fmt.Sprintf(\"insert into %s (%s, %s) values ($1, $2) returning $3;\",\n\t\tSanitize(collConf.Name),\n\t\tSanitize(collConf.UserUnique),\n\t\tSanitize(collConf.UserConfirm))\n\treturn s.RawQuery(sql, insUserData.UserUnique, insUserData.UserConfirm, collConf.Pk)\n}", "func (ue *UserEvent) Insert(ctx context.Context) *spanner.Mutation {\n\tvalues, _ := ue.columnsToValues(UserEventWritableColumns())\n\treturn spanner.Insert(\"UserEvent\", UserEventWritableColumns(), values)\n}", "func (u *User) Insert(db *sql.DB) (sql.Result, error) {\n\treturn db.Exec(\n\t\tfmt.Sprintf(\"INSERT INTO %s (%s, %s, %s) VALUES(?, ?, ?)\", UserTableName, UserUrl1Col, UserUrl2Col, UserUrl3Col),\n\t\tu.Url1,\n\t\tu.Url2,\n\t\tu.Url3,\n\t)\n}", "func InsertUser(u models.User) (string, bool, error, models.User) {\n\n\t//Here set Timeout\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\n\tdefer cancel()\n\n\tdb := MongoConection.Database(\"twittor\")\n\tcol := db.Collection(\"users\")\n\n\tu.Password, _ = EncryptPassword(u.Password)\n\n\tresult, err := col.InsertOne(ctx, u)\n\n\tif err != nil {\n\t\treturn \"\", false, err, models.User{}\n\t}\n\n\tObjID, _ := result.InsertedID.(primitive.ObjectID)\n\treturn ObjID.String(), true, nil, u\n}", "func (tu *TempUser) Insert(ctx context.Context, db Execer) error {\n\t// if already exist, bail\n\tif tu._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tconst sqlstr = `INSERT INTO temp_users (` +\n\t\t`phone_number, auth_code, auth_key, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(ctx, sqlstr, tu.PhoneNumber, tu.AuthCode, tu.AuthKey, tu.CreatedAt, tu.UpdatedAt)\n\tres, err := db.ExecContext(ctx, sqlstr, tu.PhoneNumber, tu.AuthCode, tu.AuthKey, tu.CreatedAt, tu.UpdatedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\ttu.ID = uint64(id)\n\ttu._exists = true\n\n\treturn nil\n}", "func (_obj *WebApiAuth) SysUser_Insert(req *SysUser, id *int32, _opt ...map[string]string) (err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = req.WriteBlock(_os, 1)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = _os.Write_int32((*id), 2)\n\tif err != nil {\n\t\treturn 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, \"SysUser_Insert\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = _is.Read_int32(&(*id), 2, true)\n\tif err != nil {\n\t\treturn 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 nil\n}", "func (sr *SignUpRepository) InsertUser(u *models.Users) error {\n\t_, err := sr.db.Exec(\"INSERT INTO users(id,first_name, last_name, email, mobile_phone, created_at, modified_at, roles) VALUES($1, $2, $3, $4, $5, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, $6)\", u.ID, u.FirstName, u.LastName, u.Email, u.MobilePhone, u.Roles)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (u *UserService) InsertUser(user *User) error {\n\t_, err := u.Exec(\"INSERT INTO users (name, phone, email, password) VALUES($1, $2, $3, $4)\", user.Name, user.Phone, user.Email, user.HashedPassword)\n\treturn err\n}", "func (auup *AuthUserUserPermission) Insert(ctx context.Context, db DB) error {\n\tswitch {\n\tcase auup._exists: // already exists\n\t\treturn logerror(&ErrInsertFailed{ErrAlreadyExists})\n\tcase auup._deleted: // deleted\n\t\treturn logerror(&ErrInsertFailed{ErrMarkedForDeletion})\n\t}\n\t// insert (primary key generated and returned by database)\n\tconst sqlstr = `INSERT INTO django.auth_user_user_permissions (` +\n\t\t`user_id, permission_id` +\n\t\t`) VALUES (` +\n\t\t`:1, :2` +\n\t\t`) RETURNING id INTO :3`\n\t// run\n\tlogf(sqlstr, auup.UserID, auup.PermissionID)\n\tvar id int64\n\tif _, err := db.ExecContext(ctx, sqlstr, auup.UserID, auup.PermissionID, sql.Out{Dest: &id}); err != nil {\n\t\treturn logerror(err)\n\t} // set primary key\n\tauup.ID = int64(id)\n\t// set exists\n\tauup._exists = true\n\treturn nil\n}", "func (mr *MockStudentRepositoryMockRecorder) Insert(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Insert\", reflect.TypeOf((*MockStudentRepository)(nil).Insert), arg0)\n}", "func InsertNewUser(user *User, uc *mongo.Collection) (string, error) {\n\tresult, err := uc.InsertOne(context.Background(), user)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn \"\", err\n\t}\n\n\treturn result.InsertedID.(primitive.ObjectID).Hex(), nil\n}", "func ExampleInsert() {\n\tuser := q.T(\"user\")\n\tins := q.Insert().Into(user).Set(user.C(\"name\"), \"hackme\")\n\tfmt.Println(ins)\n\t// Output:\n\t// INSERT INTO \"user\"(\"name\") VALUES (?) [hackme]\n}", "func (xcu *XCatalogUser) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif xcu._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tconst sqlstr = `INSERT INTO x_showroom.x_catalog_users (` +\n\t\t`user_id, catalog_id, created_by, updated_by, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, xcu.UserID, xcu.CatalogID, xcu.CreatedBy, xcu.UpdatedBy, xcu.CreatedAt, xcu.UpdatedAt)\n\tres, err := db.Exec(sqlstr, xcu.UserID, xcu.CatalogID, xcu.CreatedBy, xcu.UpdatedBy, xcu.CreatedAt, xcu.UpdatedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\txcu.ID = uint(id)\n\txcu._exists = true\n\n\treturn nil\n}", "func InsertUser(u models.User) (string, bool, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\n\tdefer cancel()\n\n\tdataBase := MongoConnection.Database(config.DBName)\n\tcollection := dataBase.Collection(\"users\")\n\n\t// Cifrar password\n\tu.Password, _ = EncryptPassword(u.Password)\n\n\t// Meter usuario en la base de datos\n\tresult, err := collection.InsertOne(ctx, u)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\t// ID del usuario insertado\n\tobjID, _ := result.InsertedID.(primitive.ObjectID)\n\n\treturn objID.String(), true, nil\n}", "func InsertUser(uid string) error {\n\ttx, err := Db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := tx.Prepare(\"insert into users(unique_id) values(?)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(uid)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttx.Commit()\n\treturn nil\n}", "func (store *MySQLStore) Insert(user *User) (*User, error) {\n\tquery := \"INSERT INTO users (email, first_name, last_name, pass_hash, username, photo_url) VALUES (?, ?, ?, ?, ?, ?)\"\n\tres, err := store.db.Exec(query, user.Email, user.FirstName, user.LastName, user.PassHash, user.UserName, user.PhotoURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuser.ID = id\n\treturn user, nil\n}", "func (gou *GroupOrderdUser) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif gou._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key must be provided\n\tconst sqlstr = `INSERT INTO sun_chat.group_orderd_user (` +\n\t\t`OrderId, GroupId, UserId` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tif LogTableSqlReq.GroupOrderdUser {\n\t\tXOLog(sqlstr, gou.OrderId, gou.GroupId, gou.UserId)\n\t}\n\t_, err = db.Exec(sqlstr, gou.OrderId, gou.GroupId, gou.UserId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\tgou._exists = true\n\n\tOnGroupOrderdUser_AfterInsert(gou)\n\n\treturn nil\n}", "func InsertAccount(r *http.Request, email, hashedPassword string, aUUID uuid.UUID, firstName, lastName string, isUser, isMiner bool, newUserCredit int) error {\n\tctx := r.Context()\n\ttx, txerr := db.BeginTx(ctx, nil)\n\tif message, err := func() (string, error) {\n\t\tif txerr != nil {\n\t\t\treturn errBeginTx, txerr\n\t\t}\n\n\t\tsqlStmt := `\n\t\tINSERT INTO accounts (uuid, email, password, first_name, last_name, credit)\n\t\tVALUES ($1, $2, $3, $4, $5, $6)\n\t\t`\n\t\tif _, err := tx.Exec(sqlStmt, aUUID, email, hashedPassword, firstName, lastName, newUserCredit); err != nil {\n\t\t\treturn \"error inserting account\", err\n\t\t}\n\n\t\tif isUser {\n\t\t\tsqlStmt = `\n\t\t\tINSERT INTO users (uuid)\n\t\t\tVALUES ($1)\n\t\t\t`\n\t\t\tif _, err := tx.Exec(sqlStmt, aUUID); err != nil {\n\t\t\t\treturn \"error inserting user\", err\n\t\t\t}\n\t\t}\n\n\t\tif isMiner {\n\t\t\tsqlStmt = `\n\t\t\tINSERT INTO miners (uuid)\n\t\t\tVALUES ($1)\n\t\t\t`\n\t\t\tif _, err := tx.Exec(sqlStmt, aUUID); err != nil {\n\t\t\t\treturn \"error inserting miner\", err\n\t\t\t}\n\t\t}\n\n\t\tif err := tx.Commit(); err != nil {\n\t\t\treturn errCommitTx, err\n\t\t}\n\n\t\treturn \"\", nil\n\t}(); err != nil {\n\t\tpqErr, ok := err.(*pq.Error)\n\t\tif ok {\n\t\t\tlog.Sugar.Errorw(message,\n\t\t\t\t\"method\", r.Method,\n\t\t\t\t\"url\", r.URL,\n\t\t\t\t\"err\", err.Error(),\n\t\t\t\t\"aID\", aUUID,\n\t\t\t\t\"email\", email,\n\t\t\t\t\"pq_sev\", pqErr.Severity,\n\t\t\t\t\"pq_code\", pqErr.Code,\n\t\t\t\t\"pq_msg\", pqErr.Message,\n\t\t\t\t\"pq_detail\", pqErr.Detail,\n\t\t\t)\n\t\t\tif pqErr.Code == errEmailExistsCode {\n\t\t\t\treturn ErrEmailExists\n\t\t\t} else if pqErr.Code == errNullViolationCode {\n\t\t\t\treturn ErrNullViolation\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Sugar.Errorw(message,\n\t\t\t\t\"method\", r.Method,\n\t\t\t\t\"url\", r.URL,\n\t\t\t\t\"err\", err.Error(),\n\t\t\t\t\"aID\", aUUID,\n\t\t\t\t\"email\", email,\n\t\t\t)\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func TestUpdateUserNotValid(t *testing.T) {\n\tdb := database.Connect()\n\tu := User{\n\t\tEmail: \"[email protected]\",\n\t}\n\tr := u.Update(db)\n\tif r != false {\n\t\tt.Errorf(\"Expected failed update, got %t\", r)\n\t}\n}", "func (wu *WxUser) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif wu._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetWxUserTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`openid, session_id, unionid, appid, uid, gcode, tcode, tuid, tfid, tsid, session_key, expires_in, nickName, gender, avatarUrl, city, province, country, created, updated` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, wu.Openid, wu.SessionID, wu.Unionid, wu.Appid, wu.UID, wu.Gcode, wu.Tcode, wu.Tuid, wu.Tfid, wu.Tsid, wu.SessionKey, wu.ExpiresIn, wu.Nickname, wu.Gender, wu.Avatarurl, wu.City, wu.Province, wu.Country, wu.Created, wu.Updated)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, wu.Openid, wu.SessionID, wu.Unionid, wu.Appid, wu.UID, wu.Gcode, wu.Tcode, wu.Tuid, wu.Tfid, wu.Tsid, wu.SessionKey, wu.ExpiresIn, wu.Nickname, wu.Gender, wu.Avatarurl, wu.City, wu.Province, wu.Country, wu.Created, wu.Updated)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, wu.Openid, wu.SessionID, wu.Unionid, wu.Appid, wu.UID, wu.Gcode, wu.Tcode, wu.Tuid, wu.Tfid, wu.Tsid, wu.SessionKey, wu.ExpiresIn, wu.Nickname, wu.Gender, wu.Avatarurl, wu.City, wu.Province, wu.Country, wu.Created, wu.Updated)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\twu.ID = int(id)\n\twu._exists = true\n\n\treturn nil\n}", "func TestStore_CreateUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create user.\n\tif ui, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if ui.Name != \"susy\" || ui.Hash == \"\" || ui.Admin != true {\n\t\tt.Fatalf(\"unexpected user: %#v\", ui)\n\t}\n}", "func Test() int {\n\tGetConnection()\n\tdb.Create(&model.User{Email: \"[email protected]\", Password: \"test\"})\n\treturn 1\n}", "func UserSignUp(username string, passwd string) bool {\n\tstmt, err := mydb.DBConn().Prepare(\n\t\t\"insert ignore into tb_user(`username`, `password`, `status`) values(?,?,1)\")\n\tif err != nil {\n\t\tfmt.Println(\"Failded to prepare statement, err: \", err.Error())\n\t\treturn false\n\t}\n\tdefer stmt.Close()\n\n\tret, err := stmt.Exec(username, passwd)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to insert, err:\" + err.Error())\n\t\treturn false\n\t}\n\trows, err := ret.RowsAffected()\n\tfmt.Printf(\"rows: %d\\n\", rows)\n\tif nil == err && rows > 0 {\n\t\tfmt.Printf(\"user %s creat OK\\n\", username)\n\t\treturn true\n\t}\n\treturn false\n}", "func (dau *DdgAdminUser) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif dau._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetDdgAdminUserTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`name, account, password, permission_ids, status` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, dau.Name, dau.Account, dau.Password, dau.PermissionIds, dau.Status)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, dau.Name, dau.Account, dau.Password, dau.PermissionIds, dau.Status)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, dau.Name, dau.Account, dau.Password, dau.PermissionIds, dau.Status)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tdau.ID = uint64(id)\n\tdau._exists = true\n\n\treturn nil\n}", "func (u *UserModel) Insert(uid uuid.UUID, firstName models.NullString, lastName models.NullString, email models.NullString, phone string, statusID int, password string) (*models.User, error) {\n\tcreated := time.Now()\n\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), PW_HASH_COST)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstmt := `INSERT INTO user (\n uuid,\n\t\tfirst_name,\n\t\tlast_name,\n\t\temail,\n\t\tphone,\n\t\tstatus_id,\n\t\thashed_password,\n\t\tcreated\n\t) VALUES (\n\t ?,\n\t\t?,\n\t\t?,\n\t\t?,\n\t\t?,\n\t\t?,\n\t\t?,\n\t\t?\n\t)`\n\n\tresult, err := u.DB.Exec(stmt, uid.String(), firstName.String, lastName.String, email.String, NormalizePhone(phone), statusID, hashedPassword, created)\n\tif err != nil {\n\t\tif mysqlErr, ok := err.(*mysql.MySQLError); ok {\n\t\t\tif mysqlErr.Number == 1062 && strings.Contains(mysqlErr.Message, \"uk_user_email\") {\n\t\t\t\treturn nil, models.ErrDuplicateEmail\n\t\t\t}\n\t\t\tif mysqlErr.Number == 1062 && strings.Contains(mysqlErr.Message, \"uk_user_phone\") {\n\t\t\t\treturn nil, models.ErrDuplicatePhone\n\t\t\t}\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuserStatus := models.UserStatus(statusID)\n\n\tuser := &models.User{\n\t\tID: id,\n\t\tUUID: uid,\n\t\tFirstName: firstName,\n\t\tLastName: lastName,\n\t\tEmail: email,\n\t\tPhone: phone,\n\t\tStatus: userStatus.Slug(),\n\t\tCreated: created,\n\t}\n\n\treturn user, nil\n}", "func (mysql *MySqlStore) Insert(user *User) (*User, error) {\n\ttx, err := mysql.db.Begin() // begin transaction\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := tx.Exec(ins, user.Email, user.PassHash, user.UserName, user.FirstName, user.LastName, user.PhotoURL)\n\tif err != nil {\n\t\ttx.Rollback() // rollback transaction\n\t\treturn nil, err\n\t}\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\ttx.Rollback() // rollback transaction\n\t\treturn nil, err\n\t}\n\tuser.ID = id\n\ttx.Commit()\n\treturn user, nil\n}", "func PrepareUserInsert(user *User) error {\n\tvar err error\n\tif user.Password, err = utils.HashAndSalt([]byte(user.Password)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func InsertRegister(object models.User) (string, bool, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\n\n\t//When end instruction remove timeout operation and liberate context\n\tdefer cancel()\n\n\tdb := MongoConnection.Database(\"socialnetwork\")\n\tcollection := db.Collection(\"Users\")\n\n\t//Set password encrypted\n\tpassWordEncrypted, _ := utils.EcryptPasswordUtil(object.Password)\n\tobject.Password = passWordEncrypted\n\n\tresult, err := collection.InsertOne(ctx, object)\n\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\t//Get id of created object\n\tObjectID, _ := result.InsertedID.(primitive.ObjectID)\n\n\t//Return created object id\n\treturn ObjectID.String(), true, nil\n\n}", "func (mr *MockSessionRepMockRecorder) Insert(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Insert\", reflect.TypeOf((*MockSessionRep)(nil).Insert), arg0)\n}", "func (h UserHook) OnInsert(ctx context.Context, items []*resource.Item) error {\n\tfor _, i := range items {\n\t\temail := i.GetField(\"email\")\n\t\tpassword := i.GetField(\"password\")\n\t\tif email == nil || password == nil {\n\t\t\t// We dont allow users with blank email or passwords, deny if blank.\n\t\t\treturn rest.ErrUnauthorized\n\t\t}\n\n\t\t// Determine if a user with this email address already exists\n\t\tuserList, err := utils.FindUser(ctx, h.UserResource, email.(string))\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error finding user: %s\\n\", err)\n\t\t\treturn err\n\t\t}\n\t\tif len(userList.Items) > 0 {\n\t\t\t// @todo add details for deny to body... user already exists\n\t\t\treturn rest.ErrConflict\n\t\t}\n\t}\n\treturn nil\n}", "func (o *AuthUser) Insert(exec boil.Executor, whitelist ...string) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no auth_user provided for insertion\")\n\t}\n\n\tvar err error\n\n\tnzDefaults := queries.NonZeroDefaultSet(authUserColumnsWithDefault, o)\n\n\tkey := makeCacheKey(whitelist, nzDefaults)\n\tauthUserInsertCacheMut.RLock()\n\tcache, cached := authUserInsertCache[key]\n\tauthUserInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := strmangle.InsertColumnSet(\n\t\t\tauthUserColumns,\n\t\t\tauthUserColumnsWithDefault,\n\t\t\tauthUserColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t\twhitelist,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(authUserType, authUserMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(authUserType, authUserMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.query = fmt.Sprintf(\"INSERT INTO `auth_user` (`%s`) VALUES (%s)\", strings.Join(wl, \"`,`\"), strmangle.Placeholders(dialect.IndexPlaceholders, len(wl), 1, 1))\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tcache.retQuery = fmt.Sprintf(\"SELECT `%s` FROM `auth_user` WHERE %s\", strings.Join(returnColumns, \"`,`\"), strmangle.WhereClause(\"`\", \"`\", 0, authUserPrimaryKeyColumns))\n\t\t}\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, vals)\n\t}\n\n\tresult, err := exec.Exec(cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to insert into auth_user\")\n\t}\n\n\tvar lastID int64\n\tvar identifierCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tlastID, err = result.LastInsertId()\n\tif err != nil {\n\t\treturn ErrSyncFail\n\t}\n\n\to.ID = int(lastID)\n\tif lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == authUserMapping[\"ID\"] {\n\t\tgoto CacheNoHooks\n\t}\n\n\tidentifierCols = []interface{}{\n\t\to.ID,\n\t}\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.retQuery)\n\t\tfmt.Fprintln(boil.DebugWriter, identifierCols...)\n\t}\n\n\terr = exec.QueryRow(cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to populate default values for auth_user\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\tauthUserInsertCacheMut.Lock()\n\t\tauthUserInsertCache[key] = cache\n\t\tauthUserInsertCacheMut.Unlock()\n\t}\n\n\treturn nil\n}", "func (mr *MockProductMockRecorder) InsertNominativeUserFileUploadDetails(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InsertNominativeUserFileUploadDetails\", reflect.TypeOf((*MockProduct)(nil).InsertNominativeUserFileUploadDetails), arg0, arg1)\n}", "func TestCreateUser(t *testing.T) {\n user := User{\n Name: \"Mohammd Osama\",\n Password: \"helloworld\",\n Email: \"[email protected]\",\n }\n if user.ID == 0 {\n t.Errorf(\"Expected ID > 0, Received %d\", user.ID)\n }\n}", "func (rd *RedisHelper)InsertUser(user user.User)(err error){\n\tif rd==nil{\n\t\tlog4go.Error(\"RedisHelper instance is nil\")\n\t\treturn errors.New(\"Nil point receivcer\")\n\t}\n\t_, err = rd.conn.Do(\"DEL\", user.GetUserName())\n\tif err != nil{\n\t\tlog4go.Error(fmt.Sprintf(\"Fail to insert user, err: %v\", err))\n\t\treturn\n\t}\n\tif user.GetToken()==\"\" {\n\t\t_, err = rd.conn.Do(\"RPUSH\", user.GetUserName(), user.GetPassword())\n\t}else{\n\t\t_, err = rd.conn.Do(\"RPUSH\", user.GetUserName(), user.GetPassword(), user.GetToken())\n\t}\n\tif err != nil{\n\t\tlog4go.Error(fmt.Sprintf(\"Fail to insert user, err: %v\", err))\n\t}\n\treturn\n}", "func (e *Entity) AssertUser() {\n\tif e.data.Kind != member.User {\n\t\tpanic(\"AssertUser\")\n\t}\n}", "func (db *DataBase) Register(user *models.UserPrivateInfo) (userID int, err error) {\n\n\tvar (\n\t\ttx *sql.Tx\n\t)\n\n\tif tx, err = db.Db.Begin(); err != nil {\n\t\treturn\n\t}\n\tdefer tx.Rollback()\n\n\tif userID, err = db.createPlayer(tx, user); err != nil {\n\t\treturn\n\t}\n\n\tif err = db.createRecords(tx, userID); err != nil {\n\t\treturn\n\t}\n\n\terr = tx.Commit()\n\treturn\n}", "func (tx *TestTX) Insert(list ...interface{}) error {\n\targs := tx.Called(list...)\n\treturn args.Error(0)\n}", "func (t *tx) AddUser(user *model.User) error {\n\t// FIXME: handle sql constraint errors\n\terr := t.Create(user).Error\n\n\treturn errors.Wrap(err, \"create user failed\")\n}", "func InsertIntoDB(userinfo types.ThirdPartyResponse) error {\n\tmeta, err := json.Marshal(userinfo.MetaData)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\tif userinfo.Name == \"\" {\n\t\tfmt.Println(\"Name is not issued from third party\")\n\t} else if userinfo.Id == 0 {\n\t\tfmt.Println(\"Email is not issued from third party\")\n\t}\n\n\tinsertQuery := `INSERT INTO loggedinuser (id, name, email, meta) VALUES ($1, $2, $3, $4)`\n\t_, err = db.Exec(insertQuery, userinfo.Id, userinfo.Name, userinfo.Email, string(meta))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mr *MockFamilyRepoMockRecorder) Insert(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Insert\", reflect.TypeOf((*MockFamilyRepo)(nil).Insert), arg0)\n}", "func (mr *MockHandlerMockRecorder) UserCreate(username, email, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserCreate\", reflect.TypeOf((*MockHandler)(nil).UserCreate), username, email, password)\n}" ]
[ "0.7395526", "0.72752655", "0.69016844", "0.6803165", "0.6682902", "0.6643966", "0.6637905", "0.6635979", "0.66051245", "0.6561782", "0.6548562", "0.65464014", "0.6475641", "0.6442573", "0.64139915", "0.63772273", "0.634393", "0.63358545", "0.6325098", "0.6310754", "0.6272394", "0.62722075", "0.62666744", "0.6243662", "0.6242746", "0.6237014", "0.6232626", "0.62194455", "0.61956143", "0.61856425", "0.6180842", "0.61727244", "0.6156327", "0.613445", "0.6131696", "0.61275136", "0.61044383", "0.6099339", "0.60980767", "0.6095984", "0.6092226", "0.60775703", "0.6054994", "0.60482997", "0.60439265", "0.60301614", "0.6019314", "0.6013292", "0.6011287", "0.60088885", "0.6008744", "0.60019296", "0.6000159", "0.599861", "0.5992948", "0.5987538", "0.5985642", "0.5964655", "0.5963586", "0.5945765", "0.59329504", "0.59110034", "0.58951503", "0.5890276", "0.58799064", "0.5876744", "0.5864519", "0.5863072", "0.58594507", "0.5856214", "0.5854711", "0.58529127", "0.58468175", "0.5834739", "0.58172", "0.58136535", "0.5810224", "0.5806614", "0.58001995", "0.57983017", "0.5794262", "0.5790863", "0.5785691", "0.5780026", "0.5775068", "0.57654846", "0.575946", "0.57497805", "0.5739207", "0.57365024", "0.57354987", "0.5733627", "0.5722583", "0.5720918", "0.5718068", "0.57156384", "0.56992763", "0.5697943", "0.568613", "0.56693685" ]
0.70800346
2
GetUserWhereUsername mocks base method
func (m *MockUserRepositoryInterface) GetUserWhereUsername(arg0 string) (*db.User, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetUserWhereUsername", arg0) ret0, _ := ret[0].(*db.User) ret1, _ := ret[1].(error) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockDataSource) GetUserByUsername(username string) (model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByUsername\", username)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPersister) GetUserByUsername(username string, curUserID int) (User, error) {\n\tret := m.ctrl.Call(m, \"GetUserByUsername\", username, curUserID)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUserID(arg0 uint64) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUserID\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUser) GetByUsername(ctx context.Context, db repo.DB, username string) (model.User, *internal.E) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByUsername\", ctx, db, username)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(*internal.E)\n\treturn ret0, ret1\n}", "func (mock *Mock) GetUser(username string) (entities.User, error) {\n\tinputHash := toHash(getInputForGetUser(username))\n\tarrOutputForGetUser, exists := mock.patchGetUserMap[inputHash]\n\tif !exists || len(arrOutputForGetUser) == 0 {\n\t\tpanic(\"Mock not available for GetUser\")\n\t}\n\n\toutput := arrOutputForGetUser[0]\n\tarrOutputForGetUser = arrOutputForGetUser[1:]\n\tmock.patchGetUserMap[inputHash] = arrOutputForGetUser\n\n\treturn output.user, output.error\n}", "func (m *MockRepository) GetByUsername(ctx context.Context, username string, password []byte) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByUsername\", ctx, username, password)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPersister) GetUser(username, password string) (User, error) {\n\tret := m.ctrl.Call(m, \"GetUser\", username, password)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUsersRepoInterface) GetByUserName(arg0 string) (*user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByUserName\", arg0)\n\tret0, _ := ret[0].(*user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) FindUser(query string, params ...interface{}) (easyalert.User, error) {\n\tvarargs := []interface{}{query}\n\tfor _, a := range params {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"FindUser\", varargs...)\n\tret0, _ := ret[0].(easyalert.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockHandler) UserGet(userName string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserGet\", userName)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockDB) GetUser(arg0 uint) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockTx) GetUser(_a0 string) (*model.User, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(string) *model.User); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserLogic) UserGet(userName string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserGet\", userName)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockStore) GetUserByEmail(arg0 context.Context, arg1 string) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByEmail\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepositoryInterface) GetUsersWhereUserIDs(arg0 []uint64) ([]*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersWhereUserIDs\", arg0)\n\tret0, _ := ret[0].([]*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserServer) GetUserByName(arg0 context.Context, arg1 *pb.UserRequest) (*pb.UserReply, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByName\", arg0, arg1)\n\tret0, _ := ret[0].(*pb.UserReply)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *API) GetUser(username string) (*model.User, int, error) {\n\tret := _m.Called(username)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(string) *model.User); ok {\n\t\tr0 = rf(username)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(string) int); ok {\n\t\tr1 = rf(username)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string) error); ok {\n\t\tr2 = rf(username)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockDatabase) GetUserByGitSourceNameAndID(gitSourceName string, id uint64) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByGitSourceNameAndID\", gitSourceName, id)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockService) GetUser(ctx context.Context, id string) (*User, error) {\n\tret := _m.ctrl.Call(_m, \"GetUser\", ctx, id)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserClient) GetUserByName(ctx context.Context, in *pb.UserRequest, opts ...grpc.CallOption) (*pb.UserReply, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetUserByName\", varargs...)\n\tret0, _ := ret[0].(*pb.UserReply)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Client) GetUser(arg0 context.Context, arg1 int64) (zendesk.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0, arg1)\n\tret0, _ := ret[0].(zendesk.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIUser) GetUser(arg0 uint) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) GetUserById(arg0 context.Context, arg1 uuid.UUID) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserById\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) Find(arg0 sweeper.Snowflake) (*sweeper.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Find\", arg0)\n\tret0, _ := ret[0].(*sweeper.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) GetUser(arg0 *iam.GetUserInput) (*iam.GetUserOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*iam.GetUserOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) GetUser(arg0 *iam.GetUserInput) (*iam.GetUserOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*iam.GetUserOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIUserRepository) GetUser(arg0 uuid.UUID) *model.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*model.User)\n\treturn ret0\n}", "func (m *MockIUserService) QueryUserByName(name string) (*model.UserDB, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryUserByName\", name)\n\tret0, _ := ret[0].(*model.UserDB)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserTokenService) GetUser(arg0 context.Context, arg1 string) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0, arg1)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *UserRepo) GetUser(_a0 uint64) (*models.User, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *models.User\n\tif rf, ok := ret.Get(0).(func(uint64) *models.User); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(uint64) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockValidationService) Username(username string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Username\", username)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserFinder) Lookup(arg0 string) (specs.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Lookup\", arg0)\n\tret0, _ := ret[0].(specs.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPersister) GetUserByToken(token string) (User, error) {\n\tret := m.ctrl.Call(m, \"GetUserByToken\", token)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\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 (suite *SubscriptionsTestSuite) mockUserFiltering(user *accounts.User) {\n\tsuite.accountsServiceMock.On(\n\t\t\"GetUserFromQueryString\",\n\t\tmock.AnythingOfType(\"*http.Request\"),\n\t).Return(user, nil)\n}", "func (m *MockIDistributedEnforcer) GetUsersForRole(arg0 string, arg1 ...string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetUsersForRole\", varargs...)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Service) RetrieveUserByUsername(ctx context.Context, username string) (*users.User, error) {\n\tret := _m.Called(ctx, username)\n\n\tvar r0 *users.User\n\tif rf, ok := ret.Get(0).(func(context.Context, string) *users.User); ok {\n\t\tr0 = rf(ctx, username)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*users.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string) error); ok {\n\t\tr1 = rf(ctx, username)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserUsecase) GetUser(id int64) entity.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", id)\n\tret0, _ := ret[0].(entity.User)\n\treturn ret0\n}", "func (_m *MockUserProvider) FindOneByUsername(username string) (*UserEntity, error) {\n\tret := _m.Called(username)\n\n\tvar r0 *UserEntity\n\tif rf, ok := ret.Get(0).(func(string) *UserEntity); ok {\n\t\tr0 = rf(username)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*UserEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(username)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserServer) GetUser(arg0 context.Context, arg1 *pb.UserRequest) (*pb.UserReply, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0, arg1)\n\tret0, _ := ret[0].(*pb.UserReply)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockDatabase) GetUserByName(name string) *model.User {\n\tret := _m.Called(name)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(string) *model.User); ok {\n\t\tr0 = rf(name)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockUnitOfWork) GetUserRepository() repositories.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserRepository\")\n\tret0, _ := ret[0].(repositories.User)\n\treturn ret0\n}", "func (_m *UserService) GetUser(username string, password string) (*oauth2.User, error) {\n\tret := _m.Called(username, password)\n\n\tvar r0 *oauth2.User\n\tif rf, ok := ret.Get(0).(func(string, string) *oauth2.User); ok {\n\t\tr0 = rf(username, password)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*oauth2.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, string) error); ok {\n\t\tr1 = rf(username, password)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestGetUserService (t *testing.T){\n\tuser1, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user1)\n\n\tuser2, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user2)\n\n\tuser3, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user3)\n\n\tuser4, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user4)\n}", "func (m *MockUserStore) Get(arg0 context.Context, arg1 *sql.Tx, arg2 []byte) (*proto.User, error) {\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*proto.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAuthGateway) GetUserByID(arg0 int64) (entity.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByID\", arg0)\n\tret0, _ := ret[0].(entity.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func PrepareGetUser(roundTripper *mhttp.MockRoundTripper, rootURL, user, passwd string) (\n\tresponse *http.Response) {\n\trequest, _ := http.NewRequest(http.MethodGet, fmt.Sprintf(\"%s/user/%s/api/json\", rootURL, user), nil)\n\tresponse = &http.Response{\n\t\tStatusCode: 200,\n\t\tRequest: request,\n\t\tBody: ioutil.NopCloser(bytes.NewBufferString(`{\"fullName\":\"admin\",\"description\":\"fake-description\"}`)),\n\t}\n\troundTripper.EXPECT().\n\t\tRoundTrip(NewRequestMatcher(request)).Return(response, nil)\n\n\tif user != \"\" && passwd != \"\" {\n\t\trequest.SetBasicAuth(user, passwd)\n\t}\n\treturn\n}", "func TestGetUserServicePatched (t *testing.T){\n\tuser1, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user1.Name, new_name_user_01)\n}", "func (m *MockRepository) GetUserByEmail(email string) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByEmail\", arg0, arg1)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDatabase) GetUserByUserId(userId uint64) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByUserId\", userId)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetUserById(arg0 int) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserById\", arg0)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDB) Get(key string) (*minesweepersvc.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", key)\n\tret0, _ := ret[0].(*minesweepersvc.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Client) GetUserByUsername(ctx context.Context, realm string, username string) (*libregraph.User, error) {\n\tret := _m.Called(ctx, realm, username)\n\n\tvar r0 *libregraph.User\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, string, string) (*libregraph.User, error)); ok {\n\t\treturn rf(ctx, realm, username)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, string, string) *libregraph.User); ok {\n\t\tr0 = rf(ctx, realm, username)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*libregraph.User)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, string, string) error); ok {\n\t\tr1 = rf(ctx, realm, username)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (p *TestProvider) GetUser(creds *common.Credentials) (common.User, error) {\n\targs := p.Called(creds)\n\treturn args.Get(0).(common.User), args.Error(1)\n}", "func (m *MockUserStorage) GetUserByID(ctx context.Context, id int64) (model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByID\", ctx, id)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserStorage) GetUserByEmail(ctx context.Context, email string) (model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByEmail\", ctx, email)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Provider) GetUser(le *logrus.Entry, token string) (*auth.User, int64, int, error) {\n\tret := _m.Called(le, token)\n\n\tvar r0 *auth.User\n\tif rf, ok := ret.Get(0).(func(*logrus.Entry, string) *auth.User); ok {\n\t\tr0 = rf(le, token)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*auth.User)\n\t\t}\n\t}\n\n\tvar r1 int64\n\tif rf, ok := ret.Get(1).(func(*logrus.Entry, string) int64); ok {\n\t\tr1 = rf(le, token)\n\t} else {\n\t\tr1 = ret.Get(1).(int64)\n\t}\n\n\tvar r2 int\n\tif rf, ok := ret.Get(2).(func(*logrus.Entry, string) int); ok {\n\t\tr2 = rf(le, token)\n\t} else {\n\t\tr2 = ret.Get(2).(int)\n\t}\n\n\tvar r3 error\n\tif rf, ok := ret.Get(3).(func(*logrus.Entry, string) error); ok {\n\t\tr3 = rf(le, token)\n\t} else {\n\t\tr3 = ret.Error(3)\n\t}\n\n\treturn r0, r1, r2, r3\n}", "func (m *MockUserClient) GetUser(ctx context.Context, in *pb.UserRequest, opts ...grpc.CallOption) (*pb.UserReply, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetUser\", varargs...)\n\tret0, _ := ret[0].(*pb.UserReply)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUser) Get(userKey api.UserKey) (api.User, error) {\n\tret := m.ctrl.Call(m, \"Get\", userKey)\n\tret0, _ := ret[0].(api.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetUserNotFoundInDatabase(t *testing.T) {\n\t// customize the return value for getUserFunction\n\tgetUserFunction = func(userID int64) (*domain.User, *utils.ApplicationError) {\n\t\treturn nil, &utils.ApplicationError{\n\t\t\tMessage: fmt.Sprintf(\"user %v was not found\", userID),\n\t\t\tStatusCode: http.StatusNotFound,\n\t\t\tCode: \"not_found\",\n\t\t}\n\t}\n\n\t// mock domain.UserDao layer\n\tuser, err := UserService.GetUser(0)\n\tassert.Nil(t, user)\n\tassert.NotNil(t, err)\n\tassert.EqualValues(t, http.StatusNotFound, err.StatusCode)\n\tassert.EqualValues(t, \"user 0 was not found\", err.Message)\n}", "func (m *MockrepoProvider) FindUserByMail(ctx context.Context, email string) (*types.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindUserByMail\", ctx, email)\n\tret0, _ := ret[0].(*types.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockTx) GetUserByToken(_a0 string) (*model.User, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(string) *model.User); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockRepository) SelectUserByEmail(arg0 string) (*models.AuthUser, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SelectUserByEmail\", arg0)\n\tret0, _ := ret[0].(*models.AuthUser)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDB) GetOrCreateUser(arg0 *User, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetOrCreateUser\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserRepositoryInterface) DeleteUserWhereUsername(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUserWhereUsername\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUser) Index(filters ...UserFilter) (api.Users, error) {\n\tvarargs := []interface{}{}\n\tfor _, a := range filters {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Index\", varargs...)\n\tret0, _ := ret[0].(api.Users)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (suite *InjectorSuite) TestGetBTCUsername() {\n\tbtcUsername := BTCUsername()\n\n\tsuite.NotNil(btcUsername, \"btcUser should not be nil\")\n}", "func (_m *UserRepo) GetUserByEmail(_a0 string) (*models.User, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *models.User\n\tif rf, ok := ret.Get(0).(func(string) *models.User); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserDB) GetUserByEmail(email string) (*UserModel.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByEmail\", email)\n\tret0, _ := ret[0].(*UserModel.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInterface) GetUserByUID(arg0 *userService.Uid) (*userService.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByUID\", arg0)\n\tret0, _ := ret[0].(*userService.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDatabase) GetUsersIDByGitSourceName(gitSourceName string) ([]uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersIDByGitSourceName\", gitSourceName)\n\tret0, _ := ret[0].([]uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) FindUser(email, password string) (*users.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindUser\", email, password)\n\tret0, _ := ret[0].(*users.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInterface) GetUserByEmail(arg0 *userService.Email) (*userService.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByEmail\", arg0)\n\tret0, _ := ret[0].(*userService.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) GetUsersForRoleInDomain(arg0, arg1 string) []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersForRoleInDomain\", arg0, arg1)\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (m *MockUserRepo) FindByEmail(arg0 string) (*app.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindByEmail\", arg0)\n\tret0, _ := ret[0].(*app.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockISearchRepository) ListByUserName(q string) ([]*model.Post, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListByUserName\", q)\n\tret0, _ := ret[0].([]*model.Post)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockFamilyRepo) UserInFamily(arg0, arg1 int) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UserInFamily\", arg0, arg1)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mr *MockUserRepositoryInterfaceMockRecorder) GetUserWhereUsername(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserWhereUsername\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUserWhereUsername), arg0)\n}", "func (_m *API) GetUserStats(username string) (*model.UserStats, int, error) {\n\tret := _m.Called(username)\n\n\tvar r0 *model.UserStats\n\tif rf, ok := ret.Get(0).(func(string) *model.UserStats); ok {\n\t\tr0 = rf(username)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.UserStats)\n\t\t}\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(string) int); ok {\n\t\tr1 = rf(username)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string) error); ok {\n\t\tr2 = rf(username)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockOrderRepository) FindAllOrdersByUserID(arg0 int) (models.Orders, error) {\n\tret := m.ctrl.Call(m, \"FindAllOrdersByUserID\", arg0)\n\tret0, _ := ret[0].(models.Orders)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *API) GetUserHistory(username string, _type string) ([]model.UserHistory, int, error) {\n\tret := _m.Called(username, _type)\n\n\tvar r0 []model.UserHistory\n\tif rf, ok := ret.Get(0).(func(string, string) []model.UserHistory); ok {\n\t\tr0 = rf(username, _type)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]model.UserHistory)\n\t\t}\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(string, string) int); ok {\n\t\tr1 = rf(username, _type)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string, string) error); ok {\n\t\tr2 = rf(username, _type)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockUserStore) BySet(arg0 context.Context, arg1 *sql.Tx, arg2 string) ([]*proto.User, error) {\n\tret := m.ctrl.Call(m, \"BySet\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]*proto.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *UserRepository) FindAllCustom() ([]domain.User, error) {\n\tret := _m.Called()\n\n\tvar r0 []domain.User\n\tif rf, ok := ret.Get(0).(func() []domain.User); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]domain.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockHandler) ProfileGet(requestingUserName, userName string) (*domain.User, bool, error) {\n\tret := m.ctrl.Call(m, \"ProfileGet\", requestingUserName, userName)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockIUserService) QueryUsersByName(name string) ([]model.UserDB, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryUsersByName\", name)\n\tret0, _ := ret[0].([]model.UserDB)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (repo *UserRepo) GetUser(username string) (user *models.User) {\n\tuser = &models.User{}\n\terr := repo.db.Where(\"user_name = ?\", username).Find(user)\n\tif err.RecordNotFound() {\n\t\tlog.Println(\"Username not correct\")\n\t\treturn nil\n\t}\n\tlog.Println(\"Correct username and password\")\n\treturn\n}", "func (_m *API) GetUserClub(username string) ([]model.Item, int, error) {\n\tret := _m.Called(username)\n\n\tvar r0 []model.Item\n\tif rf, ok := ret.Get(0).(func(string) []model.Item); ok {\n\t\tr0 = rf(username)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]model.Item)\n\t\t}\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(string) int); ok {\n\t\tr1 = rf(username)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string) error); ok {\n\t\tr2 = rf(username)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (_m *UserFinder) GetUserInfo(user string) (*slack.User, error) {\n\tret := _m.Called(user)\n\n\tvar r0 *slack.User\n\tif rf, ok := ret.Get(0).(func(string) *slack.User); ok {\n\t\tr0 = rf(user)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*slack.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(user)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockIUser) GetOrCreateUser(arg0 *User, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetOrCreateUser\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestFindUserById(t *testing.T) {\n\t_, mock, err := NewMock()\n\tif err != nil {\n\t\tfmt.Printf(\"error mock: \" + err.Error())\n\t}\n\n\t// simulate any sql driver behavior in tests, without needing a real database connection\n\tquery := \"select id, user_name, password from m_user where id = \\\\?\"\n\n\trows := sqlmock.NewRows([]string{\"id\", \"user_name\", \"password\"}).\n\t\tAddRow(user.ID, user.UserName, user.Password)\n\n\tmock.ExpectQuery(query).WithArgs(user.ID).WillReturnRows(rows)\n\t// ------------ end of mock ---------------\n\n\tassert.NotNil(t, user)\n}", "func (m *MockProduct) GetNominativeUserByID(arg0 context.Context, arg1 db.GetNominativeUserByIDParams) (db.NominativeUser, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetNominativeUserByID\", arg0, arg1)\n\tret0, _ := ret[0].(db.NominativeUser)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) GetUserById(ctx context.Context, id string) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserById\", ctx, id)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIUserStore) GetByPhoneNumber(phoneNo string) (*dto.User, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByPhoneNumber\", phoneNo)\n\tret0, _ := ret[0].(*dto.User)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (_m *API) SearchUser(query model.UserQuery) ([]model.UserSearch, int, error) {\n\tret := _m.Called(query)\n\n\tvar r0 []model.UserSearch\n\tif rf, ok := ret.Get(0).(func(model.UserQuery) []model.UserSearch); ok {\n\t\tr0 = rf(query)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]model.UserSearch)\n\t\t}\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(model.UserQuery) int); ok {\n\t\tr1 = rf(query)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(model.UserQuery) error); ok {\n\t\tr2 = rf(query)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockrepoProvider) FindAll(arg0 context.Context) ([]*types.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindAll\", arg0)\n\tret0, _ := ret[0].([]*types.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUCCodeHubI) GetUserStaredList(repoID, limit, offset int64) (models.UserSet, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserStaredList\", repoID, limit, offset)\n\tret0, _ := ret[0].(models.UserSet)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *CognitoIdentityProviderAPI) GetUser(_a0 *cognitoidentityprovider.GetUserInput) (*cognitoidentityprovider.GetUserOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *cognitoidentityprovider.GetUserOutput\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.GetUserInput) *cognitoidentityprovider.GetUserOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*cognitoidentityprovider.GetUserOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.GetUserInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *API) GetUserFavorite(username string) (*model.UserFavorite, int, error) {\n\tret := _m.Called(username)\n\n\tvar r0 *model.UserFavorite\n\tif rf, ok := ret.Get(0).(func(string) *model.UserFavorite); ok {\n\t\tr0 = rf(username)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.UserFavorite)\n\t\t}\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(string) int); ok {\n\t\tr1 = rf(username)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string) error); ok {\n\t\tr2 = rf(username)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockSessionManager) GetUserIdBySessionId(sessionId string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserIdBySessionId\", sessionId)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockContract) GetUserStats(arg0, arg1, arg2 string) (*services.UserResponseContract, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserStats\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*services.UserResponseContract)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
[ "0.702446", "0.6941575", "0.6893093", "0.6502977", "0.6467", "0.6447574", "0.64441705", "0.6427677", "0.6425123", "0.63681364", "0.6282326", "0.62816316", "0.6277929", "0.62494534", "0.6241573", "0.6165517", "0.6151281", "0.61430705", "0.6120192", "0.60933584", "0.60831285", "0.6065631", "0.6063824", "0.6021146", "0.598838", "0.598838", "0.59830946", "0.5982286", "0.5929501", "0.5919731", "0.591942", "0.59068847", "0.5896486", "0.5894957", "0.5882179", "0.5879616", "0.5873793", "0.5867325", "0.5856918", "0.5851292", "0.58427334", "0.5834497", "0.5829334", "0.58245283", "0.58207124", "0.58198917", "0.5805661", "0.58043706", "0.5794961", "0.57893384", "0.5784983", "0.57824916", "0.5773794", "0.5770733", "0.5761886", "0.5757163", "0.57534045", "0.57385", "0.5733348", "0.57299024", "0.5723273", "0.5714139", "0.5694783", "0.56925076", "0.56903464", "0.5683473", "0.56650215", "0.56502473", "0.5642887", "0.56301683", "0.56238437", "0.5621888", "0.5594098", "0.557972", "0.5560732", "0.55529773", "0.55527693", "0.554992", "0.55478865", "0.5535166", "0.5524049", "0.5521881", "0.55195236", "0.5513552", "0.55104446", "0.5504899", "0.5500245", "0.5497669", "0.54878896", "0.54760844", "0.54698926", "0.54638666", "0.54610384", "0.54506385", "0.5447063", "0.5442606", "0.54391116", "0.54351264", "0.5421294", "0.54199535" ]
0.781246
0
GetUserWhereUsername indicates an expected call of GetUserWhereUsername
func (mr *MockUserRepositoryInterfaceMockRecorder) GetUserWhereUsername(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserWhereUsername", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUserWhereUsername), arg0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockDataSourceMockRecorder) GetUserByUsername(username interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByUsername\", reflect.TypeOf((*MockDataSource)(nil).GetUserByUsername), username)\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUsername(arg0 string) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUsername\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mr *MockUserRepositoryInterfaceMockRecorder) GetUserWhereUserID(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserWhereUserID\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUserWhereUserID), arg0)\n}", "func (mr *MockPersisterMockRecorder) GetUserByUsername(username, curUserID interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByUsername\", reflect.TypeOf((*MockPersister)(nil).GetUserByUsername), username, curUserID)\n}", "func TestGetUserNotFoundInDatabase(t *testing.T) {\n\t// customize the return value for getUserFunction\n\tgetUserFunction = func(userID int64) (*domain.User, *utils.ApplicationError) {\n\t\treturn nil, &utils.ApplicationError{\n\t\t\tMessage: fmt.Sprintf(\"user %v was not found\", userID),\n\t\t\tStatusCode: http.StatusNotFound,\n\t\t\tCode: \"not_found\",\n\t\t}\n\t}\n\n\t// mock domain.UserDao layer\n\tuser, err := UserService.GetUser(0)\n\tassert.Nil(t, user)\n\tassert.NotNil(t, err)\n\tassert.EqualValues(t, http.StatusNotFound, err.StatusCode)\n\tassert.EqualValues(t, \"user 0 was not found\", err.Message)\n}", "func (mr *MockUserRepositoryInterfaceMockRecorder) GetUsersWhereUserIDs(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsersWhereUserIDs\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUsersWhereUserIDs), arg0)\n}", "func (mr *MockRepositoryMockRecorder) GetByUsername(ctx, username, password interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetByUsername\", reflect.TypeOf((*MockRepository)(nil).GetByUsername), ctx, username, password)\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUserID(arg0 uint64) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUserID\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDataSource) GetUserByUsername(username string) (model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByUsername\", username)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\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 (mr *MockUserMockRecorder) GetByUsername(ctx, db, username interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetByUsername\", reflect.TypeOf((*MockUser)(nil).GetByUsername), ctx, db, username)\n}", "func TestGetUserByIDUserNotFound(t *testing.T) {\n\tuser, err := GetUserByID(0)\n\tassert.Nil(t, user, \"Id nao esperado\")\n\tassert.NotNil(t, err)\n\n\tassert.EqualValues(t, http.StatusNotFound, err.StatusCode)\n\tassert.EqualValues(t, \"User not found\", err.Message)\n}", "func CheckUsername(ctx context.Context, client *elastic.Client, index string, username string) (string, error) {\n\tuserQuery := elastic.NewMatchQuery(\"username\", username)\n\tsearchResult, err := client.Search().\n\t\tIndex(index).\n\t\tQuery(userQuery).\n\t\tDo(ctx)\n\n\tif err != nil {\n\t\treturn \"false\", err\n\t}\n\n\tif searchResult.Hits.TotalHits.Value == 0 {\n\t\treturn \"false\", nil\n\t}\n\n\treturn \"true\", nil\n}", "func (mr *MockUsersRepoInterfaceMockRecorder) GetByUserName(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetByUserName\", reflect.TypeOf((*MockUsersRepoInterface)(nil).GetByUserName), arg0)\n}", "func TestGetUserIDInvalid(t *testing.T) {\n\tts := initAPITestServer(t)\n\tdefer test.CloseServer(ts)\n\n\tinvalidUsername := \"not_\" + username\n\tid, err := GetUserID(invalidUsername)\n\tif err == nil || err.Error() != \"Username not found\" {\n\t\tt.Fatalf(\"Expected error\")\n\t}\n\tif id != \"\" {\n\t\tt.Fatalf(\"Expected empty userID\")\n\t}\n}", "func (mock *Mock) GetUser(username string) (entities.User, error) {\n\tinputHash := toHash(getInputForGetUser(username))\n\tarrOutputForGetUser, exists := mock.patchGetUserMap[inputHash]\n\tif !exists || len(arrOutputForGetUser) == 0 {\n\t\tpanic(\"Mock not available for GetUser\")\n\t}\n\n\toutput := arrOutputForGetUser[0]\n\tarrOutputForGetUser = arrOutputForGetUser[1:]\n\tmock.patchGetUserMap[inputHash] = arrOutputForGetUser\n\n\treturn output.user, output.error\n}", "func TestGetUser(t *testing.T) {\n\ttests := []struct {\n\t\tid int64\n\t\texceptResult *schedule.User\n\t}{\n\t\t{1, &schedule.User{ID: 1}},\n\t}\n\n\tfor _, test := range tests {\n\t\tr, err := ss.GetUser(ctx, test.id)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"GetUser(%d) fail, err %s, result %+v\", test.id, err, r)\n\t\t\treturn\n\t\t}\n\n\t\tif r.ID != test.exceptResult.ID {\n\t\t\tt.Errorf(\"GetUser(%d) = %+v, except %+v\", test.id, r, test.exceptResult)\n\t\t\treturn\n\t\t}\n\t}\n}", "func TryToGetUser(c *gin.Context) {\n\ttokenStr := c.Request.Header.Get(\"Authorization\")\n\tusername, _, _ := model.ParseToken(tokenStr[7:])\n\tif username != \"\" {\n\t\tc.Set(\"username\", username)\n\t}\n\tc.Next()\n}", "func AssertUsername(m *stun.Message, expectedUsername string) error {\n\tvar username stun.Username\n\tif err := username.GetFrom(m); err != nil {\n\t\treturn err\n\t} else if string(username) != expectedUsername {\n\t\treturn fmt.Errorf(\"%w expected(%x) actual(%x)\", errMismatchUsername, expectedUsername, string(username))\n\t}\n\n\treturn nil\n}", "func (mr *MockUserRepositoryInterfaceMockRecorder) DeleteUserWhereUsername(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUserWhereUsername\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).DeleteUserWhereUsername), arg0)\n}", "func TestClientUserInfoBadUser(t *testing.T) {\n\tusername := \"mdlayher\"\n\tc, done := userInfoTestClient(t, func(t *testing.T, w http.ResponseWriter, r *http.Request) {\n\t\tpath := \"/v4/user/info/\" + username + \"/\"\n\t\tif p := r.URL.Path; p != path {\n\t\t\tt.Fatalf(\"unexpected URL path: %q != %q\", p, path)\n\t\t}\n\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tw.Write(invalidUserErrJSON)\n\t})\n\tdefer done()\n\n\t_, _, err := c.User.Info(username, false)\n\tassertInvalidUserErr(t, err)\n}", "func (dp *dataProvider) GetUserByUserName(user *models.User) error {\n\treturn wrapError(dp.db.Model(user).Where(\"user_name = ?user_name\").Select())\n}", "func (m *MockPersister) GetUserByUsername(username string, curUserID int) (User, error) {\n\tret := m.ctrl.Call(m, \"GetUserByUsername\", username, curUserID)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func isUsername(username string) bool {\n\tpanic(\"Implement me!\")\n}", "func (repo *UserRepo) GetUser(username string) (user *models.User) {\n\tuser = &models.User{}\n\terr := repo.db.Where(\"user_name = ?\", username).Find(user)\n\tif err.RecordNotFound() {\n\t\tlog.Println(\"Username not correct\")\n\t\treturn nil\n\t}\n\tlog.Println(\"Correct username and password\")\n\treturn\n}", "func (ctx UserManagement) TryGetUserInformation(username string, password string) (config.User, bool) {\n\tuser, userCouldBeFound := ctx.users[username]\n\tif !userCouldBeFound || user.Password != password {\n\t\treturn user, false\n\t}\n\n\treturn user, true\n}", "func checkUsernameToReturn(c *gin.Context, username string) bool {\n\tif !isValidUsername(username) {\n\t\tc.Status(http.StatusBadRequest)\n\t\treturn true\n\t}\n\treturn false\n}", "func TestGetUserByIDUserMatches(t *testing.T) {\n\tuser, err := GetUserByID(123)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, user)\n\n\tassert.EqualValues(t, 123, user.ID)\n\tassert.EqualValues(t, \"Marcus\", user.Name)\n}", "func (mr *MockPersisterMockRecorder) GetUser(username, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockPersister)(nil).GetUser), username, password)\n}", "func (a *UserApiService) GetUserByUsername(ctx context.Context, username string) UserApiGetUserByUsernameRequest {\n\treturn UserApiGetUserByUsernameRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tusername: username,\n\t}\n}", "func GetUserOrUnexpected(c appengine.Context, w http.ResponseWriter,\n\tr *http.Request) (*user.User, bool) {\n\n\t// Get the current user.\n\tu := user.Current(c)\n\tif u == nil {\n\t\tLogAndUnexpected(c, w, r,\n\t\t\tfmt.Errorf(\"no user found, but auth is required.\"))\n\t\treturn nil, false\n\t}\n\n\treturn u, true\n\n}", "func (_mr *MockServiceMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"GetUser\", reflect.TypeOf((*MockService)(nil).GetUser), arg0, arg1)\n}", "func (mr *MockUserClientMockRecorder) GetUserByName(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByName\", reflect.TypeOf((*MockUserClient)(nil).GetUserByName), varargs...)\n}", "func (mr *MockIUserRepositoryMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockIUserRepository)(nil).GetUser), arg0)\n}", "func (v *Validator) GetUser(username string) (*model.User, int, error) {\n\tif len(username) < 2 || len(username) > 16 {\n\t\treturn nil, http.StatusBadRequest, errors.ErrInvalidUsername\n\t}\n\n\t// Check empty id.\n\tkey := internal.GetKey(internal.KeyEmptyUser, username)\n\tif v.isEmptyID(key) {\n\t\treturn nil, http.StatusNotFound, errors.ErrNot200\n\t}\n\n\t// Parse.\n\tdata, code, err := v.api.GetUser(username)\n\n\t// Save empty id.\n\tv.saveEmptyID(code, key)\n\n\treturn data, code, err\n}", "func GetUserByUsername(c *gin.Context, username string, client *statsd.Client) {\n\tlog.Info(\"getting user by username\")\n\tvar user entity.User\n\terr := model.GetUserByUsername(&user, username, 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} else {\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 (ctx *TestContext) ThereIsAUser(name string) error {\n\treturn ctx.ThereIsAUserWith(getParameterString(map[string]string{\n\t\t\"group_id\": name,\n\t\t\"user\": name,\n\t}))\n}", "func GetUserByUsernameAndAPIKey(ctx context.Context, username string, key string) (*models.User, error) {\n\tuser := &models.User{}\n\terr := Query(ctx).Where(\"api_key = ?\", key).First(user).Error\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif user.Username != username {\n\t\treturn nil, gorm.ErrRecordNotFound\n\t}\n\n\treturn user, nil\n}", "func BenchmarkGetUserByIDUserNotFound(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tGetUserByID(0)\n\t}\n}", "func (m *MockUserRepositoryInterface) GetUsersWhereUserIDs(arg0 []uint64) ([]*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersWhereUserIDs\", arg0)\n\tret0, _ := ret[0].([]*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (dp *dataProvider) GetUserByEmailOrUserName(user *models.User) error {\n\treturn wrapError(dp.db.Model(user).Where(\"email = ?email OR user_name = ?user_name\").Select())\n}", "func (mr *MockClientMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockClient)(nil).GetUser), arg0)\n}", "func (mr *MockClientMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockClient)(nil).GetUser), arg0)\n}", "func (mr *MockInterfaceMockRecorder) GetUserByUID(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByUID\", reflect.TypeOf((*MockInterface)(nil).GetUserByUID), arg0)\n}", "func (server *Server) UserGetIgnored(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\tusers []User\n\t\tuid int\n\t\terr error\n\t\tctx context.Context\n\t)\n\n\tctx = r.Context()\n\tuid = ctx.Value(\"uid\").(int)\n\n\tusers, err = server.Db.GetIgnoredUsers(uid)\n\tif err != nil {\n\t\tserver.Logger.LogError(r, \"GetIgnoredUsers returned error - \"+err.Error())\n\t\tserver.error(w, errors.DatabaseError)\n\t\treturn\n\t}\n\n\tjsonUsers, err := json.Marshal(users)\n\tif err != nil {\n\t\tserver.Logger.LogError(r, \"Marshal returned error \"+err.Error())\n\t\tserver.error(w, errors.MarshalError)\n\t\treturn\n\t}\n\n\t// This is my valid case\n\tw.WriteHeader(http.StatusOK) // 200\n\tw.Write(jsonUsers)\n\tserver.Logger.LogSuccess(r, \"Users was found successfully. Total amount \"+BLUE+strconv.Itoa(len(users))+NO_COLOR)\n}", "func getUser(username string) (*sqlx.Rows, error) {\n rows, err := model.Database.Queryx(\"SELECT * FROM users WHERE username = ?\", username)\n if err != nil {\n return nil, err\n }\n return rows, nil\n}", "func (mr *MockDBMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockDB)(nil).GetUser), arg0)\n}", "func (mr *MockUserServerMockRecorder) GetUserByName(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByName\", reflect.TypeOf((*MockUserServer)(nil).GetUserByName), arg0, arg1)\n}", "func (p *TestProvider) GetUser(creds *common.Credentials) (common.User, error) {\n\targs := p.Called(creds)\n\treturn args.Get(0).(common.User), args.Error(1)\n}", "func (mr *MockUserClientMockRecorder) GetUser(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserClient)(nil).GetUser), varargs...)\n}", "func (mr *MockUserServerMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserServer)(nil).GetUser), arg0, arg1)\n}", "func (mr *ClientMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*Client)(nil).GetUser), arg0, arg1)\n}", "func (kc KeycloakContext) GetUser(username Username) (gocloak.User, error) {\n\tfor _, u := range kc.Users {\n\t\tif u != nil && u.Username != nil && strings.EqualFold(*u.Username, string(username)) {\n\t\t\treturn *u, nil\n\t\t}\n\t}\n\treturn gocloak.User{},\n\t\tfmt.Errorf(\n\t\t\t\"l'utilisateur '%s' n'existe pas dans le contexte Keycloak\",\n\t\t\tusername,\n\t\t)\n}", "func (suite *InjectorSuite) TestGetBTCUsername() {\n\tbtcUsername := BTCUsername()\n\n\tsuite.NotNil(btcUsername, \"btcUser should not be nil\")\n}", "func (c *AppContext) FindUser(w http.ResponseWriter, r *http.Request) {\n\tquery := r.URL.Query()\n\n\temail := query.Get(\"email\")\n\tlog.Println(\"Valid\", email)\n\tif err := validation.Validate(email, validation.Required.Error(\"Email is required\"), is.Email.Error(\"Invalid email\")); err != nil {\n\t\tnewResponse(w, http.StatusBadRequest, \"FindUserInvalidEmail\", \"Email address is not valid\", []map[string]string{}).send()\n\t\treturn\n\t}\n\n\tinput := &dynamodb.QueryInput{\n\t\tTableName: aws.String(\"GoChatUsers\"),\n\t\tIndexName: aws.String(\"email-index\"),\n\t\tExpressionAttributeNames: map[string]*string{\n\t\t\t\"#E\": aws.String(\"email\"),\n\t\t},\n\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\":email\": &dynamodb.AttributeValue{\n\t\t\t\tS: aws.String(email),\n\t\t\t},\n\t\t},\n\t\tKeyConditionExpression: aws.String(\"#E = :email\"),\n\t}\n\n\toutput, err := c.DB.Query(input)\n\tif err != nil {\n\t\tlog.Println(\"QueryFailed\", err.Error())\n\t\tnewResponse(w, http.StatusInternalServerError, \"FindUserNotFound\", \"User not found\", []map[string]string{}).send()\n\t\treturn\n\t}\n\n\tif *output.Count == 0 {\n\t\tnewResponse(w, http.StatusOK, \"FindUserNotFound\", \"User not found\", []map[string]string{}).send()\n\t\treturn\n\t}\n\n\tu := make([]interface{}, *output.Count)\n\tdynamodbattribute.UnmarshalListOfMaps(output.Items, &u)\n\n\tnewResponse(w, http.StatusOK, \"FindUserFound\", \"Found user\", u).send()\n}", "func getVerifyUser(user *models.User, code string) bool {\n\tif len(code) <= utils.TimeLimitCodeLength {\n\t\treturn false\n\t}\n\n\t// use tail hex username query user\n\thexStr := code[utils.TimeLimitCodeLength:]\n\tif b, err := hex.DecodeString(hexStr); err == nil {\n\t\tuser.UserName = string(b)\n\t\tif user.Read(\"UserName\") == nil {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (d *DataSource) GetByUsername(username string) (Model, bool) {\n\treturn d.GetBy(func(u Model) bool {\n\t\treturn u.Username == username\n\t})\n}", "func (mr *MockUserLogicMockRecorder) UserGet(userName interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserGet\", reflect.TypeOf((*MockUserLogic)(nil).UserGet), userName)\n}", "func (_m *MockTx) GetUser(_a0 string) (*model.User, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(string) *model.User); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mr *MockIUserMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockIUser)(nil).GetUser), arg0)\n}", "func (o *TransactionSplit) GetUserOk() (*string, bool) {\n\tif o == nil || o.User == nil {\n\t\treturn nil, false\n\t}\n\treturn o.User, true\n}", "func (m *MockUserRepository) FindUser(query string, params ...interface{}) (easyalert.User, error) {\n\tvarargs := []interface{}{query}\n\tfor _, a := range params {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"FindUser\", varargs...)\n\tret0, _ := ret[0].(easyalert.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetUserUsername(c *gin.Context) {\n\tuserName := c.Param(\"user_name\")\n\tdb := dbConn()\n\tselDB, err := db.Query(\"CALL read_user_username(?)\", userName)\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 (ur UserRepository) IsUserNameTaken(UserName string) (bool, error) {\n\tctx := context.Background()\n\topt := option.WithCredentialsFile(\"model/go-login-service-firebase-adminsdk-rkpp7-075307324f.json\")\n\n\tapp, err := firebase.NewApp(ctx, nil, opt)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\n\tclient, err := app.Firestore(ctx)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\n\t_, err = client.Collection(\"Users\").Doc(UserName).Get(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn true, err\n}", "func UserNotFoundException() error {\n\treturn fmt.Errorf(\"user does not exist or wrong credentials\")\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 TestGetUserService (t *testing.T){\n\tuser1, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user1)\n\n\tuser2, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user2)\n\n\tuser3, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user3)\n\n\tuser4, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user4)\n}", "func getUserFromUsername(c appengine.Context, username string) (User, error) {\n\tuser := User{}\n\n\t// get user based on Username\n\tquery := datastore.NewQuery(\"Users\").Filter(\"Username =\", username)\n\n\tvar users []User\n\tkeys, err := query.GetAll(c, &users)\n\tif err != nil {\n\t\treturn user, err\n\t}\n\tif len(users) > 1 {\n\t\treturn user, errors.New(\"More than one user is returned, something bad happened\")\n\t}\n\n\tif len(users) == 0 {\n\t\treturn User{}, nil\n\t}\n\tuser = users[0]\n\tuser.ID = keys[0].IntID()\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 (mr *MockRepositoryMockRecorder) GetUserById(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserById\", reflect.TypeOf((*MockRepository)(nil).GetUserById), arg0)\n}", "func (mr *MockUserTokenServiceMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserTokenService)(nil).GetUser), arg0, arg1)\n}", "func (mr *MockHandlerMockRecorder) UserGet(userName interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserGet\", reflect.TypeOf((*MockHandler)(nil).UserGet), userName)\n}", "func (r *Repository) GetUser(username string) (u User, err error) {\n\n\terr = r.db.Where(\"username = ?\", username).First(&u).Error\n\n\treturn\n}", "func (c cognitoClient) CheckUsernameTaken(ctx context.Context, username string) (bool, error) {\n\tlogger := log.With(c.logger, \"method\", \"CheckUsernameTaken\")\n\n\tcu := &cognito.AdminGetUserInput{\n\t\tUserPoolId: aws.String(c.userPoolID),\n\t\tUsername: aws.String(username),\n\t}\n\t_, err := c.cognitoClient.AdminGetUser(cu)\n\tif err != nil {\n\t\terr2, ok := err.(awserr.Error)\n\t\tif ok {\n\t\t\tif err2.Code() == cognito.ErrCodeUserNotFoundException {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\n\t\treturn false, err\n\t}\n\n\tlogger.Log(\"Username taken\")\n\treturn true, nil\n}", "func getUserOrNullLogin(db *gorm.DB, appUserID string, w http.ResponseWriter, r *http.Request) *models.AppUser {\n\tuser := models.AppUser{}\n\tif err := db.Where(\"app_user_status = ?\", true).First(&user, models.AppUser{AppUserID: appUserID}).Error; err != nil {\n\t\treturn nil\n\t}\n\treturn &user\n}", "func TestGetUserServicePatched (t *testing.T){\n\tuser1, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user1.Name, new_name_user_01)\n}", "func (s *Service) Verify(username string) bool {\n\treturn s.store.FindUser(username) != DoesNotExist\n}", "func Username(ctx iris.Context) string {\n\tusername := ctx.Values().GetString(usernameContextKey)\n\tif username == \"\" {\n\t\tif u := ctx.User(); u != nil {\n\t\t\tusername, _ = u.GetUsername()\n\t\t}\n\n\t}\n\treturn username\n}", "func (m *Client) GetUser(arg0 context.Context, arg1 int64) (zendesk.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0, arg1)\n\tret0, _ := ret[0].(zendesk.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\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 TestGetUserIDValid(t *testing.T) {\n\tts := initAPITestServer(t)\n\tdefer test.CloseServer(ts)\n\n\tid, err := GetUserID(username)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error %v\", err)\n\t}\n\tif id != userID {\n\t\tt.Fatalf(\"Expected userID %v got %v\", userID, id)\n\t}\n}", "func (_m *API) GetUser(username string) (*model.User, int, error) {\n\tret := _m.Called(username)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(string) *model.User); ok {\n\t\tr0 = rf(username)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(string) int); ok {\n\t\tr1 = rf(username)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string) error); ok {\n\t\tr2 = rf(username)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (mr *MockDatabaseMockRecorder) GetUserByUserId(userId interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByUserId\", reflect.TypeOf((*MockDatabase)(nil).GetUserByUserId), userId)\n}", "func (o *UserDisco) GetUsernameOk() (*string, bool) {\n\tif o == nil || o.Username == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Username, true\n}", "func (fc FlarumClient) GetUserByUsername(username string) (user map[string]interface{}, err error) {\n\tresponse, err := fc.sendApiRequest(request.GET, \"/users?filter[q]=\\\"\"+username + \"\\\"\", map[string]interface{}{})\n\treturn response, err\n}", "func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request) {\n\tusernameParam := chi.URLParam(r, \"username\")\n\tresult, err := c.service.GetUserByName(r.Context(), usernameParam)\n\t// If an error occurred, encode the error with the status code\n\tif err != nil {\n\t\tc.errorHandler(w, r, err, &result)\n\t\treturn\n\t}\n\t// If no error, encode the body and the result code\n\tEncodeJSONResponse(result.Body, &result.Code, result.Headers, w)\n}", "func GetUserCount(db sqlx.Queryer, search string) (int32, error) {\n\tvar count int32\n\tif search != \"\" {\n\t\tsearch = \"%\" + search + \"%\"\n\t}\n\terr := sqlx.Get(db, &count, `\n\t\tselect\n\t\t\tcount(*)\n\t\tfrom \"user\"\n\t\twhere\n\t\t\t($1 != '' and username ilike $1)\n\t\t\tor ($1 = '')\n\t\t`, search)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"select error\")\n\t}\n\treturn count, nil\n}", "func (t *tx) GetUser(username string) (*model.User, error) {\n\tuser := &model.User{}\n\terr := t.Where(&model.User{\n\t\tUsername: username,\n\t}).First(user).Error\n\tif gorm.IsRecordNotFoundError(err) {\n\t\treturn nil, nil\n\t}\n\n\treturn user, errors.Wrap(err, \"select user by username failed\")\n}", "func getUser(username string) (User, error) {\n\tuser, ok := users[username]\n\tif !ok {\n\t\treturn user, errors.New(ErrUserNotFound).WithField(\"username\", username)\n\t}\n\n\tif !user.Active {\n\t\treturn user, errors.New(ErrUserInactive).WithField(\"username\", username)\n\t}\n\n\t// Simulate \"critical\" error occurring when trying to look up this particular user. For example,\n\t// maybe our database server has just died.\n\tif username == \"stephen\" {\n\t\t// Pretend for a moment that this error was returned from some third-party library, etc. It\n\t\t// can be a regular error, we only expect the standard Go `error` interface when wrapping.\n\t\terr := errors.New(\"database went down, oh no\")\n\n\t\t// Wrap is identical to New, but must always take a non-nil Go `error` as it's first\n\t\t// parameter. That means you could create kinds to handle built-in \"sentinel\" errors.\n\t\treturn user, errors.Wrap(err, \"errors without a 'Kind' should probably always be handled\").\n\t\t\tWithField(\"username\", username)\n\t}\n\n\treturn user, nil\n}", "func (o *UserPasswordCredentials) GetUserOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.User, true\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 Username(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUsername), v))\n\t})\n}", "func Username(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUsername), v))\n\t})\n}", "func isUsernameAllowed(name string) error {\n\treturn isNameAllowed(reservedUsernames, reservedUsernamePatterns, name)\n}", "func (mr *MockUserUsecaseMockRecorder) GetUser(id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserUsecase)(nil).GetUser), id)\n}", "func (tc *testContext) checkUsernameAnnotation(node *core.Node) (bool, error) {\n\tprivKey, _, err := tc.getExpectedKeyPair()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tusernameValue, present := node.Annotations[controllers.UsernameAnnotation]\n\tif !present {\n\t\treturn false, nil\n\t}\n\tusername, err := crypto.DecryptFromJSONString(usernameValue, privKey)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif username != tc.vmUsername() {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}", "func getUser(req *http.Request) *grepbook.User {\n\tif rv := context.Get(req, UserKeyName); rv != nil {\n\t\tres := rv.(*grepbook.User)\n\t\treturn res\n\t}\n\treturn nil\n}", "func NewGetUserNotFound() *GetUserNotFound {\n\treturn &GetUserNotFound{}\n}", "func (mr *MockValidationServiceMockRecorder) Username(username interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Username\", reflect.TypeOf((*MockValidationService)(nil).Username), username)\n}", "func UsernameNotIn(vs ...string) predicate.User {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.User(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldUsername), v...))\n\t})\n}" ]
[ "0.6577385", "0.65723103", "0.6450824", "0.60818624", "0.6080859", "0.60337627", "0.60160303", "0.5928431", "0.58877057", "0.58712345", "0.5863223", "0.58487535", "0.5802033", "0.5750402", "0.5748335", "0.56843114", "0.5659485", "0.560906", "0.5599345", "0.55778307", "0.5574881", "0.55506223", "0.5550247", "0.55455524", "0.5536376", "0.5511889", "0.5495399", "0.54915136", "0.54896057", "0.5486802", "0.5477269", "0.547133", "0.5459725", "0.54581356", "0.54512995", "0.5450253", "0.54489535", "0.54457635", "0.54158986", "0.54117954", "0.5406378", "0.5396729", "0.5396729", "0.5393396", "0.53892034", "0.538828", "0.53742033", "0.53735846", "0.5371789", "0.5367151", "0.5347793", "0.5345751", "0.5325946", "0.53234625", "0.5323234", "0.53198665", "0.53124696", "0.53012705", "0.52955806", "0.52943027", "0.52924335", "0.5288345", "0.52852625", "0.5271866", "0.526823", "0.52664006", "0.5262264", "0.5259572", "0.52580255", "0.5244179", "0.5240999", "0.5231505", "0.52288294", "0.5225918", "0.52233946", "0.52091295", "0.520776", "0.52053654", "0.52018887", "0.52001363", "0.51833236", "0.51825815", "0.5173902", "0.5171427", "0.51685184", "0.51625395", "0.5159763", "0.515768", "0.5148194", "0.5136218", "0.5134621", "0.5131365", "0.5131365", "0.5127431", "0.51266366", "0.512465", "0.51240796", "0.5110546", "0.510999", "0.5106651" ]
0.733629
0
GetUserWhereUserID mocks base method
func (m *MockUserRepositoryInterface) GetUserWhereUserID(arg0 uint64) (*db.User, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetUserWhereUserID", arg0) ret0, _ := ret[0].(*db.User) ret1, _ := ret[1].(error) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockUserRepositoryInterface) GetUsersWhereUserIDs(arg0 []uint64) ([]*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersWhereUserIDs\", arg0)\n\tret0, _ := ret[0].([]*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUsername(arg0 string) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUsername\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) GetUserById(arg0 context.Context, arg1 uuid.UUID) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserById\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDatabase) GetUserByUserId(userId uint64) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByUserId\", userId)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAuthGateway) GetUserByID(arg0 int64) (entity.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByID\", arg0)\n\tret0, _ := ret[0].(entity.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserStorage) GetUserByID(ctx context.Context, id int64) (model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByID\", ctx, id)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetUserById(arg0 int) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserById\", arg0)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockService) GetUser(ctx context.Context, id string) (*User, error) {\n\tret := _m.ctrl.Call(_m, \"GetUser\", ctx, id)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockConn) UserID() uint64 {\n\tret := m.ctrl.Call(m, \"UserID\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *MockDatabase) GetUserByGitSourceNameAndID(gitSourceName string, id uint64) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByGitSourceNameAndID\", gitSourceName, id)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPersister) GetUserByUsername(username string, curUserID int) (User, error) {\n\tret := m.ctrl.Call(m, \"GetUserByUsername\", username, curUserID)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *StatusRepository) GetStatusByUserId(ctx context.Context, userid int) record.Status {\n\tret := _m.Called(ctx, userid)\n\n\tvar r0 record.Status\n\tif rf, ok := ret.Get(0).(func(context.Context, int) record.Status); ok {\n\t\tr0 = rf(ctx, userid)\n\t} else {\n\t\tr0 = ret.Get(0).(record.Status)\n\t}\n\n\treturn r0\n}", "func (m *MockUCAuth) GetByID(ctx context.Context, userID uint) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", ctx, userID)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDB) GetUser(arg0 uint) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserService) GetByID(tx *sqlx.Tx, userID int64) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", tx, userID)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) FindUser(query string, params ...interface{}) (easyalert.User, error) {\n\tvarargs := []interface{}{query}\n\tfor _, a := range params {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"FindUser\", varargs...)\n\tret0, _ := ret[0].(easyalert.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockDatabase) GetUserByID(id uint) *model.User {\n\tret := _m.Called(id)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(uint) *model.User); ok {\n\t\tr0 = rf(id)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockOrderRepository) FindAllOrdersByUserID(arg0 int) (models.Orders, error) {\n\tret := m.ctrl.Call(m, \"FindAllOrdersByUserID\", arg0)\n\tret0, _ := ret[0].(models.Orders)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetByID(ctx context.Context, userID uint) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", ctx, userID)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockHandler) UserGet(userName string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserGet\", userName)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func TestFindUserById(t *testing.T) {\n\t_, mock, err := NewMock()\n\tif err != nil {\n\t\tfmt.Printf(\"error mock: \" + err.Error())\n\t}\n\n\t// simulate any sql driver behavior in tests, without needing a real database connection\n\tquery := \"select id, user_name, password from m_user where id = \\\\?\"\n\n\trows := sqlmock.NewRows([]string{\"id\", \"user_name\", \"password\"}).\n\t\tAddRow(user.ID, user.UserName, user.Password)\n\n\tmock.ExpectQuery(query).WithArgs(user.ID).WillReturnRows(rows)\n\t// ------------ end of mock ---------------\n\n\tassert.NotNil(t, user)\n}", "func (m *MockUserUsecase) GetUser(id int64) entity.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", id)\n\tret0, _ := ret[0].(entity.User)\n\treturn ret0\n}", "func (m *MockStore) GetUserByEmail(arg0 context.Context, arg1 string) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByEmail\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockContentRepository) FindByUserID(arg0 int) (domain.Contents, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindByUserID\", arg0)\n\tret0, _ := ret[0].(domain.Contents)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) GetUserById(ctx context.Context, id string) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserById\", ctx, id)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetUserNotFoundInDatabase(t *testing.T) {\n\t// customize the return value for getUserFunction\n\tgetUserFunction = func(userID int64) (*domain.User, *utils.ApplicationError) {\n\t\treturn nil, &utils.ApplicationError{\n\t\t\tMessage: fmt.Sprintf(\"user %v was not found\", userID),\n\t\t\tStatusCode: http.StatusNotFound,\n\t\t\tCode: \"not_found\",\n\t\t}\n\t}\n\n\t// mock domain.UserDao layer\n\tuser, err := UserService.GetUser(0)\n\tassert.Nil(t, user)\n\tassert.NotNil(t, err)\n\tassert.EqualValues(t, http.StatusNotFound, err.StatusCode)\n\tassert.EqualValues(t, \"user 0 was not found\", err.Message)\n}", "func TestGetUserByIDUserMatches(t *testing.T) {\n\tuser, err := GetUserByID(123)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, user)\n\n\tassert.EqualValues(t, 123, user.ID)\n\tassert.EqualValues(t, \"Marcus\", user.Name)\n}", "func (_m *MockTx) GetUser(_a0 string) (*model.User, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(string) *model.User); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserLogic) UserGet(userName string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserGet\", userName)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockSessionManager) GetUserIdBySessionId(sessionId string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserIdBySessionId\", sessionId)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDataSource) GetUserByUsername(username string) (model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByUsername\", username)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *UserRepo) GetUser(_a0 uint64) (*models.User, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *models.User\n\tif rf, ok := ret.Get(0).(func(uint64) *models.User); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(uint64) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestGetUserService (t *testing.T){\n\tuser1, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user1)\n\n\tuser2, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user2)\n\n\tuser3, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user3)\n\n\tuser4, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user4)\n}", "func (_m *UserFinder) FindUserByID(_a0 context.Context, _a1 uint64) (users.User, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 users.User\n\tif rf, ok := ret.Get(0).(func(context.Context, uint64) users.User); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Get(0).(users.User)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockPermissionProvider) FindByUserID(userID int64) ([]*PermissionEntity, error) {\n\tret := _m.Called(userID)\n\n\tvar r0 []*PermissionEntity\n\tif rf, ok := ret.Get(0).(func(int64) []*PermissionEntity); ok {\n\t\tr0 = rf(userID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*PermissionEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64) error); ok {\n\t\tr1 = rf(userID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockIUser) GetUser(arg0 uint) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDatabase) GetUsersIDByGitSourceName(gitSourceName string) ([]uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersIDByGitSourceName\", gitSourceName)\n\tret0, _ := ret[0].([]uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDatabase) GetUsersID() ([]uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersID\")\n\tret0, _ := ret[0].([]uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInterface) GetUserByUID(arg0 *userService.Uid) (*userService.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByUID\", arg0)\n\tret0, _ := ret[0].(*userService.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *TeamStore) GetCommonTeamIDsForTwoUsers(userID string, otherUserID string) ([]string, error) {\n\tret := _m.Called(userID, otherUserID)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(string, string) []string); ok {\n\t\tr0 = rf(userID, otherUserID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, string) error); ok {\n\t\tr1 = rf(userID, otherUserID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockProduct) GetNominativeUserByID(arg0 context.Context, arg1 db.GetNominativeUserByIDParams) (db.NominativeUser, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetNominativeUserByID\", arg0, arg1)\n\tret0, _ := ret[0].(db.NominativeUser)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (u *usersDaoMock) GetUser(userID int64) (*domain.User, *utils.ApplicationError) {\n\treturn getUserFunction(userID)\n}", "func (suite *SubscriptionsTestSuite) mockUserFiltering(user *accounts.User) {\n\tsuite.accountsServiceMock.On(\n\t\t\"GetUserFromQueryString\",\n\t\tmock.AnythingOfType(\"*http.Request\"),\n\t).Return(user, nil)\n}", "func (m *MockProduct) GetConcurrentUserByID(arg0 context.Context, arg1 db.GetConcurrentUserByIDParams) (db.ProductConcurrentUser, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetConcurrentUserByID\", arg0, arg1)\n\tret0, _ := ret[0].(db.ProductConcurrentUser)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetUser(t *testing.T) {\n\ttests := []struct {\n\t\tid int64\n\t\texceptResult *schedule.User\n\t}{\n\t\t{1, &schedule.User{ID: 1}},\n\t}\n\n\tfor _, test := range tests {\n\t\tr, err := ss.GetUser(ctx, test.id)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"GetUser(%d) fail, err %s, result %+v\", test.id, err, r)\n\t\t\treturn\n\t\t}\n\n\t\tif r.ID != test.exceptResult.ID {\n\t\t\tt.Errorf(\"GetUser(%d) = %+v, except %+v\", test.id, r, test.exceptResult)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *MockUserUsecase) GetByID(id int) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", id)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetUsersFromIDs(arg0 []uuid.UUID) ([]user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersFromIDs\", arg0)\n\tret0, _ := ret[0].([]user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetByID(id UserID) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", id)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetUserByID(userID int64) (*domain.User, error) {\n\tuser, ok := MockData[userID]\n\tif ok {\n\t\treturn &user, nil\n\t}\n\treturn nil, domain.NotFoundError\n}", "func (_m *MockGroupProvider) FindByUserID(_a0 int64) ([]*GroupEntity, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 []*GroupEntity\n\tif rf, ok := ret.Get(0).(func(int64) []*GroupEntity); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*GroupEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *Client) GetUser(arg0 context.Context, arg1 int64) (zendesk.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0, arg1)\n\tret0, _ := ret[0].(zendesk.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Repository) GetUserByID(ctx context.Context, id uint64) (*models.User, error) {\n\tret := _m.Called(ctx, id)\n\n\tvar r0 *models.User\n\tif rf, ok := ret.Get(0).(func(context.Context, uint64) *models.User); ok {\n\t\tr0 = rf(ctx, id)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok {\n\t\tr1 = rf(ctx, id)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockPersister) GetUser(username, password string) (User, error) {\n\tret := m.ctrl.Call(m, \"GetUser\", username, password)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIUserRepository) GetUser(arg0 uuid.UUID) *model.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*model.User)\n\treturn ret0\n}", "func (mock *Mock) GetUser(username string) (entities.User, error) {\n\tinputHash := toHash(getInputForGetUser(username))\n\tarrOutputForGetUser, exists := mock.patchGetUserMap[inputHash]\n\tif !exists || len(arrOutputForGetUser) == 0 {\n\t\tpanic(\"Mock not available for GetUser\")\n\t}\n\n\toutput := arrOutputForGetUser[0]\n\tarrOutputForGetUser = arrOutputForGetUser[1:]\n\tmock.patchGetUserMap[inputHash] = arrOutputForGetUser\n\n\treturn output.user, output.error\n}", "func (m *MockUserPGRepository) FindById(ctx context.Context, userID uuid.UUID) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindById\", ctx, userID)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mock *RepositoryMock) GetUserProductAffinitiesByUserIDCalls() []struct {\n\tCtx context.Context\n\tUserID int64\n\tOptions GetUserProductAffinitiesByUserIDOptions\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tUserID int64\n\t\tOptions GetUserProductAffinitiesByUserIDOptions\n\t}\n\tlockRepositoryMockGetUserProductAffinitiesByUserID.RLock()\n\tcalls = mock.calls.GetUserProductAffinitiesByUserID\n\tlockRepositoryMockGetUserProductAffinitiesByUserID.RUnlock()\n\treturn calls\n}", "func (m *MockUserRepo) FindByID(arg0 string) (*app.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindByID\", arg0)\n\tret0, _ := ret[0].(*app.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetByID(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"can't create mock: %s\", err)\n\t}\n\tdefer db.Close()\n\n\tuserID := \"1\"\n\n\t// good query\n\trows := sqlmock.\n\t\tNewRows([]string{\"username\", \"admin\", \"id\", \"passwordHash\", \"token\"})\n\tuser := &User{\n\t\tUsername: \"Coolguy\",\n\t\tAdmin: false,\n\t\tID: userID,\n\t\tPasswordHash: \"CoolHash\",\n\t\tToken: \"CoolToken\",\n\t}\n\texpect := []*User{\n\t\tuser,\n\t}\n\tfor _, item := range expect {\n\t\trows = rows.AddRow(item.ID, item.Username, item.Admin, item.PasswordHash, item.Token)\n\t}\n\n\tmock.\n\t\tExpectQuery(\"SELECT id, username, admin, passwordHash, token\").\n\t\tWithArgs(userID).\n\t\tWillReturnRows(rows)\n\n\trepo := &Repo{\n\t\tDB: db,\n\t}\n\titem, err := repo.GetByID(userID)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected err: %s\", err)\n\t\treturn\n\t}\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expectations: %s\", err)\n\t\treturn\n\t}\n\tif !reflect.DeepEqual(item, expect[0]) {\n\t\tt.Errorf(\"results not match, want %v, have %v\", expect[0], item)\n\t\treturn\n\t}\n\n\t// query db error\n\tmock.\n\t\tExpectQuery(\"SELECT id, username, admin, passwordHash, token\").\n\t\tWithArgs(userID).\n\t\tWillReturnError(fmt.Errorf(\"db_error\"))\n\n\t_, err = repo.GetByID(userID)\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expectations: %s\", err)\n\t\treturn\n\t}\n\tif err == nil {\n\t\tt.Errorf(\"expected error, got nil\")\n\t\treturn\n\t}\n}", "func (t TestRepo) GetUserByExternalID(id string) (*User, error) {\n\tt.ArgsIn[GetUserByExternalIDMethod][0] = id\n\tif specialFunc, ok := t.SpecialFuncs[GetUserByExternalIDMethod].(func(id string) (*User, error)); ok && specialFunc != nil {\n\t\treturn specialFunc(id)\n\t}\n\tvar user *User\n\tif t.ArgsOut[GetUserByExternalIDMethod][0] != nil {\n\t\tuser = t.ArgsOut[GetUserByExternalIDMethod][0].(*User)\n\t}\n\tvar err error\n\tif t.ArgsOut[GetUserByExternalIDMethod][1] != nil {\n\t\terr = t.ArgsOut[GetUserByExternalIDMethod][1].(error)\n\t}\n\treturn user, err\n}", "func (m *MockUserDB) GetUserByUID(uid uint64) (*UserModel.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByUID\", uid)\n\tret0, _ := ret[0].(*UserModel.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *UsersRepository) FindById(userID int) (*entities.User, error) {\n\tret := _m.Called(userID)\n\n\tvar r0 *entities.User\n\tif rf, ok := ret.Get(0).(func(int) *entities.User); ok {\n\t\tr0 = rf(userID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*entities.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int) error); ok {\n\t\tr1 = rf(userID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Usecase) GetItemBasedOnUserOwner(_a0 context.Context) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *TeamStore) GetUserTeamIds(userID string, allowFromCache bool) ([]string, error) {\n\tret := _m.Called(userID, allowFromCache)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(string, bool) []string); ok {\n\t\tr0 = rf(userID, allowFromCache)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, bool) error); ok {\n\t\tr1 = rf(userID, allowFromCache)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Provider) GetUser(le *logrus.Entry, token string) (*auth.User, int64, int, error) {\n\tret := _m.Called(le, token)\n\n\tvar r0 *auth.User\n\tif rf, ok := ret.Get(0).(func(*logrus.Entry, string) *auth.User); ok {\n\t\tr0 = rf(le, token)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*auth.User)\n\t\t}\n\t}\n\n\tvar r1 int64\n\tif rf, ok := ret.Get(1).(func(*logrus.Entry, string) int64); ok {\n\t\tr1 = rf(le, token)\n\t} else {\n\t\tr1 = ret.Get(1).(int64)\n\t}\n\n\tvar r2 int\n\tif rf, ok := ret.Get(2).(func(*logrus.Entry, string) int); ok {\n\t\tr2 = rf(le, token)\n\t} else {\n\t\tr2 = ret.Get(2).(int)\n\t}\n\n\tvar r3 error\n\tif rf, ok := ret.Get(3).(func(*logrus.Entry, string) error); ok {\n\t\tr3 = rf(le, token)\n\t} else {\n\t\tr3 = ret.Error(3)\n\t}\n\n\treturn r0, r1, r2, r3\n}", "func (m *MockUserRepo) GetByID(id string) (model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", id)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserTokenService) GetUser(arg0 context.Context, arg1 string) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0, arg1)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockFamilyRepo) UserInFamily(arg0, arg1 int) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UserInFamily\", arg0, arg1)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mr *MockUserRepositoryInterfaceMockRecorder) GetUserWhereUserID(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserWhereUserID\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUserWhereUserID), arg0)\n}", "func (m *Repository) GetAllByUserID(arg0 context.Context, arg1 int64) ([]*models.Task, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllByUserID\", arg0, arg1)\n\tret0, _ := ret[0].([]*models.Task)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserStore) Get(arg0 context.Context, arg1 *sql.Tx, arg2 []byte) (*proto.User, error) {\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*proto.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) GetUser(arg0 *iam.GetUserInput) (*iam.GetUserOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*iam.GetUserOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) GetUser(arg0 *iam.GetUserInput) (*iam.GetUserOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*iam.GetUserOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUsersRepoInterface) GetByID(arg0 string) (*user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", arg0)\n\tret0, _ := ret[0].(*user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetUserServicePatched (t *testing.T){\n\tuser1, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user1.Name, new_name_user_01)\n}", "func (_m *API) GetUser(username string) (*model.User, int, error) {\n\tret := _m.Called(username)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(string) *model.User); ok {\n\t\tr0 = rf(username)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(string) int); ok {\n\t\tr1 = rf(username)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string) error); ok {\n\t\tr2 = rf(username)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockUsersRepo) GetByID(id int) (auth.User, error) {\n\tret := m.ctrl.Call(m, \"GetByID\", id)\n\tret0, _ := ret[0].(auth.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserFinder) Lookup(arg0 string) (specs.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Lookup\", arg0)\n\tret0, _ := ret[0].(specs.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDb) GetProductsByUserFilter(filter model.FilterUProduct) ([]model.UserProduct, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetProductsByUserFilter\", filter)\n\tret0, _ := ret[0].([]model.UserProduct)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserServer) GetUser(arg0 context.Context, arg1 *pb.UserRequest) (*pb.UserReply, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0, arg1)\n\tret0, _ := ret[0].(*pb.UserReply)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUser) GetById(id int64) entity.User {\n\tret := m.ctrl.Call(m, \"GetById\", id)\n\tret0, _ := ret[0].(entity.User)\n\treturn ret0\n}", "func (m *MockIUserStore) GetByPhoneNumber(phoneNo string) (*dto.User, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByPhoneNumber\", phoneNo)\n\tret0, _ := ret[0].(*dto.User)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockPersister) GetUserByToken(token string) (User, error) {\n\tret := m.ctrl.Call(m, \"GetUserByToken\", token)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestReadUser(t *testing.T) {\r\n/////////////////////////////////// MOCKING ////////////////////////////////////////////\r\n\tvar batches = []string{\r\n\t\t`CREATE TABLE Users (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Name TEXT NOT NULL UNIQUE);`,\r\n\t\t`INSERT INTO Users (Id,Name) VALUES (1,'anonymous');`,\r\n\t}\r\n\t//open pseudo database for function\r\n\tdb, err := sql.Open(\"ramsql\", \"TestReadUser\")\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Error creating mock sql : %s\\n\", err)\r\n\t}\r\n\tdefer db.Close()\r\n\r\n\t// Exec every line of batch and create database\r\n\tfor _, b := range batches {\r\n\t\t_, err = db.Exec(b)\r\n\t\tif err != nil {\r\n\t\t\tt.Fatalf(\"Error exec query in query: %s\\n Error:%s\", b, err)\r\n\t\t}\r\n\t}\r\n/////////////////////////////////// MOCKING ////////////////////////////////////////////\r\n\r\n\t// Specify test variables and expected results.\r\n\ttests := []struct {\r\n\t\tid int\r\n\t\t// we need to use models.User for passing to object.This is different with \"database.User\".\r\n\t\tresult models.User\r\n\t\terr error\r\n\t}{\r\n\t\t// When give to first parameter(id) 1 , We expect result :1 error nil\r\n\t\t{id: 1, result: models.User{Id: 1, Name: \"anonymous\"}, err: nil},\r\n\t\t// When give to first parameter(id) 1 , We expect result :1 error nil\r\n\t\t//{id: 2, result: models.User{Id: 2, Name: \"test\"}, err: nil},\r\n\t}\r\n\r\n\t// test all of the variables.\r\n\tfor _, test := range tests {\r\n\t\t//get result after test.\r\n\t\ts, err := u.ReadUser(db, test.id)\r\n\t\t// if expected error type nil we need to compare with actual error different way.\r\n\t\tif test.err == nil {\r\n\t\t\t// If test fails give error.It checks expected result and expected error\r\n\t\t\tif err != test.err || s != test.result {\r\n\t\t\t\t// Compare expected error and actual error\r\n\t\t\t\tt.Errorf(\"Error is: %v . Expected: %v\", err, test.err)\r\n\t\t\t\t// Compare expected result and actual result\r\n\t\t\t\tt.Errorf(\"Result is: %v . Expected: %v\", s, test.result)\r\n\t\t\t}\r\n\t\t\t// if expected error type is not nil we need to compare with actual error different way.\r\n\t\t} else {\r\n\t\t\tif err.Error() != test.err.Error() || s != test.result {\r\n\t\t\t\t// Compare expected error and actual error\r\n\t\t\t\tt.Errorf(\"Error is: %v . Expected: %v\", err, test.err)\r\n\t\t\t\t// Compare expected result and actual result\r\n\t\t\t\tt.Errorf(\"Result is: %v . Expected: %v\", s, test.result)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func (m *MockUsersRepoInterface) GetByUserName(arg0 string) (*user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByUserName\", arg0)\n\tret0, _ := ret[0].(*user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) SelectUserByEmail(arg0 string) (*models.AuthUser, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SelectUserByEmail\", arg0)\n\tret0, _ := ret[0].(*models.AuthUser)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) Find(arg0 sweeper.Snowflake) (*sweeper.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Find\", arg0)\n\tret0, _ := ret[0].(*sweeper.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetUserByEmail(email string) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByEmail\", arg0, arg1)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *QueryResolver) User(ctx context.Context, where prisma.UserWhereUniqueInput) (*prisma.User, error) {\n\tret := _m.Called(ctx, where)\n\n\tvar r0 *prisma.User\n\tif rf, ok := ret.Get(0).(func(context.Context, prisma.UserWhereUniqueInput) *prisma.User); ok {\n\t\tr0 = rf(ctx, where)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*prisma.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, prisma.UserWhereUniqueInput) error); ok {\n\t\tr1 = rf(ctx, where)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserStorage) GetUserByEmail(ctx context.Context, email string) (model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByEmail\", ctx, email)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) GetUsersForRole(arg0 string, arg1 ...string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetUsersForRole\", varargs...)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockrepoProvider) FindUserByMail(ctx context.Context, email string) (*types.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindUserByMail\", ctx, email)\n\tret0, _ := ret[0].(*types.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDao) UID(steamID int64) (*model.Info, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UID\", steamID)\n\tret0, _ := ret[0].(*model.Info)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmGetUser *mStorageMockGetUser) When(ctx context.Context, userID int64) *StorageMockGetUserExpectation {\n\tif mmGetUser.mock.funcGetUser != nil {\n\t\tmmGetUser.mock.t.Fatalf(\"StorageMock.GetUser mock is already set by Set\")\n\t}\n\n\texpectation := &StorageMockGetUserExpectation{\n\t\tmock: mmGetUser.mock,\n\t\tparams: &StorageMockGetUserParams{ctx, userID},\n\t}\n\tmmGetUser.expectations = append(mmGetUser.expectations, expectation)\n\treturn expectation\n}", "func (_m *MockUserRepositoryProvider) GetByID(id int) (*model.User, error) {\n\tret := _m.Called(id)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(int) *model.User); ok {\n\t\tr0 = rf(id)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int) error); ok {\n\t\tr1 = rf(id)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserDB) GetUserByEmail(email string) (*UserModel.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByEmail\", email)\n\tret0, _ := ret[0].(*UserModel.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *UserRepositoryI) FetchOne(tx database.TransactionI, userID int32, difficult int) (*models.UserPublicInfo, error) {\n\tret := _m.Called(tx, userID, difficult)\n\n\tvar r0 *models.UserPublicInfo\n\tif rf, ok := ret.Get(0).(func(database.TransactionI, int32, int) *models.UserPublicInfo); ok {\n\t\tr0 = rf(tx, userID, difficult)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.UserPublicInfo)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(database.TransactionI, int32, int) error); ok {\n\t\tr1 = rf(tx, userID, difficult)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockProduct) GetConcurrentUsersByDay(arg0 context.Context, arg1 db.GetConcurrentUsersByDayParams) ([]db.GetConcurrentUsersByDayRow, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetConcurrentUsersByDay\", arg0, arg1)\n\tret0, _ := ret[0].([]db.GetConcurrentUsersByDayRow)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (dp *dataProvider) GetUserByID(user *models.User) error {\n\t//Where(\"id = ?id\")\n\treturn wrapError(dp.db.Select(user))\n}", "func (m *MockUserClient) GetUser(ctx context.Context, in *pb.UserRequest, opts ...grpc.CallOption) (*pb.UserReply, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetUser\", varargs...)\n\tret0, _ := ret[0].(*pb.UserReply)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
[ "0.6997609", "0.68632466", "0.67604893", "0.66143733", "0.6583118", "0.64520305", "0.6437574", "0.640814", "0.64033085", "0.6350979", "0.63398397", "0.629975", "0.6285981", "0.6272878", "0.6267905", "0.6262503", "0.6211759", "0.6198792", "0.6188819", "0.61851734", "0.6174459", "0.61727154", "0.61630464", "0.6143847", "0.6138647", "0.61274815", "0.61210316", "0.61063755", "0.6094857", "0.60896385", "0.6083004", "0.6080867", "0.6050089", "0.6041065", "0.6012367", "0.60024863", "0.59893936", "0.5986985", "0.59849113", "0.5955938", "0.5950548", "0.59431076", "0.5921315", "0.59211326", "0.59184355", "0.5912355", "0.5904446", "0.59024304", "0.590159", "0.5894879", "0.5874364", "0.58700436", "0.5865867", "0.58631706", "0.5862116", "0.5856912", "0.5825821", "0.5820957", "0.5816857", "0.5809485", "0.5797907", "0.57698655", "0.5763995", "0.57543457", "0.5747688", "0.5746416", "0.57248074", "0.5720905", "0.5714562", "0.57058215", "0.5693294", "0.5692414", "0.5692414", "0.56809723", "0.5672555", "0.56653404", "0.5662034", "0.5657641", "0.56566423", "0.5650067", "0.5631322", "0.56308305", "0.5630261", "0.5623312", "0.56205535", "0.56183416", "0.5611663", "0.56086296", "0.56081086", "0.5607573", "0.5602845", "0.55799645", "0.5567521", "0.55672705", "0.5560541", "0.55583835", "0.554484", "0.5543476", "0.5538669", "0.5536992" ]
0.7768862
0
GetUserWhereUserID indicates an expected call of GetUserWhereUserID
func (mr *MockUserRepositoryInterfaceMockRecorder) GetUserWhereUserID(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserWhereUserID", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUserWhereUserID), arg0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockUserRepositoryInterfaceMockRecorder) GetUsersWhereUserIDs(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsersWhereUserIDs\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUsersWhereUserIDs), arg0)\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUserID(arg0 uint64) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUserID\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mr *MockUserRepositoryInterfaceMockRecorder) GetUserWhereUsername(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserWhereUsername\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUserWhereUsername), arg0)\n}", "func (mr *MockDatabaseMockRecorder) GetUserByUserId(userId interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByUserId\", reflect.TypeOf((*MockDatabase)(nil).GetUserByUserId), userId)\n}", "func TestGetUserNotFoundInDatabase(t *testing.T) {\n\t// customize the return value for getUserFunction\n\tgetUserFunction = func(userID int64) (*domain.User, *utils.ApplicationError) {\n\t\treturn nil, &utils.ApplicationError{\n\t\t\tMessage: fmt.Sprintf(\"user %v was not found\", userID),\n\t\t\tStatusCode: http.StatusNotFound,\n\t\t\tCode: \"not_found\",\n\t\t}\n\t}\n\n\t// mock domain.UserDao layer\n\tuser, err := UserService.GetUser(0)\n\tassert.Nil(t, user)\n\tassert.NotNil(t, err)\n\tassert.EqualValues(t, http.StatusNotFound, err.StatusCode)\n\tassert.EqualValues(t, \"user 0 was not found\", err.Message)\n}", "func BenchmarkGetUserByIDUserNotFound(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tGetUserByID(0)\n\t}\n}", "func TestGetUser(t *testing.T) {\n\ttests := []struct {\n\t\tid int64\n\t\texceptResult *schedule.User\n\t}{\n\t\t{1, &schedule.User{ID: 1}},\n\t}\n\n\tfor _, test := range tests {\n\t\tr, err := ss.GetUser(ctx, test.id)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"GetUser(%d) fail, err %s, result %+v\", test.id, err, r)\n\t\t\treturn\n\t\t}\n\n\t\tif r.ID != test.exceptResult.ID {\n\t\t\tt.Errorf(\"GetUser(%d) = %+v, except %+v\", test.id, r, test.exceptResult)\n\t\t\treturn\n\t\t}\n\t}\n}", "func TestGetUserByIDUserNotFound(t *testing.T) {\n\tuser, err := GetUserByID(0)\n\tassert.Nil(t, user, \"Id nao esperado\")\n\tassert.NotNil(t, err)\n\n\tassert.EqualValues(t, http.StatusNotFound, err.StatusCode)\n\tassert.EqualValues(t, \"User not found\", err.Message)\n}", "func (mr *MockStoreMockRecorder) GetUserById(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserById\", reflect.TypeOf((*MockStore)(nil).GetUserById), arg0, arg1)\n}", "func (mr *MockRepositoryMockRecorder) GetUserById(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserById\", reflect.TypeOf((*MockRepository)(nil).GetUserById), arg0)\n}", "func (mr *MockInterfaceMockRecorder) GetUserByUID(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByUID\", reflect.TypeOf((*MockInterface)(nil).GetUserByUID), arg0)\n}", "func (mr *MockUserUsecaseMockRecorder) GetUser(id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserUsecase)(nil).GetUser), id)\n}", "func (mr *MockClientMockRecorder) GetUserById(ctx, id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserById\", reflect.TypeOf((*MockClient)(nil).GetUserById), ctx, id)\n}", "func TestGetUserByIDUserMatches(t *testing.T) {\n\tuser, err := GetUserByID(123)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, user)\n\n\tassert.EqualValues(t, 123, user.ID)\n\tassert.EqualValues(t, \"Marcus\", user.Name)\n}", "func (mr *MockUserStorageMockRecorder) GetUserByID(ctx, id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByID\", reflect.TypeOf((*MockUserStorage)(nil).GetUserByID), ctx, id)\n}", "func (m *MockUserRepositoryInterface) GetUsersWhereUserIDs(arg0 []uint64) ([]*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersWhereUserIDs\", arg0)\n\tret0, _ := ret[0].([]*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetUserIDInvalid(t *testing.T) {\n\tts := initAPITestServer(t)\n\tdefer test.CloseServer(ts)\n\n\tinvalidUsername := \"not_\" + username\n\tid, err := GetUserID(invalidUsername)\n\tif err == nil || err.Error() != \"Username not found\" {\n\t\tt.Fatalf(\"Expected error\")\n\t}\n\tif id != \"\" {\n\t\tt.Fatalf(\"Expected empty userID\")\n\t}\n}", "func (mr *MockAuthGatewayMockRecorder) GetUserByID(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByID\", reflect.TypeOf((*MockAuthGateway)(nil).GetUserByID), arg0)\n}", "func TestGetUserIDValid(t *testing.T) {\n\tts := initAPITestServer(t)\n\tdefer test.CloseServer(ts)\n\n\tid, err := GetUserID(username)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error %v\", err)\n\t}\n\tif id != userID {\n\t\tt.Fatalf(\"Expected userID %v got %v\", userID, id)\n\t}\n}", "func (dp *dataProvider) GetUserByFacebookID(user *models.User) error {\n\t//return dp.NoArgFunc(drop)\n\t//return dp.FuncWithUser(fe, user).Do()\n\t// return dp.Arg(\"user\", user).ReturnUserAndError()\n\treturn wrapError(dp.db.Model(user).Where(\"facebook_id = ?facebook_id\").Select())\n}", "func checkUserID(userID string) error {\n\tif userID == \"\" {\n\t\tfmt.Println(\"UserID not found\")\n\t\treturn fmt.Errorf(\"Something went wrong\")\n\t}\n\treturn nil\n}", "func (_mr *MockServiceMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"GetUser\", reflect.TypeOf((*MockService)(nil).GetUser), arg0, arg1)\n}", "func (mr *MockUserDBMockRecorder) GetUserByUID(uid interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByUID\", reflect.TypeOf((*MockUserDB)(nil).GetUserByUID), uid)\n}", "func (dp *dataProvider) GetUserByID(user *models.User) error {\n\t//Where(\"id = ?id\")\n\treturn wrapError(dp.db.Select(user))\n}", "func (mr *MockContentRepositoryMockRecorder) FindByUserID(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"FindByUserID\", reflect.TypeOf((*MockContentRepository)(nil).FindByUserID), arg0)\n}", "func GetUserID(ctx context.Context) (string, bool) {\n\tv, ok := ctx.Value(UserIDKey).(string)\n\treturn v, ok\n}", "func (mr *MockDBMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockDB)(nil).GetUser), arg0)\n}", "func (mr *MockPersisterMockRecorder) GetUserByUsername(username, curUserID interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByUsername\", reflect.TypeOf((*MockPersister)(nil).GetUserByUsername), username, curUserID)\n}", "func (mr *MockDataSourceMockRecorder) GetUserByUsername(username interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByUsername\", reflect.TypeOf((*MockDataSource)(nil).GetUserByUsername), username)\n}", "func NewGetUserByPlatformUserIDNotFound() *GetUserByPlatformUserIDNotFound {\n\treturn &GetUserByPlatformUserIDNotFound{}\n}", "func NewGetUserByPlatformUserIDNotFound() *GetUserByPlatformUserIDNotFound {\n\treturn &GetUserByPlatformUserIDNotFound{}\n}", "func (mr *MockUCAuthMockRecorder) GetByID(ctx, userID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetByID\", reflect.TypeOf((*MockUCAuth)(nil).GetByID), ctx, userID)\n}", "func (mr *MockUserServiceMockRecorder) GetByID(tx, userID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetByID\", reflect.TypeOf((*MockUserService)(nil).GetByID), tx, userID)\n}", "func (o *AccessRequestData) GetUserIdOk() (*string, bool) {\n\tif o == nil || o.UserId == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UserId, true\n}", "func (mr *MockSessionManagerMockRecorder) GetUserIdBySessionId(sessionId interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserIdBySessionId\", reflect.TypeOf((*MockSessionManager)(nil).GetUserIdBySessionId), sessionId)\n}", "func (mr *MockClientMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockClient)(nil).GetUser), arg0)\n}", "func (mr *MockClientMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockClient)(nil).GetUser), arg0)\n}", "func (mock *RepositoryMock) GetUserProductAffinitiesByUserIDCalls() []struct {\n\tCtx context.Context\n\tUserID int64\n\tOptions GetUserProductAffinitiesByUserIDOptions\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tUserID int64\n\t\tOptions GetUserProductAffinitiesByUserIDOptions\n\t}\n\tlockRepositoryMockGetUserProductAffinitiesByUserID.RLock()\n\tcalls = mock.calls.GetUserProductAffinitiesByUserID\n\tlockRepositoryMockGetUserProductAffinitiesByUserID.RUnlock()\n\treturn calls\n}", "func (mr *MockRepositoryMockRecorder) GetUsersFromIDs(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsersFromIDs\", reflect.TypeOf((*MockRepository)(nil).GetUsersFromIDs), arg0)\n}", "func getUserOrNull(db *gorm.DB, appUserID string, w http.ResponseWriter, r *http.Request) *models.AppUser {\n\tuser := models.AppUser{}\n\tif err := db.First(&user, models.AppUser{AppUserID: appUserID}).Error; err != nil {\n\t\treturn nil\n\t}\n\treturn &user\n}", "func (mr *MockProductMockRecorder) GetConcurrentUserByID(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetConcurrentUserByID\", reflect.TypeOf((*MockProduct)(nil).GetConcurrentUserByID), arg0, arg1)\n}", "func (mr *MockRepositoryMockRecorder) GetByID(ctx, userID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetByID\", reflect.TypeOf((*MockRepository)(nil).GetByID), ctx, userID)\n}", "func (mr *MockIUserMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockIUser)(nil).GetUser), arg0)\n}", "func (t TestRepo) GetUserByExternalID(id string) (*User, error) {\n\tt.ArgsIn[GetUserByExternalIDMethod][0] = id\n\tif specialFunc, ok := t.SpecialFuncs[GetUserByExternalIDMethod].(func(id string) (*User, error)); ok && specialFunc != nil {\n\t\treturn specialFunc(id)\n\t}\n\tvar user *User\n\tif t.ArgsOut[GetUserByExternalIDMethod][0] != nil {\n\t\tuser = t.ArgsOut[GetUserByExternalIDMethod][0].(*User)\n\t}\n\tvar err error\n\tif t.ArgsOut[GetUserByExternalIDMethod][1] != nil {\n\t\terr = t.ArgsOut[GetUserByExternalIDMethod][1].(error)\n\t}\n\treturn user, err\n}", "func (mr *MockIUserRepositoryMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockIUserRepository)(nil).GetUser), arg0)\n}", "func (mr *MockConnMockRecorder) UserID() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserID\", reflect.TypeOf((*MockConn)(nil).UserID))\n}", "func getUserOrNullLogin(db *gorm.DB, appUserID string, w http.ResponseWriter, r *http.Request) *models.AppUser {\n\tuser := models.AppUser{}\n\tif err := db.Where(\"app_user_status = ?\", true).First(&user, models.AppUser{AppUserID: appUserID}).Error; err != nil {\n\t\treturn nil\n\t}\n\treturn &user\n}", "func (mr *MockUserServerMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserServer)(nil).GetUser), arg0, arg1)\n}", "func (o *ViewUserDashboard) GetUserIdOk() (*int32, bool) {\n\tif o == nil || o.UserId == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UserId, true\n}", "func (mr *MockUserClientMockRecorder) GetUser(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserClient)(nil).GetUser), varargs...)\n}", "func (u *usersDaoMock) GetUser(userID int64) (*domain.User, *utils.ApplicationError) {\n\treturn getUserFunction(userID)\n}", "func GetUserByID(c *gin.Context) {\n\tvar user, condition Users\n\n\tuserID, _ := strconv.ParseUint(c.Param(\"id\"), 10, 64)\n\tcondition.ID = uint(userID)\n\tuser.FindOne(condition)\n\n\tif user.ID == 0 {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"status\": http.StatusOK,\n\t\t\t\"message\": \"user is not found\",\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"status\": http.StatusOK,\n\t\t\t\"data\": user,\n\t\t})\n\t}\n}", "func GetUserById(context *fiber.Ctx) error {\n\tid, err := ParseId(context)\n\n\tif err != nil {\n\t\treturn context.Status(400).JSON(&fiber.Map{\"error\": err.Error()})\n\t}\n\n\tvar user = repository.GetUserById(id)\n\n\tif user.ID == 0 {\n\t\tlog.Printf(\"user not found: %d\", id)\n\t\treturn context.Status(404).JSON(&fiber.Map{\"response\": \"not found\"})\n\t} else {\n\t\treturn context.Status(200).JSON(user)\n\t}\n}", "func (mr *ClientMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*Client)(nil).GetUser), arg0, arg1)\n}", "func (mr *RepositoryMockRecorder) GetAllByUserID(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetAllByUserID\", reflect.TypeOf((*Repository)(nil).GetAllByUserID), arg0, arg1)\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 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 (o *Authorization) GetUserIDOk() (*string, bool) {\n\tif o == nil || o.UserID == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UserID, true\n}", "func (ctx *TestContext) ThereIsAUser(name string) error {\n\treturn ctx.ThereIsAUserWith(getParameterString(map[string]string{\n\t\t\"group_id\": name,\n\t\t\"user\": name,\n\t}))\n}", "func (mr *MockProductMockRecorder) GetNominativeUserByID(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetNominativeUserByID\", reflect.TypeOf((*MockProduct)(nil).GetNominativeUserByID), arg0, arg1)\n}", "func (_obj *DataService) HasUserWithContext(tarsCtx context.Context, wx_id string, userExist *bool, _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 = _os.Write_string(wx_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_bool((*userExist), 2)\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, \"hasUser\", _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\terr = _is.Read_bool(&(*userExist), 2, 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 (mr *MockHandlerMockRecorder) UserGet(userName interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserGet\", reflect.TypeOf((*MockHandler)(nil).UserGet), userName)\n}", "func UserID(v int) predicate.User {\n\treturn predicate.User(sql.FieldEQ(FieldUserID, v))\n}", "func (mr *MockUserTokenServiceMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserTokenService)(nil).GetUser), arg0, arg1)\n}", "func (mr *MockUserLogicMockRecorder) UserGet(userName interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserGet\", reflect.TypeOf((*MockUserLogic)(nil).UserGet), userName)\n}", "func NewGetUserByIDNotFound() *GetUserByIDNotFound {\n\treturn &GetUserByIDNotFound{}\n}", "func UserByIDGet(c *gin.Context) {\n\tid, _ := strconv.ParseInt(c.Param(\"id\"), 10, 64)\n\tlog.Info(\"UserByIDGet \", id)\n\tm := model.UserByID(uint(id))\n\tginutils.WriteGinJSON(c, http.StatusOK, m)\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 (server *Server) UserGetIgnored(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\tusers []User\n\t\tuid int\n\t\terr error\n\t\tctx context.Context\n\t)\n\n\tctx = r.Context()\n\tuid = ctx.Value(\"uid\").(int)\n\n\tusers, err = server.Db.GetIgnoredUsers(uid)\n\tif err != nil {\n\t\tserver.Logger.LogError(r, \"GetIgnoredUsers returned error - \"+err.Error())\n\t\tserver.error(w, errors.DatabaseError)\n\t\treturn\n\t}\n\n\tjsonUsers, err := json.Marshal(users)\n\tif err != nil {\n\t\tserver.Logger.LogError(r, \"Marshal returned error \"+err.Error())\n\t\tserver.error(w, errors.MarshalError)\n\t\treturn\n\t}\n\n\t// This is my valid case\n\tw.WriteHeader(http.StatusOK) // 200\n\tw.Write(jsonUsers)\n\tserver.Logger.LogSuccess(r, \"Users was found successfully. Total amount \"+BLUE+strconv.Itoa(len(users))+NO_COLOR)\n}", "func (mr *MockInterfaceMockRecorder) GetUserByEmail(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByEmail\", reflect.TypeOf((*MockInterface)(nil).GetUserByEmail), arg0)\n}", "func GetUserID(ctx context.Context) (int64, error) {\n\treturn getInt64(ctx, userIDKey)\n}", "func (_obj *DataService) HasUser(wx_id string, userExist *bool, _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 = _os.Write_string(wx_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_bool((*userExist), 2)\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, \"hasUser\", _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\terr = _is.Read_bool(&(*userExist), 2, 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 (mr *MockDatabaseMockRecorder) GetUsersID() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsersID\", reflect.TypeOf((*MockDatabase)(nil).GetUsersID))\n}", "func (m *MockDatabase) GetUserByUserId(userId uint64) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByUserId\", userId)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (server *Server) GetUserPointByUserID(c *gin.Context) {\n\tuserID := c.Param(\"id\")\n\tconvertedUserID, err := strconv.ParseUint(userID, 10, 64)\n\tif err != nil {\n\t\tlog.Printf(err.Error())\n\t\terrList[\"invalid_request\"] = \"Invalid request\"\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"error\": errList,\n\t\t})\n\t\treturn\n\t}\n\n\tuserPoint := models.UserPoint{}\n\tuserPoints, err := userPoint.FindPointHistoryByUserID(server.DB, convertedUserID)\n\tif err != nil {\n\t\tlog.Printf(err.Error())\n\t\terrList[\"no_user\"] = \"No user found\"\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\": errList,\n\t\t})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"response\": userPoints,\n\t})\n}", "func (mr *MockOrderRepositoryMockRecorder) FindAllOrdersByUserID(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"FindAllOrdersByUserID\", reflect.TypeOf((*MockOrderRepository)(nil).FindAllOrdersByUserID), arg0)\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 (mr *MockDatabaseMockRecorder) GetUserByGitSourceNameAndID(gitSourceName, id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByGitSourceNameAndID\", reflect.TypeOf((*MockDatabase)(nil).GetUserByGitSourceNameAndID), gitSourceName, id)\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUsername(arg0 string) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUsername\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetUser(qy db.Queryer, userid int64) (*User, error) {\n\treturn GetUserWithID(qy, userid)\n}", "func (m *MockDatabase) LoadUserID(ID string) (general.User, error) {\n\targs := m.Called(ID)\n\treturn args.Get(0).(general.User), args.Error(1)\n}", "func (d *DynamoDB)GetUser(id string) (models.User, error){\n\tfmt.Printf(logRoot + \"Searching %v table for user with id:%v\\n\", userTable, id)\n\tfmt.Println(\"UNIMPLEMENTED\")\n\treturn models.User{}, nil\n}", "func UserIDNotIn(vs ...int) predicate.User {\n\treturn predicate.User(sql.FieldNotIn(FieldUserID, vs...))\n}", "func TestClientUserInfoBadUser(t *testing.T) {\n\tusername := \"mdlayher\"\n\tc, done := userInfoTestClient(t, func(t *testing.T, w http.ResponseWriter, r *http.Request) {\n\t\tpath := \"/v4/user/info/\" + username + \"/\"\n\t\tif p := r.URL.Path; p != path {\n\t\t\tt.Fatalf(\"unexpected URL path: %q != %q\", p, path)\n\t\t}\n\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tw.Write(invalidUserErrJSON)\n\t})\n\tdefer done()\n\n\t_, _, err := c.User.Info(username, false)\n\tassertInvalidUserErr(t, err)\n}", "func GetUserOrUnexpected(c appengine.Context, w http.ResponseWriter,\n\tr *http.Request) (*user.User, bool) {\n\n\t// Get the current user.\n\tu := user.Current(c)\n\tif u == nil {\n\t\tLogAndUnexpected(c, w, r,\n\t\t\tfmt.Errorf(\"no user found, but auth is required.\"))\n\t\treturn nil, false\n\t}\n\n\treturn u, true\n\n}", "func (o *ViewUserUtilization) GetUserIdOk() (*int32, bool) {\n\tif o == nil || o.UserId == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UserId, true\n}", "func GetUserID(r *http.Request) string {\n\treturn strx.Or(r.Header.Get(\"X-User\"), r.Header.Get(\"X-User-Id\"))\n}", "func IsUserNotFound(err error) bool {\n\treturn internal.HasErrorCode(err, userNotFound)\n}", "func GetUser(db sqlx.Queryer, id int64) (User, error) {\n\tvar user User\n\terr := sqlx.Get(db, &user, \"select \"+externalUserFields+\" from \\\"user\\\" where id = $1\", id)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn user, ErrDoesNotExist\n\t\t}\n\t\treturn user, errors.Wrap(err, \"select error\")\n\t}\n\n\treturn user, nil\n}", "func TestGetUserService (t *testing.T){\n\tuser1, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user1)\n\n\tuser2, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user2)\n\n\tuser3, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user3)\n\n\tuser4, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user4)\n}", "func UserID(generator *Generator) Criterion {\n\treturn userCriterion{g: generator}\n}", "func getUser(req *http.Request) *grepbook.User {\n\tif rv := context.Get(req, UserKeyName); rv != nil {\n\t\tres := rv.(*grepbook.User)\n\t\treturn res\n\t}\n\treturn nil\n}", "func MustGetUserInfo(r *http.Request) store.User {\n\tuser, err := GetUserInfo(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn user\n}", "func (pr *Preemption) QueryUserID() *UserQuery {\n\treturn (&PreemptionClient{config: pr.config}).QueryUserID(pr)\n}", "func (mr *MockIDbMockRecorder) GetProductsByUserFilter(filter interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetProductsByUserFilter\", reflect.TypeOf((*MockIDb)(nil).GetProductsByUserFilter), filter)\n}", "func (u userDao) GetUser(userID int64) (*User, *utils.ApplicationError) {\n\tlog.Println(\"We are accessing the Database\")\n\tif user := users[userID]; user != nil {\n\t\treturn user, nil\n\t}\n\n\treturn nil, &utils.ApplicationError{\n\t\tMessage: fmt.Sprintf(\"user %v was not found\", userID),\n\t\tStatusCode: http.StatusNotFound,\n\t\tCode: \"Not found\",\n\t}\n}", "func UserID(ctx *context.APIContext) int64 {\n\tif ctx.User == nil {\n\t\treturn 0\n\t}\n\treturn ctx.User.ID\n}", "func (w *ServerInterfaceWrapper) GetUser(ctx echo.Context) error {\n\tvar err error\n\t// ------------- Path parameter \"id\" -------------\n\tvar id string\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\t// HasSecurity is set\n\n\tctx.Set(\"OpenId.Scopes\", []string{\"exitus/user.read\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetUser(ctx, id)\n\treturn err\n}", "func (mr *MockStoreMockRecorder) GetUserByEmail(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserByEmail\", reflect.TypeOf((*MockStore)(nil).GetUserByEmail), arg0, arg1)\n}", "func (f *FlightLogApi) getUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\n\tuserid := vars[\"id\"]\n\n\tlog.Printf(\"Get user for ID: %v\", userid)\n\n\tif len(userid) > 0 {\n\t\tvar user common.User\n\n\t\t// If it does not work\n\t\tif err := f.service.GetUser(userid, &user); err != nil {\n\t\t\tlog.Printf(\"Unable to get userId: %s, got error %v\", userid, err)\n\t\t\tjsend.FormatResponse(w, \"Unable to fetch user\", jsend.InternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Println(user)\n\n\t\t// If it worked\n\t\tif &user == nil {\n\t\t\tlog.Println(\"this was wrong\")\n\t\t\tjsend.FormatResponse(w, nil, jsend.NoContent)\n\t\t\treturn\n\t\t}\n\n\t\tjsend.FormatResponse(w, &user, jsend.Success)\n\t\treturn\n\t}\n\n\t// The userId is empty\n\tjsend.FormatResponse(w, \"No userid given. uid-parameter must be set\", jsend.BadRequest)\n}" ]
[ "0.6836436", "0.6559179", "0.65139097", "0.63091433", "0.6263295", "0.622489", "0.62192273", "0.6161417", "0.611775", "0.6093823", "0.6064132", "0.60126424", "0.59587145", "0.59397334", "0.58930707", "0.5874747", "0.58372027", "0.58258766", "0.5822576", "0.5822036", "0.57947725", "0.5768465", "0.5761387", "0.57608277", "0.5750448", "0.573289", "0.56965154", "0.5673579", "0.56688446", "0.5666171", "0.5666171", "0.5665133", "0.56548107", "0.56356084", "0.5632207", "0.56122756", "0.56122756", "0.56032383", "0.5599892", "0.55837166", "0.55783087", "0.55677074", "0.5567636", "0.5561946", "0.5560953", "0.55297375", "0.5522568", "0.5515846", "0.5513864", "0.5508127", "0.55065894", "0.5496177", "0.54907024", "0.5480543", "0.54679096", "0.54475874", "0.543345", "0.54122806", "0.5410666", "0.5393171", "0.53878355", "0.5386478", "0.53821355", "0.53794366", "0.5368648", "0.5363167", "0.53438914", "0.5341111", "0.5337559", "0.53278494", "0.5319154", "0.5305652", "0.5289785", "0.528496", "0.5284481", "0.52833074", "0.5280763", "0.5278069", "0.52764434", "0.5274502", "0.5271881", "0.52691555", "0.52639717", "0.5260371", "0.5258024", "0.5257204", "0.5256678", "0.5256661", "0.5253306", "0.5248251", "0.5244998", "0.5244559", "0.5241429", "0.5238804", "0.52362674", "0.5236101", "0.5222135", "0.5216939", "0.52101976", "0.5209342" ]
0.75357175
0
GetUsersWhereUserIDs mocks base method
func (m *MockUserRepositoryInterface) GetUsersWhereUserIDs(arg0 []uint64) ([]*db.User, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetUsersWhereUserIDs", arg0) ret0, _ := ret[0].([]*db.User) ret1, _ := ret[1].(error) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockRepository) GetUsersFromIDs(arg0 []uuid.UUID) ([]user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersFromIDs\", arg0)\n\tret0, _ := ret[0].([]user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestSelectUsersByIdsArray(t *testing.T) {\n\tdb, mock, repo := initUserTest(t)\n\tdefer db.Close()\n\n\t// Mock DB statements and execute\n\trows := getUserRows()\n\tmock.ExpectPrepare(\"^SELECT (.+) FROM users WHERE id IN (.+)\").\n\t\tExpectQuery().\n\t\tWillReturnRows(rows)\n\tgot, err := repo.SelectByIds(testUtils.Context, []uint{1})\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %v\", err)\n\t}\n\n\t// Validate results\n\twant := map[uint]domains.User{\n\t\t1: getUser(),\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"Values not equal: got = %v, want = %v\", got, want)\n\t}\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"Unfulfilled expectations: %s\", err)\n\t}\n}", "func (m *MockDatabase) GetUsersID() ([]uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersID\")\n\tret0, _ := ret[0].([]uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) FindUsersWithIds(ctx context.Context, ids []string) ([]*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindUsersWithIds\", ctx, ids)\n\tret0, _ := ret[0].([]*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) GetUsersForRole(arg0 string, arg1 ...string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetUsersForRole\", varargs...)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetUsersByIDs(userIDs []int64) map[int64]*domain.User {\n\tuserMap := map[int64]*domain.User{}\n\tfor _, userID := range userIDs {\n\t\tuser, ok := MockData[userID]\n\t\tif ok {\n\t\t\tuserMap[userID] = &user\n\t\t}\n\t}\n\treturn userMap\n}", "func (m *MockDatabase) GetUsersIDByGitSourceName(gitSourceName string) ([]uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersIDByGitSourceName\", gitSourceName)\n\tret0, _ := ret[0].([]uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDataSource) GetUsers() ([]model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsers\")\n\tret0, _ := ret[0].([]model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockOrderRepository) FindAllOrdersByUserID(arg0 int) (models.Orders, error) {\n\tret := m.ctrl.Call(m, \"FindAllOrdersByUserID\", arg0)\n\tret0, _ := ret[0].(models.Orders)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIUserRepository) GetUsers() []*model.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsers\")\n\tret0, _ := ret[0].([]*model.User)\n\treturn ret0\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUserID(arg0 uint64) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUserID\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAnonymous) GetUsersInChannel(arg0, arg1 string, arg2, arg3 int) ([]*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersInChannel\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].([]*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPersister) GetUsers() (MultipleUsers, error) {\n\tret := m.ctrl.Call(m, \"GetUsers\")\n\tret0, _ := ret[0].(MultipleUsers)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockUserRepositoryProvider) FindUsers(sb *UserSearchBuilder) ([]model.User, int, int, error) {\n\tret := _m.Called(sb)\n\n\tvar r0 []model.User\n\tif rf, ok := ret.Get(0).(func(*UserSearchBuilder) []model.User); ok {\n\t\tr0 = rf(sb)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]model.User)\n\t\t}\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(*UserSearchBuilder) int); ok {\n\t\tr1 = rf(sb)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 int\n\tif rf, ok := ret.Get(2).(func(*UserSearchBuilder) int); ok {\n\t\tr2 = rf(sb)\n\t} else {\n\t\tr2 = ret.Get(2).(int)\n\t}\n\n\tvar r3 error\n\tif rf, ok := ret.Get(3).(func(*UserSearchBuilder) error); ok {\n\t\tr3 = rf(sb)\n\t} else {\n\t\tr3 = ret.Error(3)\n\t}\n\n\treturn r0, r1, r2, r3\n}", "func (m *MockIDistributedEnforcer) GetUsersForRoleInDomain(arg0, arg1 string) []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersForRoleInDomain\", arg0, arg1)\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func TestSelectUsersByAccountId(t *testing.T) {\n\tdb, mock, repo := initUserTest(t)\n\tdefer db.Close()\n\n\t// Mock DB statements and execute\n\trows := getUserRows()\n\tmock.ExpectPrepare(\"^SELECT (.+) FROM users WHERE account_id=?\").\n\t\tExpectQuery().\n\t\tWithArgs(2).\n\t\tWillReturnRows(rows)\n\tgot, err := repo.SelectByAccountId(testUtils.Context, 2)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %v\", err)\n\t}\n\n\t// Validate results\n\twant := []domains.User{getUser()}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"Values not equal: got = %v, want = %v\", got, want)\n\t}\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"Unfulfilled expectations: %s\", err)\n\t}\n}", "func (m *MockIDb) GetProductsByUserFilter(filter model.FilterUProduct) ([]model.UserProduct, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetProductsByUserFilter\", filter)\n\tret0, _ := ret[0].([]model.UserProduct)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *TeamStore) GetCommonTeamIDsForTwoUsers(userID string, otherUserID string) ([]string, error) {\n\tret := _m.Called(userID, otherUserID)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(string, string) []string); ok {\n\t\tr0 = rf(userID, otherUserID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, string) error); ok {\n\t\tr1 = rf(userID, otherUserID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserRepository) FindUsers() ([]easyalert.User, error) {\n\tret := m.ctrl.Call(m, \"FindUsers\")\n\tret0, _ := ret[0].([]easyalert.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *TeamStore) GetUserTeamIds(userID string, allowFromCache bool) ([]string, error) {\n\tret := _m.Called(userID, allowFromCache)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(string, bool) []string); ok {\n\t\tr0 = rf(userID, allowFromCache)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, bool) error); ok {\n\t\tr1 = rf(userID, allowFromCache)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockTx) GetUsers() ([]*model.User, error) {\n\tret := _m.Called()\n\n\tvar r0 []*model.User\n\tif rf, ok := ret.Get(0).(func() []*model.User); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*model.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserClient) GetUsers(ctx context.Context, in *pb.UserRequest, opts ...grpc.CallOption) (*pb.UsersReply, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetUsers\", varargs...)\n\tret0, _ := ret[0].(*pb.UsersReply)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (h *Harness) WaitAndAssertOnCallUsers(serviceID string, userIDs ...string) {\n\th.t.Helper()\n\tdoQL := func(query string, res interface{}) {\n\t\tg := h.GraphQLQuery2(query)\n\t\tfor _, err := range g.Errors {\n\t\t\th.t.Error(\"GraphQL Error:\", err.Message)\n\t\t}\n\t\tif len(g.Errors) > 0 {\n\t\t\th.t.Fatal(\"errors returned from GraphQL\")\n\t\t}\n\t\tif res == nil {\n\t\t\treturn\n\t\t}\n\t\terr := json.Unmarshal(g.Data, &res)\n\t\tif err != nil {\n\t\t\th.t.Fatal(\"failed to parse response:\", err)\n\t\t}\n\t}\n\n\tgetUsers := func() []string {\n\t\tvar result struct {\n\t\t\tService struct {\n\t\t\t\tOnCallUsers []struct {\n\t\t\t\t\tUserID string\n\t\t\t\t\tUserName string\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdoQL(fmt.Sprintf(`\n\t\t\tquery{\n\t\t\t\tservice(id: \"%s\"){\n\t\t\t\t\tonCallUsers{\n\t\t\t\t\t\tuserID\n\t\t\t\t\t\tuserName\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`, serviceID), &result)\n\n\t\tvar ids []string\n\t\tfor _, oc := range result.Service.OnCallUsers {\n\t\t\tids = append(ids, oc.UserID)\n\t\t}\n\t\tif len(ids) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tsort.Strings(ids)\n\t\tuniq := ids[:1]\n\t\tlast := ids[0]\n\t\tfor _, id := range ids[1:] {\n\t\t\tif id == last {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tuniq = append(uniq, id)\n\t\t\tlast = id\n\t\t}\n\t\treturn uniq\n\t}\n\tsort.Strings(userIDs)\n\tmatch := func(final bool) bool {\n\t\tids := getUsers()\n\t\tif len(ids) != len(userIDs) {\n\t\t\tif final {\n\t\t\t\th.t.Fatalf(\"got %d on-call users; want %d\", len(ids), len(userIDs))\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\tfor i, id := range userIDs {\n\t\t\tif ids[i] != id {\n\t\t\t\tif final {\n\t\t\t\t\th.t.Fatalf(\"on-call[%d] = %s; want %s\", i, ids[i], id)\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\th.Trigger() // run engine cycle\n\n\tmatch(true) // assert result\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 (m *MockUserStore) BySet(arg0 context.Context, arg1 *sql.Tx, arg2 string) ([]*proto.User, error) {\n\tret := m.ctrl.Call(m, \"BySet\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]*proto.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *QueryResolver) Users(ctx context.Context, where *prisma.UserWhereInput, orderBy *prisma.UserOrderByInput, skip *int, after *string, before *string, first *int, last *int) ([]*prisma.User, error) {\n\tret := _m.Called(ctx, where, orderBy, skip, after, before, first, last)\n\n\tvar r0 []*prisma.User\n\tif rf, ok := ret.Get(0).(func(context.Context, *prisma.UserWhereInput, *prisma.UserOrderByInput, *int, *string, *string, *int, *int) []*prisma.User); ok {\n\t\tr0 = rf(ctx, where, orderBy, skip, after, before, first, last)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*prisma.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, *prisma.UserWhereInput, *prisma.UserOrderByInput, *int, *string, *string, *int, *int) error); ok {\n\t\tr1 = rf(ctx, where, orderBy, skip, after, before, first, last)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserServer) GetUsers(arg0 context.Context, arg1 *pb.UserRequest) (*pb.UsersReply, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsers\", arg0, arg1)\n\tret0, _ := ret[0].(*pb.UsersReply)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func getUsers(githubAccessToken string, githubOrganization string, githubTeams string) []githubUser {\n\n\tvar users = make([]githubUser, 0)\n\n\tctx := context.Background()\n\tgithubClient := getGithubClient(ctx, githubAccessToken)\n\tteamsIds := getTeamsIds(ctx, githubClient, githubOrganization, githubTeams)\n\tfor _, teamId := range teamsIds {\n\t\tusers = append(users, getTeamUsers(ctx, githubClient, teamId, users)...)\n\t}\n\treturn users\n}", "func getTeamUsers(context context.Context, githubClient github.Client, teamId int64, actualUsers []githubUser) []githubUser {\n\n\tvar users = make([]githubUser, 0)\n\n\tmembers, _, err := githubClient.Teams.ListTeamMembers(context, teamId, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %s\", err)\n\t}\n\tfor _, member := range members {\n\t\tif !usersContain(actualUsers, *member.Login) {\n\t\t\tvar user githubUser\n\t\t\tuser.keys = make([]string, 0)\n\t\t\tuser.name = *member.Login\n\t\t\tkeys, _, err := githubClient.Users.ListKeys(context, *member.Login, nil)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Error: %s\", err)\n\t\t\t}\n\t\t\tfor _, key := range keys {\n\t\t\t\tuser.keys = append(user.keys, *key.Key)\n\t\t\t}\n\t\t\tusers = append(users, user)\n\t\t}\n\t}\n\treturn users\n}", "func (m *MockIUserRepository) GetActiveUsers() []*model.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetActiveUsers\")\n\tret0, _ := ret[0].([]*model.User)\n\treturn ret0\n}", "func (m *MockManager) ListUsers() (map[string]string, error) {\n\tret := m.ctrl.Call(m, \"ListUsers\")\n\tret0, _ := ret[0].(map[string]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Client) SearchUsers(arg0 context.Context, arg1 *zendesk.SearchUsersOptions) ([]zendesk.User, zendesk.Page, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SearchUsers\", arg0, arg1)\n\tret0, _ := ret[0].([]zendesk.User)\n\tret1, _ := ret[1].(zendesk.Page)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockProduct) GetConcurrentUsersByDay(arg0 context.Context, arg1 db.GetConcurrentUsersByDayParams) ([]db.GetConcurrentUsersByDayRow, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetConcurrentUsersByDay\", arg0, arg1)\n\tret0, _ := ret[0].([]db.GetConcurrentUsersByDayRow)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) GetImplicitUsersForPermission(arg0 ...string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetImplicitUsersForPermission\", varargs...)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Repository) GetAllByUserID(arg0 context.Context, arg1 int64) ([]*models.Task, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllByUserID\", arg0, arg1)\n\tret0, _ := ret[0].([]*models.Task)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func UserIDs(generator *Generator) Criterion {\n\treturn usersCriterion{g: generator}\n}", "func TestListUsers(t *testing.T) {\n\n\t// Get all users (we should have at least one)\n\tresults, err := FindAll(Query())\n\tif err != nil {\n\t\tt.Fatalf(\"users: List no user found :%s\", err)\n\t}\n\n\tif len(results) < 1 {\n\t\tt.Fatalf(\"users: List no users found :%s\", err)\n\t}\n\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 (m *MockIUserService) QueryUsersByName(name string) ([]model.UserDB, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryUsersByName\", name)\n\tret0, _ := ret[0].([]model.UserDB)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockManager) UsersByID() (map[string]uaac.User, error) {\n\tret := m.ctrl.Call(m, \"UsersByID\")\n\tret0, _ := ret[0].(map[string]uaac.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockrepoProvider) FindAll(arg0 context.Context) ([]*types.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindAll\", arg0)\n\tret0, _ := ret[0].([]*types.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mock *RepositoryMock) UserGetByEmailCalls() []struct {\n\tCtx context.Context\n\tEmail string\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tEmail string\n\t}\n\tlockRepositoryMockUserGetByEmail.RLock()\n\tcalls = mock.calls.UserGetByEmail\n\tlockRepositoryMockUserGetByEmail.RUnlock()\n\treturn calls\n}", "func (m *MockUCCodeHubI) GetUserStaredList(repoID, limit, offset int64) (models.UserSet, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserStaredList\", repoID, limit, offset)\n\tret0, _ := ret[0].(models.UserSet)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserUsecase) GetAll() ([]*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAll\")\n\tret0, _ := ret[0].([]*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetUsers(c router.Context) (interface{}, error) {\n\t// get the data from the request and parse it as structure\n\tdata := c.Param(`data`).(UserId)\n\n\t// Validate the inputed data\n\terr := data.Validate()\n\tif err != nil {\n\t\tif _, ok := err.(validation.InternalError); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, status.ErrStatusUnprocessableEntity.WithValidationError(err.(validation.Errors))\n\t}\n\tstub := c.Stub()\n\tqueryString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"_id\\\":{\\\"$ne\\\":\\\"%s\\\"},\\\"doc_type\\\":\\\"%s\\\"}}\", data.ID, utils.DocTypeUser)\n\tresultsIterator, err := stub.GetQueryResult(queryString)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, status.ErrInternal.WithError(err)\n\t}\n\n\tdefer resultsIterator.Close()\n\n\t// buffer is a JSON array containing QueryResults\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"{\")\n\tbuffer.WriteString(\"\\\"users\\\": [\")\n\taArrayMemberAlreadyWritten := false\n\tfor resultsIterator.HasNext() {\n\t\tqueryResponse, err2 := resultsIterator.Next()\n\t\tif err2 != nil {\n\t\t\treturn nil, status.ErrInternal.WithError(err2)\n\t\t}\n\n\t\t// Add a comma before array members, suppress it for the first array member\n\t\tif aArrayMemberAlreadyWritten == true {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t\tuserData := UserResponse{}\n\t\terr3 := json.Unmarshal(queryResponse.Value, &userData)\n\t\tif err3 != nil {\n\t\t\treturn nil, status.ErrInternal.WithError(err3)\n\t\t}\n\n\t\tuserData.ID = queryResponse.Key\n\t\tuserDataBytes, _ := json.Marshal(userData)\n\n\t\tbuffer.WriteString(string(userDataBytes))\n\t\taArrayMemberAlreadyWritten = true\n\t}\n\tbuffer.WriteString(\"]}\")\n\n\t//return the response\n\treturn buffer.Bytes(), nil\n}", "func GetUsers(c *gin.Context) {\n\n\tlog := logger.WithFields(logrus.Fields{\"tag\": \"GetUsers\"})\n\tlog.Info(\"Fetching users\")\n\n\torganization := auth.GetCurrentOrganization(c.Request)\n\n\tidParam := c.Param(\"id\")\n\tid, err := strconv.ParseUint(idParam, 10, 32)\n\tif idParam != \"\" && err != nil {\n\t\tmessage := fmt.Sprintf(\"error parsing user id: %s\", err)\n\t\tlog.Info(message)\n\t\tc.JSON(http.StatusBadRequest, components.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: message,\n\t\t\tError: message,\n\t\t})\n\t\treturn\n\t}\n\n\tvar users []auth.User\n\tdb := model.GetDB()\n\terr = db.Model(organization).Related(&users, \"Users\").Error\n\tif err != nil {\n\t\tmessage := \"failed to fetch users\"\n\t\tlog.Info(message + \": \" + err.Error())\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, components.ErrorResponse{\n\t\t\tCode: http.StatusInternalServerError,\n\t\t\tMessage: message,\n\t\t\tError: message,\n\t\t})\n\t} else if id == 0 {\n\t\tc.JSON(http.StatusOK, users)\n\t} else if len(users) == 1 {\n\t\tc.JSON(http.StatusOK, users[0])\n\t} else if len(users) > 1 {\n\t\tmessage := fmt.Sprintf(\"multiple users found with id: %d\", id)\n\t\tlog.Info(message)\n\t\tc.AbortWithStatusJSON(http.StatusConflict, components.ErrorResponse{\n\t\t\tCode: http.StatusConflict,\n\t\t\tMessage: message,\n\t\t\tError: message,\n\t\t})\n\t} else {\n\t\tmessage := fmt.Sprintf(\"user not found with id: %d\", id)\n\t\tlog.Info(message)\n\t\tc.AbortWithStatusJSON(http.StatusNotFound, components.ErrorResponse{\n\t\t\tCode: http.StatusNotFound,\n\t\t\tMessage: message,\n\t\t\tError: message,\n\t\t})\n\t}\n}", "func (mr *MockUserRepositoryInterfaceMockRecorder) GetUsersWhereUserIDs(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsersWhereUserIDs\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUsersWhereUserIDs), arg0)\n}", "func (m *MockClient) ListUsers(arg0 *iam.ListUsersInput) (*iam.ListUsersOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListUsers\", arg0)\n\tret0, _ := ret[0].(*iam.ListUsersOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mock *RepositoryMock) GetUserProductAffinitiesByUserIDCalls() []struct {\n\tCtx context.Context\n\tUserID int64\n\tOptions GetUserProductAffinitiesByUserIDOptions\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tUserID int64\n\t\tOptions GetUserProductAffinitiesByUserIDOptions\n\t}\n\tlockRepositoryMockGetUserProductAffinitiesByUserID.RLock()\n\tcalls = mock.calls.GetUserProductAffinitiesByUserID\n\tlockRepositoryMockGetUserProductAffinitiesByUserID.RUnlock()\n\treturn calls\n}", "func TestGetUsersByAccessID(t *testing.T) {\r\n\tlog.Printf(\"--------------------------------------------------------\")\r\n\ttrace2()\r\n\tfmt.Println(nameOf((*A).Method))\r\n\tlog.Printf(\"--------------------------------------------------------\")\r\n\tmyDB := db.Connect()\r\n\tmyUser := &Video{}\r\n\tvideoUsersAccess, errTest := myUser.GetUsersByAccessID(myDB, 2)\r\n\tif errTest != nil {\r\n\t\tlog.Printf(\" Test Failed in TestGetUsersBySensorID: %v\", errTest)\r\n\t\tlog.Printf(\" %v\", videoUsersAccess)\r\n\t\treturn\r\n\t}\r\n\tlog.Printf(\"%d users found inside TestGetUsersByAccessID()\", len(videoUsersAccess))\r\n\tfor i := 0; i < len(videoUsersAccess); i++ {\r\n\t\tlog.Printf(\" %v\\n\", videoUsersAccess[i])\r\n\t}\r\n\r\n}", "func getUsersHandler(c *gin.Context) {\n\tuser, _ := c.Get(JwtIdentityKey)\n\n\t// Role check.\n\tif !isAdmin(user) {\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\"message\": \"unauthorized\"})\n\t\treturn\n\t}\n\n\tpage := c.DefaultQuery(\"page\", \"1\")\n\tcount := c.DefaultQuery(\"count\", \"10\")\n\tpageInt, _ := strconv.Atoi(page)\n\tcountInt, _ := strconv.Atoi(count)\n\n\tif page == \"0\" {\n\t\tpageInt = 1\n\t}\n\n\tvar wg sync.WaitGroup\n\tvar users *[]types.User\n\tvar usersCount int\n\n\tdb := data.New()\n\twg.Add(1)\n\tgo func() {\n\t\tusers = db.Users.GetUsers((pageInt-1)*countInt, countInt)\n\t\twg.Done()\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tusersCount = db.Users.GetUsersCount()\n\t\twg.Done()\n\t}()\n\twg.Wait()\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"code\": http.StatusOK,\n\t\t\"users\": users,\n\t\t\"count\": usersCount,\n\t})\n}", "func (m *MockProduct) GetConcurrentNominativeUsersBySwidTag(arg0 context.Context, arg1 db.GetConcurrentNominativeUsersBySwidTagParams) ([]db.GetConcurrentNominativeUsersBySwidTagRow, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetConcurrentNominativeUsersBySwidTag\", arg0, arg1)\n\tret0, _ := ret[0].([]db.GetConcurrentNominativeUsersBySwidTagRow)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepo) FindAll() ([]app.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindAll\")\n\tret0, _ := ret[0].([]app.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *TeamStore) GetMembersByIds(teamID string, userIds []string, restrictions *model.ViewUsersRestrictions) ([]*model.TeamMember, error) {\n\tret := _m.Called(teamID, userIds, restrictions)\n\n\tvar r0 []*model.TeamMember\n\tif rf, ok := ret.Get(0).(func(string, []string, *model.ViewUsersRestrictions) []*model.TeamMember); ok {\n\t\tr0 = rf(teamID, userIds, restrictions)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*model.TeamMember)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, []string, *model.ViewUsersRestrictions) error); ok {\n\t\tr1 = rf(teamID, userIds, restrictions)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUsername(arg0 string) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUsername\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Client) GetUsers(arg0 context.Context, arg1 *zendesk.UserListOptions) ([]zendesk.User, zendesk.Page, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsers\", arg0, arg1)\n\tret0, _ := ret[0].([]zendesk.User)\n\tret1, _ := ret[1].(zendesk.Page)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func TestListUser(t *testing.T) {\n\tctx := context.Background()\n\tconn, err := grpc.DialContext(ctx, \"\", grpc.WithInsecure(), grpc.WithContextDialer(bufDialer))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Close()\n\tclient := api.NewUserServiceClient(conn)\n\tuser1 := createUser(t, ctx, client, 0)\n\tuser2 := createUser(t, ctx, client, 0)\n\tuser3 := createUser(t, ctx, client, 0)\n\tuser4 := createUser(t, ctx, client, 0)\n\n\ttestCases := []struct {\n\t\tcaseName string\n\t\tlistUserRequest api.ListUserRequest\n\t\tresultLen int\n\t\tisPositive bool\n\t\terrCode codes.Code\n\t\terrMsg string\n\t}{\n\t\t{\n\t\t\tcaseName: \"ListUser: limit = 1, page = 1\",\n\t\t\tlistUserRequest: api.ListUserRequest{\n\t\t\t\tPageFilter: &api.PageFilter{\n\t\t\t\t\tLimit: 1,\n\t\t\t\t\tPage: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t\tresultLen: 1,\n\t\t\tisPositive: true,\n\t\t},\n\t\t{\n\t\t\tcaseName: \"ListUser: limit = 2, page = 1\",\n\t\t\tlistUserRequest: api.ListUserRequest{\n\t\t\t\tPageFilter: &api.PageFilter{\n\t\t\t\t\tLimit: 2,\n\t\t\t\t\tPage: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t\tresultLen: 2,\n\t\t\tisPositive: true,\n\t\t},\n\t\t{\n\t\t\tcaseName: \"ListUser: limit = 2, page = 2\",\n\t\t\tlistUserRequest: api.ListUserRequest{\n\t\t\t\tPageFilter: &api.PageFilter{\n\t\t\t\t\tLimit: 2,\n\t\t\t\t\tPage: 2,\n\t\t\t\t},\n\t\t\t},\n\t\t\tresultLen: 2,\n\t\t\tisPositive: true,\n\t\t},\n\t\t{\n\t\t\tcaseName: \"ListUser: limit = 2, page = 0\",\n\t\t\tlistUserRequest: api.ListUserRequest{\n\t\t\t\tPageFilter: &api.PageFilter{\n\t\t\t\t\tLimit: 2,\n\t\t\t\t\tPage: 0,\n\t\t\t\t},\n\t\t\t},\n\t\t\tisPositive: false,\n\t\t\terrMsg: \"page must be > 0, page = 0\",\n\t\t\terrCode: codes.InvalidArgument,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.caseName, func(t *testing.T) {\n\t\t\tusers, err := client.ListUser(ctx, &tc.listUserRequest)\n\t\t\tif tc.isPositive {\n\t\t\t\tassert.Empty(t, err)\n\t\t\t\tassert.Equal(t, tc.resultLen, len(users.Users))\n\t\t\t} else {\n\t\t\t\tassert.NotEmpty(t, err)\n\t\t\t\tfromError, _ := status.FromError(err)\n\t\t\t\tassert.Equal(t, tc.errCode, fromError.Code())\n\t\t\t\tassert.Equal(t, tc.errMsg, fromError.Message())\n\t\t\t}\n\t\t})\n\t}\n\tdeleteUser(t, ctx, client, user1.Id)\n\tdeleteUser(t, ctx, client, user2.Id)\n\tdeleteUser(t, ctx, client, user3.Id)\n\tdeleteUser(t, ctx, client, user4.Id)\n}", "func (_m *UserRepository) FindAllCustom() ([]domain.User, error) {\n\tret := _m.Called()\n\n\tvar r0 []domain.User\n\tif rf, ok := ret.Get(0).(func() []domain.User); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]domain.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (a UsersApi) GetUsers(pageSize int, pageNumber int, id []string, jabberId []string, sortOrder string, expand []string, integrationPresenceSource string, state string) (*Userentitylisting, *APIResponse, error) {\n\tvar httpMethod = \"GET\"\n\t// create path and map variables\n\tpath := a.Configuration.BasePath + \"/api/v2/users\"\n\tdefaultReturn := new(Userentitylisting)\n\tif true == false {\n\t\treturn defaultReturn, nil, errors.New(\"This message brought to you by the laws of physics being broken\")\n\t}\n\n\n\theaderParams := make(map[string]string)\n\tqueryParams := make(map[string]string)\n\tformParams := url.Values{}\n\tvar postBody interface{}\n\tvar postFileName string\n\tvar fileBytes []byte\n\t// authentication (PureCloud OAuth) required\n\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\t\n\tqueryParams[\"pageSize\"] = a.Configuration.APIClient.ParameterToString(pageSize, \"\")\n\t\n\tqueryParams[\"pageNumber\"] = a.Configuration.APIClient.ParameterToString(pageNumber, \"\")\n\t\n\tqueryParams[\"id\"] = a.Configuration.APIClient.ParameterToString(id, \"multi\")\n\t\n\tqueryParams[\"jabberId\"] = a.Configuration.APIClient.ParameterToString(jabberId, \"multi\")\n\t\n\tqueryParams[\"sortOrder\"] = a.Configuration.APIClient.ParameterToString(sortOrder, \"\")\n\t\n\tqueryParams[\"expand\"] = a.Configuration.APIClient.ParameterToString(expand, \"multi\")\n\t\n\tqueryParams[\"integrationPresenceSource\"] = a.Configuration.APIClient.ParameterToString(integrationPresenceSource, \"\")\n\t\n\tqueryParams[\"state\"] = a.Configuration.APIClient.ParameterToString(state, \"\")\n\t\n\n\t// Find an replace keys that were altered to avoid clashes with go keywords \n\tcorrectedQueryParams := make(map[string]string)\n\tfor k, v := range queryParams {\n\t\tif k == \"varType\" {\n\t\t\tcorrectedQueryParams[\"type\"] = v\n\t\t\tcontinue\n\t\t}\n\t\tcorrectedQueryParams[k] = v\n\t}\n\tqueryParams = correctedQueryParams\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\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\tvar successPayload *Userentitylisting\n\tresponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, postFileName, fileBytes)\n\tif err != nil {\n\t\t// Nothing special to do here, but do avoid processing the response\n\t} else if err == nil && response.Error != nil {\n\t\terr = errors.New(response.ErrorMessage)\n\t} else if response.HasBody {\n\t\tif \"Userentitylisting\" == \"string\" {\n\t\t\tcopy(response.RawBody, &successPayload)\n\t\t} else {\n\t\t\terr = json.Unmarshal(response.RawBody, &successPayload)\n\t\t}\n\t}\n\treturn successPayload, response, err\n}", "func (m *MockSiteRepo) GetEndpointsBySiteIDs(arg0 context.Context, arg1 string, arg2 []string) ([]gocql.UUID, error) {\n\tret := m.ctrl.Call(m, \"GetEndpointsBySiteIDs\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]gocql.UUID)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *ChannelStore) GetChannelsByUser(userID string, includeDeleted bool, lastDeleteAt int, pageSize int, fromChannelID string) (model.ChannelList, error) {\n\tret := _m.Called(userID, includeDeleted, lastDeleteAt, pageSize, fromChannelID)\n\n\tvar r0 model.ChannelList\n\tif rf, ok := ret.Get(0).(func(string, bool, int, int, string) model.ChannelList); ok {\n\t\tr0 = rf(userID, includeDeleted, lastDeleteAt, pageSize, fromChannelID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(model.ChannelList)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, bool, int, int, string) error); ok {\n\t\tr1 = rf(userID, includeDeleted, lastDeleteAt, pageSize, fromChannelID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUser) Index(filters ...UserFilter) (api.Users, error) {\n\tvarargs := []interface{}{}\n\tfor _, a := range filters {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Index\", varargs...)\n\tret0, _ := ret[0].(api.Users)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestPagination(t *testing.T) {\n\tts := NewTestServer(allowedAccessToken)\n\tdefer ts.Close()\n\n\tresp, _ := ts.Client.FindUsers(SearchRequest{\n\t\tLimit: 4,\n\t\tOffset: 0,\n\t})\n\n\tif len(resp.Users) != 4 {\n\t\tt.Errorf(\"invalid nums of users: %d\", len(resp.Users))\n\t\treturn\n\t}\n\n\tif resp.Users[3].Id != 3 {\n\t\tt.Errorf(\"invalid user at row 3: %v\", resp.Users[3])\n\t\treturn\n\t}\n\n\tresp, _ = ts.Client.FindUsers(SearchRequest{\n\t\tLimit: 6,\n\t\tOffset: 3,\n\t})\n\n\tif len(resp.Users) != 6 {\n\t\tt.Errorf(\"invalid number of users: %d\", len(resp.Users))\n\t\treturn\n\t}\n\n\tif resp.Users[0].Name != \"Everett Dillard\" {\n\t\tt.Errorf(\"invalid user at row 3: %v\", resp.Users[0])\n\t\treturn\n\t}\n}", "func (dp *dataProvider) GetUsersByIDs(users *models.Users) error {\n\tinUsers := *users\n\tids := make([]interface{}, len(*users))\n\tvar outUsers []*models.User\n\n\tfor idx, user := range inUsers {\n\t\tids[idx] = user.ID\n\t}\n\n\terr := dp.db.Model(&outUsers).\n\t\tWhere(\"id IN (?)\", types.In(ids)).\n\t\tSelect()\n\tif err != nil {\n\t\treturn wrapError(err)\n\t}\n\n\tif len(inUsers) != len(outUsers) {\n\t\treturn fmt.Errorf(\"could not find all users\")\n\t}\n\n\t// Make a map for fast ordering\n\toutUserMap := make(map[string]*models.User)\n\tfor _, user := range outUsers {\n\t\toutUserMap[user.ID] = user\n\t}\n\n\t// Order outUsers based on input ID ordering\n\tfor idx, user := range inUsers {\n\t\toutUser, ok := outUserMap[user.ID]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"could not find all users\")\n\t\t}\n\t\tinUsers[idx] = outUser\n\t}\n\treturn nil\n}", "func (_m *MockStore) GetUsersBasicRoles(ctx context.Context, userFilter []int64, orgID int64) (map[int64][]string, error) {\n\tret := _m.Called(ctx, userFilter, orgID)\n\n\tvar r0 map[int64][]string\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, []int64, int64) (map[int64][]string, error)); ok {\n\t\treturn rf(ctx, userFilter, orgID)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, []int64, int64) map[int64][]string); ok {\n\t\tr0 = rf(ctx, userFilter, orgID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[int64][]string)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, []int64, int64) error); ok {\n\t\tr1 = rf(ctx, userFilter, orgID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (as *ActionSuite) TestUsersQuery() {\n\tt := as.T()\n\n\tf := fixturesForUserQuery(as)\n\n\ttype testCase struct {\n\t\tName string\n\t\tPayload string\n\t\tTestUser models.User\n\t\tExpectError bool\n\t\tTest func(t *testing.T)\n\t}\n\n\tvar resp UsersResponse\n\n\ttestCases := []testCase{\n\t\t{\n\t\t\tName: \"good\",\n\t\t\tPayload: \"{users {id nickname}}\",\n\t\t\tTestUser: f.Users[0],\n\t\t\tTest: func(t *testing.T) {\n\t\t\t\tas.Equal(2, len(resp.Users), \"incorrect number of users returned\")\n\t\t\t\tas.Equal(f.Users[0].UUID.String(), resp.Users[0].ID, \"incorrect ID\")\n\t\t\t\tas.Equal(f.Users[0].Nickname, resp.Users[0].Nickname, \"incorrect nickname\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"not allowed\",\n\t\t\tPayload: \"{users {id nickname}}\",\n\t\t\tTestUser: f.Users[1],\n\t\t\tTest: func(t *testing.T) {},\n\t\t\tExpectError: true,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\terr := as.testGqlQuery(test.Payload, test.TestUser.Nickname, &resp)\n\n\t\tif test.ExpectError {\n\t\t\tas.Error(err)\n\t\t} else {\n\t\t\tas.NoError(err)\n\t\t}\n\t\tt.Run(test.Name, test.Test)\n\t}\n}", "func TestGetUserService (t *testing.T){\n\tuser1, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user1)\n\n\tuser2, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user2)\n\n\tuser3, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user3)\n\n\tuser4, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user4)\n}", "func TestFindUserById(t *testing.T) {\n\t_, mock, err := NewMock()\n\tif err != nil {\n\t\tfmt.Printf(\"error mock: \" + err.Error())\n\t}\n\n\t// simulate any sql driver behavior in tests, without needing a real database connection\n\tquery := \"select id, user_name, password from m_user where id = \\\\?\"\n\n\trows := sqlmock.NewRows([]string{\"id\", \"user_name\", \"password\"}).\n\t\tAddRow(user.ID, user.UserName, user.Password)\n\n\tmock.ExpectQuery(query).WithArgs(user.ID).WillReturnRows(rows)\n\t// ------------ end of mock ---------------\n\n\tassert.NotNil(t, user)\n}", "func (m_2 *MockUserUsecaser) List(c context.Context, m *model.User) (model.Users, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"List\", c, m)\n\tret0, _ := ret[0].(model.Users)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetList(limit, offset int) ([]entity.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetList\", limit, offset)\n\tret0, _ := ret[0].([]entity.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *ChannelStore) GetMembersByIds(channelID string, userIds []string) (model.ChannelMembers, error) {\n\tret := _m.Called(channelID, userIds)\n\n\tvar r0 model.ChannelMembers\n\tif rf, ok := ret.Get(0).(func(string, []string) model.ChannelMembers); ok {\n\t\tr0 = rf(channelID, userIds)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(model.ChannelMembers)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, []string) error); ok {\n\t\tr1 = rf(channelID, userIds)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m_2 *MockUserRepository) List(m *model.User) (model.Users, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"List\", m)\n\tret0, _ := ret[0].(model.Users)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetUser(t *testing.T) {\n\ttests := []struct {\n\t\tid int64\n\t\texceptResult *schedule.User\n\t}{\n\t\t{1, &schedule.User{ID: 1}},\n\t}\n\n\tfor _, test := range tests {\n\t\tr, err := ss.GetUser(ctx, test.id)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"GetUser(%d) fail, err %s, result %+v\", test.id, err, r)\n\t\t\treturn\n\t\t}\n\n\t\tif r.ID != test.exceptResult.ID {\n\t\t\tt.Errorf(\"GetUser(%d) = %+v, except %+v\", test.id, r, test.exceptResult)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (apiContext Context) UsersGet(w http.ResponseWriter, r *http.Request) {\n\n\t// Get context variables.\n\tmodelContext := context.Get(r, \"modelContext\").(model.Context)\n\n\t// Extract query parameters.\n\tquery := r.URL.Query()\n\tidStr := query.Get(\"id\")\n\tstatus := query.Get(\"status\")\n\tcursor := query.Get(\"cursor\")\n\tlimitStr := query.Get(\"limit\")\n\torderBy := query.Get(\"order-by\")\n\torder := query.Get(\"order\")\n\n\t// Parse non-string parametes.\n\tid := []string{}\n\tif idStr != \"\" {\n\t\tid = strings.Split(idStr, \",\")\n\t}\n\tlimit := 20\n\tif limitStr != \"\" {\n\t\tvar err error\n\t\tlimit, err = strconv.Atoi(limitStr)\n\t\tif err != nil {\n\t\t\tresponses.Context(apiContext).RespondWithError(w, r, http.StatusBadRequest, \"The 'limit' parameter is not a valid integer.\", errors.WithStack(err))\n\t\t\treturn\n\t\t}\n\t\tif limit < 1 {\n\t\t\tlimit = 1\n\t\t}\n\t\tif limit > 100 {\n\t\t\tlimit = 100\n\t\t}\n\t}\n\n\t// Build the filters map.\n\tvar filters = map[string]interface{}{}\n\tif len(id) > 0 {\n\t\tfilters[\"id\"] = id\n\t}\n\tif status != \"\" {\n\t\tfilters[\"status\"] = status\n\t}\n\n\t// Access model.\n\tresult, cm, err := modelContext.GetUsers(filters, limit, cursor, orderBy, order)\n\tif errors.Cause(err) == model.ErrBadInput {\n\t\tresponses.Context(apiContext).RespondWithError(w, r, http.StatusBadRequest, \"Parameters were wrong.\", errors.WithStack(err))\n\t\treturn\n\t} else if err != nil {\n\t\tresponses.Context(apiContext).RespondWithError(w, r, http.StatusInternalServerError, \"Something went wrong.\", errors.WithStack(err))\n\t\treturn\n\t}\n\n\t// We never return the user's password.\n\tfor i := 0; i < len(result); i++ {\n\t\tresult[i].PasswordHash = \"\"\n\t}\n\n\t// Build the response.\n\tvar response = map[string]interface{}{}\n\tresponse[\"data\"] = result\n\tresponse[\"metadata\"] = cm\n\n\t// Add the next link.\n\tresponse[\"links\"] = map[string]interface{}{\n\t\t\"next\": nil,\n\t}\n\tif cm.NextPageCursor != \"\" {\n\t\tquery = url.Values{}\n\t\tquery.Set(\"id\", strings.Join(id, \",\"))\n\t\tquery.Set(\"status\", status)\n\t\tquery.Set(\"limit\", strconv.Itoa(limit))\n\t\tquery.Set(\"order-by\", orderBy)\n\t\tquery.Set(\"order\", order)\n\t\tquery.Set(\"cursor\", cm.NextPageCursor)\n\t\tfor key := range query {\n\t\t\tif query.Get(key) == \"\" {\n\t\t\t\tquery.Del(key)\n\t\t\t}\n\t\t}\n\t\tnextURL := url.URL{\n\t\t\tScheme: \"http\",\n\t\t\tHost: r.Host,\n\t\t\tPath: r.URL.Path,\n\t\t\tRawQuery: query.Encode(),\n\t\t}\n\t\tresponse[\"links\"].(map[string]interface{})[\"next\"] = nextURL.String()\n\t}\n\n\t// Return response.\n\tresponses.RespondWithJSON(w, http.StatusOK, response)\n}", "func (m *MockDatabase) GetUserByGitSourceNameAndID(gitSourceName string, id uint64) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByGitSourceNameAndID\", gitSourceName, id)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (db *Store) getUsersForTeam(teamID string) ([]string, error) {\n\tsince := model.GetMillis() - period\n\n\tquery := db.sq.Select(\"U.Id\").\n\t\tFrom(\"Users AS U\").\n\t\tJoin(\"TeamMembers tm ON ( tm.UserId = U.Id AND tm.DeleteAt = 0 )\").Where(\"tm.TeamId = ?\", teamID).\n\t\tLeftJoin(\"Bots ON U.Id = Bots.UserId\").Where(\"Bots.UserId IS NULL\").\n\t\tLeftJoin(\"Posts AS P ON P.UserId = U.Id\").\n\t\tWhere(sq.Gt{\"P.CreateAt\": since}).\n\t\tWhere(sq.Eq{\"P.DeleteAt\": 0}).\n\t\tGroupBy(\"U.Id\").\n\t\tOrderBy(\"Count(P.Id) DESC\").\n\t\tLimit(userLimit)\n\n\trows, err := query.Query()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Can't query users\")\n\t}\n\tdefer rows.Close()\n\tusers := []string{}\n\tfor rows.Next() {\n\t\tvar userID string\n\t\tif err := rows.Scan(&userID); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tusers = append(users, userID)\n\t}\n\treturn users, nil\n}", "func GetUsers(db sqlx.Queryer, limit, offset int, search string) ([]User, error) {\n\tvar users []User\n\tif search != \"\" {\n\t\tsearch = \"%\" + search + \"%\"\n\t}\n\terr := sqlx.Select(db, &users, \"select \"+externalUserFields+` from \"user\" where ($3 != '' and username ilike $3) or ($3 = '') order by username limit $1 offset $2`, limit, offset, search)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"select error\")\n\t}\n\treturn users, nil\n}", "func (mr *MockRepositoryMockRecorder) GetUsersFromIDs(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsersFromIDs\", reflect.TypeOf((*MockRepository)(nil).GetUsersFromIDs), arg0)\n}", "func (_m *MockPermissionProvider) FindByUserID(userID int64) ([]*PermissionEntity, error) {\n\tret := _m.Called(userID)\n\n\tvar r0 []*PermissionEntity\n\tif rf, ok := ret.Get(0).(func(int64) []*PermissionEntity); ok {\n\t\tr0 = rf(userID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*PermissionEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64) error); ok {\n\t\tr1 = rf(userID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\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 (m *MockUCCodeHubI) GetAllMRUser(userID, limit, offset int64) (models.PullReqSet, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllMRUser\", userID, limit, offset)\n\tret0, _ := ret[0].(models.PullReqSet)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProduct) ListConcurrentUsers(arg0 context.Context, arg1 db.ListConcurrentUsersParams) ([]db.ListConcurrentUsersRow, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListConcurrentUsers\", arg0, arg1)\n\tret0, _ := ret[0].([]db.ListConcurrentUsersRow)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (ctlr *userServiceController) GetUsers(ctx context.Context, req *mygrpc.GetUsersRequest) (*mygrpc.GetUsersResponse, error) {\n\tresultMap := ctlr.userService.GetUsersByIDs(req.GetIds())\n\n\tresp := &mygrpc.GetUsersResponse{}\n\tfor _, u := range resultMap {\n\t\tresp.Users = append(resp.Users, marshalUser(u))\n\t}\n\treturn resp, nil\n}", "func (m *MockIDistributedEnforcer) GetRolesForUser(arg0 string, arg1 ...string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetRolesForUser\", varargs...)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) FindAll() (*entities.Users, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindAll\")\n\tret0, _ := ret[0].(*entities.Users)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockGroupProvider) FindByUserID(_a0 int64) ([]*GroupEntity, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 []*GroupEntity\n\tif rf, ok := ret.Get(0).(func(int64) []*GroupEntity); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*GroupEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockClient) Users() UsersService {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Users\")\n\tret0, _ := ret[0].(UsersService)\n\treturn ret0\n}", "func (m *MockStore) GetUserById(arg0 context.Context, arg1 uuid.UUID) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserById\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetUsers(ctx context.Context, req *pb.GetUserRequest) (*pb.GetUserResponse, error) {\n\tgetUserFunction := func(conn *grpc.ClientConn) (interface{}, error) {\n\t\tclient := pb.NewUserServiceClient(conn)\n\n\t\tmd1 := metadata.Pairs(\n\t\t\t\"X-Custom-orgname\", \"This is my Custom Header O_o Weird\",\n\t\t\t\"authorization\", \"bearer some_token_if8y3498eufhkfj\")\n\t\tctx := metadata.NewOutgoingContext(context.Background(), md1)\n\n\t\tresp, err := client.GetUser(ctx, req)\n\t\tif err != nil {\n\t\t\tentry.WithField(logrus.ErrorKey, err).Errorln(\"Error occurred while trying to Get Users Table\")\n\n\t\t\tst := status.Convert(err)\n\t\t\tfor _, detail := range st.Details() {\n\t\t\t\tswitch t := detail.(type) {\n\t\t\t\tcase *pb.Error:\n\t\t\t\t\tfmt.Println(\"Oops! Get request was rejected by the server.\")\n\t\t\t\t\tfmt.Printf(\"The %q field was wrong:\\n\", t.Message)\n\t\t\t\t\tfmt.Printf(\"\\t%d\\n\", t.Code)\n\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", t.Type)\n\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", t.DetailedMessage)\n\t\t\t\tdefault:\n\t\t\t\t\tfmt.Printf(\"Object found was %v with type %v\", detail, reflect.TypeOf(detail))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil, err\n\t\t}\n\t\treturn resp, nil\n\t}\n\tresp, err := SafeExecute(getUserFunction)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgetUserResponse, ok := resp.(*pb.GetUserResponse)\n\tif !ok {\n\t\treturn nil, errors.New(\"Could not cast response to get user\")\n\t}\n\treturn getUserResponse, nil\n}", "func (_m *TeamStore) GetTeamsByUserId(userID string) ([]*model.Team, error) {\n\tret := _m.Called(userID)\n\n\tvar r0 []*model.Team\n\tif rf, ok := ret.Get(0).(func(string) []*model.Team); ok {\n\t\tr0 = rf(userID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*model.Team)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(userID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (w *ServerInterfaceWrapper) GetUsers(ctx echo.Context) error {\n\tvar err error\n\n\tctx.Set(\"OAuth.Scopes\", []string{\"\"})\n\n\t// Parameter object where we will unmarshal all parameters from the context\n\tvar params GetUsersParams\n\t// ------------- Optional query parameter \"page_size\" -------------\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"page_size\", ctx.QueryParams(), &params.PageSize)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter page_size: %s\", err))\n\t}\n\n\t// ------------- Optional query parameter \"page_number\" -------------\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"page_number\", ctx.QueryParams(), &params.PageNumber)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter page_number: %s\", err))\n\t}\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetUsers(ctx, params)\n\treturn err\n}", "func (m *MockFeatureService) GetByIDs(arg0 context.Context, arg1 []uint) ([]entity.Feature, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByIDs\", arg0, arg1)\n\tret0, _ := ret[0].([]entity.Feature)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *UserRepository) FindAll() ([]domain.User, error) {\n\tret := _m.Called()\n\n\tvar r0 []domain.User\n\tif rf, ok := ret.Get(0).(func() []domain.User); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]domain.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *CognitoIdentityProviderAPI) ListUsers(_a0 *cognitoidentityprovider.ListUsersInput) (*cognitoidentityprovider.ListUsersOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *cognitoidentityprovider.ListUsersOutput\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.ListUsersInput) *cognitoidentityprovider.ListUsersOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*cognitoidentityprovider.ListUsersOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.ListUsersInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (u *UserInfoLDAPSource) getallUsersNonCached() ([]string, error) {\n\tsearchPaths := []string{u.UserSearchBaseDNs, u.ServiceAccountBaseDNs}\n\tconn, err := u.getTargetLDAPConnection()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\n\tvar AllUsers []string\n\tAttributes := []string{\"uid\"}\n\tfor _, searchPath := range searchPaths {\n\t\tsearchrequest := ldap.NewSearchRequest(searchPath, ldap.ScopeWholeSubtree,\n\t\t\tldap.NeverDerefAliases, 0, 0, false, u.UserSearchFilter, Attributes, nil)\n\t\tt0 := time.Now()\n\t\tresult, err := conn.SearchWithPaging(searchrequest, pageSearchSize)\n\t\tt1 := time.Now()\n\t\tlog.Printf(\"GetallUsers search Took %v to run\", t1.Sub(t0))\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(result.Entries) == 0 {\n\t\t\tlog.Println(\"No records found\")\n\t\t\treturn nil, errors.New(\"No records found\")\n\t\t}\n\t\tfor _, entry := range result.Entries {\n\t\t\tuid := entry.GetAttributeValue(\"uid\")\n\t\t\tAllUsers = append(AllUsers, uid)\n\t\t}\n\t}\n\n\treturn AllUsers, nil\n}", "func (m *MockOrganizationServiceClient) FetchUserListByOrganization(arg0 context.Context, arg1 *organization.ByOrganizationRequest, arg2 ...grpc.CallOption) (*organization.UserListResponse, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"FetchUserListByOrganization\", varargs...)\n\tret0, _ := ret[0].(*organization.UserListResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) GetPermissionsForUser(arg0 string, arg1 ...string) [][]string {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetPermissionsForUser\", varargs...)\n\tret0, _ := ret[0].([][]string)\n\treturn ret0\n}", "func (db *Client) GetUsers(filter models.User, sort []persistance.Sorter, pg persistance.Paginator) ([]models.User, error) {\n\ttx := db.DB\n\t// prepare filter statments\n\tif !utils.IsZeroOfUnderlyingType(filter.Name) {\n\t\ttx = tx.Where(\"name LIKE ?\", \"%\"+filter.Name+\"%\")\n\t}\n\tif !utils.IsZeroOfUnderlyingType(filter.Email) {\n\t\ttx = tx.Where(\"email LIKE ?\", \"%\"+filter.Email+\"%\")\n\t}\n\n\t// prepare sort statements\n\tfor _, s := range sort {\n\t\ttx = tx.Order(s.Attr + \" \" + string(s.Direction))\n\t}\n\ttx = tx.Order(\"id asc\")\n\n\t// prepare pagination\n\tif pg.Index != \"\" {\n\t\ttx = tx.Where(\"id > ?\", pg.Index)\n\t}\n\ttx = tx.Limit(pg.PageSize)\n\n\tvar users []models.User\n\tresult := tx.Find(&users)\n\treturn users, result.Error\n}", "func (ln *LnDatabase) GetUserByIDs(ids []primitive.ObjectID) []*models.User {\n\tvar users []*models.User\n\tcursor, err := ln.DB.Collection(\"test\").\n\t\tFind(context.Background(), bson.D{{\n\t\t\tKey: \"_id\",\n\t\t\tValue: bson.D{{\n\t\t\t\tKey: \"$in\",\n\t\t\t\tValue: ids,\n\t\t\t}},\n\t\t}})\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer cursor.Close(context.Background())\n\n\tfor cursor.Next(context.Background()) {\n\t\tuser := &models.User{}\n\t\tif err := cursor.Decode(user); err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tusers = append(users, user)\n\t}\n\n\treturn users\n}", "func (m *MockTenantServiceDao) GetServiceIDsByAppID(appID string) []model.ServiceID {\n\tret := m.ctrl.Call(m, \"GetServiceIDsByAppID\", appID)\n\tret0, _ := ret[0].([]model.ServiceID)\n\treturn ret0\n}" ]
[ "0.7373233", "0.70045984", "0.6989277", "0.6738905", "0.66500705", "0.65903264", "0.658684", "0.6514446", "0.6512055", "0.64303535", "0.64012545", "0.63828254", "0.63659155", "0.6347572", "0.6335323", "0.6328387", "0.6297302", "0.62960035", "0.6282402", "0.6265858", "0.6239271", "0.6193215", "0.6182318", "0.6132064", "0.61253923", "0.6122614", "0.61194956", "0.6088288", "0.6077063", "0.606826", "0.60597223", "0.6026093", "0.60136044", "0.601329", "0.5996964", "0.59958035", "0.5990904", "0.59519833", "0.5939916", "0.5924799", "0.59109575", "0.5902344", "0.5900418", "0.58981663", "0.58835775", "0.58713084", "0.5869045", "0.5832165", "0.5789334", "0.5789226", "0.5787726", "0.57847774", "0.57763153", "0.57640225", "0.57577467", "0.5752803", "0.5745212", "0.5738605", "0.57362443", "0.57323784", "0.5730252", "0.5727789", "0.57232565", "0.5717519", "0.57094824", "0.5699162", "0.5688945", "0.568739", "0.56784743", "0.5641911", "0.56368744", "0.5621092", "0.55868846", "0.55797666", "0.5576531", "0.5566141", "0.55608106", "0.55509305", "0.55509007", "0.55487436", "0.55474263", "0.5543291", "0.55394095", "0.5539192", "0.55368817", "0.5524813", "0.5523298", "0.55177504", "0.5516109", "0.55156684", "0.55087", "0.54992485", "0.5493059", "0.5484601", "0.54786634", "0.5475527", "0.5474176", "0.5472463", "0.5470974", "0.5470934" ]
0.8304331
0
GetUsersWhereUserIDs indicates an expected call of GetUsersWhereUserIDs
func (mr *MockUserRepositoryInterfaceMockRecorder) GetUsersWhereUserIDs(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUsersWhereUserIDs", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUsersWhereUserIDs), arg0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockUserRepositoryInterface) GetUsersWhereUserIDs(arg0 []uint64) ([]*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersWhereUserIDs\", arg0)\n\tret0, _ := ret[0].([]*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestSelectUsersByIdsArray(t *testing.T) {\n\tdb, mock, repo := initUserTest(t)\n\tdefer db.Close()\n\n\t// Mock DB statements and execute\n\trows := getUserRows()\n\tmock.ExpectPrepare(\"^SELECT (.+) FROM users WHERE id IN (.+)\").\n\t\tExpectQuery().\n\t\tWillReturnRows(rows)\n\tgot, err := repo.SelectByIds(testUtils.Context, []uint{1})\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %v\", err)\n\t}\n\n\t// Validate results\n\twant := map[uint]domains.User{\n\t\t1: getUser(),\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"Values not equal: got = %v, want = %v\", got, want)\n\t}\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"Unfulfilled expectations: %s\", err)\n\t}\n}", "func (mr *MockRepositoryMockRecorder) GetUsersFromIDs(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsersFromIDs\", reflect.TypeOf((*MockRepository)(nil).GetUsersFromIDs), arg0)\n}", "func UserIDs(generator *Generator) Criterion {\n\treturn usersCriterion{g: generator}\n}", "func (mr *MockClientMockRecorder) FindUsersWithIds(ctx, ids interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"FindUsersWithIds\", reflect.TypeOf((*MockClient)(nil).FindUsersWithIds), ctx, ids)\n}", "func (u *User) GetUserByNotUserIds(userIds []string) (users []map[string]string, err error) {\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\trs, err = db.Query(db.AR().From(Table_User_Name).Where(map[string]interface{}{\n\t\t\"user_id NOT\": userIds,\n\t\t\"is_delete\": User_Delete_False,\n\t}))\n\tif err != nil {\n\t\treturn\n\t}\n\tusers = rs.Rows()\n\treturn\n}", "func (mr *MockUserRepositoryInterfaceMockRecorder) GetUserWhereUserID(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserWhereUserID\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUserWhereUserID), arg0)\n}", "func (h *Harness) WaitAndAssertOnCallUsers(serviceID string, userIDs ...string) {\n\th.t.Helper()\n\tdoQL := func(query string, res interface{}) {\n\t\tg := h.GraphQLQuery2(query)\n\t\tfor _, err := range g.Errors {\n\t\t\th.t.Error(\"GraphQL Error:\", err.Message)\n\t\t}\n\t\tif len(g.Errors) > 0 {\n\t\t\th.t.Fatal(\"errors returned from GraphQL\")\n\t\t}\n\t\tif res == nil {\n\t\t\treturn\n\t\t}\n\t\terr := json.Unmarshal(g.Data, &res)\n\t\tif err != nil {\n\t\t\th.t.Fatal(\"failed to parse response:\", err)\n\t\t}\n\t}\n\n\tgetUsers := func() []string {\n\t\tvar result struct {\n\t\t\tService struct {\n\t\t\t\tOnCallUsers []struct {\n\t\t\t\t\tUserID string\n\t\t\t\t\tUserName string\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdoQL(fmt.Sprintf(`\n\t\t\tquery{\n\t\t\t\tservice(id: \"%s\"){\n\t\t\t\t\tonCallUsers{\n\t\t\t\t\t\tuserID\n\t\t\t\t\t\tuserName\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`, serviceID), &result)\n\n\t\tvar ids []string\n\t\tfor _, oc := range result.Service.OnCallUsers {\n\t\t\tids = append(ids, oc.UserID)\n\t\t}\n\t\tif len(ids) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tsort.Strings(ids)\n\t\tuniq := ids[:1]\n\t\tlast := ids[0]\n\t\tfor _, id := range ids[1:] {\n\t\t\tif id == last {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tuniq = append(uniq, id)\n\t\t\tlast = id\n\t\t}\n\t\treturn uniq\n\t}\n\tsort.Strings(userIDs)\n\tmatch := func(final bool) bool {\n\t\tids := getUsers()\n\t\tif len(ids) != len(userIDs) {\n\t\t\tif final {\n\t\t\t\th.t.Fatalf(\"got %d on-call users; want %d\", len(ids), len(userIDs))\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\tfor i, id := range userIDs {\n\t\t\tif ids[i] != id {\n\t\t\t\tif final {\n\t\t\t\t\th.t.Fatalf(\"on-call[%d] = %s; want %s\", i, ids[i], id)\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\th.Trigger() // run engine cycle\n\n\tmatch(true) // assert result\n}", "func (o *NotificationProjectBudgetNotification) GetUserIdsOk() (*[]int32, bool) {\n\tif o == nil || o.UserIds == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UserIds, true\n}", "func UserIDNotIn(vs ...string) predicate.User {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.User(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldUserID), v...))\n\t})\n}", "func (m *MockRepository) GetUsersFromIDs(arg0 []uuid.UUID) ([]user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersFromIDs\", arg0)\n\tret0, _ := ret[0].([]user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDatabase) GetUsersID() ([]uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersID\")\n\tret0, _ := ret[0].([]uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) FindUsersWithIds(ctx context.Context, ids []string) ([]*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindUsersWithIds\", ctx, ids)\n\tret0, _ := ret[0].([]*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetUsersByIDs(userIDs []int64) map[int64]*domain.User {\n\tuserMap := map[int64]*domain.User{}\n\tfor _, userID := range userIDs {\n\t\tuser, ok := MockData[userID]\n\t\tif ok {\n\t\t\tuserMap[userID] = &user\n\t\t}\n\t}\n\treturn userMap\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 UserIDIn(vs ...string) predicate.User {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.User(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldUserID), v...))\n\t})\n}", "func UseridNotIn(vs ...string) predicate.Project {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldUserid), v...))\n\t})\n}", "func UserIDNotIn(vs ...int) predicate.User {\n\treturn predicate.User(sql.FieldNotIn(FieldUserID, vs...))\n}", "func (mr *MockDatabaseMockRecorder) GetUsersID() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsersID\", reflect.TypeOf((*MockDatabase)(nil).GetUsersID))\n}", "func (op *ListSharedAccessOp) UserIds(val ...string) *ListSharedAccessOp {\n\tif op != nil {\n\t\top.QueryOpts.Set(\"user_ids\", strings.Join(val, \",\"))\n\t}\n\treturn op\n}", "func BenchmarkGetUserByIDUserNotFound(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tGetUserByID(0)\n\t}\n}", "func TestGetUser(t *testing.T) {\n\ttests := []struct {\n\t\tid int64\n\t\texceptResult *schedule.User\n\t}{\n\t\t{1, &schedule.User{ID: 1}},\n\t}\n\n\tfor _, test := range tests {\n\t\tr, err := ss.GetUser(ctx, test.id)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"GetUser(%d) fail, err %s, result %+v\", test.id, err, r)\n\t\t\treturn\n\t\t}\n\n\t\tif r.ID != test.exceptResult.ID {\n\t\t\tt.Errorf(\"GetUser(%d) = %+v, except %+v\", test.id, r, test.exceptResult)\n\t\t\treturn\n\t\t}\n\t}\n}", "func getUserIDs(c models.Context, database *mgo.Database) ([]string, error) {\n\tif database == nil {\n\t\tdir, err := argValueWithMkdir(c, twitterFlagName)\n\t\tif err != nil {\n\t\t\treturn nil, utils.WithStack(err)\n\t\t}\n\t\tfiles, err := filepath.Glob(filepath.Join(dir, \"*.toml\"))\n\t\tif err != nil {\n\t\t\treturn nil, utils.WithStack(err)\n\t\t}\n\t\tuserIDs := []string{}\n\t\tfor _, file := range files {\n\t\t\tbase := filepath.Base(file)\n\t\t\text := filepath.Ext(file)\n\t\t\tuserIDs = append(userIDs, base[0:len(base)-len(ext)])\n\t\t}\n\t\treturn userIDs, nil\n\t}\n\n\tcol := database.C(\"twitter-user-auth\")\n\tauths := []map[string]interface{}{}\n\terr := col.Find(nil).All(&auths)\n\tif err != nil {\n\t\treturn nil, utils.WithStack(err)\n\t}\n\tuserIDs := []string{}\n\tfor _, auth := range auths {\n\t\tid, ok := auth[\"id\"].(string)\n\t\tif ok && id != \"\" {\n\t\t\tuserIDs = append(userIDs, id)\n\t\t}\n\t}\n\treturn userIDs, nil\n}", "func UseridIn(vs ...string) predicate.Project {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldUserid), v...))\n\t})\n}", "func (_m *TeamStore) GetCommonTeamIDsForTwoUsers(userID string, otherUserID string) ([]string, error) {\n\tret := _m.Called(userID, otherUserID)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(string, string) []string); ok {\n\t\tr0 = rf(userID, otherUserID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, string) error); ok {\n\t\tr1 = rf(userID, otherUserID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestSelectUsersByAccountId(t *testing.T) {\n\tdb, mock, repo := initUserTest(t)\n\tdefer db.Close()\n\n\t// Mock DB statements and execute\n\trows := getUserRows()\n\tmock.ExpectPrepare(\"^SELECT (.+) FROM users WHERE account_id=?\").\n\t\tExpectQuery().\n\t\tWithArgs(2).\n\t\tWillReturnRows(rows)\n\tgot, err := repo.SelectByAccountId(testUtils.Context, 2)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %v\", err)\n\t}\n\n\t// Validate results\n\twant := []domains.User{getUser()}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"Values not equal: got = %v, want = %v\", got, want)\n\t}\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"Unfulfilled expectations: %s\", err)\n\t}\n}", "func (mr *ClientMockRecorder) GetManyUsers(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetManyUsers\", reflect.TypeOf((*Client)(nil).GetManyUsers), arg0, arg1)\n}", "func UserIDIn(vs ...int) predicate.User {\n\treturn predicate.User(sql.FieldIn(FieldUserID, vs...))\n}", "func TestGetUnsolvedProblemsValidUserid(t *testing.T) {\n\tts := initAPITestServer(t)\n\tdefer test.CloseServer(ts)\n\n\tproblems := GetUnsolvedProblems(userID, \"star\")\n\tif len(problems) != nUnsolvedProblems {\n\t\tt.Fatalf(\"Expected %d problems to solve, got %d\", nUnsolvedProblems, len(problems))\n\t}\n}", "func (_m *TeamStore) GetUserTeamIds(userID string, allowFromCache bool) ([]string, error) {\n\tret := _m.Called(userID, allowFromCache)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(string, bool) []string); ok {\n\t\tr0 = rf(userID, allowFromCache)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, bool) error); ok {\n\t\tr1 = rf(userID, allowFromCache)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestGetUsersByAccessID(t *testing.T) {\r\n\tlog.Printf(\"--------------------------------------------------------\")\r\n\ttrace2()\r\n\tfmt.Println(nameOf((*A).Method))\r\n\tlog.Printf(\"--------------------------------------------------------\")\r\n\tmyDB := db.Connect()\r\n\tmyUser := &Video{}\r\n\tvideoUsersAccess, errTest := myUser.GetUsersByAccessID(myDB, 2)\r\n\tif errTest != nil {\r\n\t\tlog.Printf(\" Test Failed in TestGetUsersBySensorID: %v\", errTest)\r\n\t\tlog.Printf(\" %v\", videoUsersAccess)\r\n\t\treturn\r\n\t}\r\n\tlog.Printf(\"%d users found inside TestGetUsersByAccessID()\", len(videoUsersAccess))\r\n\tfor i := 0; i < len(videoUsersAccess); i++ {\r\n\t\tlog.Printf(\" %v\\n\", videoUsersAccess[i])\r\n\t}\r\n\r\n}", "func (mr *MockDataSourceMockRecorder) GetUsers() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsers\", reflect.TypeOf((*MockDataSource)(nil).GetUsers))\n}", "func getTeamUsers(context context.Context, githubClient github.Client, teamId int64, actualUsers []githubUser) []githubUser {\n\n\tvar users = make([]githubUser, 0)\n\n\tmembers, _, err := githubClient.Teams.ListTeamMembers(context, teamId, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %s\", err)\n\t}\n\tfor _, member := range members {\n\t\tif !usersContain(actualUsers, *member.Login) {\n\t\t\tvar user githubUser\n\t\t\tuser.keys = make([]string, 0)\n\t\t\tuser.name = *member.Login\n\t\t\tkeys, _, err := githubClient.Users.ListKeys(context, *member.Login, nil)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Error: %s\", err)\n\t\t\t}\n\t\t\tfor _, key := range keys {\n\t\t\t\tuser.keys = append(user.keys, *key.Key)\n\t\t\t}\n\t\t\tusers = append(users, user)\n\t\t}\n\t}\n\treturn users\n}", "func GetUsers(c router.Context) (interface{}, error) {\n\t// get the data from the request and parse it as structure\n\tdata := c.Param(`data`).(UserId)\n\n\t// Validate the inputed data\n\terr := data.Validate()\n\tif err != nil {\n\t\tif _, ok := err.(validation.InternalError); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, status.ErrStatusUnprocessableEntity.WithValidationError(err.(validation.Errors))\n\t}\n\tstub := c.Stub()\n\tqueryString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"_id\\\":{\\\"$ne\\\":\\\"%s\\\"},\\\"doc_type\\\":\\\"%s\\\"}}\", data.ID, utils.DocTypeUser)\n\tresultsIterator, err := stub.GetQueryResult(queryString)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, status.ErrInternal.WithError(err)\n\t}\n\n\tdefer resultsIterator.Close()\n\n\t// buffer is a JSON array containing QueryResults\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"{\")\n\tbuffer.WriteString(\"\\\"users\\\": [\")\n\taArrayMemberAlreadyWritten := false\n\tfor resultsIterator.HasNext() {\n\t\tqueryResponse, err2 := resultsIterator.Next()\n\t\tif err2 != nil {\n\t\t\treturn nil, status.ErrInternal.WithError(err2)\n\t\t}\n\n\t\t// Add a comma before array members, suppress it for the first array member\n\t\tif aArrayMemberAlreadyWritten == true {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t\tuserData := UserResponse{}\n\t\terr3 := json.Unmarshal(queryResponse.Value, &userData)\n\t\tif err3 != nil {\n\t\t\treturn nil, status.ErrInternal.WithError(err3)\n\t\t}\n\n\t\tuserData.ID = queryResponse.Key\n\t\tuserDataBytes, _ := json.Marshal(userData)\n\n\t\tbuffer.WriteString(string(userDataBytes))\n\t\taArrayMemberAlreadyWritten = true\n\t}\n\tbuffer.WriteString(\"]}\")\n\n\t//return the response\n\treturn buffer.Bytes(), nil\n}", "func (op *UpdateSharedAccessOp) UserIds(val ...string) *UpdateSharedAccessOp {\n\tif op != nil {\n\t\top.QueryOpts.Set(\"user_ids\", strings.Join(val, \",\"))\n\t}\n\treturn op\n}", "func (mock *RepositoryMock) GetUserProductAffinitiesByUserIDCalls() []struct {\n\tCtx context.Context\n\tUserID int64\n\tOptions GetUserProductAffinitiesByUserIDOptions\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tUserID int64\n\t\tOptions GetUserProductAffinitiesByUserIDOptions\n\t}\n\tlockRepositoryMockGetUserProductAffinitiesByUserID.RLock()\n\tcalls = mock.calls.GetUserProductAffinitiesByUserID\n\tlockRepositoryMockGetUserProductAffinitiesByUserID.RUnlock()\n\treturn calls\n}", "func TestPagination(t *testing.T) {\n\tts := NewTestServer(allowedAccessToken)\n\tdefer ts.Close()\n\n\tresp, _ := ts.Client.FindUsers(SearchRequest{\n\t\tLimit: 4,\n\t\tOffset: 0,\n\t})\n\n\tif len(resp.Users) != 4 {\n\t\tt.Errorf(\"invalid nums of users: %d\", len(resp.Users))\n\t\treturn\n\t}\n\n\tif resp.Users[3].Id != 3 {\n\t\tt.Errorf(\"invalid user at row 3: %v\", resp.Users[3])\n\t\treturn\n\t}\n\n\tresp, _ = ts.Client.FindUsers(SearchRequest{\n\t\tLimit: 6,\n\t\tOffset: 3,\n\t})\n\n\tif len(resp.Users) != 6 {\n\t\tt.Errorf(\"invalid number of users: %d\", len(resp.Users))\n\t\treturn\n\t}\n\n\tif resp.Users[0].Name != \"Everett Dillard\" {\n\t\tt.Errorf(\"invalid user at row 3: %v\", resp.Users[0])\n\t\treturn\n\t}\n}", "func (m *CarserviceMutation) UseridIDs() (ids []int) {\n\tif id := m.userid; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\n}", "func (mr *ClientMockRecorder) GetUsers(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsers\", reflect.TypeOf((*Client)(nil).GetUsers), arg0, arg1)\n}", "func (o *NotificationProjectBudgetNotification) GetUserIds() []int32 {\n\tif o == nil || o.UserIds == nil {\n\t\tvar ret []int32\n\t\treturn ret\n\t}\n\treturn *o.UserIds\n}", "func (mr *MockUserClientMockRecorder) GetUsers(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsers\", reflect.TypeOf((*MockUserClient)(nil).GetUsers), varargs...)\n}", "func (dp *dataProvider) GetUsersByIDs(users *models.Users) error {\n\tinUsers := *users\n\tids := make([]interface{}, len(*users))\n\tvar outUsers []*models.User\n\n\tfor idx, user := range inUsers {\n\t\tids[idx] = user.ID\n\t}\n\n\terr := dp.db.Model(&outUsers).\n\t\tWhere(\"id IN (?)\", types.In(ids)).\n\t\tSelect()\n\tif err != nil {\n\t\treturn wrapError(err)\n\t}\n\n\tif len(inUsers) != len(outUsers) {\n\t\treturn fmt.Errorf(\"could not find all users\")\n\t}\n\n\t// Make a map for fast ordering\n\toutUserMap := make(map[string]*models.User)\n\tfor _, user := range outUsers {\n\t\toutUserMap[user.ID] = user\n\t}\n\n\t// Order outUsers based on input ID ordering\n\tfor idx, user := range inUsers {\n\t\toutUser, ok := outUserMap[user.ID]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"could not find all users\")\n\t\t}\n\t\tinUsers[idx] = outUser\n\t}\n\treturn nil\n}", "func SocialUserIDNotIn(vs ...string) predicate.User {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.User(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldSocialUserID), v...))\n\t})\n}", "func (ctlr *userServiceController) GetUsers(ctx context.Context, req *mygrpc.GetUsersRequest) (*mygrpc.GetUsersResponse, error) {\n\tresultMap := ctlr.userService.GetUsersByIDs(req.GetIds())\n\n\tresp := &mygrpc.GetUsersResponse{}\n\tfor _, u := range resultMap {\n\t\tresp.Users = append(resp.Users, marshalUser(u))\n\t}\n\treturn resp, nil\n}", "func (mr *MockUserServerMockRecorder) GetUsers(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsers\", reflect.TypeOf((*MockUserServer)(nil).GetUsers), arg0, arg1)\n}", "func (mr *MockIUserRepositoryMockRecorder) GetUsers() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsers\", reflect.TypeOf((*MockIUserRepository)(nil).GetUsers))\n}", "func TestListUsers(t *testing.T) {\n\n\t// Get all users (we should have at least one)\n\tresults, err := FindAll(Query())\n\tif err != nil {\n\t\tt.Fatalf(\"users: List no user found :%s\", err)\n\t}\n\n\tif len(results) < 1 {\n\t\tt.Fatalf(\"users: List no users found :%s\", err)\n\t}\n\n}", "func TestGetUserIDValid(t *testing.T) {\n\tts := initAPITestServer(t)\n\tdefer test.CloseServer(ts)\n\n\tid, err := GetUserID(username)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error %v\", err)\n\t}\n\tif id != userID {\n\t\tt.Fatalf(\"Expected userID %v got %v\", userID, id)\n\t}\n}", "func (server *Server) UserGetIgnored(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\tusers []User\n\t\tuid int\n\t\terr error\n\t\tctx context.Context\n\t)\n\n\tctx = r.Context()\n\tuid = ctx.Value(\"uid\").(int)\n\n\tusers, err = server.Db.GetIgnoredUsers(uid)\n\tif err != nil {\n\t\tserver.Logger.LogError(r, \"GetIgnoredUsers returned error - \"+err.Error())\n\t\tserver.error(w, errors.DatabaseError)\n\t\treturn\n\t}\n\n\tjsonUsers, err := json.Marshal(users)\n\tif err != nil {\n\t\tserver.Logger.LogError(r, \"Marshal returned error \"+err.Error())\n\t\tserver.error(w, errors.MarshalError)\n\t\treturn\n\t}\n\n\t// This is my valid case\n\tw.WriteHeader(http.StatusOK) // 200\n\tw.Write(jsonUsers)\n\tserver.Logger.LogSuccess(r, \"Users was found successfully. Total amount \"+BLUE+strconv.Itoa(len(users))+NO_COLOR)\n}", "func GetUsersID(clients *common.ClientContainer, handler common.HandlerInterface) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tuserID := chi.URLParam(r, \"userID\")\n\t\tID, err := strconv.Atoi(userID)\n\t\tif err != nil {\n\t\t\tcommon.WriteErrorToResponse(w, http.StatusUnprocessableEntity,\n\t\t\t\thttp.StatusText(http.StatusUnprocessableEntity),\n\t\t\t\t\"ID provided is not integer\")\n\t\t\treturn\n\t\t}\n\t\tuserlist, err := handler.GetUserID(clients, ID)\n\t\tif err != nil {\n\t\t\tswitch err.(type) {\n\t\t\t// grafanaclient.NotFound means, that user provided the\n\t\t\t// ID of non existent user. We return 404\n\t\t\tcase grafanaclient.NotFound:\n\t\t\t\terrMsg := fmt.Sprintf(\"User Not Found\")\n\t\t\t\tcommon.WriteErrorToResponse(w, http.StatusNotFound,\n\t\t\t\t\terrMsg, err.Error())\n\t\t\t\treturn\n\t\t\t// If any other error happened -> return 500 error\n\t\t\tdefault:\n\t\t\t\tlog.Logger.Error(err)\n\t\t\t\tcommon.WriteErrorToResponse(w, http.StatusInternalServerError,\n\t\t\t\t\thttp.StatusText(http.StatusInternalServerError),\n\t\t\t\t\t\"Internal server error occured\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tw.Write(userlist)\n\t}\n}", "func (as *ActionSuite) TestUsersQuery() {\n\tt := as.T()\n\n\tf := fixturesForUserQuery(as)\n\n\ttype testCase struct {\n\t\tName string\n\t\tPayload string\n\t\tTestUser models.User\n\t\tExpectError bool\n\t\tTest func(t *testing.T)\n\t}\n\n\tvar resp UsersResponse\n\n\ttestCases := []testCase{\n\t\t{\n\t\t\tName: \"good\",\n\t\t\tPayload: \"{users {id nickname}}\",\n\t\t\tTestUser: f.Users[0],\n\t\t\tTest: func(t *testing.T) {\n\t\t\t\tas.Equal(2, len(resp.Users), \"incorrect number of users returned\")\n\t\t\t\tas.Equal(f.Users[0].UUID.String(), resp.Users[0].ID, \"incorrect ID\")\n\t\t\t\tas.Equal(f.Users[0].Nickname, resp.Users[0].Nickname, \"incorrect nickname\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"not allowed\",\n\t\t\tPayload: \"{users {id nickname}}\",\n\t\t\tTestUser: f.Users[1],\n\t\t\tTest: func(t *testing.T) {},\n\t\t\tExpectError: true,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\terr := as.testGqlQuery(test.Payload, test.TestUser.Nickname, &resp)\n\n\t\tif test.ExpectError {\n\t\t\tas.Error(err)\n\t\t} else {\n\t\t\tas.NoError(err)\n\t\t}\n\t\tt.Run(test.Name, test.Test)\n\t}\n}", "func getUsers(githubAccessToken string, githubOrganization string, githubTeams string) []githubUser {\n\n\tvar users = make([]githubUser, 0)\n\n\tctx := context.Background()\n\tgithubClient := getGithubClient(ctx, githubAccessToken)\n\tteamsIds := getTeamsIds(ctx, githubClient, githubOrganization, githubTeams)\n\tfor _, teamId := range teamsIds {\n\t\tusers = append(users, getTeamUsers(ctx, githubClient, teamId, users)...)\n\t}\n\treturn users\n}", "func (m *memstore) GetUserIDsForTeam(ctx context.Context, id string) ([]string, error) {\n\tteamUserIDs, usersFound := m.usersByTeam[id]\n\tif !usersFound {\n\t\treturn nil, storage.ErrNotFound\n\t}\n\n\treturn teamUserIDs, nil\n}", "func (mr *MockPersisterMockRecorder) GetUsers() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsers\", reflect.TypeOf((*MockPersister)(nil).GetUsers))\n}", "func (mr *MockOrderRepositoryMockRecorder) FindAllOrdersByUserID(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"FindAllOrdersByUserID\", reflect.TypeOf((*MockOrderRepository)(nil).FindAllOrdersByUserID), arg0)\n}", "func (i *ImportedContacts) GetUserIDs() (value []int64) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.UserIDs\n}", "func (mock *RepositoryMock) UserGetByEmailCalls() []struct {\n\tCtx context.Context\n\tEmail string\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tEmail string\n\t}\n\tlockRepositoryMockUserGetByEmail.RLock()\n\tcalls = mock.calls.UserGetByEmail\n\tlockRepositoryMockUserGetByEmail.RUnlock()\n\treturn calls\n}", "func TestGetUserIDInvalid(t *testing.T) {\n\tts := initAPITestServer(t)\n\tdefer test.CloseServer(ts)\n\n\tinvalidUsername := \"not_\" + username\n\tid, err := GetUserID(invalidUsername)\n\tif err == nil || err.Error() != \"Username not found\" {\n\t\tt.Fatalf(\"Expected error\")\n\t}\n\tif id != \"\" {\n\t\tt.Fatalf(\"Expected empty userID\")\n\t}\n}", "func (mr *MockIDistributedEnforcerMockRecorder) GetUsersForRole(arg0 interface{}, arg1 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{arg0}, arg1...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsersForRole\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).GetUsersForRole), varargs...)\n}", "func TestListUser(t *testing.T) {\n\tctx := context.Background()\n\tconn, err := grpc.DialContext(ctx, \"\", grpc.WithInsecure(), grpc.WithContextDialer(bufDialer))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Close()\n\tclient := api.NewUserServiceClient(conn)\n\tuser1 := createUser(t, ctx, client, 0)\n\tuser2 := createUser(t, ctx, client, 0)\n\tuser3 := createUser(t, ctx, client, 0)\n\tuser4 := createUser(t, ctx, client, 0)\n\n\ttestCases := []struct {\n\t\tcaseName string\n\t\tlistUserRequest api.ListUserRequest\n\t\tresultLen int\n\t\tisPositive bool\n\t\terrCode codes.Code\n\t\terrMsg string\n\t}{\n\t\t{\n\t\t\tcaseName: \"ListUser: limit = 1, page = 1\",\n\t\t\tlistUserRequest: api.ListUserRequest{\n\t\t\t\tPageFilter: &api.PageFilter{\n\t\t\t\t\tLimit: 1,\n\t\t\t\t\tPage: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t\tresultLen: 1,\n\t\t\tisPositive: true,\n\t\t},\n\t\t{\n\t\t\tcaseName: \"ListUser: limit = 2, page = 1\",\n\t\t\tlistUserRequest: api.ListUserRequest{\n\t\t\t\tPageFilter: &api.PageFilter{\n\t\t\t\t\tLimit: 2,\n\t\t\t\t\tPage: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t\tresultLen: 2,\n\t\t\tisPositive: true,\n\t\t},\n\t\t{\n\t\t\tcaseName: \"ListUser: limit = 2, page = 2\",\n\t\t\tlistUserRequest: api.ListUserRequest{\n\t\t\t\tPageFilter: &api.PageFilter{\n\t\t\t\t\tLimit: 2,\n\t\t\t\t\tPage: 2,\n\t\t\t\t},\n\t\t\t},\n\t\t\tresultLen: 2,\n\t\t\tisPositive: true,\n\t\t},\n\t\t{\n\t\t\tcaseName: \"ListUser: limit = 2, page = 0\",\n\t\t\tlistUserRequest: api.ListUserRequest{\n\t\t\t\tPageFilter: &api.PageFilter{\n\t\t\t\t\tLimit: 2,\n\t\t\t\t\tPage: 0,\n\t\t\t\t},\n\t\t\t},\n\t\t\tisPositive: false,\n\t\t\terrMsg: \"page must be > 0, page = 0\",\n\t\t\terrCode: codes.InvalidArgument,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.caseName, func(t *testing.T) {\n\t\t\tusers, err := client.ListUser(ctx, &tc.listUserRequest)\n\t\t\tif tc.isPositive {\n\t\t\t\tassert.Empty(t, err)\n\t\t\t\tassert.Equal(t, tc.resultLen, len(users.Users))\n\t\t\t} else {\n\t\t\t\tassert.NotEmpty(t, err)\n\t\t\t\tfromError, _ := status.FromError(err)\n\t\t\t\tassert.Equal(t, tc.errCode, fromError.Code())\n\t\t\t\tassert.Equal(t, tc.errMsg, fromError.Message())\n\t\t\t}\n\t\t})\n\t}\n\tdeleteUser(t, ctx, client, user1.Id)\n\tdeleteUser(t, ctx, client, user2.Id)\n\tdeleteUser(t, ctx, client, user3.Id)\n\tdeleteUser(t, ctx, client, user4.Id)\n}", "func (mr *MockIDbMockRecorder) GetProductsByUserFilter(filter interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetProductsByUserFilter\", reflect.TypeOf((*MockIDb)(nil).GetProductsByUserFilter), filter)\n}", "func (mr *MockIDistributedEnforcerMockRecorder) GetUsersForRoleInDomain(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsersForRoleInDomain\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).GetUsersForRoleInDomain), arg0, arg1)\n}", "func SocialUserIDIn(vs ...string) predicate.User {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.User(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldSocialUserID), v...))\n\t})\n}", "func GetUsers(c *gin.Context) {\n\n\tlog := logger.WithFields(logrus.Fields{\"tag\": \"GetUsers\"})\n\tlog.Info(\"Fetching users\")\n\n\torganization := auth.GetCurrentOrganization(c.Request)\n\n\tidParam := c.Param(\"id\")\n\tid, err := strconv.ParseUint(idParam, 10, 32)\n\tif idParam != \"\" && err != nil {\n\t\tmessage := fmt.Sprintf(\"error parsing user id: %s\", err)\n\t\tlog.Info(message)\n\t\tc.JSON(http.StatusBadRequest, components.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: message,\n\t\t\tError: message,\n\t\t})\n\t\treturn\n\t}\n\n\tvar users []auth.User\n\tdb := model.GetDB()\n\terr = db.Model(organization).Related(&users, \"Users\").Error\n\tif err != nil {\n\t\tmessage := \"failed to fetch users\"\n\t\tlog.Info(message + \": \" + err.Error())\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, components.ErrorResponse{\n\t\t\tCode: http.StatusInternalServerError,\n\t\t\tMessage: message,\n\t\t\tError: message,\n\t\t})\n\t} else if id == 0 {\n\t\tc.JSON(http.StatusOK, users)\n\t} else if len(users) == 1 {\n\t\tc.JSON(http.StatusOK, users[0])\n\t} else if len(users) > 1 {\n\t\tmessage := fmt.Sprintf(\"multiple users found with id: %d\", id)\n\t\tlog.Info(message)\n\t\tc.AbortWithStatusJSON(http.StatusConflict, components.ErrorResponse{\n\t\t\tCode: http.StatusConflict,\n\t\t\tMessage: message,\n\t\t\tError: message,\n\t\t})\n\t} else {\n\t\tmessage := fmt.Sprintf(\"user not found with id: %d\", id)\n\t\tlog.Info(message)\n\t\tc.AbortWithStatusJSON(http.StatusNotFound, components.ErrorResponse{\n\t\t\tCode: http.StatusNotFound,\n\t\t\tMessage: message,\n\t\t\tError: message,\n\t\t})\n\t}\n}", "func users(ds *datastore.Client) ([]User, error) {\n\tdst := make([]User, 0)\n\t_, err := ds.GetAll(context.Background(), datastore.NewQuery(userKind).Limit(limit).Project(usernameField, userIDField).Order(usernameField), &dst)\n\treturn dst, err\n}", "func (m *GraphBaseServiceClient) UsersById(id string)(*i009581390843c78f63b06f9dcefeeb5ef2a124a2ac1dcbad3adbe4d0d5e650af.UserItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"user%2Did\"] = id\n }\n return i009581390843c78f63b06f9dcefeeb5ef2a124a2ac1dcbad3adbe4d0d5e650af.NewUserItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) UsersById(id string)(*i009581390843c78f63b06f9dcefeeb5ef2a124a2ac1dcbad3adbe4d0d5e650af.UserItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"user%2Did\"] = id\n }\n return i009581390843c78f63b06f9dcefeeb5ef2a124a2ac1dcbad3adbe4d0d5e650af.NewUserItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func GetReviewees(db *sql.DB, email string, cycle string) ([]UserInfoLite, error) {\n\tvar uil []UserInfoLite\n\tq := `\n SELECT name,\n email\n FROM users\n JOIN user_teams\n ON users.id = user_teams.user_id\n WHERE team_id = (SELECT team_id\n FROM user_teams\n JOIN users\n ON user_teams.user_id=users.id\n WHERE users.email = ?\n )\n\t\t\t AND email <> ?\n\t`\n\n\trows, err := db.Query(q, email, email)\n\tif err != nil {\n\t\treturn uil, errors.Wrap(err, \"unable to query for team mates in GetReviewees\")\n\t}\n\tfor rows.Next() {\n\t\tvar name, email string\n\t\tif err = rows.Scan(&name, &email); err != nil {\n\t\t\treturn uil, errors.Wrap(err, \"unable to scan for team mates in GetReviewees\")\n\t\t}\n\t\tuil = append(uil, UserInfoLite{Name: name, Email: email})\n\t}\n\tif rows.Err() != nil {\n\t\treturn uil, errors.Wrap(err, \"error post scan q1 in GetReviewees\")\n\t}\n\n\tq = `\n SELECT users.name,\n users.email\n FROM users\n JOIN review_requests\n ON reviewer_id = users.id\n JOIN review_cycles\n ON review_requests.cycle_id = review_cycles.id\n WHERE review_requests.recipient_id = (SELECT id\n FROM users\n WHERE email =?\n )\n AND review_cycles.name =?;\n `\n\trows, err = db.Query(q, email, cycle)\n\tif err != nil {\n\t\treturn uil, errors.Wrap(err, \"unable to query for reviewers in GetReviewees\")\n\t}\n\n\tfor rows.Next() {\n\t\tvar name, email string\n\t\tif err = rows.Scan(&name, &email); err != nil {\n\t\t\treturn uil, errors.Wrap(err, \"unable to scan for reviewers in GetReviewees\")\n\t\t}\n\t\tuil = append(uil, UserInfoLite{Name: name, Email: email})\n\t}\n\tif rows.Err() != nil {\n\t\treturn uil, errors.Wrap(err, \"error post scan q2 in GetReviewees\")\n\t}\n\n\treturn uil, nil\n}", "func UserIDNotIn(vs ...string) predicate.OfflineSession {\n\treturn predicate.OfflineSession(sql.FieldNotIn(FieldUserID, vs...))\n}", "func UserIDIn(vs ...string) predicate.OfflineSession {\n\treturn predicate.OfflineSession(sql.FieldIn(FieldUserID, vs...))\n}", "func (ln *LnDatabase) GetUserByIDs(ids []primitive.ObjectID) []*models.User {\n\tvar users []*models.User\n\tcursor, err := ln.DB.Collection(\"test\").\n\t\tFind(context.Background(), bson.D{{\n\t\t\tKey: \"_id\",\n\t\t\tValue: bson.D{{\n\t\t\t\tKey: \"$in\",\n\t\t\t\tValue: ids,\n\t\t\t}},\n\t\t}})\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer cursor.Close(context.Background())\n\n\tfor cursor.Next(context.Background()) {\n\t\tuser := &models.User{}\n\t\tif err := cursor.Decode(user); err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tusers = append(users, user)\n\t}\n\n\treturn users\n}", "func (ctx *Upgrader) getUsers(notReturn ...*Socket) []*Socket {\n\tvar users []*Socket\n\t//\n\tcontain := func(user *Socket) bool {\n\t\tfor indc := range notReturn {\n\t\t\tif user == notReturn[indc] {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t//\n\tfor _, val := range ctx.usersSk {\n\t\tif !contain(val) {\n\t\t\tusers = append(users, val)\n\t\t}\n\t}\n\treturn users\n}", "func usersToUserIDPredicates(users []*ent.User) []predicate.User {\n\tpredicates := make([]predicate.User, len(users))\n\tfor i, u := range users {\n\t\tpredicates[i] = user.ID(u.ID)\n\t}\n\treturn predicates\n}", "func (uq *UserQuery) IDs(ctx context.Context) ([]int, error) {\n\tvar ids []int\n\tif err := uq.Select(user.FieldID).Scan(ctx, &ids); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ids, nil\n}", "func (s *Storage) GetUserIDs() []int64 {\n\tvar results []int64\n\ts.queryScreenNamesOrIDs(\"SELECT user_id from userids where processed=1\", &results)\n\treturn results\n}", "func (ctl *controller) APIUserIDsGetAction(ctx *gin.Context) {\n\tctl.logger.Info(\"[GET] UserIDsGetAction\")\n\n\tids, err := ctl.userRepo.GetUserIDs()\n\tif err != nil {\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\t// json response\n\tctx.JSON(http.StatusOK, jsonresp.CreateUserIDsJSON(ids))\n}", "func TestGetUserByIDUserNotFound(t *testing.T) {\n\tuser, err := GetUserByID(0)\n\tassert.Nil(t, user, \"Id nao esperado\")\n\tassert.NotNil(t, err)\n\n\tassert.EqualValues(t, http.StatusNotFound, err.StatusCode)\n\tassert.EqualValues(t, \"User not found\", err.Message)\n}", "func (mr *MockStoreMockRecorder) GetUserById(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserById\", reflect.TypeOf((*MockStore)(nil).GetUserById), arg0, arg1)\n}", "func (m *MockIDistributedEnforcer) GetImplicitUsersForPermission(arg0 ...string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetImplicitUsersForPermission\", varargs...)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mr *RepositoryMockRecorder) GetAllByUserID(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetAllByUserID\", reflect.TypeOf((*Repository)(nil).GetAllByUserID), arg0, arg1)\n}", "func (g *GetChatEventLogRequest) GetUserIDs() (value []int64) {\n\tif g == nil {\n\t\treturn\n\t}\n\treturn g.UserIDs\n}", "func ArrayContainsUser(arr []*discordgo.User, el *discordgo.User) bool {\n\tif len(arr) == 0 {\n\t\treturn false\n\t}\n\n\tfor _, element := range arr {\n\t\tif element.ID == el.ID {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func GetUsers(db sqlx.Queryer, limit, offset int, search string) ([]User, error) {\n\tvar users []User\n\tif search != \"\" {\n\t\tsearch = \"%\" + search + \"%\"\n\t}\n\terr := sqlx.Select(db, &users, \"select \"+externalUserFields+` from \"user\" where ($3 != '' and username ilike $3) or ($3 = '') order by username limit $1 offset $2`, limit, offset, search)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"select error\")\n\t}\n\treturn users, nil\n}", "func (mr *MockProductMockRecorder) GetConcurrentUserByID(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetConcurrentUserByID\", reflect.TypeOf((*MockProduct)(nil).GetConcurrentUserByID), arg0, arg1)\n}", "func (s *Server) GetUsers(ctx context.Context,\n\treq *teams.GetUsersReq) (*teams.GetUsersResp, error) {\n\n\tid, err := uuid.FromString(req.Id)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid team id: %q\", id)\n\t}\n\n\tuserIDs, err := s.service.Storage.GetUserIDsForTeam(ctx, id)\n\tif err != nil {\n\t\treturn nil, service.ParseStorageError(err, req.Id, \"team\")\n\t}\n\n\treturn &teams.GetUsersResp{\n\t\tUserIds: userIDs,\n\t}, err\n\n}", "func (runners RunnerList) GetUserIDs() []int64 {\n\tids := make(container.Set[int64], len(runners))\n\tfor _, runner := range runners {\n\t\tif runner.OwnerID == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tids.Add(runner.OwnerID)\n\t}\n\treturn ids.Values()\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUserID(arg0 uint64) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUserID\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mr *MockProductMockRecorder) GetConcurrentUsersByDay(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetConcurrentUsersByDay\", reflect.TypeOf((*MockProduct)(nil).GetConcurrentUsersByDay), arg0, arg1)\n}", "func (db *Store) getUsersForTeam(teamID string) ([]string, error) {\n\tsince := model.GetMillis() - period\n\n\tquery := db.sq.Select(\"U.Id\").\n\t\tFrom(\"Users AS U\").\n\t\tJoin(\"TeamMembers tm ON ( tm.UserId = U.Id AND tm.DeleteAt = 0 )\").Where(\"tm.TeamId = ?\", teamID).\n\t\tLeftJoin(\"Bots ON U.Id = Bots.UserId\").Where(\"Bots.UserId IS NULL\").\n\t\tLeftJoin(\"Posts AS P ON P.UserId = U.Id\").\n\t\tWhere(sq.Gt{\"P.CreateAt\": since}).\n\t\tWhere(sq.Eq{\"P.DeleteAt\": 0}).\n\t\tGroupBy(\"U.Id\").\n\t\tOrderBy(\"Count(P.Id) DESC\").\n\t\tLimit(userLimit)\n\n\trows, err := query.Query()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Can't query users\")\n\t}\n\tdefer rows.Close()\n\tusers := []string{}\n\tfor rows.Next() {\n\t\tvar userID string\n\t\tif err := rows.Scan(&userID); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tusers = append(users, userID)\n\t}\n\treturn users, nil\n}", "func (T *GetUsers) filterUsers(input []KiteUser) (users []KiteUser, err error) {\n\t// Match bool variables\n\tmatchBool := func(input KiteUser, key string, value bool) bool {\n\t\tvar bool_var bool\n\n\t\tswitch key {\n\t\tcase \"suspended\":\n\t\t\tbool_var = input.Suspended\n\t\tcase \"active\":\n\t\t\tbool_var = input.Active\n\t\tcase \"deleted\":\n\t\t\tbool_var = input.Deleted\n\t\tcase \"verified\":\n\t\t\tbool_var = input.Verified\n\t\t}\n\n\t\tif bool_var == value {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tfor key, val := range T.filter {\n\t\tkey = strings.ToLower(key)\n\t\tswitch key {\n\t\tcase \"suspended\":\n\t\t\tfallthrough\n\t\tcase \"active\":\n\t\t\tfallthrough\n\t\tcase \"deleted\":\n\t\t\tfallthrough\n\t\tcase \"verified\":\n\t\t\tif v, ok := val.(bool); ok {\n\t\t\t\ttmp := input[0:0]\n\t\t\t\tfor _, user := range input {\n\t\t\t\t\tif matchBool(user, key, v) {\n\t\t\t\t\t\ttmp = append(tmp, user)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tinput = tmp\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"Invalid filter for \\\"%s\\\", expected bool got %v(%v) instead.\", key, reflect.TypeOf(val), val)\n\t\t\t}\n\t\t}\n\t}\n\treturn input, nil\n}", "func (mr *MockClientMockRecorder) GetUserById(ctx, id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserById\", reflect.TypeOf((*MockClient)(nil).GetUserById), ctx, id)\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 (mr *MockDatabaseMockRecorder) GetUsersIDByGitSourceName(gitSourceName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUsersIDByGitSourceName\", reflect.TypeOf((*MockDatabase)(nil).GetUsersIDByGitSourceName), gitSourceName)\n}", "func (m *UserMutation) UserofIDs() (ids []int) {\n\tfor id := range m.userof {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func (mr *ClientMockRecorder) GetOrganizationUsers(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetOrganizationUsers\", reflect.TypeOf((*Client)(nil).GetOrganizationUsers), arg0, arg1, arg2)\n}", "func (w *ServerInterfaceWrapper) GetUsers(ctx echo.Context) error {\n\tvar err error\n\n\tctx.Set(\"OAuth.Scopes\", []string{\"\"})\n\n\t// Parameter object where we will unmarshal all parameters from the context\n\tvar params GetUsersParams\n\t// ------------- Optional query parameter \"page_size\" -------------\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"page_size\", ctx.QueryParams(), &params.PageSize)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter page_size: %s\", err))\n\t}\n\n\t// ------------- Optional query parameter \"page_number\" -------------\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"page_number\", ctx.QueryParams(), &params.PageNumber)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter page_number: %s\", err))\n\t}\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetUsers(ctx, params)\n\treturn err\n}", "func GetUsers(filters *Filter) []*User {\n\n\tuser := make([]*User, 0)\n\tvar err error\n\n\tif filters != nil {\n\t\terr = GetDB().Select(filters.Column).Find(&user).Error\n\t} else {\n\t\terr = GetDB().Select([]string{\"id\", \"name\", \"email\", \"google_photo_url\", \"facebook_photo_url\"}).Find(&user).Error\n\t}\n\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn user\n}", "func (m *CarInspectionMutation) UserIDs() (ids []int) {\n\tif id := m.user; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\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 (mr *MockProductMockRecorder) GetConcurrentNominativeUsersBySwidTag(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetConcurrentNominativeUsersBySwidTag\", reflect.TypeOf((*MockProduct)(nil).GetConcurrentNominativeUsersBySwidTag), arg0, arg1)\n}" ]
[ "0.7310258", "0.68961126", "0.67332506", "0.63587415", "0.63334304", "0.625967", "0.6245924", "0.60865736", "0.60831183", "0.600005", "0.59956676", "0.5959423", "0.5932733", "0.5887517", "0.5874619", "0.5845255", "0.5779157", "0.57637155", "0.57446516", "0.5744162", "0.5706276", "0.5706114", "0.56914717", "0.56816477", "0.56732684", "0.5659001", "0.56435454", "0.56420213", "0.56275994", "0.56242675", "0.5596581", "0.55963147", "0.558095", "0.5577373", "0.5574544", "0.55609953", "0.5539196", "0.5537317", "0.55264163", "0.551325", "0.5509988", "0.5480458", "0.5470893", "0.54516965", "0.5446784", "0.5432918", "0.5419291", "0.5415347", "0.54146975", "0.5406171", "0.5401906", "0.53920215", "0.53866225", "0.5380084", "0.53792256", "0.53735405", "0.5371638", "0.5365637", "0.5358514", "0.53509367", "0.53491586", "0.5348737", "0.5348585", "0.5330906", "0.532277", "0.5314708", "0.5314708", "0.5312443", "0.53026307", "0.5299919", "0.5299784", "0.52863574", "0.52705497", "0.5253929", "0.52419406", "0.5241593", "0.5240728", "0.52340627", "0.5225668", "0.5222821", "0.52141535", "0.5210577", "0.52088314", "0.52043533", "0.52009094", "0.5189911", "0.51879543", "0.5180729", "0.5178725", "0.51768", "0.51762784", "0.5171368", "0.5170159", "0.5158675", "0.5154448", "0.514968", "0.514625", "0.5144339", "0.51436067", "0.5141932" ]
0.77534914
0
DeleteUserWhereUsername mocks base method
func (m *MockUserRepositoryInterface) DeleteUserWhereUsername(arg0 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteUserWhereUsername", arg0) ret0, _ := ret[0].(error) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_m *MockService) DeleteUser(ctx context.Context, id string) error {\n\tret := _m.ctrl.Call(_m, \"DeleteUser\", ctx, id)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockStore) DeleteUser(arg0 context.Context, arg1 uuid.UUID) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUser\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) DeleteUser(arg0 string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUser\", arg0)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserStore) Delete(arg0 context.Context, arg1 *sql.Tx, arg2 proto.User) error {\n\tret := m.ctrl.Call(m, \"Delete\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockDatabase) DeleteUser(userId uint64) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUser\", userId)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUser) Delete(userKey api.UserKey, checksum api.Checksum) error {\n\tret := m.ctrl.Call(m, \"Delete\", userKey, checksum)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockPersister) DeleteUser(targetID, userID int) error {\n\tret := m.ctrl.Call(m, \"DeleteUser\", targetID, userID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m_2 *MockUserRepository) Delete(m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Delete\", m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProduct) DeleteNominativeUserByID(arg0 context.Context, arg1 db.DeleteNominativeUserByIDParams) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteNominativeUserByID\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m_2 *MockUserUsecaser) Delete(c context.Context, m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Delete\", c, m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) DeletePermissionForUser(arg0 string, arg1 ...string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"DeletePermissionForUser\", varargs...)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUCAuth) Delete(ctx context.Context, userID uint) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, userID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *UserRepo) DeleteUser(_a0 uint64) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(uint64) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *UserRepositoryI) Delete(tx database.TransactionI, user *models.UserPrivateInfo) error {\n\tret := _m.Called(tx, user)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(database.TransactionI, *models.UserPrivateInfo) error); ok {\n\t\tr0 = rf(tx, user)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockClient) DeleteUser(ctx context.Context, id string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUser\", ctx, id)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestDeleteUserService (t *testing.T){\n\terr := DeleteUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = DeleteUserService(user_02.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = DeleteUserService(user_03.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = DeleteUserService(user_04.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n}", "func (m *MockRepository) DeleteSubscribeUser(arg0 uint64) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteSubscribeUser\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestCreateDeleteUserAccount(t *testing.T) {\n var account UserAccount\n\n if err := Create(\"TestyTesterson1134\", \"[email protected]\", \"pass\", &account); err != nil {\n t.Error(err)\n }\n\n if err := Delete(account.Key); err != nil {\n t.Error(err)\n }\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUsername(arg0 string) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUsername\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) DeleteRoleForUser(arg0, arg1 string, arg2 ...string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"DeleteRoleForUser\", varargs...)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSessionStorage) DeleteUserSession(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUserSession\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func DeleteUser(c *gin.Context) {}", "func (_m *Repository) DeleteUser(ctx context.Context, id uint64) error {\n\tret := _m.Called(ctx, id)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, uint64) error); ok {\n\t\tr0 = rf(ctx, id)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockUserRepository) DeleteUser(user easyalert.User) error {\n\tret := m.ctrl.Call(m, \"DeleteUser\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) DeleteRolesForUser(arg0 string, arg1 ...string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"DeleteRolesForUser\", varargs...)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIUserService) RemoveUserByName(name string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RemoveUserByName\", name)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockClient) DeleteUserSessions(ctx context.Context, id string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUserSessions\", ctx, id)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) DeletePermissionsForUser(arg0 string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeletePermissionsForUser\", arg0)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUseCase) DeleteUser(ctx context.Context, userID uint64) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUser\", ctx, userID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockUserRepositoryInterfaceMockRecorder) DeleteUserWhereUsername(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUserWhereUsername\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).DeleteUserWhereUsername), arg0)\n}", "func (m *MockUserRepository) Delete(id UserUUID) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", id)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func DeleteUser(userid int64) error {\n _, err := model.Database.Exec(\"DELETE FROM users WHERE userid = ? AND isadmin = ?\", userid, false)\n if err != nil {\n return err\n }\n return nil\n}", "func (m *MockRepository) Delete(ctx context.Context, userID uint) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, userID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockClusterAdmin) DeleteUserScramCredentials(arg0 []sarama.AlterUserScramCredentialsDelete) ([]*sarama.AlterUserScramCredentialsResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUserScramCredentials\", arg0)\n\tret0, _ := ret[0].([]*sarama.AlterUserScramCredentialsResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *EducationBackend) DeleteEducationUser(ctx context.Context, nameOrID string) error {\n\tret := _m.Called(ctx, nameOrID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, string) error); ok {\n\t\tr0 = rf(ctx, nameOrID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockUserRepo) DeleteByEmail(arg0 string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteByEmail\", arg0)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockBusinessContract) DeleteUser(ctx context.Context, request *business.DeleteUserRequest) (*business.DeleteUserResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUser\", ctx, request)\n\tret0, _ := ret[0].(*business.DeleteUserResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockUserRepositoryProvider) Delete(userID int) (bool, error) {\n\tret := _m.Called(userID)\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func(int) bool); ok {\n\t\tr0 = rf(userID)\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int) error); ok {\n\t\tr1 = rf(userID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func deleteTest(t *testing.T, creds client.Credentials, deleteData []testDeleteData) {\n\tserver := setup(t, testMultiUserFilenameJSON)\n\tdefer teardown(t, server)\n\ttokenCookie := login(t, server, creds)\n\tdefer logout(t, server, tokenCookie)\n\n\tfor _, d := range deleteData {\n\t\tt.Run(fmt.Sprintf(\"ID-%s\", d.id),\n\t\t\tfunc(t *testing.T) {\n\t\t\t\trequest := httptest.NewRequest(http.MethodDelete, \"http://user/Delete/\"+d.id, nil)\n\t\t\t\trequest.AddCookie(tokenCookie)\n\t\t\t\tresponse := httptest.NewRecorder()\n\t\t\t\tps := httprouter.Params{\n\t\t\t\t\thttprouter.Param{\n\t\t\t\t\t\tKey: \"id\",\n\t\t\t\t\t\tValue: d.id},\n\t\t\t\t}\n\t\t\t\tserver.DeleteUser(response, request, ps)\n\t\t\t\tassert.Equalf(t, d.expectedResponse, response.Code,\n\t\t\t\t\t\"%s attempted to delete user ID %s, expected '%s' got '%s'\", creds.Username, d.id,\n\t\t\t\t\thttp.StatusText(d.expectedResponse), http.StatusText(response.Code))\n\t\t\t})\n\t}\n}", "func PrepareForDeleteUser(roundTripper *mhttp.MockRoundTripper, rootURL, userName, user, passwd string) (\n\tresponse *http.Response) {\n\trequest, _ := http.NewRequest(http.MethodPost, fmt.Sprintf(\"%s/securityRealm/user/%s/doDelete\", rootURL, userName), nil)\n\trequest.Header.Add(httpdownloader.ContentType, httpdownloader.ApplicationForm)\n\tresponse = PrepareCommonPost(request, \"\", roundTripper, user, passwd, rootURL)\n\treturn\n}", "func (_m *MutationResolver) DeleteUser(ctx context.Context, id int64) (*pg.User, error) {\n\tret := _m.Called(ctx, id)\n\n\tvar r0 *pg.User\n\tif rf, ok := ret.Get(0).(func(context.Context, int64) *pg.User); ok {\n\t\tr0 = rf(ctx, id)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*pg.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, int64) error); ok {\n\t\tr1 = rf(ctx, id)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockService) DeleteWhere(arg0, arg1, arg2 interface{}) error {\n\tret := m.ctrl.Call(m, \"DeleteWhere\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserRepository) Delete(id int) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", id)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserDataAccessor) delete(id UserUUID) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"delete\", id)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *UserRepository) Delete(id uuid.UUID) error {\n\tret := _m.Called(id)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(uuid.UUID) error); ok {\n\t\tr0 = rf(id)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (a *Client) DeleteUsername(params *DeleteUsernameParams, authInfo runtime.ClientAuthInfoWriter) (*DeleteUsernameOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteUsernameParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"deleteUsername\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/usernames/{userName}\",\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: &DeleteUsernameReader{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.(*DeleteUsernameOK), nil\n\n}", "func (m *MockClient) DeleteUser(arg0 *iam.DeleteUserInput) (*iam.DeleteUserOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUser\", arg0)\n\tret0, _ := ret[0].(*iam.DeleteUserOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) DeleteUser(arg0 *iam.DeleteUserInput) (*iam.DeleteUserOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUser\", arg0)\n\tret0, _ := ret[0].(*iam.DeleteUserOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (u *UserRepository) Delete(ID uint) error {\n\targs := u.Called(ID)\n\treturn args.Error(0)\n}", "func (m *MockValidationService) Username(username string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Username\", username)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *MockStore) DeleteUserPermissions(ctx context.Context, orgID int64, userID int64) error {\n\tret := _m.Called(ctx, orgID, userID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, int64, int64) error); ok {\n\t\tr0 = rf(ctx, orgID, userID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockUser) Delete(ctx context.Context, accountID string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, accountID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *CognitoIdentityProviderAPI) DeleteUser(_a0 *cognitoidentityprovider.DeleteUserInput) (*cognitoidentityprovider.DeleteUserOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *cognitoidentityprovider.DeleteUserOutput\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.DeleteUserInput) *cognitoidentityprovider.DeleteUserOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*cognitoidentityprovider.DeleteUserOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.DeleteUserInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockUsersService) DeleteUser(u *models.User) *errs.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUser\", u)\n\tret0, _ := ret[0].(*errs.Error)\n\treturn ret0\n}", "func (_m *TransactionRepo) DeleteUserTransactions(id int64, userID int64) (int64, error) {\n\tret := _m.Called(id, userID)\n\n\tvar r0 int64\n\tif rf, ok := ret.Get(0).(func(int64, int64) int64); ok {\n\t\tr0 = rf(id, userID)\n\t} else {\n\t\tr0 = ret.Get(0).(int64)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64, int64) error); ok {\n\t\tr1 = rf(id, userID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func UserDelete(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\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 (m *MockRepository) Delete(id UserID) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", id)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockProjectServiceIface) DeleteUserFromProject(p *DeleteUserFromProjectParams) (*DeleteUserFromProjectResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUserFromProject\", p)\n\tret0, _ := ret[0].(*DeleteUserFromProjectResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (store *dbStore) DeleteUserByUsername(username string) error {\r\n\tsqlStatement := fmt.Sprint(\"DELETE FROM user where username= '\", username, \"'\")\r\n\r\n\tfmt.Println(sqlStatement)\r\n\r\n\t_, err := store.db.Query(sqlStatement)\r\n\tif err != nil {\r\n\t\tfmt.Printf(\"failed to execute delete user query on the database: %v\", err)\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn nil\r\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 (m *MockUsecase) DeletePlaylistFromUser(userID, playlistID int) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeletePlaylistFromUser\", userID, playlistID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockDBStorage) DeleteCallback(arg0, arg1 string) (sql.Result, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteCallback\", arg0, arg1)\n\tret0, _ := ret[0].(sql.Result)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func db_delete_user(username string) {\n file_path := path.Join(\"db/users\", strings.ToLower(username) + \".json\")\n\n err := os.Remove(file_path)\n \n if err != nil {\n fmt.Println(err.Error())\n return\n }\n fmt.Println(\"User Removed: \", username)\n}", "func TestDeleteUserServiceDoesntExist (t *testing.T){\n\terr := DeleteUserService(user_01.SocialNumber)\n\tassert.Equal(t, 404, err.HTTPStatus)\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 (c *SQLiteConn) authUserDelete(username string) int {\n\t// NOOP\n\treturn 0\n}", "func (c *SQLiteConn) AuthUserDelete(username string) error {\n\t// NOOP\n\treturn nil\n}", "func (u *UserTest) Delete() error {\n\treturn nil\n}", "func (call *UserUsecaseImpl) Delete(id int) error {\n\treturn call.userRepo.Delete(id)\n}", "func (_m *MockMessageDatabase) DeleteMessagesByUser(userID uint) error {\n\tret := _m.Called(userID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(uint) error); ok {\n\t\tr0 = rf(userID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func userDeleteCommandFunc(cmd *cobra.Command, args []string) {\n\tif len(args) != 1 {\n\t\tExitWithError(ExitBadArgs, fmt.Errorf(\"user delete command requires user name as its argument\"))\n\t}\n\n\tfmt.Println(\"删除用户成功\", args[0])\n}", "func (m *MockLikeRepository) Delete(ctx context.Context, postID int, userReferenceID string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, postID, userReferenceID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockStudentRepository) Delete(arg0 gocql.UUID) *exception.AppError {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", arg0)\n\tret0, _ := ret[0].(*exception.AppError)\n\treturn ret0\n}", "func (m *MockReviewRepository) DeleteUserReviewForMovie(arg0, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUserReviewForMovie\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIUserService) QueryUserByName(name string) (*model.UserDB, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryUserByName\", name)\n\tret0, _ := ret[0].(*model.UserDB)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *DB) DeleteUserSubscription(userID string, subscriptionID string) error {\n\tret := _m.Called(userID, subscriptionID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, string) error); ok {\n\t\tr0 = rf(userID, subscriptionID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockUserRepo) DeleteAll() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteAll\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *ChannelStore) PermanentDeleteMembersByUser(userID string) error {\n\tret := _m.Called(userID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(userID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockReminds) HandleDeleteRemindCommand(arg0 *discordgo.Session, arg1 *discordgo.MessageCreate, arg2 []string, arg3 context.Context) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"HandleDeleteRemindCommand\", arg0, arg1, arg2, arg3)\n}", "func (userRepository UserRepository) Delete(userId uint64) error {\n\tstatement, err := userRepository.db.Prepare(\n\t\t\"delete from users where id = ?\",\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer statement.Close()\n\n\tif _, err = statement.Exec(userId); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUserID(arg0 uint64) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUserID\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *mysqlUserRepository) Delete(id int64) (err error) {\n\tquery := `DELETE FROM user WHERE id = ?`\n\n\tstmt, err := m.Conn.Prepare(query)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tres, err := stmt.Exec(id)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trowsAffected, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif rowsAffected != 1 {\n\t\terr = fmt.Errorf(\"Something not expected: %d rows affected\", rowsAffected)\n\t\treturn\n\t}\n\treturn\n}", "func (m *MockRepository) GetByUsername(ctx context.Context, username string, password []byte) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByUsername\", ctx, username, password)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Repository) DeleteUserSkill(ctx context.Context, cid uint64, sid uint64) error {\n\tret := _m.Called(ctx, cid, sid)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, uint64, uint64) error); ok {\n\t\tr0 = rf(ctx, cid, sid)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockUserRepo) DeleteByID(arg0 string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteByID\", arg0)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestSuccessDeleteUser(t *testing.T) {\n\terr := database.ConnectDB()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar client = graphql.NewClient(\"http://localhost:8082/query\")\n\n\tuser := models.User{}\n\tdatabase.DB.Model(&models.User{}).First(&user)\n\t// database.DB.First(&user)\n\tid := user.ID\n\n\tfmt.Println(strconv.Itoa(int(id)))\n\tvar req = graphql.NewRequest(`\n\t\tmutation {\n\t\t\tdeleteUser(id:\"` + strconv.Itoa(int(id)) + `\")\n\t\t}\n\t`)\n\n\tctx := context.Background()\n\n\t// err to run and catch the response\n\tvar respData map[string]interface{}\n\tif err := client.Run(ctx, req, &respData); err != nil {\n\t\tt.Error(err)\n\t}\n\tfmt.Print(respData)\n\n\tisDeleted := respData[\"deleteUser\"]\n\tassert.Equal(t, isDeleted, true, \"Must be deleted\")\n}", "func (m *MockUserRepository) ExistUser(email string) bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ExistUser\", email)\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (_m *CognitoIdentityProviderAPI) AdminDeleteUser(_a0 *cognitoidentityprovider.AdminDeleteUserInput) (*cognitoidentityprovider.AdminDeleteUserOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *cognitoidentityprovider.AdminDeleteUserOutput\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.AdminDeleteUserInput) *cognitoidentityprovider.AdminDeleteUserOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*cognitoidentityprovider.AdminDeleteUserOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.AdminDeleteUserInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockAuthCheckerClient) Delete(arg0 context.Context, arg1 *auth.SessionToken, arg2 ...grpc.CallOption) (*auth.Nothing, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Delete\", varargs...)\n\tret0, _ := ret[0].(*auth.Nothing)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) DeleteRoleForUserInDomain(arg0, arg1, arg2 string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteRoleForUserInDomain\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserService) Delete(ctx context.Context, id int64) error {\n\tret := m.ctrl.Call(m, \"Delete\", ctx, id)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *CognitoIdentityProviderAPI) DeleteUserRequest(_a0 *cognitoidentityprovider.DeleteUserInput) (*request.Request, *cognitoidentityprovider.DeleteUserOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.DeleteUserInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *cognitoidentityprovider.DeleteUserOutput\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.DeleteUserInput) *cognitoidentityprovider.DeleteUserOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*cognitoidentityprovider.DeleteUserOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (m *Mockpersistent) Delete(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *UserExtModel) Delete(ctx context.Context, builders ...query.SQLBuilder) (int64, error) {\n\n\tsqlStr, params := m.query.Merge(builders...).AppendCondition(m.applyScope()).Table(m.tableName).ResolveDelete()\n\n\tres, err := m.db.ExecContext(ctx, sqlStr, params...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn res.RowsAffected()\n\n}", "func DeleteUser(username string) bool {\n\tDeleteProjectByUsername(username)\n\tclient := pb.NewMysqlClient(MysqlGrpcClient)\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tresult, _ := client.DeleteUser(ctx, &pb.Condition{Value: []*pb.Value{\n\t\t{Key: \"username\", Value: username},\n\t}})\n\tfmt.Println(result.Value)\n\treturn result.IsVaild\n}", "func (m *MockDataSource) GetUserByUsername(username string) (model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByUsername\", username)\n\tret0, _ := ret[0].(model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\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 (m *MockCredentialsStorer) Delete(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestFailDeleteUser(t *testing.T) {\n\tvar client = graphql.NewClient(fmt.Sprintf(\"%s\", defaultUrl))\n\n\tvar req = graphql.NewRequest(`\n\t\tmutation deleteUser {\n\t\t\tdeleteUser(id : \"20\")\n\t\t}\n\t`)\n\n\tctx := context.Background()\n\n\t// err to run and catch the response\n\tvar respData map[string]interface{}\n\tif err := client.Run(ctx, req, &respData); err != nil {\n\t\tisDeleted := respData[\"deleteUser\"]\n\t\tassert.Nil(t, isDeleted)\n\t}\n\n}" ]
[ "0.67324287", "0.6550971", "0.6482611", "0.64584106", "0.64239967", "0.6369055", "0.63083726", "0.63040715", "0.6300774", "0.6292007", "0.62919134", "0.62467676", "0.6225556", "0.6211452", "0.6209731", "0.6206393", "0.6206031", "0.61804986", "0.61734676", "0.6117033", "0.61118406", "0.60884994", "0.6066987", "0.60626405", "0.6057911", "0.59446704", "0.59384906", "0.5929819", "0.5922343", "0.5896012", "0.5879283", "0.5879139", "0.5853565", "0.5844837", "0.58275807", "0.581274", "0.5801006", "0.5796098", "0.5783809", "0.5763428", "0.5752177", "0.5729693", "0.5719551", "0.5706742", "0.57037973", "0.56975955", "0.5696467", "0.5696467", "0.56864005", "0.5685539", "0.56752634", "0.56740004", "0.5673129", "0.56723315", "0.56718904", "0.5668462", "0.56321716", "0.56178176", "0.56135356", "0.56060296", "0.55978733", "0.55926377", "0.55872834", "0.55528057", "0.5546773", "0.55426174", "0.5540007", "0.55335516", "0.5519757", "0.5513288", "0.55125016", "0.55078346", "0.55063385", "0.5501479", "0.5499001", "0.54722655", "0.54707956", "0.54621094", "0.54403615", "0.54320496", "0.5431636", "0.5430561", "0.5426022", "0.54222906", "0.542085", "0.54179", "0.5417397", "0.54052895", "0.5402599", "0.5371466", "0.53572357", "0.5353431", "0.5350878", "0.5339827", "0.5338656", "0.53371453", "0.53264093", "0.5322814", "0.53181595", "0.53176653" ]
0.8132437
0
DeleteUserWhereUsername indicates an expected call of DeleteUserWhereUsername
func (mr *MockUserRepositoryInterfaceMockRecorder) DeleteUserWhereUsername(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUserWhereUsername", reflect.TypeOf((*MockUserRepositoryInterface)(nil).DeleteUserWhereUsername), arg0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockUserRepositoryInterface) DeleteUserWhereUsername(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUserWhereUsername\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (a *Client) DeleteUsername(params *DeleteUsernameParams, authInfo runtime.ClientAuthInfoWriter) (*DeleteUsernameOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteUsernameParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"deleteUsername\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/usernames/{userName}\",\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: &DeleteUsernameReader{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.(*DeleteUsernameOK), nil\n\n}", "func (c *SQLiteConn) authUserDelete(username string) int {\n\t// NOOP\n\treturn 0\n}", "func DeleteUser(c *gin.Context) {}", "func DeleteUser(username string) bool {\n\tDeleteProjectByUsername(username)\n\tclient := pb.NewMysqlClient(MysqlGrpcClient)\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tresult, _ := client.DeleteUser(ctx, &pb.Condition{Value: []*pb.Value{\n\t\t{Key: \"username\", Value: username},\n\t}})\n\tfmt.Println(result.Value)\n\treturn result.IsVaild\n}", "func (store *dbStore) DeleteUserByUsername(username string) error {\r\n\tsqlStatement := fmt.Sprint(\"DELETE FROM user where username= '\", username, \"'\")\r\n\r\n\tfmt.Println(sqlStatement)\r\n\r\n\t_, err := store.db.Query(sqlStatement)\r\n\tif err != nil {\r\n\t\tfmt.Printf(\"failed to execute delete user query on the database: %v\", err)\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn nil\r\n}", "func TestFailDeleteUser(t *testing.T) {\n\tvar client = graphql.NewClient(fmt.Sprintf(\"%s\", defaultUrl))\n\n\tvar req = graphql.NewRequest(`\n\t\tmutation deleteUser {\n\t\t\tdeleteUser(id : \"20\")\n\t\t}\n\t`)\n\n\tctx := context.Background()\n\n\t// err to run and catch the response\n\tvar respData map[string]interface{}\n\tif err := client.Run(ctx, req, &respData); err != nil {\n\t\tisDeleted := respData[\"deleteUser\"]\n\t\tassert.Nil(t, isDeleted)\n\t}\n\n}", "func (c *SQLiteConn) AuthUserDelete(username string) error {\n\t// NOOP\n\treturn nil\n}", "func TestDeleteUserService (t *testing.T){\n\terr := DeleteUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = DeleteUserService(user_02.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = DeleteUserService(user_03.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = DeleteUserService(user_04.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n}", "func DeleteUser(userid int64) error {\n _, err := model.Database.Exec(\"DELETE FROM users WHERE userid = ? AND isadmin = ?\", userid, false)\n if err != nil {\n return err\n }\n return nil\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 (_mr *MockServiceMockRecorder) DeleteUser(arg0, arg1 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"DeleteUser\", reflect.TypeOf((*MockService)(nil).DeleteUser), arg0, arg1)\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 userDeleteCommandFunc(cmd *cobra.Command, args []string) {\n\tif len(args) != 1 {\n\t\tExitWithError(ExitBadArgs, fmt.Errorf(\"user delete command requires user name as its argument\"))\n\t}\n\n\tfmt.Println(\"删除用户成功\", args[0])\n}", "func (db Database) DeleteUser(username string) error {\n\treturn errors.New(\"I'm not implemented yet\")\n}", "func deleteUser(username string) bool {\n\tlog.Printf(\"Deleting user: %s\", username)\n\tcmd := exec.Command(\"/bin/sh\", \"-c\", fmt.Sprintf(delUserCommand, username))\n\tif _, err := cmd.CombinedOutput(); err != nil {\n\t\tlog.Printf(\"Error: Can't delete user: %s: %s\", username, err)\n\t\treturn false\n\t}\n\treturn true\n}", "func (mr *MockDatabaseMockRecorder) DeleteUser(userId interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUser\", reflect.TypeOf((*MockDatabase)(nil).DeleteUser), userId)\n}", "func DeleteUser(username string) {\n\tmagentaBold := color.New(color.FgMagenta, color.Bold, color.Underline)\n\tmagentaBold.Println(\"Action selected: Delete user from Github\")\n\tusername = listUser.CheckUsername(username)\n\tgithubUser := listUser.GetGithubUser(username)\n\tlistUser.PrintUserInfo(githubUser)\n\tcheck := PromptDelete(username)\n\tswitch check {\n\tcase \"yes\":\n\t\tDeleteFromGithub(username)\n\tcase \"no\":\n\t\treturn\n\t}\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\n\n\thttpext.SuccessAPI(w, \"ok\")\n}", "func (mr *MockClientMockRecorder) DeleteUser(ctx, id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUser\", reflect.TypeOf((*MockClient)(nil).DeleteUser), ctx, id)\n}", "func (mr *MockClientMockRecorder) DeleteUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUser\", reflect.TypeOf((*MockClient)(nil).DeleteUser), arg0)\n}", "func (mr *MockClientMockRecorder) DeleteUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUser\", reflect.TypeOf((*MockClient)(nil).DeleteUser), arg0)\n}", "func TestSuccessDeleteUser(t *testing.T) {\n\terr := database.ConnectDB()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar client = graphql.NewClient(\"http://localhost:8082/query\")\n\n\tuser := models.User{}\n\tdatabase.DB.Model(&models.User{}).First(&user)\n\t// database.DB.First(&user)\n\tid := user.ID\n\n\tfmt.Println(strconv.Itoa(int(id)))\n\tvar req = graphql.NewRequest(`\n\t\tmutation {\n\t\t\tdeleteUser(id:\"` + strconv.Itoa(int(id)) + `\")\n\t\t}\n\t`)\n\n\tctx := context.Background()\n\n\t// err to run and catch the response\n\tvar respData map[string]interface{}\n\tif err := client.Run(ctx, req, &respData); err != nil {\n\t\tt.Error(err)\n\t}\n\tfmt.Print(respData)\n\n\tisDeleted := respData[\"deleteUser\"]\n\tassert.Equal(t, isDeleted, true, \"Must be deleted\")\n}", "func (mr *MockStoreMockRecorder) DeleteUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUser\", reflect.TypeOf((*MockStore)(nil).DeleteUser), arg0, arg1)\n}", "func (mr *MockIDistributedEnforcerMockRecorder) DeleteUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUser\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).DeleteUser), arg0)\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 TestCreateDeleteUserAccount(t *testing.T) {\n var account UserAccount\n\n if err := Create(\"TestyTesterson1134\", \"[email protected]\", \"pass\", &account); err != nil {\n t.Error(err)\n }\n\n if err := Delete(account.Key); err != nil {\n t.Error(err)\n }\n}", "func (mr *MockUseCaseMockRecorder) DeleteUser(ctx, userID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUser\", reflect.TypeOf((*MockUseCase)(nil).DeleteUser), ctx, userID)\n}", "func UserDelete(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\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 TestDeleteUserServiceDoesntExist (t *testing.T){\n\terr := DeleteUserService(user_01.SocialNumber)\n\tassert.Equal(t, 404, err.HTTPStatus)\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(username string) int {\n\tif isServerAlive() {\n\t\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\t\tdefer cancel()\n\t\treply, err := rpcCaller.DeleteUser(ctx, &pb.Credentials{Uname: username, Broadcast: true})\n\t\tif err == nil {\n\t\t\tfmt.Println(\"Delete User RPC successful\", reply)\n\t\t\treturn 0\n\t\t} else {\n\t\t\tfmt.Println(\"Delete User RPC failed\", reply, err)\n\t\t\treturn -1\n\t\t}\n\t} else {\n\t\tdebugPrint(\"Debug: Primary server down, cant process requests\")\n\t\treturn -1\n\t}\n}", "func (_m *MockService) DeleteUser(ctx context.Context, id string) error {\n\tret := _m.ctrl.Call(_m, \"DeleteUser\", ctx, id)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (s *Store) DeleteUser(email string) error {\r\n\r\n\tfilter := bson.M{\r\n\t\t\"email\": bson.M{\r\n\t\t\t\"$eq\": email,\r\n\t\t},\r\n\t}\r\n\r\n\tuserCollection := s.Collection(\"userDetails\")\r\n\r\n\tdeleteResult, err := userCollection.DeleteOne(context.TODO(), filter)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tfmt.Printf(\"Deleted %v documents in the userDetails collection\\n\", deleteResult.DeletedCount)\r\n\r\n\tuserCollection = s.Collection(\"userCredentials\")\r\n\r\n\tdeleteResult, err = userCollection.DeleteOne(context.TODO(), filter)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tfmt.Printf(\"Deleted %v documents in the userCredentials collection\\n\", deleteResult.DeletedCount)\r\n\r\n\treturn nil\r\n}", "func (a *Server) DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"delete a user\")\n}", "func _delete(context echo.Context, user *User) error {\n\tdeleteErr := Remove(user.Key)\n\tif deleteErr != nil {\n\t\tlog.Printf(\"Cannot delete user %v\", deleteErr)\n\t\treturn context.JSON(http.StatusInternalServerError, errors.New(\"Cannot delete user with ID: \"+user.ID))\n\t}\n\treturn context.NoContent(http.StatusNoContent)\n}", "func (mr *MockPersisterMockRecorder) DeleteUser(targetID, userID interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUser\", reflect.TypeOf((*MockPersister)(nil).DeleteUser), targetID, userID)\n}", "func DeleteUser(username string) error {\n\tif err := r.Table(\"users\").Filter(map[string]interface{}{\"Name\": &username}).Delete().Exec(session); err != nil {\n\t\treturn err\n\t}\n\treturn errors.New(\"The user has been deleted successful!\")\n}", "func (mr *MockClusterAdminMockRecorder) DeleteUserScramCredentials(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUserScramCredentials\", reflect.TypeOf((*MockClusterAdmin)(nil).DeleteUserScramCredentials), arg0)\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 (m *MockIDistributedEnforcer) DeletePermissionForUser(arg0 string, arg1 ...string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"DeletePermissionForUser\", varargs...)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Manager) Delete(ctx context.Context, tx *sql.Tx, user v0.User) error {\n\tresult, err := tx.ExecContext(ctx, `\n\t\t\t\tUPDATE users \n\t\t\t\tSET deleted_at = ?, \n\t\t\t\tdeleted = TRUE \n\t\t\t\tWHERE primary_public_key = ?;`,\n\t\ttime.Now(),\n\t\tuser.PrimaryPublicKey,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\taffected, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif affected == 0 {\n\t\treturn ErrUserDoesNotExists\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 ExampleDelete() {\n\tuser := q.T(\"user\")\n\tdel := q.Delete(user).Where(q.Eq(user.C(\"id\"), 1))\n\t// del := q.Delete().From(user).Where(q.Eq(user.C(\"id\"), 1)) // same\n\tfmt.Println(del)\n\n\t// Even in this case, the original name is used as a table and a column name\n\t// because Insert, Delete and Update aren't supporting \"AS\" syntax.\n\tu := q.T(\"user\", \"u\")\n\tfmt.Println(q.Delete(u).Where(q.Eq(u.C(\"id\", \"i\"), 1)))\n\t// Output:\n\t// DELETE FROM \"user\" WHERE \"id\" = ? [1]\n\t// DELETE FROM \"user\" WHERE \"id\" = ? [1]\n}", "func DeleteUser(Id int32) (rowsAffected int64, err error) {\n\trecord := &User{}\n\tdb := gdb.GetDB().First(record, Id)\n\tif db.Error != nil {\n\t\treturn -1, ErrNotFound\n\t}\n\n\tdb = gdb.GetDB().Delete(record)\n\tif err = db.Error; err != nil {\n\t\treturn -1, ErrDeleteFailed\n\t}\n\n\treturn db.RowsAffected, nil\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 (mr *MockBusinessContractMockRecorder) DeleteUser(ctx, request interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUser\", reflect.TypeOf((*MockBusinessContract)(nil).DeleteUser), ctx, request)\n}", "func (a *UserApiService) DeleteUser(ctx context.Context, username string) UserApiDeleteUserRequest {\n\treturn UserApiDeleteUserRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tusername: username,\n\t}\n}", "func Delete() error {\n\ti, err := orm.SetTable(\"tb_user\").SetPK(\"uid\").Where(\"name=$1 and uid>$2\", \"viney\", 3).DeleteRow()\n\tif err == nil {\n\t\tfmt.Println(i)\n\t\treturn nil\n\t}\n\treturn err\n}", "func (userRepository UserRepository) Delete(userId uint64) error {\n\tstatement, err := userRepository.db.Prepare(\n\t\t\"delete from users where id = ?\",\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer statement.Close()\n\n\tif _, err = statement.Exec(userId); err != nil {\n\t\treturn err\n\t}\n\treturn nil\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 PrepareForDeleteUser(roundTripper *mhttp.MockRoundTripper, rootURL, userName, user, passwd string) (\n\tresponse *http.Response) {\n\trequest, _ := http.NewRequest(http.MethodPost, fmt.Sprintf(\"%s/securityRealm/user/%s/doDelete\", rootURL, userName), nil)\n\trequest.Header.Add(httpdownloader.ContentType, httpdownloader.ApplicationForm)\n\tresponse = PrepareCommonPost(request, \"\", roundTripper, user, passwd, rootURL)\n\treturn\n}", "func db_delete_user(username string) {\n file_path := path.Join(\"db/users\", strings.ToLower(username) + \".json\")\n\n err := os.Remove(file_path)\n \n if err != nil {\n fmt.Println(err.Error())\n return\n }\n fmt.Println(\"User Removed: \", username)\n}", "func (u *UserRepository) Delete(ID uint) error {\n\targs := u.Called(ID)\n\treturn args.Error(0)\n}", "func Delete(userC *mgo.Collection, username, password string) error {\n\tok, err := Authenticate(userC, username, password)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ok {\n\t\terr = userC.Remove(bson.M{\n\t\t\t\"username\": username,\n\t\t})\n\t\tif err != nil {\n\t\t\tif err == mgo.ErrNotFound {\n\t\t\t\treturn errors.NewNotFound(\"user\", username)\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\treturn errors.ErrAuthentication\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(db *sql.DB, user *models.UserResponse) (int, error) {\n\tif user.ID > 0 {\n\t\tres, err := db.Exec(\"DELETE from users WHERE id = ?\", user.ID)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error inserting\")\n\t\t\tlog.Error(err)\n\t\t\treturn 0, err\n\t\t}\n\n\t\trowsAffected, err := res.RowsAffected()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error inserting\")\n\t\t\tlog.Error(err)\n\t\t\treturn 0, err\n\t\t}\n\t\treturn int(rowsAffected), nil\n\t}\n\treturn 0, errors.New(\"User ID is empty\")\n\n}", "func (_m *UserRepo) DeleteUser(_a0 uint64) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(uint64) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\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 (mr *MockUserRepositoryInterfaceMockRecorder) GetUserWhereUsername(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserWhereUsername\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).GetUserWhereUsername), arg0)\n}", "func DeleteUser(id int) {\n\tvar i int\n\ti = GetIndexOfUser(id)\n\tDeleteUserFromDatabase(i)\n}", "func (us *UserService) DeleteUser(username string) error {\n\tstatement := \"DELETE FROM users WHERE username = $1;\"\n\tresult, err := us.db.Exec(statement, username)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n == 0 {\n\t\treturn shuttletracker.ErrUserNotFound\n\t}\n\n\treturn nil\n}", "func (o *UsernameListing) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no UsernameListing provided for delete\")\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), usernameListingPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"username_listings\\\" WHERE \\\"id\\\"=$1\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from username_listings\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for username_listings\")\n\t}\n\n\treturn rowsAff, nil\n}", "func (mr *MockUserMockRecorder) Delete(userKey, checksum interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockUser)(nil).Delete), userKey, checksum)\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 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 (db *MongoDB) DeleteUser(username string) {\n\tsession, err := mgo.Dial(db.DatabaseURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer session.Close()\n\n\terr = session.DB(db.DatabaseName).C(db.DatabaseAnnounce).Remove(bson.M{\"username\": username})\n\n\tif err != nil {\n\t\tlog.Printf(\"Somethings wrong with Remove():%v\", err.Error())\n\t}\n\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(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 (mr *MockUserRepositoryMockRecorder) DeleteUser(user interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUser\", reflect.TypeOf((*MockUserRepository)(nil).DeleteUser), user)\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 (d *database) deleteUser(publicKey string) (err error) {\n\ttx, err := d.db.Begin()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\tquery := \"DELETE FROM letters WHERE sender == ?;\"\n\tlogger.Log.Debug(query)\n\tstmt, err := tx.Prepare(query)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(publicKey)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\treturn\n}", "func (c APIClient) DeleteUser(username string) error {\n\treturn c.doHTTPDelete(fmt.Sprintf(\"https://api.nsone.net/v1/account/users/%s\", username))\n}", "func DeleteUser(username, baseURL string) int {\n\tif utils.LoginCheck() {\n\t\tt := utils.GetToken()\n\t\tclient := &http.Client{}\n\t\treq, _ := http.NewRequest(\"DELETE\", baseURL+\"/v1/users/\" + username + \"?token=\"+t, nil)\n\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tutils.PrintError(err.Error())\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tutils.PrintError(err.Error())\n\t\t}\n\n\t\tif resp.StatusCode == 204 {\n\t\t\tfmt.Println(\"Delete User Succeed!\")\n\t\t\treturn 0\n\t\t}\n\n\t\tr := &Resp{}\n\t\terr = json.Unmarshal([]byte(string(body)), &r)\n\t\tif err != nil {\n\t\t\tutils.PrintError(err.Error())\n\t\t}\n\n\t\tif resp.StatusCode == 401 {\n\t\t\tfmt.Println(r.Message)\n\t\t\treturn 1\n\t\t}\n\n\t\treturn 0\n\t} else {\n\t\tfmt.Println(\"Please login first\")\n\t\treturn 1\n\t}\n\treturn 0\n}", "func deleteUser(userID int) error {\n\tdb, err := sql.Open(\"mysql\", DB_USER_NAME+\":\"+DB_PASSWORD+\"@unix(/var/run/mysql/mysql.sock)/\"+DB_NAME)\n\tif err != nil {\n\t\treturn errors.New(\"No connection\")\n\t}\n\n\tres, err := db.Exec(\"delete from Users where UserID=? and not exists(select 1 from StudentCourses where Student=? limit 1)\", userID, userID)\n\n\tif err != nil {\n\t\treturn errors.New(\"User is currently enrolled in a class. Please remove the student from the class before deleting the user.\")\n\t}\n\trowsAffected, err := res.RowsAffected()\n\n\tif rowsAffected != 1 {\n\t\treturn errors.New(\"Query didn't match any users.\")\n\t}\n\n\treturn nil\n}", "func (uh *UserHandler) Delete(c echo.Context) error {\n\tid_, err := strconv.Atoi(c.Param(\"id\"))\n\tid := uint(id_)\n\n\terr = uh.UserUseCase.Delete(id)\n\n\tif err != nil {\n\t\treturn c.JSON(GetStatusCode(err), ResponseError{Message: err.Error()})\n\t}\n\n\treturn c.NoContent(http.StatusNoContent)\n}", "func (m *MockClusterAdmin) DeleteUserScramCredentials(arg0 []sarama.AlterUserScramCredentialsDelete) ([]*sarama.AlterUserScramCredentialsResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUserScramCredentials\", arg0)\n\tret0, _ := ret[0].([]*sarama.AlterUserScramCredentialsResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\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 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 DeleteUser(person *Person, id string) (err error) {\n\tConfig.DB.Where(\"id = ?\", id).Delete(person)\n\treturn nil\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 (_m *Repository) DeleteUser(ctx context.Context, id uint64) error {\n\tret := _m.Called(ctx, id)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, uint64) error); ok {\n\t\tr0 = rf(ctx, id)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func DeleteUsers(c *gin.Context) {\n\tclient := mongoconn.Client\n\tcollection := client.Database(\"demo\").Collection(\"users\")\n\tctx, err := context.WithTimeout(context.Background(), 5*time.Second)\n\tif err != nil {\n\t}\n\tusername := c.Query(\"username\")\n\tvar dbquery dictionary\n\tif username != \"\" {\n\t\tdbquery = dictionary{\"name\": username}\n\t} else {\n\t\tdbquery = dictionary{}\n\t}\n\tresult, err2 := collection.DeleteMany(ctx, dbquery)\n\tif err2 != nil {\n\t\tfmt.Println(\"Error deleting items\")\n\t}\n\trecordsDeleted := result.DeletedCount\n\tif recordsDeleted == 0 {\n\t\tc.JSON(200, gin.H{\n\t\t\t\"message\": \"No records to delete\",\n\t\t})\n\t\treturn\n\t}\n\tc.JSON(200, gin.H{\n\t\t\"message\": \"Successfully deleted users\",\n\t})\n}", "func (u *UserTest) Delete() error {\n\treturn nil\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 (d *database) deleteUsers() (err error) {\n\ttx, err := d.db.Begin()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\tquery := \"DELETE FROM letters WHERE sender IN (SELECT sender FROM letters WHERE letter_purpose == '\" + purpose.ActionErase + \"');\"\n\tlogger.Log.Debug(query)\n\tstmt, err := tx.Prepare(query)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\treturn\n}", "func deleteTest(t *testing.T, creds client.Credentials, deleteData []testDeleteData) {\n\tserver := setup(t, testMultiUserFilenameJSON)\n\tdefer teardown(t, server)\n\ttokenCookie := login(t, server, creds)\n\tdefer logout(t, server, tokenCookie)\n\n\tfor _, d := range deleteData {\n\t\tt.Run(fmt.Sprintf(\"ID-%s\", d.id),\n\t\t\tfunc(t *testing.T) {\n\t\t\t\trequest := httptest.NewRequest(http.MethodDelete, \"http://user/Delete/\"+d.id, nil)\n\t\t\t\trequest.AddCookie(tokenCookie)\n\t\t\t\tresponse := httptest.NewRecorder()\n\t\t\t\tps := httprouter.Params{\n\t\t\t\t\thttprouter.Param{\n\t\t\t\t\t\tKey: \"id\",\n\t\t\t\t\t\tValue: d.id},\n\t\t\t\t}\n\t\t\t\tserver.DeleteUser(response, request, ps)\n\t\t\t\tassert.Equalf(t, d.expectedResponse, response.Code,\n\t\t\t\t\t\"%s attempted to delete user ID %s, expected '%s' got '%s'\", creds.Username, d.id,\n\t\t\t\t\thttp.StatusText(d.expectedResponse), http.StatusText(response.Code))\n\t\t\t})\n\t}\n}", "func (m *mysqlUserRepository) Delete(id int64) (err error) {\n\tquery := `DELETE FROM user WHERE id = ?`\n\n\tstmt, err := m.Conn.Prepare(query)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tres, err := stmt.Exec(id)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trowsAffected, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif rowsAffected != 1 {\n\t\terr = fmt.Errorf(\"Something not expected: %d rows affected\", rowsAffected)\n\t\treturn\n\t}\n\treturn\n}", "func (s *service) DeleteUser(ctx context.Context, userID string) error {\n\tlog.Trace(\"userservice.DeleteUser(%v) called\", userID)\n\n\terr := s.repository.DeleteUser(ctx, userID)\n\tif err != nil {\n\t\tlog.Errorf(\"DeleteUser error: %v\", err)\n\t}\n\treturn s.errTranslator(err)\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 (mr *MockProjectServiceIfaceMockRecorder) DeleteUserFromProject(p interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteUserFromProject\", reflect.TypeOf((*MockProjectServiceIface)(nil).DeleteUserFromProject), p)\n}", "func (m *MockStore) DeleteUser(arg0 context.Context, arg1 uuid.UUID) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUser\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockProductMockRecorder) DeleteNominativeUserByID(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteNominativeUserByID\", reflect.TypeOf((*MockProduct)(nil).DeleteNominativeUserByID), arg0, arg1)\n}", "func (b *UserServiceImpl) DeleteUser(ctx context.Context, strID string) (interface{}, error) {\n\tlog.Logger(ctx).Info(\"DeleteUser: \", strID)\n\t//Created filter to find and update\n\tid, err := primitive.ObjectIDFromHex(strID)\n\tif err != nil {\n\t\tlog.Logger(ctx).Errorf(\"Error in stingId To Hex conversion %v\", err)\n\t\treturn nil, err\n\t}\n\t//filter to delete user by id\n\t//TODO create more optinal filters e.g serch by name, email, mobile, fname_lname\n\tfilter := bson.M{\"_id\": bson.M{\"$eq\": id}}\n\n\t//call repository and return\n\tresp, err := b.userRepository.DeleteUser(ctx, filter)\n\tif err != nil {\n\t\tlog.Logger(ctx).Error(err)\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n\n}", "func (mr *MockIDistributedEnforcerMockRecorder) DeleteRoleForUser(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteRoleForUser\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).DeleteRoleForUser), varargs...)\n}", "func (m *MockIDistributedEnforcer) DeleteUser(arg0 string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteUser\", arg0)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\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 (h *ServiceUsersHandler) Delete(ctx context.Context, project, service, user string) error {\n\tpath := buildPath(\"project\", project, \"service\", service, \"user\", user)\n\tbts, err := h.client.doDeleteRequest(ctx, path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn checkAPIResponse(bts, nil)\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}" ]
[ "0.70574117", "0.6597945", "0.64133424", "0.6302239", "0.6301759", "0.6238256", "0.62380433", "0.62342966", "0.6198578", "0.6151277", "0.6141428", "0.6110286", "0.60958946", "0.6074485", "0.60712856", "0.60356736", "0.594845", "0.5945797", "0.5944643", "0.5921654", "0.5899822", "0.5899822", "0.5885531", "0.5872936", "0.5842205", "0.5822348", "0.5812011", "0.57959974", "0.5793403", "0.5774539", "0.57738984", "0.5766041", "0.5765263", "0.57371163", "0.57357347", "0.5724311", "0.5706076", "0.57052666", "0.57025236", "0.56970394", "0.5691269", "0.5690497", "0.5684226", "0.5681649", "0.5674609", "0.56698835", "0.56681085", "0.56640923", "0.56512135", "0.5650695", "0.5644444", "0.5625442", "0.5619246", "0.5618501", "0.56081915", "0.5607803", "0.558811", "0.5578888", "0.5575612", "0.55678964", "0.55671805", "0.55605793", "0.55603313", "0.55598855", "0.55522877", "0.5551062", "0.5526652", "0.55083644", "0.55031604", "0.55023515", "0.549958", "0.54993105", "0.5496009", "0.54919314", "0.5490995", "0.5488184", "0.5485775", "0.54748744", "0.5463535", "0.5459329", "0.5459112", "0.545119", "0.5445913", "0.54415894", "0.5431553", "0.5431205", "0.5428407", "0.5422031", "0.54195994", "0.5417996", "0.54159874", "0.541343", "0.5394515", "0.5390089", "0.5388341", "0.53843015", "0.53811616", "0.5376406", "0.53737366", "0.53649503" ]
0.75422233
0
MarshalText implements the encoding.TextMarshaler interface.
func (sa ServiceAccount) MarshalText() ([]byte, error) { return []byte(sa.String()), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i Transform) MarshalText() ([]byte, error) {\n\treturn []byte(i.String()), nil\n}", "func (t Temporality) MarshalText() ([]byte, error) {\n\treturn []byte(t.String()), nil\n}", "func (record Packed) MarshalText() ([]byte, error) {\n\tsize := hex.EncodedLen(len(record))\n\tb := make([]byte, size)\n\thex.Encode(b, record)\n\treturn b, nil\n}", "func (b Bytes) MarshalText() ([]byte, error) {\n\treturn []byte(FormatBytes(int64(b))), nil\n}", "func (u unmarshalerText) MarshalText() ([]byte, error) {\n\treturn []byte(u.A + \":\" + u.B), nil\n}", "func (b Bytes) MarshalText() ([]byte, error) {\n\tif len(b) == 0 {\n\t\treturn nil, nil\n\t}\n\n\thex := hexutil.BytesToHex(b)\n\treturn []byte(hex), nil\n}", "func (t *Type) MarshalText() ([]byte, error) {\n\treturn []byte(t.String()), nil\n}", "func (v Class) MarshalText() ([]byte, error) {\n\treturn []byte(v.String()), nil\n}", "func (i UOM) MarshalText() ([]byte, error) {\n\treturn []byte(i.String()), nil\n}", "func (v Major) MarshalText() ([]byte, error) {\n\treturn []byte(v.String()), nil\n}", "func (a *atom) MarshalText() ([]byte, error) {\n\tif a == nil {\n\t\treturn nil, nil\n\t}\n\treturn []byte(a.Raw()), nil\n}", "func (x Prefecture) MarshalText() ([]byte, error) {\n\treturn []byte(x.String()), nil\n}", "func (x XID) MarshalText() (dst []byte, err error) {\n\tdst = make([]byte, 20)\n\tx.encode(dst)\n\treturn\n}", "func (v MType) MarshalText() ([]byte, error) {\n\treturn []byte(v.String()), nil\n}", "func (x Group) MarshalText() ([]byte, *Error) {\n\treturn []byte(x.String()), nil\n}", "func (k PublicKey) MarshalText() ([]byte, error) {\n\treturn []byte(k.String()), nil\n}", "func (a KeyAlgorithm) MarshalText() ([]byte, error) {\n\treturn []byte(a.String()), nil\n}", "func (ot OutputType) MarshalText() ([]byte, error) {\n\treturn []byte(ot.String()), nil\n}", "func (x ContextKey) MarshalText() ([]byte, error) {\n\treturn []byte(x.String()), nil\n}", "func (m Money) MarshalText() ([]byte, error) {\n\treturn []byte(m.String()), nil\n}", "func (t TopicType) MarshalText() ([]byte, error) {\n\treturn hexutil.Bytes(t[:]).MarshalText()\n}", "func (x IntShop) MarshalText() ([]byte, error) {\n\treturn []byte(x.String()), nil\n}", "func (id ID) MarshalText() ([]byte, error) {\n\ttext := make([]byte, encodedLen)\n\tencode(text, id[:])\n\treturn text, nil\n}", "func (v Season_Ic_Ta) MarshalText() ([]byte, error) {\n\ts, err := v.marshalText()\n\treturn []byte(s), err\n}", "func (i MessageType) MarshalText() ([]byte, error) {\n\treturn []byte(i.String()), nil\n}", "func (sk ShardKey) MarshalText() (text []byte, err error) {\n\treturn []byte(sk.String()), nil\n}", "func (s *Scalar) MarshalText() (text []byte, err error) {\n\tb := s.Encode([]byte{})\n\treturn []byte(base64.StdEncoding.EncodeToString(b)), nil\n}", "func (r *Record) MarshalText() ([]byte, error) {\n\treturn r.MarshalSAM(0)\n}", "func (buf Hex) MarshalText() ([]byte, error) {\n\treturn []byte(hex.EncodeToString(buf)), nil\n}", "func (hash Hash) MarshalText() ([]byte, error) {\n\treturn []byte(hash.String()), nil\n}", "func (i TaskType) MarshalText() ([]byte, error) {\n\treturn []byte(i.String()), nil\n}", "func (s *LenString) MarshalText() (text []byte, err error) {\n\tif s == nil {\n\t\treturn nil, nil\n\t}\n\treturn []byte(s.str), nil\n}", "func (x *PackageType) MarshalText() ([]byte, error) {\n\treturn []byte(x.String()), nil\n}", "func (v Season_Uc_Ta) MarshalText() ([]byte, error) {\n\ts, err := v.marshalText()\n\treturn []byte(s), err\n}", "func (jid JID) MarshalText() ([]byte, error) {\n\treturn []byte(jid.String()), nil\n}", "func (animal Animal) MarshalText() ([]byte, error) {\n\tstr := animal.String()\n\treturn *(*[]byte)(unsafe.Pointer(&str)), nil\n}", "func (f F128d16) MarshalText() ([]byte, error) {\n\treturn []byte(f.String()), nil\n}", "func (b Balance) MarshalText() ([]byte, error) {\n\ts := fmt.Sprintf(`\"%s\"`, b.String())\n\treturn []byte(s), nil\n}", "func (bc *ByteCount) MarshalText() ([]byte, error) {\n\treturn ([]byte)(fmt.Sprintf(\"%d B\", uint64(AtomicLoadByteCount(bc)))), nil\n}", "func (id *ID) MarshalText() ([]byte, error) {\n\treturn []byte(id.String()), nil\n}", "func (b *Block) MarshalText() ([]byte, error) {\n\tbits, err := b.Bytes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenc := make([]byte, hex.EncodedLen(len(bits)))\n\thex.Encode(enc, bits)\n\treturn enc, nil\n}", "func (env Environment) MarshalText() ([]byte, error) {\n\treturn []byte(env.String()), nil\n}", "func (i Int) MarshalText() ([]byte, error) {\n\tif i.Nil {\n\t\treturn []byte(\"\"), nil\n\t}\n\n\treturn asByteSlice(i.String()), nil\n}", "func (r ToS) MarshalText() ([]byte, error) {\n\treturn []byte(_tosValueToName[r]), nil\n}", "func (s NullString) MarshalText() ([]byte, error) {\n\tif !s.Valid {\n\t\treturn []byte{}, nil\n\t}\n\treturn []byte(s.String), nil\n}", "func (l *Level) MarshalText() ([]byte, error) {\n\tif l == nil {\n\t\treturn nil, errMarshalNilLevel\n\t}\n\treturn []byte(l.String()), nil\n}", "func (l *Level) MarshalText() ([]byte, error) {\n\tif l == nil {\n\t\treturn nil, errMarshalNilLevel\n\t}\n\treturn []byte(l.String()), nil\n}", "func (t Timestamp) MarshalText() ([]byte, error) {\n\tbuf := make([]byte, 0, 20)\n\tbuf = strconv.AppendInt(buf, int64(t), 10)\n\treturn buf, nil\n}", "func (a Action) MarshalText() (text []byte, err error) {\n\treturn []byte(a.String()), nil\n}", "func (i State) MarshalText() ([]byte, error) {\n\treturn []byte(i.String()), nil\n}", "func (i EventType) MarshalText() ([]byte, error) {\n\treturn []byte(i.String()), nil\n}", "func (c Collection) MarshalText() ([]byte, error) {\n\treturn []byte(c.String()), nil\n}", "func (a Address) MarshalText() ([]byte, error) {\n\treturn []byte(a.String()), nil\n}", "func (u ISBN) MarshalText() ([]byte, error) {\n\treturn []byte(string(u)), nil\n}", "func (f Field) MarshalText() (p []byte, err error) {\n\treturn []byte(f.reference.String()), nil\n}", "func (a ArchType) MarshalText() ([]byte, error) {\n\treturn []byte(strconv.Quote(a.String())), nil\n}", "func (signature Signature) MarshalText() ([]byte, error) {\n\tbytes, err := signature.Marshal()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbytes = AddChecksum(bytes)\n\treturn []byte(b32.Encode(bytes)), nil\n}", "func (salt *Salt) MarshalText() []byte {\n\t// encode to hex\n\tsize := hex.EncodedLen(saltSize)\n\tbuffer := make([]byte, size)\n\thex.Encode(buffer, salt.Bytes())\n\n\treturn buffer\n}", "func (name ImageName) MarshalText() ([]byte, error) {\n\treturn []byte(name.String()), nil\n}", "func (x EnvironmentType) MarshalText() ([]byte, *errorAVA.Error) {\n\treturn []byte(x.String()), nil\n}", "func (u ISBN10) MarshalText() ([]byte, error) {\n\treturn []byte(string(u)), nil\n}", "func (d Decimal) MarshalText() (text []byte, err error) {\n\treturn []byte(d.String()), nil\n}", "func (h Hex8) MarshalText() ([]byte, error) {\n\treturn []byte(h.String()), nil\n}", "func (i Int8) MarshalText() ([]byte, error) {\n\tif !i.Valid {\n\t\treturn []byte{}, nil\n\t}\n\treturn []byte(strconv.FormatInt(int64(i.Int8), 10)), nil\n}", "func (e *Eth) MarshalText() ([]byte, error) {\n\treturn e.ToInt().MarshalText()\n}", "func (v DataRateOffset) MarshalText() ([]byte, error) {\n\treturn []byte(v.String()), nil\n}", "func (a *Action) MarshalText() ([]byte, error) {\n\tvar buf bytes.Buffer\n\tif err := a.appendTo(&buf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (x StrState) MarshalText() ([]byte, error) {\n\treturn []byte(string(x)), nil\n}", "func (v RejoinCountExponent) MarshalText() ([]byte, error) {\n\treturn []byte(v.String()), nil\n}", "func (u SSN) MarshalText() ([]byte, error) {\n\treturn []byte(string(u)), nil\n}", "func (v PHYVersion) MarshalText() ([]byte, error) {\n\treturn []byte(v.String()), nil\n}", "func (b Base64) MarshalText() ([]byte, error) {\n\tenc := base64.URLEncoding\n\tsrc := []byte(b)\n\tbuf := make([]byte, enc.EncodedLen(len(src)))\n\tenc.Encode(buf, src)\n\treturn buf, nil\n}", "func (p Privacy) MarshalText() ([]byte, error) {\n\treturn []byte(p), nil\n}", "func (v DeviceEIRP) MarshalText() ([]byte, error) {\n\treturn []byte(v.String()), nil\n}", "func (v ShortCode) MarshalText() ([]byte, error) {\n\treturn []byte(v.value), nil\n}", "func (m ValueMap) MarshalText() ([]byte, error) {\n\treturn m.MarshalJSON()\n}", "func (v Value) MarshalText() ([]byte, error) {\n\treturn v.MarshalJSON()\n}", "func (h Hex) MarshalText() ([]byte, error) {\n\treturn []byte(h.String()), nil\n}", "func (t *Topic) MarshalText() ([]byte, error) {\n\thandle, err := t.Handle.MarshalText()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttxt := fmt.Sprintf(\"%x.\", *t.SigningPrivateKey)\n\treturn append([]byte(txt), handle...), nil\n}", "func (receiver Request) MarshalText() ([]byte, error) {\n\tif nothing() == receiver {\n\t\treturn nil, errNothing\n\t}\n\n\treturn []byte(receiver.value), nil\n}", "func (d Decimal) MarshalText() ([]byte, error) {\n\treturn d.val.MarshalText()\n}", "func (n NodesID) MarshalText() ([]byte, error) {\n\treturn []byte(hex.EncodeToString(n[:])), nil\n}", "func (x Gender) MarshalText() ([]byte, error) {\n\treturn []byte(x.String()), nil\n}", "func (v MACVersion) MarshalText() ([]byte, error) {\n\treturn []byte(v.String()), nil\n}", "func (u ISBN13) MarshalText() ([]byte, error) {\n\treturn []byte(string(u)), nil\n}", "func (e Email) MarshalText() ([]byte, error) {\n\treturn []byte(string(e)), nil\n}", "func (h Hex64) MarshalText() ([]byte, error) {\n\treturn []byte(h.String()), nil\n}", "func (u MAC) MarshalText() ([]byte, error) {\n\treturn []byte(string(u)), nil\n}", "func (h Hash) MarshalText() ([]byte, error) {\n\treturn []byte(h.String()), nil\n}", "func (v MACCommandIdentifier) MarshalText() ([]byte, error) {\n\treturn []byte(v.String()), nil\n}", "func (id ID) MarshalText() (text []byte, err error) {\n\ttext = make([]byte, encodedLen)\n\tbase64.URLEncoding.Encode(text, id[:])\n\treturn\n}", "func (i UserGroupAccess) MarshalText() ([]byte, error) {\n\treturn []byte(i.String()), nil\n}", "func (x MainMatchingStatus) MarshalText() ([]byte, error) {\n\treturn []byte(x.String()), nil\n}", "func (account ED25519Account) MarshalText() ([]byte, error) {\n\treturn []byte(account.String()), nil\n}", "func (a Address) MarshalText() ([]byte, error) {\n\treturn (address.Address)(a).MarshalBech32(AddressBech32HRP)\n}", "func (l List) MarshalText() (text []byte, err error) {\n\tvar buf bytes.Buffer\n\tl.writeToBuffer(&buf)\n\treturn buf.Bytes(), nil\n}", "func (h Hex32) MarshalText() ([]byte, error) {\n\treturn []byte(h.String()), nil\n}", "func (addr DevAddr) MarshalText() ([]byte, error) {\n\treturn []byte(addr.String()), nil\n}", "func (data AlertData) MarshalText() (text []byte, err error) {\n\ttype x AlertData\n\treturn json.Marshal(x(data))\n}", "func (prefix DevAddrPrefix) MarshalText() ([]byte, error) {\n\treturn []byte(prefix.String()), nil\n}", "func (u CreditCard) MarshalText() ([]byte, error) {\n\treturn []byte(string(u)), nil\n}" ]
[ "0.8228678", "0.80167735", "0.7942326", "0.79334956", "0.7886933", "0.7855675", "0.78280884", "0.7812759", "0.7767125", "0.776674", "0.776519", "0.77160496", "0.769444", "0.7693002", "0.76895845", "0.7683634", "0.7660127", "0.76516336", "0.7642476", "0.76185024", "0.7612158", "0.7587745", "0.75876725", "0.7582204", "0.7579868", "0.75747126", "0.75694424", "0.7564527", "0.75568104", "0.7546788", "0.7543363", "0.75333065", "0.75323856", "0.7531698", "0.75282055", "0.7516476", "0.7509798", "0.75090045", "0.74996793", "0.74921423", "0.74802697", "0.7477335", "0.74767023", "0.7476262", "0.74698794", "0.74665207", "0.74665207", "0.7463566", "0.7462621", "0.7461042", "0.7460363", "0.7434778", "0.7431016", "0.7421553", "0.74192375", "0.7409221", "0.7407242", "0.7379792", "0.73750615", "0.737263", "0.73628074", "0.73586243", "0.7349726", "0.73430765", "0.7340784", "0.732229", "0.73074913", "0.7296591", "0.72846484", "0.72789943", "0.72772217", "0.72718406", "0.7270136", "0.7266735", "0.7263793", "0.72623193", "0.7261742", "0.7256808", "0.7242204", "0.723663", "0.723104", "0.7216969", "0.7216844", "0.7214974", "0.7208913", "0.7206558", "0.7195306", "0.71919954", "0.7185404", "0.7184282", "0.71828926", "0.7178272", "0.7166976", "0.7165404", "0.71588755", "0.7158352", "0.71496207", "0.71442795", "0.714229", "0.7141051", "0.7126049" ]
0.0
-1
String returns sa in a string as "/" or "default/" if sa.Namespace is empty.
func (sa ServiceAccount) String() string { if sa.Namespace == "" { return fmt.Sprintf("default/%s", sa.Name) } return fmt.Sprintf("%s/%s", sa.Namespace, sa.Name) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func defaultNamespace(deploymentID string) (string, error) {\n\treturn strings.ToLower(deploymentID), nil\n}", "func (namespace Namespace) String() string {\n\treturn fmt.Sprintf(\"Namespace<URI=[%s] PREFIX=[%s]>\", namespace.Uri, namespace.PreferredPrefix)\n}", "func Namespace(ctx context.Context) string {\n\tv := ctx.Value(ContextKey(\"namespace\"))\n\tif v == nil {\n\t\treturn \"\"\n\t} else {\n\t\treturn v.(string)\n\t}\n}", "func defaultNS(c context.Context) context.Context {\n\tc, err := info.Get(c).Namespace(\"\")\n\tif err != nil {\n\t\tpanic(err) // should not happen, Namespace errors only on bad namespace name\n\t}\n\treturn c\n}", "func (ls *LocationStore) Namespace() string {\n\treturn fmt.Sprintf(\"locations.%s\", ls.name)\n}", "func (o MrScalarCoreScalingUpPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarCoreScalingUpPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (a *Application) Namespace() string {\n\treturn fmt.Sprintf(\"app_%d_%d\", a.OrgID, a.ID)\n}", "func (o MrScalarTerminationPolicyStatementOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarTerminationPolicyStatement) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o MrScalarCoreScalingDownPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarCoreScalingDownPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func GetNamespaceOrDefault(namespace string) string {\n\tif namespace == \"\" {\n\t\treturn v1.NamespaceDefault\n\t}\n\treturn namespace\n}", "func (o MfaPingidOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MfaPingid) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ForwardingRuleServiceDirectoryRegistrationResponseOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ForwardingRuleServiceDirectoryRegistrationResponse) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o AppV2Output) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AppV2) pulumi.StringOutput { return v.Namespace }).(pulumi.StringOutput)\n}", "func (s Namespace) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o MrScalarTaskScalingUpPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingUpPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o ElastigroupScalingDownPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingDownPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o ElastigroupScalingUpPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingUpPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (c *Current) Namespace() string {\n\tswitch c.selectedRadio {\n\tcase FocusOnInvolved, FocusOnCurrentNamespace:\n\t\treturn curr.namespace\n\tcase FocusOnAllNamespace:\n\t\treturn \"\"\n\t}\n\treturn \"\"\n}", "func (o FluxConfigurationOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FluxConfiguration) pulumi.StringOutput { return v.Namespace }).(pulumi.StringOutput)\n}", "func DefaultNamespace(ns string) Transformer {\n\treturn TransformFunc(func(n nodes.Node) (nodes.Node, bool, error) {\n\t\tobj, ok := n.(nodes.Object)\n\t\tif !ok {\n\t\t\treturn n, false, nil\n\t\t}\n\t\ttp, ok := obj[uast.KeyType].(nodes.String)\n\t\tif !ok {\n\t\t\treturn n, false, nil\n\t\t}\n\t\tif strings.Contains(string(tp), \":\") {\n\t\t\treturn n, false, nil\n\t\t}\n\t\tobj = obj.CloneObject()\n\t\tobj[uast.KeyType] = nodes.String(ns + \":\" + string(tp))\n\t\treturn obj, true, nil\n\t})\n}", "func (r *Policy) ServiceNamespace() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"serviceNamespace\"])\n}", "func (o GetReposRepoOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetReposRepo) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (mr *Merger) DefaultNamespace(v string) *Merger {\n\tif len(v) == 0 {\n\t\tmr.defaultNamespace = DefaultNamespace\n\t} else {\n\t\tmr.defaultNamespace = v\n\t}\n\n\treturn mr\n}", "func (o ApplicationSpecDestinationOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecDestination) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ApplicationSpecRolloutplanCanarymetricTemplaterefOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecRolloutplanCanarymetricTemplateref) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o MrScalarTaskScalingDownPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingDownPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func getQualifiedName(name string, namespace string) string {\n\tname = addLeadSlash(name)\n\tif strings.HasPrefix(name, \"/\") {\n\t\treturn name\n\t} else if strings.HasPrefix(namespace, \"/\") {\n\t\treturn fmt.Sprintf(\"%s/%s\", namespace, name)\n\t} else {\n\t\tif len(namespace) == 0 {\n\t\t\tnamespace = getNamespaceFromProp()\n\t\t}\n\t\treturn fmt.Sprintf(\"/%s/%s\", namespace, name)\n\t}\n}", "func (o ApplicationStatusWorkflowContextbackendOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusWorkflowContextbackend) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func PathFromNamespace(ns string) string {\n\treturn strings.Replace(ns, \"\\\\\", \"/\", -1)\n}", "func (o ForwardingRuleServiceDirectoryRegistrationOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ForwardingRuleServiceDirectoryRegistration) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func GetDefaultStr(in string) string {\n\treturn in\n}", "func (o AppProjectSpecDestinationsOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AppProjectSpecDestinations) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (c *Census) CleanNamespace() string {\n\tif strings.Contains(c.namespace, \":\") {\n\t\treturn strings.Split(c.namespace, \":\")[0]\n\t}\n\treturn c.namespace\n}", "func (o ApplicationSpecDestinationPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecDestination) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (this *KeyspaceTerm) Namespace() string {\n\tif this.path != nil {\n\t\treturn this.path.Namespace()\n\t}\n\treturn \"\"\n}", "func (o ApplicationStatusWorkflowContextbackendPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusWorkflowContextbackend) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ApplicationStatusServicesScopesOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusServicesScopes) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func NS(s string) string {\n\tparts := strings.SplitN(s, \":\", 2)\n\tif len(parts) > 1 {\n\t\treturn parts[1]\n\t}\n\treturn \"\"\n}", "func (o ApplicationSpecRolloutplanCanarymetricTemplaterefPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecRolloutplanCanarymetricTemplateref) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ApplicationStatusAppliedresourcesOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusAppliedresources) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (av AttributeNamespaceComponent) String() string {\n\tswitch av {\n\tcase AttributeNamespaceComponentData:\n\t\treturn \"data\"\n\tcase AttributeNamespaceComponentIndex:\n\t\treturn \"index\"\n\tcase AttributeNamespaceComponentSetIndex:\n\t\treturn \"set_index\"\n\tcase AttributeNamespaceComponentSecondaryIndex:\n\t\treturn \"secondary_index\"\n\t}\n\treturn \"\"\n}", "func getNamespace() (string, error) {\n\n\tns, found := os.LookupEnv(namespaceEnvVar)\n\tif !found {\n\t\terr := fmt.Errorf(\"%s must be set\", namespaceEnvVar)\n\t\treturn \"\", err\n\t}\n\treturn ns, nil\n}", "func DefaultNamespace(obj runtime.Object, namespace string) error {\n\tif namespace == \"\" {\n\t\treturn errors.New(\"default namespace cannot be empty\")\n\t}\n\n\taccessor, _ := meta.Accessor(obj)\n\n\tif accessor.GetNamespace() != \"\" {\n\t\treturn nil\n\t}\n\n\taccessor.SetNamespace(namespace)\n\n\treturn nil\n}", "func (o ApplicationStatusComponentsOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusComponents) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (s GetNamespaceOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func GetNamespace() string {\n\tns, found := os.LookupEnv(\"POD_NAMESPACE\")\n\tif found {\n\t\treturn ns\n\t}\n\tnsb, err := ioutil.ReadFile(\"/var/run/secrets/kubernetes.io/serviceaccount/namespace\")\n\tif err == nil && len(nsb) > 0 {\n\t\treturn string(nsb)\n\t}\n\treturn DefaultNamespace\n}", "func (*Prefix) Default() string { return defaultPrefix }", "func (o ElastigroupScalingTargetPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingTargetPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (r *ScheduledAction) ServiceNamespace() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"serviceNamespace\"])\n}", "func HandleNamespace(ns, defaultNamespace string) string {\n\tif ns == v1.NamespaceAll {\n\t\tns = defaultNamespace\n\t}\n\treturn ns\n}", "func namespace() string {\n\tif ns := os.Getenv(\"TILLER_NAMESPACE\"); ns != \"\" {\n\t\treturn ns\n\t}\n\n\t// Fall back to the namespace associated with the service account token, if available\n\tif data, err := ioutil.ReadFile(\"/var/run/secrets/kubernetes.io/serviceaccount/namespace\"); err == nil {\n\t\tif ns := strings.TrimSpace(string(data)); len(ns) > 0 {\n\t\t\treturn ns\n\t\t}\n\t}\n\n\treturn environment.DefaultTillerNamespace\n}", "func (o SecretBackendV2Output) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SecretBackendV2) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (n NamespaceStar) String() string {\n\treturn string(n)\n}", "func (o AuthBackendRoleOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AuthBackendRole) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func Namespace(iops *v1alpha1.IstioOperatorSpec) string {\n\tif iops.Namespace != \"\" {\n\t\treturn iops.Namespace\n\t}\n\tif iops.Values == nil {\n\t\treturn \"\"\n\t}\n\tif iops.Values[globalKey] == nil {\n\t\treturn \"\"\n\t}\n\tv := iops.Values[globalKey].(map[string]interface{})\n\tn := v[istioNamespaceKey]\n\tif n == nil {\n\t\treturn \"\"\n\t}\n\treturn n.(string)\n}", "func (o ParamRefOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ParamRef) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ApplicationSpecRolloutplanRolloutbatchesCanarymetricTemplaterefOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecRolloutplanRolloutbatchesCanarymetricTemplateref) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (k *k8sUtil) NS() (string, error) {\n\tif nil == k.volProfile {\n\t\treturn \"\", fmt.Errorf(\"Volume provisioner profile not initialized at '%s'\", k.Name())\n\t}\n\n\t// Fetch pvc from volume provisioner profile\n\tpvc, err := k.volProfile.PVC()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Get orchestrator provider profile from pvc\n\toPrfle, err := orchProfile.GetOrchProviderProfile(pvc)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Get the namespace which will be queried\n\tns, err := oPrfle.NS()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn ns, nil\n}", "func (o SecretBackendRoleOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SecretBackendRole) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o SecretBackendRoleOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SecretBackendRole) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o *SparseClaims) GetNamespace() (out string) {\n\n\tif o.Namespace == nil {\n\t\treturn\n\t}\n\n\treturn *o.Namespace\n}", "func getUTSNamespace(pid uint32) string {\n\treturn fmt.Sprintf(utsNSFormat, pid)\n}", "func ResolveDefaultNamespace(defaultNamespace string) string {\n\tif defaultNamespace == \"@nuclio.selfNamespace\" {\n\n\t\t// get namespace from within the pod. if found, return that\n\t\tif namespacePod, err := ioutil.ReadFile(\"/var/run/secrets/kubernetes.io/serviceaccount/namespace\"); err == nil {\n\t\t\treturn string(namespacePod)\n\t\t}\n\t}\n\n\tif defaultNamespace == \"\" {\n\t\treturn \"default\"\n\t}\n\n\treturn defaultNamespace\n}", "func (o ElastigroupMultipleMetricsMetricOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupMultipleMetricsMetric) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o *KubernetesAddonDefinitionAllOf) GetDefaultNamespace() string {\n\tif o == nil || o.DefaultNamespace == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DefaultNamespace\n}", "func (o ApplicationStatusSyncComparedToDestinationOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSyncComparedToDestination) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func TestGetNamespaceDefault(t *testing.T) {\n\ttestCmd := testCommandGenerator(true)\n\texpectedNamespace := \"current\"\n\ttestCmd.Execute()\n\tkp := &KnParams{fixedCurrentNamespace: FakeNamespace}\n\tactualNamespace, err := kp.GetNamespace(testCmd)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif actualNamespace != expectedNamespace {\n\t\tt.Fatalf(\"Incorrect namespace retrieved: %v, expected: %v\", actualNamespace, expectedNamespace)\n\t}\n}", "func (o ApplicationSpecRolloutplanRolloutbatchesCanarymetricTemplaterefPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecRolloutplanRolloutbatchesCanarymetricTemplateref) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func Namespace(featureName FeatureName, componentName ComponentName, controlPlaneSpec *v1alpha2.IstioControlPlaneSpec) (string, error) {\n\tdefaultNamespaceI, found, err := tpath.GetFromStructPath(controlPlaneSpec, \"DefaultNamespace\")\n\tif !found {\n\t\treturn \"\", fmt.Errorf(\"can't find any setting for defaultNamespace for feature=%s, component=%s\", featureName, componentName)\n\t}\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in Namepsace for feature=%s, component=%s: %s\", featureName, componentName, err)\n\n\t}\n\tdefaultNamespace, ok := defaultNamespaceI.(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"defaultNamespace has bad type %T, expect string\", defaultNamespaceI)\n\t}\n\tif defaultNamespace == \"\" {\n\t\treturn \"\", fmt.Errorf(\"defaultNamespace must be set\")\n\t}\n\n\tfeatureNamespace := defaultNamespace\n\tfeatureNodeI, found, err := tpath.GetFromStructPath(controlPlaneSpec, string(featureName)+\".Components.Namespace\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in Namepsace GetFromStructPath featureNamespace for feature=%s, component=%s: %s\", featureName, componentName, err)\n\t}\n\tif found && featureNodeI != nil {\n\t\tfeatureNamespace, ok = featureNodeI.(string)\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"feature %s namespace has bad type %T, expect string\", featureName, featureNodeI)\n\t\t}\n\t\tif featureNamespace == \"\" {\n\t\t\tfeatureNamespace = defaultNamespace\n\t\t}\n\t}\n\n\tcomponentNodeI, found, err := tpath.GetFromStructPath(controlPlaneSpec, string(featureName)+\".Components.\"+string(componentName)+\".Namespace\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in Namepsace GetFromStructPath componentNamespace for feature=%s, component=%s: %s\", featureName, componentName, err)\n\t}\n\tif !found {\n\t\treturn featureNamespace, nil\n\t}\n\tif componentNodeI == nil {\n\t\treturn featureNamespace, nil\n\t}\n\tcomponentNamespace, ok := componentNodeI.(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"component %s enabled has bad type %T, expect string\", componentName, componentNodeI)\n\t}\n\tif componentNamespace == \"\" {\n\t\treturn featureNamespace, nil\n\t}\n\treturn componentNamespace, nil\n}", "func (s *STFConfig) GetNamespace() string {\n\tif s.Namespace != \"\" {\n\t\treturn s.Namespace\n\t}\n\treturn \"default\"\n}", "func (m Metadata) Namespace() string {\n\tif !m.HasNamespace() {\n\t\treturn \"\"\n\t}\n\treturn m[\"namespace\"].(string)\n}", "func (o StudioOutput) DefaultS3Location() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Studio) pulumi.StringOutput { return v.DefaultS3Location }).(pulumi.StringOutput)\n}", "func (o HybridConnectionOutput) ServiceBusNamespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *HybridConnection) pulumi.StringOutput { return v.ServiceBusNamespace }).(pulumi.StringOutput)\n}", "func (r *Root) Namespace() namespace {\n\tswitch currentVariant {\n\tcase noVariant:\n\t\tfidlgen.TemplateFatalf(\"Called Root.Namespace() when currentVariant isn't set.\\n\")\n\tcase hlcppVariant:\n\t\treturn hlcppNamespace(r.Library)\n\tcase unifiedVariant, wireVariant:\n\t\treturn unifiedNamespace(r.Library)\n\t}\n\tpanic(\"not reached\")\n}", "func NamespaceFromContext(ctx context.Context) string {\n\tif r, ok := ctx.Value(namespaceKey).(string); ok {\n\t\treturn r\n\t}\n\n\treturn \"\"\n}", "func (o DataSetRowLevelPermissionDataSetOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataSetRowLevelPermissionDataSet) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ApplicationStatusSyncComparedToDestinationPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusSyncComparedToDestination) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (opts UnsetEnvOptions) Namespace() string {\n\treturn opts.toConfig().Namespace\n}", "func ProcessNamespace(namespace string) string {\n\tif namespace == \"\" {\n\t\treturn defaults.Namespace\n\t}\n\treturn namespace\n}", "func (n Ns) String() string {\n\tif n.IsGlobal() {\n\t\treturn \"\"\n\t}\n\tres := \"\"\n\tif n.UUID != \"\" {\n\t\tres += string(NsUUIDPrefix) + n.UUID\n\t}\n\tif n.Name != \"\" {\n\t\tres += string(NsNamePrefix) + n.Name\n\t}\n\treturn res\n}", "func (o *SparseCloudSnapshotAccount) GetNamespace() (out string) {\n\n\tif o.Namespace == nil {\n\t\treturn\n\t}\n\n\treturn *o.Namespace\n}", "func GetNamespace() string {\n\tveryFlagInput()\n\treturn ns\n}", "func (o ParamRefPatchOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ParamRefPatch) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (f *EnvFlags) Namespace() string {\n\treturn f.namespace\n}", "func (n NamespacedName) String() string {\n\treturn fmt.Sprintf(\"%s%c%s\", n.Namespace, Separator, n.Name)\n}", "func Canonicalize(nsPath string) string {\n\tif nsPath == \"\" {\n\t\treturn \"\"\n\t}\n\n\t// Canonicalize the path to not have a '/' prefix\n\tnsPath = strings.TrimPrefix(nsPath, \"/\")\n\n\t// Canonicalize the path to always having a '/' suffix\n\tif !strings.HasSuffix(nsPath, \"/\") {\n\t\tnsPath += \"/\"\n\t}\n\n\treturn nsPath\n}", "func TestDefaultNamespace(t *testing.T) {\n\tcommon.CreateFile(tmpProp)\n\tcommon.WriteFile(tmpProp, []string{\"APIHOST=xyz\"})\n\n\tos.Setenv(\"WSK_CONFIG_FILE\", tmpProp)\n\tassert.Equal(t, os.Getenv(\"WSK_CONFIG_FILE\"), tmpProp, \"The environment variable WSK_CONFIG_FILE has not been set.\")\n\n\tstdout, err := wsk.RunCommand(\"property\", \"get\", \"-i\", \"--namespace\")\n\tassert.Equal(t, nil, err, \"The command property get -i --namespace failed to run.\")\n\tassert.Contains(t, common.RemoveRedundantSpaces(string(stdout)), common.PropDisplayNamespace+\" _\",\n\t\t\"The output of the command does not contain \"+common.PropDisplayCLIVersion+\" _\")\n\tcommon.DeleteFile(tmpProp)\n}", "func (s CreateNamespaceOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *ReplicaSet) Namespace() string {\n\treturn r.raw.Namespace\n}", "func Namespace(componentName ComponentName, controlPlaneSpec *v1alpha1.IstioOperatorSpec) (string, error) {\n\tdefaultNamespaceI, found, err := tpath.GetFromStructPath(controlPlaneSpec, \"MeshConfig.RootNamespace\")\n\tif !found {\n\t\treturn \"\", fmt.Errorf(\"can't find any setting for defaultNamespace for component=%s\", componentName)\n\t}\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in Namepsace for component=%s: %s\", componentName, err)\n\n\t}\n\tdefaultNamespace, ok := defaultNamespaceI.(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"defaultNamespace has bad type %T, expect string\", defaultNamespaceI)\n\t}\n\tif defaultNamespace == \"\" {\n\t\treturn \"\", fmt.Errorf(\"defaultNamespace must be set\")\n\t}\n\n\tcomponentNodeI, found, err := tpath.GetFromStructPath(controlPlaneSpec, \"Components.\"+string(componentName)+\".Namespace\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in Namepsace GetFromStructPath componentNamespace for component=%s: %s\", componentName, err)\n\t}\n\tif !found {\n\t\treturn defaultNamespace, nil\n\t}\n\tif componentNodeI == nil {\n\t\treturn defaultNamespace, nil\n\t}\n\tcomponentNamespace, ok := componentNodeI.(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"component %s enabled has bad type %T, expect string\", componentName, componentNodeI)\n\t}\n\tif componentNamespace == \"\" {\n\t\treturn defaultNamespace, nil\n\t}\n\treturn componentNamespace, nil\n}", "func (o SnapshotOutput) NamespaceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Snapshot) pulumi.StringOutput { return v.NamespaceName }).(pulumi.StringOutput)\n}", "func GetCurrentNamespace() (string, error) {\n\tdata, err := ioutil.ReadFile(\"/var/run/secrets/kubernetes.io/serviceaccount/namespace\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"couldn't read namespace from server account\")\n\t}\n\n\treturn string(data), nil\n}", "func (n NamespaceNode) String() string {\n\treturn string(n)\n}", "func (opts CreateOptions) Namespace() string {\n\treturn opts.toConfig().Namespace\n}", "func (opts CreateOptions) Namespace() string {\n\treturn opts.toConfig().Namespace\n}", "func (o DataSetRowLevelPermissionDataSetPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataSetRowLevelPermissionDataSet) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func DefaultNamespace() Namespace {\n\tnamespace, _ := NewNamespace(defaults.Namespace)\n\treturn namespace\n}", "func (p protobuf) Namespace() string {\n\tif n, ok := protoNameToNamespace[p.TypeName]; ok {\n\t\treturn n\n\t}\n\treturn \"?\"\n}", "func setDefaultPath(path string) (string) {\n\tif path != \"\" {\n\t\treturn path\n\t}\n\n\treturn \"/\"\n}", "func (c *ZtunnelComponent) Namespace() string {\n\treturn c.CommonComponentFields.Namespace\n}" ]
[ "0.598405", "0.5958957", "0.59324455", "0.58580804", "0.58558077", "0.57945585", "0.5772951", "0.5731437", "0.5699601", "0.56748503", "0.56491846", "0.56339914", "0.5620547", "0.5595185", "0.55925304", "0.5585272", "0.55844915", "0.5582787", "0.5582531", "0.55805486", "0.5576645", "0.5566843", "0.5538686", "0.5538095", "0.55168957", "0.55102664", "0.5490658", "0.54810673", "0.54738116", "0.5469162", "0.54649776", "0.546221", "0.5456844", "0.54170483", "0.5413264", "0.53979784", "0.5377328", "0.5368912", "0.5354651", "0.53453535", "0.5344773", "0.53414285", "0.53220606", "0.5304173", "0.5284685", "0.5283954", "0.527845", "0.52622324", "0.5260104", "0.52554506", "0.52514726", "0.52430815", "0.5240343", "0.52399945", "0.5226125", "0.5225297", "0.5221199", "0.521971", "0.51949185", "0.51949185", "0.5193867", "0.51932824", "0.5173263", "0.5172865", "0.5168993", "0.51674736", "0.51489663", "0.5147601", "0.51373255", "0.51269555", "0.5123928", "0.5110089", "0.5107623", "0.5106165", "0.5104532", "0.51022804", "0.50972885", "0.509559", "0.5087275", "0.50809664", "0.50717366", "0.5067506", "0.50643945", "0.50555086", "0.5054425", "0.50515825", "0.5045462", "0.504352", "0.5030952", "0.5029971", "0.50295126", "0.5023916", "0.5023789", "0.50205326", "0.50205326", "0.5017917", "0.50157", "0.50155395", "0.50008917", "0.49989623" ]
0.6035873
0
Key generates the key with the format Namespace/Name.
func (sa ServiceAccount) Key() string { return fmt.Sprintf("%s/%s", sa.Namespace, sa.Name) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Key(typ, name, namespace string) string {\n\treturn fmt.Sprintf(\"%s/%s/%s\", typ, namespace, name)\n}", "func KeyFunc(name, namespace string) string {\n\tif len(namespace) == 0 {\n\t\treturn name\n\t}\n\treturn namespace + \"/\" + name\n}", "func GetKey(namespace, name string) string {\n\treturn fmt.Sprintf(\"%s/%s\", namespace, name)\n}", "func Key(namespaceOrName string, nameOpt ...string) client.ObjectKey {\n\tnamespace, name := nameAndNamespace(namespaceOrName, nameOpt...)\n\treturn client.ObjectKey{Namespace: namespace, Name: name}\n}", "func NamespacedKey(namespace, name string) string {\n\tif namespace == \"\" {\n\t\treturn name\n\t}\n\treturn namespace + \"/\" + name\n}", "func Key(name string, namespace string) string {\n\treturn ksrkey.Key(PodKeyword, name, namespace)\n}", "func Key(name, version string) string {\n\tif version == \"\" {\n\t\treturn name\n\t}\n\treturn path.Join(name, \"v\"+strings.TrimLeft(version, \"v\"))\n}", "func newKeyWithNamespace(namespace string, kind string, key string) (k *datastore.Key) {\n\tk = datastore.NameKey(kind, key, nil)\n\tk.Namespace = namespace\n\n\treturn k\n}", "func NameKeyWithNamespace(kind, namespace, name string, parent *datastore.Key) *datastore.Key {\n\tkey := &datastore.Key{\n\t\tKind: kind,\n\t\tName: name,\n\t\tParent: parent,\n\t\tNamespace: namespace,\n\t}\n\treturn key\n}", "func (s *S3) Key(args ...string) string {\n\targs = append([]string{s.keyNamespace}, args...)\n\treturn path.Join(args...)\n}", "func KeyFor(obj runtime.Object, nsn types.NamespacedName) string {\n\tgvk := obj.GetObjectKind().GroupVersionKind()\n\treturn strings.Join([]string{gvk.Group, gvk.Version, gvk.Kind, nsn.Namespace, nsn.Name}, KeyDelimiter)\n}", "func keyGen(key string, keyPrefix string, programName string, withProgramName bool) string {\n\tif programName != \"\" && withProgramName {\n\t\tif keyPrefix == \"\" {\n\t\t\treturn fmt.Sprintf(\"%s.%s\", programName, key)\n\t\t}\n\n\t\treturn fmt.Sprintf(\"%s.%s_%s\", programName, keyPrefix, key)\n\t} else {\n\t\tif keyPrefix == \"\" {\n\t\t\treturn key\n\t\t}\n\n\t\treturn fmt.Sprintf(\"%s_%s\", keyPrefix, key)\n\t}\n}", "func (meta *Meta) Key() string {\n\treturn Key(meta.GroupVersionKind.Kind, meta.Name, meta.Namespace)\n}", "func buildObjectKey(key ctrlClient.ObjectKey) string {\n\treturn fmt.Sprintf(\"%s/%s\", key.Namespace, key.Name)\n}", "func (m *Network) MakeKey(prefix string) string {\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", prefix, \"/\", \"networks/\", m.Tenant, \"/\", m.Name)\n}", "func keyForTemplate(namespace, tmplName string) string {\n\treturn namespace + \"/\" + tmplName\n}", "func (n Name) Key() string {\n\tvar key strings.Builder\n\tfor _, l := range n {\n\t\tkey.WriteString(l.key)\n\t\tkey.WriteByte(0)\n\t}\n\treturn key.String()\n}", "func createKey(name string, version string, nodeID string) string {\n\treturn fmt.Sprintf(\"%s:%s:%s\", nodeID, name, version)\n}", "func buildKey(name, section string) (key string) {\n\tif section == \"\" {\n\t\tkey = name\n\t} else {\n\t\tkey = fmt.Sprintf(\"%s-%s\", name, section)\n\t}\n\treturn\n}", "func (k *Key) Namespace() string { return k.kc.Namespace }", "func KeyGen(key string, keyPrefix string, programName string, withProgramName bool) string {\n\tfinalKey := keyGen(key, keyPrefix, programName, withProgramName)\n\treturn escapeKey(finalKey)\n}", "func Key(parts ...string) (k string) {\n\tfor _, v := range parts {\n\t\tif v = strings.TrimSpace(v); v == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif k != \"\" {\n\t\t\tk += \"_\"\n\t\t}\n\t\tk += v\n\t}\n\treturn strings.ToUpper(k)\n}", "func genKey(code string, t time.Time) string {\n\treturn fmt.Sprintf(\"%s#%s\", code, t.Format(time.RFC3339))\n}", "func toKey(idents []string) namingContextKey {\n\t// relies on the fact that '$' is not a valid part of an identifier\n\treturn strings.Join(idents, \"$\")\n}", "func Key(poolName string) string {\n\treturn KeyPrefix() + poolName\n}", "func KeyNamespaceMutator(ns string) func(key string) string {\n\treturn func(key string) string {\n\t\tif ns == \"\" {\n\t\t\treturn key\n\t\t}\n\t\treturn nsKey(ns, key)\n\t}\n}", "func Key(n []string) string {\n\treturn strings.Join(n, \".\")\n}", "func ResourceKey(group, version, kind string) string {\n\tif group == \"\" {\n\t\tgroup = \"core\"\n\t}\n\treturn \"k8s_\" + ToSnake(group) + \"_\" + version + \"_\" + ToSnake(kind)\n}", "func (c Casing) Key() string {\n\treturn \"casing\"\n}", "func CreateKey(tokens ...string) Key {\n\treturn Key(strings.Join(tokens, \":\"))\n}", "func createRegistryKeyAndNamespace(cType reflect.Type) (string, string) {\n\tnamespace := cType.PkgPath()\n\tif idx := strings.Index(namespace, \"controllers\"); idx > -1 {\n\t\tnamespace = namespace[idx+11:]\n\t}\n\n\tif ess.IsStrEmpty(namespace) {\n\t\treturn strings.ToLower(cType.Name()), \"\"\n\t}\n\n\treturn strings.ToLower(path.Join(namespace[1:], cType.Name())), namespace[1:]\n}", "func (metric DomainMetric) Key() string {\n\treturn metric.UUIDandVersion.UUID.String()\n}", "func (pubKey PubKeySecp256k1) KeyString() string {\n\treturn Fmt(\"%X\", pubKey[:])\n}", "func makeKey(args ...string) string {\n\treturn strings.Join(args, \":\")\n}", "func (api *licenseAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"licenses\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"licenses\", \"/\", name)\n}", "func createKey(a, b string) string {\n\treturn a + \":\" + b\n}", "func (instance *DSInstance) NewKey(kind string, name string, parent *datastore.Key) *datastore.Key {\n\tkey := datastore.NameKey(kind, name, parent)\n\tkey.Namespace = instance.namespace\n\treturn key\n}", "func (m *VirtualRouter) MakeKey(prefix string) string {\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", prefix, \"/\", \"virtualrouters/\", m.Tenant, \"/\", m.Name)\n}", "func Namespace(key string) Field {\n\treturn Field{Key: key, Type: core.NamespaceType}\n}", "func GetNamespacedNameKey(namespace, name string) string {\n\treturn fmt.Sprintf(\"%s/%s\", namespace, name)\n}", "func Key(keyParts ...string) string {\n\treturn strings.Join(keyParts, \"\")\n}", "func genAnnotationKey(resource v1alpha1.BackingServiceResource) string {\n\tkey := strings.Replace(fmt.Sprintf(\"nuxeo.operator.%s.%s.%s.%s\",\n\t\tstrings.ToLower(resource.Group),\n\t\tstrings.ToLower(resource.Version),\n\t\tstrings.ToLower(resource.Kind),\n\t\tstrings.ToLower(resource.Name)), \"..\", \".\", 1)\n\treturn key\n}", "func (b KeyBuilder) Build(keys ...string) string {\n\titems := append(\n\t\t[]string{\n\t\t\tRoot,\n\t\t\tb.resourceName,\n\t\t\tb.namespace,\n\t\t},\n\t\tkeys...,\n\t)\n\n\tkey := path.Join(items...)\n\n\t// In order to not inadvertently build a key that could list across\n\t// namespaces, we need to make sure that we terminate the key with the key\n\t// separator when a namespace is involved without a specific object name\n\t// within it.\n\tif b.namespace != \"\" {\n\t\tif len(keys) == 0 || keys[len(keys)-1] == \"\" {\n\t\t\tkey += keySeparator\n\t\t}\n\t}\n\n\t// Be specific when listing sub-resources for a specific resource.\n\tif b.includeTrailingSlash {\n\t\tkey += keySeparator\n\t}\n\n\treturn key\n}", "func (s *Node) Key() (key string) {\n\tkey = \"node/\" + s.Name\n\treturn\n}", "func (x *Broker) Key() *BrokerKey {\n\treturn &BrokerKey{\n\t\tnamespace: x.Namespace,\n\t\tname: x.Name,\n\t}\n}", "func Key(args ...string) string {\n\treturn strings.Join(args, \":\")\n}", "func GenerateKeyNames(tr time.Time) *AllKeys {\n\tk := &AllKeys{\n\t\tDst: KeyNames{},\n\t\tSrc: KeyNames{},\n\t}\n\n\tk.Src.CurrentCounterSet = generateSegmentPrefix(\"set:counter:src\", tr)\n\tk.Src.CurrentCounterHSet = generateSegmentPrefix(\"hset:counter:src\", tr)\n\tk.Dst.CurrentCounterSet = generateSegmentPrefix(\"set:counter:dst\", tr)\n\tk.Dst.CurrentCounterHSet = generateSegmentPrefix(\"hset:counter:dst\", tr)\n\treturn k\n}", "func IDKeyWithNamespace(kind, namespace string, id int64, parent *datastore.Key) *datastore.Key {\n\tkey := &datastore.Key{\n\t\tKind: kind,\n\t\tID: id,\n\t\tParent: parent,\n\t\tNamespace: namespace,\n\t}\n\treturn key\n}", "func (o Operator) Key() string {\n\treturn fmt.Sprintf(\"operator.%s\", o.Aid)\n}", "func EkgKey(domain, id []byte) []byte {\n return createKey(EKG,domain,id)\n}", "func (r *ClusterServiceResource) Key() types.NamespacedName {\n\treturn types.NamespacedName{Name: r.pandaCluster.Name + \"-cluster\", Namespace: r.pandaCluster.Namespace}\n}", "func (c Client) Key() string {\n\treturn fmt.Sprintf(\"client.%s\", c.Uid)\n}", "func key(item storage.Key) []byte {\n\treturn []byte(item.Namespace() + separator + item.ID())\n}", "func (api *clusterAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"cluster\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"cluster\", \"/\", name)\n}", "func (m *message) Key() string {\n\treturn m.TS.Format(time.RFC3339) + \"|\" + m.User\n}", "func KeyPrefix() string {\n\treturn Keyword + \"/\"\n}", "func (api *objectAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"objstore\", \"/\", \"objects\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"objstore\", \"/\", \"objects\", \"/\", name)\n}", "func (s *Structure) InitKey(keySuffix string) string {\n\tif ext.StringEq(keySuffix) {\n\t\treturn s.KeyPrefixFmt\n\t}\n\n\treturn fmt.Sprintf(s.KeyPrefixFmt, keySuffix)\n}", "func FormatKey(key string) (registry.Key, string) {\n\tfor _, p := range hklmPrefixes {\n\t\tif strings.HasPrefix(key, p) {\n\t\t\treturn registry.LocalMachine, subkey(key, p)\n\t\t}\n\t}\n\tfor _, p := range hkcrPrefixes {\n\t\tif strings.HasPrefix(key, p) {\n\t\t\treturn registry.ClassesRoot, subkey(key, p)\n\t\t}\n\t}\n\n\tonce.Do(func() { initKeys() })\n\n\tif root, k := findSIDKey(key); root != registry.InvalidKey {\n\t\treturn root, k\n\t}\n\tfor _, p := range hkuPrefixes {\n\t\tif strings.HasPrefix(key, p) {\n\t\t\treturn registry.Users, subkey(key, p)\n\t\t}\n\t}\n\n\tif strings.HasPrefix(key, hive) {\n\t\treturn registry.Hive, key\n\t}\n\n\treturn registry.InvalidKey, key\n}", "func (api *versionAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"version\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"version\", \"/\", name)\n}", "func makeKey(metricElement *mqmetric.MonElement) string {\n\treturn metricElement.Parent.Parent.Name + \"/\" + metricElement.Parent.Name + \"/\" + metricElement.Description\n}", "func ResourceKey(c Codec, resourceName, pk string) string {\n\treturn path.Join(c.Key(), resourceName, pk)\n}", "func (api *nodeAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"nodes\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"nodes\", \"/\", name)\n}", "func (t Task) Key() string {\n\treturn fmt.Sprintf(\"%s:%s\", t.Name, t.ID)\n}", "func MakeKey(keyParts ...string) string {\r\n\treturn strings.Join(keyParts, \":\")\r\n}", "func (d *DynamicTranslation) Key() string {\n\treturn translationKey(d.RealmID, d.Locale, d.MessageID)\n}", "func (g GoStruct) KeyFunc(prefix string) string {\n\tkey := \"\"\n\tif len(g.Fields) == 0 {\n\t\tkey = prefix\n\t} else {\n\t\tvar builder strings.Builder\n\t\tbuilder.WriteString(prefix)\n\t\tbuilder.WriteString(strings.Repeat(\":%s\", len(g.Fields)))\n\t\tkey = builder.String()\n\t}\n\tfieldnames := make([]string, 0)\n\tfor _, f := range g.Fields {\n\t\tfieldnames = append(fieldnames, \"valueToString(r.\"+f.Name+\")\")\n\t}\n\tfieldstr := strings.Join(fieldnames, \",\\n\")\n\treturn fmt.Sprintf(\n\t\t\"// Key - cache key\\n\"+\n\t\t\t\"func (r *%s) Key() string {\\nreturn fmt.Sprintf(\\\"%s\\\", %s)\\n}\\n\",\n\t\tg.Name, key, fieldstr)\n}", "func GenerateBindingReferenceKey(namespace, name string) string {\n\tvar bindingName string\n\tif len(namespace) > 0 {\n\t\tbindingName = namespace + \"/\" + name\n\t} else {\n\t\tbindingName = name\n\t}\n\thash := fnv.New32a()\n\thashutil.DeepHashObject(hash, bindingName)\n\treturn rand.SafeEncodeString(fmt.Sprint(hash.Sum32()))\n}", "func ObjectKey(name, namespace string) types.NamespacedName {\n\treturn types.NamespacedName{\n\t\tNamespace: namespace,\n\t\tName: name,\n\t}\n}", "func (*K8S) Name() string {\n\treturn \"cipher_key_b64\"\n}", "func SKey(key ...string) Key {\n\tout := make(Key, 0, len(key))\n\tfor _, k := range key {\n\t\tout = append(out, values.String(k))\n\t}\n\treturn out\n}", "func generateObjectKey(threadIndex int, payloadSize uint64) string {\n\tvar key string\n\tkeyHash := sha1.Sum([]byte(fmt.Sprintf(\"%03d-%012d\", threadIndex, payloadSize)))\n\tfolder := strconv.Itoa(int(payloadSize))\n\tkey = folder + \"/\" + (fmt.Sprintf(\"%x\", keyHash))\n\treturn key\n}", "func (api *distributedservicecardAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"distributedservicecards\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"distributedservicecards\", \"/\", name)\n}", "func Key(keyType string) (string, error) {\n\tswitch keyType {\n\tcase \"aes:128\":\n\t\tkey := memguard.NewBufferRandom(16).Bytes()\n\t\treturn base64.StdEncoding.EncodeToString(key), nil\n\tcase \"aes:256\":\n\t\tkey := memguard.NewBufferRandom(32).Bytes()\n\t\treturn base64.StdEncoding.EncodeToString(key), nil\n\tcase \"secretbox\":\n\t\tkey := memguard.NewBufferRandom(32).Bytes()\n\t\treturn base64.StdEncoding.EncodeToString(key), nil\n\tcase \"fernet\":\n\t\t// Generate a fernet key\n\t\tk := &fernet.Key{}\n\t\tif err := k.Generate(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn k.Encode(), nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"invalid keytype (%s) [aes:128, aes:256, secretbox, fernet]\", keyType)\n\t}\n}", "func encodeKey(network net.IPNet) string {\n\treturn fmt.Sprintf(\n\t\tIPAMSubnetStorageKeyFormat,\n\t\tstrings.Replace(network.String(), \"/\", \"-\", -1),\n\t)\n}", "func (k Key) String() string {\n\tvar keyString = k.LCCN\n\tif k.Year > 0 {\n\t\tkeyString += fmt.Sprintf(\"/%04d\", k.Year)\n\t}\n\tif k.Month > 0 {\n\t\tkeyString += fmt.Sprintf(\"%02d\", k.Month)\n\t}\n\tif k.Day > 0 {\n\t\tkeyString += fmt.Sprintf(\"%02d\", k.Day)\n\t}\n\tif k.Ed > 0 {\n\t\tkeyString += fmt.Sprintf(\"%02d\", k.Ed)\n\t}\n\n\treturn keyString\n}", "func (s Crawler) s3Key(exchange exchanges.Exchange, company *quotes.Company, date time.Time) string {\n\t// {year}/{month}/{day}/{exchange}/{company}\n\treturn fmt.Sprintf(\"%s/%s/%s\", date.Format(\"2006/01/02\"), exchange.Code(), company.Code)\n}", "func (i GinJwtSignAlgorithm) Key() string {\n\tif val, ok := _GinJwtSignAlgorithmValueToKeyMap[i]; ok {\n\t\t// found\n\t\treturn val\n\t} else {\n\t\t// not found\n\t\treturn \"\"\n\t}\n}", "func (i SNSProtocol) Key() string {\n\tif val, ok := _SNSProtocolValueToKeyMap[i]; ok {\n\t\t// found\n\t\treturn val\n\t} else {\n\t\t// not found\n\t\treturn \"\"\n\t}\n}", "func (s Serializer) Key(buf cmpbin.WriteableBytesBuffer, k *Key) (err error) {\n\t// [appid ++ namespace]? ++ [1 ++ token]* ++ NULL\n\tdefer recoverTo(&err)\n\tappid, namespace, toks := k.Split()\n\tif s.WithKeyContext {\n\t\tpanicIf(buf.WriteByte(1))\n\t\t_, e := cmpbin.WriteString(buf, appid)\n\t\tpanicIf(e)\n\t\t_, e = cmpbin.WriteString(buf, namespace)\n\t\tpanicIf(e)\n\t} else {\n\t\tpanicIf(buf.WriteByte(0))\n\t}\n\tfor _, tok := range toks {\n\t\tpanicIf(buf.WriteByte(1))\n\t\tpanicIf(s.KeyTok(buf, tok))\n\t}\n\treturn buf.WriteByte(0)\n}", "func (s *Mem) Key(key interface{}) string {\n\treturn fmt.Sprintf(\"%v-%v\", s.prefix, key)\n}", "func (api *tenantAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"tenants\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"tenants\", \"/\", name)\n}", "func key(s string, noPaths bool) string {\n\tsep := \"/\"\n\tif noPaths {\n\t\tsep = \".\"\n\t}\n\ttokens := strings.Split(s, sep)\n\tsecretKey := tokens[len(tokens)-1]\n\treturn secretKey\n}", "func genTokenKey(key string, prefix string) string {\n return RedisKeyPrefix + prefix + key\n}", "func (s Stash) Key() string {\n\tvals := utils.MapValues(s.payload)\n\tif len(vals) < 1 {\n\t\treturn \"\"\n\t}\n\n\treturn fmt.Sprintf(\"$%s\", vals[0])\n}", "func (svc Service) CreateKey(lat, lng float64) Keytype {\n\tllat := int(lat * 10)\n\tllng := int(lng * 10)\n\n\treturn Keytype(fmt.Sprintf(\"%d:%d\", llat, llng))\n}", "func generateKey(cID, taskID string) (string, error) {\n\tif cutil.IsEmptyStr(cID) {\n\t\treturn \"\", errors.Wrapf(errorType.ErrEmptyValue, \"cID\")\n\t}\n\n\tif cutil.IsEmptyStr(taskID) {\n\t\treturn \"\", errors.Wrapf(errorType.ErrEmptyValue, \"taskID\")\n\t}\n\n\treturn fmt.Sprintf(\"%s%s%s\", cID, \"@\", taskID), nil\n}", "func (p *param) Key() string {\n\treturn \"conf.network.\" + p.Name()\n}", "func (api *credentialsAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"credentials\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"credentials\", \"/\", name)\n}", "func computeKey(cfg external.SharedConfig) string {\n\tvar a []string\n\t// keys must be sorted\n\tif cfg.RoleDurationSeconds != nil {\n\t\ta = append(a, fmt.Sprintf(`\"DurationSeconds\": %d`, int(cfg.RoleDurationSeconds.Seconds())))\n\t}\n\ta = append(a, `\"RoleArn\": `+strconv.Quote(cfg.RoleARN))\n\tif cfg.RoleSessionName != \"\" {\n\t\ta = append(a, `\"RoleSessionName\": `+strconv.Quote(cfg.RoleSessionName))\n\t}\n\ta = append(a, `\"SerialNumber\": `+strconv.Quote(cfg.MFASerial))\n\ts := sha1.Sum([]byte(fmt.Sprintf(\"{%s}\", strings.Join(a, \", \"))))\n\treturn hex.EncodeToString(s[:])\n}", "func generateKeyPairName() string {\n\tid := fmt.Sprintf(\"%x\", rand.Int())\n\treturn securityGroupNamePrefix + id\n}", "func (api *hostAPI) getFullKey(tenant, name string) string {\n\tif tenant != \"\" {\n\t\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"hosts\", \"/\", tenant, \"/\", name)\n\t}\n\treturn fmt.Sprint(globals.ConfigRootPrefix, \"/\", \"cluster\", \"/\", \"hosts\", \"/\", name)\n}", "func generateKey(args []string) string {\n\treturn strings.Join(args, \" \")\n}", "func (pubKey PubKeyEd25519) KeyString() string {\n\treturn Fmt(\"%X\", pubKey[:])\n}", "func (pubKey PubKeyEd25519) KeyString() string {\n\treturn Fmt(\"%X\", pubKey[:])\n}", "func (s *Subscription) GetKey() string {\n\tbaseURL, _ := url.Parse(s.BaseURL)\n\tfields := []string{\n\t\ts.VCSType,\n\t\tbaseURL.Hostname(),\n\t\ts.OrgName,\n\t\ts.RepoName,\n\t}\n\tkey := strings.Join(fields, \"_\")\n\treturn util.GetKeyHash(key)\n}", "func PathToKey(path string) (string) {\n\treturn base64.StdEncoding.EncodeToString([]byte(path))\n}", "func Key(id string) (key []byte) {\n\tkey = append(key, []byte(\"mavl-pos33-\")...)\n\tkey = append(key, []byte(id)...)\n\treturn key\n}", "func (aih AppAndImageToHash) Key() string {\n\tif aih.PurgeCounter == 0 {\n\t\treturn fmt.Sprintf(\"%s.%s\", aih.AppUUID.String(), aih.ImageID.String())\n\t} else {\n\t\treturn fmt.Sprintf(\"%s.%s.%d\", aih.AppUUID.String(), aih.ImageID.String(), aih.PurgeCounter)\n\t}\n}", "func KeyFor(p Plugin) string {\n\treturn Key(p.Name(), p.Version().String())\n}" ]
[ "0.78475267", "0.7231724", "0.72112584", "0.7159104", "0.6868532", "0.68373173", "0.68049735", "0.67363083", "0.66203", "0.6608118", "0.6600266", "0.6478343", "0.6449781", "0.642204", "0.6421565", "0.640649", "0.6386554", "0.6384255", "0.635582", "0.63047785", "0.62711596", "0.62619764", "0.62534523", "0.6239706", "0.62357026", "0.6197392", "0.6194905", "0.61825603", "0.6178301", "0.61475706", "0.60980844", "0.6079647", "0.60570776", "0.60545546", "0.6026684", "0.6017666", "0.60107154", "0.5987726", "0.59861386", "0.5976041", "0.5959315", "0.59455794", "0.5938183", "0.59354156", "0.5925511", "0.5921808", "0.59173024", "0.5897763", "0.58967924", "0.5894604", "0.5891344", "0.58834916", "0.5878588", "0.5877868", "0.5876751", "0.5857841", "0.58564615", "0.5853168", "0.5850702", "0.5847712", "0.58432364", "0.5838217", "0.58331186", "0.58245516", "0.5816022", "0.58105713", "0.581008", "0.58041704", "0.5789749", "0.57842517", "0.5780289", "0.57737863", "0.5767009", "0.5766072", "0.5765617", "0.57621026", "0.57581836", "0.5754213", "0.5751853", "0.5746985", "0.5744102", "0.5742856", "0.5741284", "0.57411456", "0.5735203", "0.57288885", "0.5724473", "0.5722166", "0.57220495", "0.5705629", "0.5705455", "0.5696484", "0.5691965", "0.56835365", "0.56835365", "0.568341", "0.56817716", "0.5680176", "0.56795263", "0.56778157" ]
0.66668534
8
Serialize returns m in its JSON encoded format or error if serialization had failed.
func (m *SAMap) Serialize() ([]byte, error) { m.RLock() defer m.RUnlock() return json.Marshal(m.ma) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (em Message) Serialize() ([]byte, error) {\n\tmsg, err := json.Marshal(em)\n\treturn msg, err\n}", "func (s *Serializer) Serialize(m telegraf.Metric) ([]byte, error) {\n\ts.buf.Reset()\n\terr := s.writeMetric(&s.buf, m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := make([]byte, 0, s.buf.Len())\n\treturn append(out, s.buf.Bytes()...), nil\n}", "func (e *InvalidPageSizeError) Serialize() []byte {\n\tg, _ := json.Marshal(map[string]interface{}{\n\t\t\"code\": \"ERR-008\",\n\t\t\"error\": \"InvalidPageSizeError\",\n\t\t\"description\": e.Error(),\n\t\t\"success\": false,\n\t})\n\n\treturn g\n}", "func (cm Message) Serialize() ([]byte, error) {\n\treturn []byte(cm.Content), nil\n}", "func (e *InvalidPageError) Serialize() []byte {\n\tg, _ := json.Marshal(map[string]interface{}{\n\t\t\"code\": \"ERR-007\",\n\t\t\"error\": \"InvalidPageError\",\n\t\t\"description\": e.Error(),\n\t\t\"success\": false,\n\t})\n\n\treturn g\n}", "func Serialize(msg Message) ([]byte, error) {\n\tvar b bytes.Buffer\n\tencoder := json.NewEncoder(&b)\n\terr := encoder.Encode(msg)\n\treturn b.Bytes(), err\n}", "func (m Message) Marshal() ([]byte, error) {\n\treturn jsoniter.Marshal(m)\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 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 (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 (m *Media) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteObjectValue(\"calleeDevice\", m.GetCalleeDevice())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"calleeNetwork\", m.GetCalleeNetwork())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"callerDevice\", m.GetCallerDevice())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"callerNetwork\", m.GetCallerNetwork())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"label\", m.GetLabel())\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.GetStreams() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetStreams())\n err := writer.WriteCollectionOfObjectValues(\"streams\", cast)\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 *NonAllowedEmailDomainError) Serialize() []byte {\n\tg, _ := json.Marshal(map[string]interface{}{\n\t\t\"code\": \"ERR-002\",\n\t\t\"error\": \"NonAllowedEmailDomainError\",\n\t\t\"description\": e.Error(),\n\t\t\"success\": false,\n\t})\n\n\treturn g\n}", "func (m *saMap) serialize() ([]byte, error) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\treturn json.Marshal(m.ma)\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 (m *MatrixMessage) Marshal() ([]byte, error) {\n\tj, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn j, nil\n}", "func (m Message) Serialize() []byte {\n\tbuff := make([]byte, 0, 512)\n\n\t// fix header counts before serialization\n\tm.Header.QuestionCount = uint16(len(m.Questions))\n\tm.Header.AnswerRecordCount = uint16(len(m.AnswerRecords))\n\tm.Header.AuthorityRecordCount = uint16(len(m.AuthorityRecords))\n\tm.Header.AdditionalRecordCount = uint16(len(m.AdditionalRecords))\n\n\tbuff = append(buff, m.Header.Serialize()...)\n\tfor _, question := range m.Questions {\n\t\tbuff = append(buff, question.Serialize()...)\n\t}\n\tfor _, rr := range m.AnswerRecords {\n\t\tbuff = append(buff, rr.Serialize()...)\n\t}\n\tfor _, rr := range m.AuthorityRecords {\n\t\tbuff = append(buff, rr.Serialize()...)\n\t}\n\tfor _, rr := range m.AdditionalRecords {\n\t\tbuff = append(buff, rr.Serialize()...)\n\t}\n\treturn buff\n}", "func (m *MSPManaged) ToJSON() (string, error) {\n\treturn codec.ToJSON(m)\n}", "func (mu *MuHash) Serialize() *SerializedMuHash {\n\tvar out SerializedMuHash\n\tmu.serializeInner(&out)\n\treturn &out\n}", "func (m *NumaMem) ToJSON() (string, error) {\n\treturn codec.ToJSON(m)\n}", "func (l *Layer) Serialize() ([]byte, error) {\n\treturn json.Marshal(l)\n}", "func Serialize(data interface{}) string {\n\tval, _ := json.Marshal(data)\n\treturn string(val);\n}", "func (o *A_2) SerializeJSON() ([]byte, error) {\r\n\treturn json.Marshal(o)\r\n}", "func (pd *pymtData) Serialize() ([]byte, error) {\n\tb, err := json.Marshal(pd)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, payment.ErrUnexpectedSysError)\n\t}\n\n\treturn 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 Serialize(o interface{}) ([]byte, error) {\n\tautil.TODO(\"CBOR-serialization\")\n\treturn nil, nil\n}", "func (m Message) String() string {\n\tjm, _ := json.Marshal(m)\n\treturn string(jm)\n}", "func (m *Meta) JSON() string {\n\tj, _ := json.MarshalIndent(m, \"\", \" \")\n\treturn string(j)\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 (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 (s *WavefrontSerializer) Serialize(m telegraf.Metric) ([]byte, error) {\n\tout := []byte{}\n\tmetricSeparator := \".\"\n\n\tfor fieldName, value := range m.Fields() {\n\t\tvar name string\n\n\t\tif fieldName == \"value\" {\n\t\t\tname = fmt.Sprintf(\"%s%s\", s.Prefix, m.Name())\n\t\t} else {\n\t\t\tname = fmt.Sprintf(\"%s%s%s%s\", s.Prefix, m.Name(), metricSeparator, fieldName)\n\t\t}\n\n\t\tif s.UseStrict {\n\t\t\tname = strictSanitizedChars.Replace(name)\n\t\t} else {\n\t\t\tname = sanitizedChars.Replace(name)\n\t\t}\n\n\t\tname = pathReplacer.Replace(name)\n\n\t\tmetric := &wavefront.MetricPoint{\n\t\t\tMetric: name,\n\t\t\tTimestamp: m.Time().Unix(),\n\t\t}\n\n\t\tmetricValue, buildError := buildValue(value, metric.Metric)\n\t\tif buildError != nil {\n\t\t\t// bad value continue to next metric\n\t\t\tcontinue\n\t\t}\n\t\tmetric.Value = metricValue\n\n\t\tsource, tags := buildTags(m.Tags(), s)\n\t\tmetric.Source = source\n\t\tmetric.Tags = tags\n\n\t\tout = append(out, formatMetricPoint(metric, s)...)\n\t}\n\treturn out, nil\n}", "func (m Error) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(m.data)\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 (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 (h HMSketch) Serialize() ([]byte, error) {\n\tvar outbytes bytes.Buffer\n\tenc := gob.NewEncoder(&outbytes)\n\terr := enc.Encode(h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn outbytes.Bytes(), nil\n}", "func (m *ConnectedMessage) ToJson() string {\n\tvar msg, _ = json.Marshal(m)\n\treturn string(msg)\n}", "func GetJSON(m Model) ([]byte, error) {\n\tdata, err := json.MarshalIndent(m, \"\", \" \")\n\trtx.Must(err, \"ERROR: failed to marshal archive.Model to JSON. This should never happen\")\n\treturn data, err\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 *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 (m Mall) String() string {\n\ts, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn string(s)\n}", "func (m *Aws) ToJSON() (string, error) {\n\treturn codec.ToJSON(m)\n}", "func (m *ChatMessage) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAttachments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAttachments())\n err = writer.WriteCollectionOfObjectValues(\"attachments\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"body\", m.GetBody())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"channelIdentity\", m.GetChannelIdentity())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"chatId\", m.GetChatId())\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.WriteTimeValue(\"deletedDateTime\", m.GetDeletedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"etag\", m.GetEtag())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"eventDetail\", m.GetEventDetail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"from\", m.GetFrom())\n if err != nil {\n return err\n }\n }\n if m.GetHostedContents() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetHostedContents())\n err = writer.WriteCollectionOfObjectValues(\"hostedContents\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetImportance() != nil {\n cast := (*m.GetImportance()).String()\n err = writer.WriteStringValue(\"importance\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastEditedDateTime\", m.GetLastEditedDateTime())\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.WriteStringValue(\"locale\", m.GetLocale())\n if err != nil {\n return err\n }\n }\n if m.GetMentions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMentions())\n err = writer.WriteCollectionOfObjectValues(\"mentions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetMessageType() != nil {\n cast := (*m.GetMessageType()).String()\n err = writer.WriteStringValue(\"messageType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"policyViolation\", m.GetPolicyViolation())\n if err != nil {\n return err\n }\n }\n if m.GetReactions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetReactions())\n err = writer.WriteCollectionOfObjectValues(\"reactions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetReplies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetReplies())\n err = writer.WriteCollectionOfObjectValues(\"replies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"replyToId\", m.GetReplyToId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"subject\", m.GetSubject())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"summary\", m.GetSummary())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"webUrl\", m.GetWebUrl())\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 toJSON(a interface{}) ([]byte, error) {\n\tbs, err := json.Marshal(a)\n\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"there was an error: %v\", err)\n\t\t// return []byte{}, fmt.Println(\"there was an error: %v\", err)\n\t\t//does not work bc Println returns n int and err => we only need err\n\t\t//fatal does not work bec no error returned but we need to return here\n\n\t}\n\treturn bs, nil\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 (s *Serializer) Serialize(p svermaker.ProjectVersion) error {\n\ts.SerializerInvoked = true\n\treturn s.SerializerFn(p)\n}", "func serialize(toMarshal interface{}) *bytes.Buffer {\n\tjsonStr, _ := json.Marshal(toMarshal)\n\treturn bytes.NewBuffer(jsonStr)\n}", "func (store_m StoreModule) ToJSON() []byte {\n\tjsonStr, _ := json.Marshal(store_m)\n\treturn jsonStr\n}", "func (m *Message) Serialize() []byte {\n\tif m == nil {\n\t\treturn make([]byte, 4)\n\t}\n\tlength := uint32(len(m.Payload) + 1) // +1 for id\n\tbuf := make([]byte, 4+length)\n\tbinary.BigEndian.PutUint32(buf[0:4], length)\n\tbuf[4] = byte(m.ID)\n\tcopy(buf[5:], m.Payload)\n\treturn buf\n}", "func (m *ActionResultPart) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteObjectValue(\"error\", m.GetError())\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 (mp MassPayment) Serialize() (string, error) {\n\tdata := url.Values{}\n\tmassPaymentType := reflect.TypeOf(mp)\n\tmassPaymentValue := reflect.ValueOf(mp)\n\n\tfor i := 0; i < massPaymentType.NumField(); i++ {\n\t\tfield := massPaymentType.Field(i)\n\t\tif fieldTag, ok := field.Tag.Lookup(\"nvp_field\"); ok {\n\t\t\tvalueContents := massPaymentValue.Field(i).String()\n\t\t\tif valueContents != \"\" {\n\t\t\t\tdata.Set(fieldTag, massPaymentValue.Field(i).String())\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i, item := range mp.Items {\n\t\titem.Serialize(&data, i)\n\t}\n\n\tif len(mp.Items) == 0 {\n\t\treturn \"\", errors.New(\"Expected at least one mass payment item\")\n\t}\n\n\treturn data.Encode(), nil\n}", "func (m *Message) String() string {\n\tjsonBytes, err := json.MarshalIndent(m, \"\", \" \")\n\t// jsonBytes, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"message error - fail to marshal message to bytes, error: %v\", err)\n\t}\n\treturn string(jsonBytes)\n}", "func toJSON(a interface{}) ([]byte, error) {\n\tbs, err := json.Marshal(a)\n\tif err != nil {\n\t\t//return []byte{}, fmt.Errorf(\"Erro no json %v\", err)\n\t\treturn []byte{}, errors.New(fmt.Sprintf(\"Erro no json %v\", err))\n\t}\n\treturn bs, nil\n}", "func (m *Metrics) String() string {\n\tb, _ := json.Marshal(m)\n\treturn string(b)\n}", "func (m *ItemItemsItemWorkbookFunctionsComplexPostRequestBody) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteObjectValue(\"iNum\", m.GetINum())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"realNum\", m.GetRealNum())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"suffix\", m.GetSuffix())\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 *Free) ToJson() ([]byte, error) {\n\treturn json.Marshal(m.Data)\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 (g *Generic) Serialize() ([]byte, error) {\n\tlog.Println(\"DEPRECATED: MarshalBinary instead\")\n\treturn g.MarshalBinary()\n}", "func (m lockCmdMessage) JSON() string {\n\tmsgBytes, e := json.MarshalIndent(m, \"\", \" \")\n\tfatalIf(probe.NewError(e), \"Unable to marshal into JSON.\")\n\treturn string(msgBytes)\n}", "func toJSON(a interface{}) ([]byte, error) {\n\tbs, err := json.Marshal(a)\n\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"Error caught by Onur Gurel\")\n\t}\n\n\treturn bs, nil\n}", "func (mm *managedAnnotation) Encode(m map[string]interface{}) error {\n\tvar buf bytes.Buffer\n\tgz := gzip.NewWriter(&buf)\n\n\tactions := []serial.Action{\n\t\tfunc() error { return json.NewEncoder(gz).Encode(m) },\n\t\tgz.Flush,\n\t\tgz.Close,\n\t}\n\n\tif err := serial.RunActions(actions...); err != nil {\n\t\treturn err\n\t}\n\n\tmm.Pristine = base64.StdEncoding.EncodeToString(buf.Bytes())\n\treturn nil\n}", "func (m *Group) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DirectoryObject.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAcceptedSenders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAcceptedSenders())\n err = writer.WriteCollectionOfObjectValues(\"acceptedSenders\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"allowExternalSenders\", m.GetAllowExternalSenders())\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.GetAssignedLabels() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAssignedLabels())\n err = writer.WriteCollectionOfObjectValues(\"assignedLabels\", 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 {\n err = writer.WriteBoolValue(\"autoSubscribeNewMembers\", m.GetAutoSubscribeNewMembers())\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.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 {\n err = writer.WriteStringValue(\"classification\", m.GetClassification())\n if err != nil {\n return err\n }\n }\n if m.GetConversations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetConversations())\n err = writer.WriteCollectionOfObjectValues(\"conversations\", 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(\"createdOnBehalfOf\", m.GetCreatedOnBehalfOf())\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(\"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 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 {\n err = writer.WriteTimeValue(\"expirationDateTime\", m.GetExpirationDateTime())\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 if m.GetGroupLifecyclePolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetGroupLifecyclePolicies())\n err = writer.WriteCollectionOfObjectValues(\"groupLifecyclePolicies\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetGroupTypes() != nil {\n err = writer.WriteCollectionOfStringValues(\"groupTypes\", m.GetGroupTypes())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hasMembersWithLicenseErrors\", m.GetHasMembersWithLicenseErrors())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hideFromAddressLists\", m.GetHideFromAddressLists())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hideFromOutlookClients\", m.GetHideFromOutlookClients())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isArchived\", m.GetIsArchived())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isAssignableToRole\", m.GetIsAssignableToRole())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isSubscribedByMail\", m.GetIsSubscribedByMail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"licenseProcessingState\", m.GetLicenseProcessingState())\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.WriteBoolValue(\"mailEnabled\", m.GetMailEnabled())\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.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.GetMembers() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMembers())\n err = writer.WriteCollectionOfObjectValues(\"members\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"membershipRule\", m.GetMembershipRule())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"membershipRuleProcessingState\", m.GetMembershipRuleProcessingState())\n if err != nil {\n return err\n }\n }\n if m.GetMembersWithLicenseErrors() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMembersWithLicenseErrors())\n err = writer.WriteCollectionOfObjectValues(\"membersWithLicenseErrors\", cast)\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 {\n err = writer.WriteStringValue(\"onPremisesDomainName\", m.GetOnPremisesDomainName())\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 {\n err = writer.WriteStringValue(\"onPremisesNetBiosName\", m.GetOnPremisesNetBiosName())\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 if m.GetOwners() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwners())\n err = writer.WriteCollectionOfObjectValues(\"owners\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetPermissionGrants() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPermissionGrants())\n err = writer.WriteCollectionOfObjectValues(\"permissionGrants\", 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(\"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 if m.GetProxyAddresses() != nil {\n err = writer.WriteCollectionOfStringValues(\"proxyAddresses\", m.GetProxyAddresses())\n if err != nil {\n return err\n }\n }\n if m.GetRejectedSenders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetRejectedSenders())\n err = writer.WriteCollectionOfObjectValues(\"rejectedSenders\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"renewedDateTime\", m.GetRenewedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"securityEnabled\", m.GetSecurityEnabled())\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 if m.GetSettings() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSettings())\n err = writer.WriteCollectionOfObjectValues(\"settings\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSites() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSites())\n err = writer.WriteCollectionOfObjectValues(\"sites\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"team\", m.GetTeam())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"theme\", m.GetTheme())\n if err != nil {\n return err\n }\n }\n if m.GetThreads() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetThreads())\n err = writer.WriteCollectionOfObjectValues(\"threads\", cast)\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 if m.GetTransitiveMembers() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTransitiveMembers())\n err = writer.WriteCollectionOfObjectValues(\"transitiveMembers\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"unseenCount\", m.GetUnseenCount())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"visibility\", m.GetVisibility())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *Reminder) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"changeKey\", m.GetChangeKey())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"eventEndTime\", m.GetEventEndTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventId\", m.GetEventId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"eventLocation\", m.GetEventLocation())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"eventStartTime\", m.GetEventStartTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventSubject\", m.GetEventSubject())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventWebLink\", m.GetEventWebLink())\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(\"reminderFireTime\", m.GetReminderFireTime())\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 (message *Message) ToJson(writer io.Writer) error {\n\tencoder := json.NewEncoder(writer)\n\tencodedMessage := encoder.Encode(message)\n\treturn encodedMessage\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 *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 (m *CalendarGroup) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetCalendars() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCalendars()))\n for i, v := range m.GetCalendars() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"calendars\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"changeKey\", m.GetChangeKey())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteUUIDValue(\"classId\", m.GetClassId())\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 return nil\n}", "func (m *Empty) ToJSON() (string, error) {\n\treturn codec.ToJSON(m)\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 (m Messages) String() string {\n\tjm, _ := json.Marshal(m)\n\treturn string(jm)\n}", "func (msg *Error) JSON() any {\n\tjsonData := H{}\n\tif msg.Meta != nil {\n\t\tvalue := reflect.ValueOf(msg.Meta)\n\t\tswitch value.Kind() {\n\t\tcase reflect.Struct:\n\t\t\treturn msg.Meta\n\t\tcase reflect.Map:\n\t\t\tfor _, key := range value.MapKeys() {\n\t\t\t\tjsonData[key.String()] = value.MapIndex(key).Interface()\n\t\t\t}\n\t\tdefault:\n\t\t\tjsonData[\"meta\"] = msg.Meta\n\t\t}\n\t}\n\tif _, ok := jsonData[\"error\"]; !ok {\n\t\tjsonData[\"error\"] = msg.Error()\n\t}\n\treturn jsonData\n}", "func (m *Metadata) ToJSON() ([]byte, error) {\n\tjson, err := json.Marshal(m)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"err dumping JSON: %w\", err)\n\n\t\treturn []byte{}, err\n\t}\n\n\treturn json, nil\n}", "func (pg *ProblemGraph) Serialize() []byte {\n\tvar result bytes.Buffer\n\tencoder := gob.NewEncoder(&result)\n\n\terr := encoder.Encode(pg)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn result.Bytes()\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 *Membership) Serialize() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\n\t// Version (uint8)\n\t{\n\t\tif err := write(buf, m.Version); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// AgeRestriction (AgeRestriction)\n\t{\n\t\tif err := write(buf, m.AgeRestriction); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// ValidFrom (Timestamp)\n\t{\n\t\tif err := write(buf, m.ValidFrom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// ExpirationTimestamp (Timestamp)\n\t{\n\t\tif err := write(buf, m.ExpirationTimestamp); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// ID (string)\n\t{\n\t\tif err := WriteVarChar(buf, m.ID, 8); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// MembershipClass (string)\n\t{\n\t\tif err := WriteVarChar(buf, m.MembershipClass, 8); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// RoleType (string)\n\t{\n\t\tif err := WriteVarChar(buf, m.RoleType, 8); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// MembershipType (string)\n\t{\n\t\tif err := WriteVarChar(buf, m.MembershipType, 8); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Description (string)\n\t{\n\t\tif err := WriteVarChar(buf, m.Description, 16); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (m *Workbook) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"application\", m.GetApplication())\n if err != nil {\n return err\n }\n }\n if m.GetComments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetComments())\n err = writer.WriteCollectionOfObjectValues(\"comments\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"functions\", m.GetFunctions())\n if err != nil {\n return err\n }\n }\n if m.GetNames() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetNames())\n err = writer.WriteCollectionOfObjectValues(\"names\", cast)\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 if m.GetTables() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTables())\n err = writer.WriteCollectionOfObjectValues(\"tables\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetWorksheets() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetWorksheets())\n err = writer.WriteCollectionOfObjectValues(\"worksheets\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *TeamsAsyncOperation) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteInt32Value(\"attemptsCount\", m.GetAttemptsCount())\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(\"error\", m.GetError())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastActionDateTime\", m.GetLastActionDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetOperationType() != nil {\n cast := (*m.GetOperationType()).String()\n err = writer.WriteStringValue(\"operationType\", &cast)\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 {\n err = writer.WriteStringValue(\"targetResourceId\", m.GetTargetResourceId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"targetResourceLocation\", m.GetTargetResourceLocation())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *ConnectedOrganizationMembers) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.SubjectSet.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"connectedOrganizationId\", m.GetConnectedOrganizationId())\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 return nil\n}", "func (msssmto MigrateSQLServerSQLMITaskOutput) MarshalJSON() ([]byte, error) {\n\tmsssmto.ResultType = ResultTypeBasicMigrateSQLServerSQLMITaskOutputResultTypeMigrateSQLServerSQLMITaskOutput\n\tobjectMap := make(map[string]interface{})\n\tif msssmto.ID != nil {\n\t\tobjectMap[\"id\"] = msssmto.ID\n\t}\n\tif msssmto.ResultType != \"\" {\n\t\tobjectMap[\"resultType\"] = msssmto.ResultType\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (m *MqMessageKey) Encode() ([]byte, error) {\n\treturn json.Marshal(m)\n\n}", "func (m Message) MarshalJSON() ([]byte, error) {\n\ttype Message struct {\n\t\tSig hexutil.Bytes `json:\"sig,omitempty\"`\n\t\tTTL uint32 `json:\"ttl\"`\n\t\tTimestamp uint32 `json:\"timestamp\"`\n\t\tTopic TopicType `json:\"topic\"`\n\t\tPayload hexutil.Bytes `json:\"payload\"`\n\t\tPadding hexutil.Bytes `json:\"padding\"`\n\t\tPoW float64 `json:\"pow\"`\n\t\tHash hexutil.Bytes `json:\"hash\"`\n\t\tDst hexutil.Bytes `json:\"recipientPublicKey,omitempty\"`\n\t}\n\tvar enc Message\n\tenc.Sig = m.Sig\n\tenc.TTL = m.TTL\n\tenc.Timestamp = m.Timestamp\n\tenc.Topic = m.Topic\n\tenc.Payload = m.Payload\n\tenc.Padding = m.Padding\n\tenc.PoW = m.PoW\n\tenc.Hash = m.Hash\n\tenc.Dst = m.Dst\n\treturn json.Marshal(&enc)\n}", "func (b Bytes) Serialize() ([]byte, error) {\n\treturn b, nil\n}", "func (t Tweet) Serialize() *[]byte {\n\tb, err := json.Marshal(t)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn &b\n}", "func (s String) Serialize() ([]byte, error) {\n\treturn []byte(s), nil\n}", "func (m *Application) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DirectoryObject.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAddIns() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAddIns())\n err = writer.WriteCollectionOfObjectValues(\"addIns\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"api\", m.GetApi())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"appId\", m.GetAppId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"applicationTemplateId\", m.GetApplicationTemplateId())\n if err != nil {\n return err\n }\n }\n if m.GetAppRoles() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAppRoles())\n err = writer.WriteCollectionOfObjectValues(\"appRoles\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"certification\", m.GetCertification())\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(\"createdOnBehalfOf\", m.GetCreatedOnBehalfOf())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"defaultRedirectUri\", m.GetDefaultRedirectUri())\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(\"disabledByMicrosoftStatus\", m.GetDisabledByMicrosoftStatus())\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 if m.GetExtensionProperties() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetExtensionProperties())\n err = writer.WriteCollectionOfObjectValues(\"extensionProperties\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetFederatedIdentityCredentials() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetFederatedIdentityCredentials())\n err = writer.WriteCollectionOfObjectValues(\"federatedIdentityCredentials\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"groupMembershipClaims\", m.GetGroupMembershipClaims())\n if err != nil {\n return err\n }\n }\n if m.GetHomeRealmDiscoveryPolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetHomeRealmDiscoveryPolicies())\n err = writer.WriteCollectionOfObjectValues(\"homeRealmDiscoveryPolicies\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetIdentifierUris() != nil {\n err = writer.WriteCollectionOfStringValues(\"identifierUris\", m.GetIdentifierUris())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"info\", m.GetInfo())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isDeviceOnlyAuthSupported\", m.GetIsDeviceOnlyAuthSupported())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isFallbackPublicClient\", m.GetIsFallbackPublicClient())\n if err != nil {\n return err\n }\n }\n if m.GetKeyCredentials() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetKeyCredentials())\n err = writer.WriteCollectionOfObjectValues(\"keyCredentials\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteByteArrayValue(\"logo\", m.GetLogo())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"notes\", m.GetNotes())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"oauth2RequirePostResponse\", m.GetOauth2RequirePostResponse())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"optionalClaims\", m.GetOptionalClaims())\n if err != nil {\n return err\n }\n }\n if m.GetOwners() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwners())\n err = writer.WriteCollectionOfObjectValues(\"owners\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"parentalControlSettings\", m.GetParentalControlSettings())\n if err != nil {\n return err\n }\n }\n if m.GetPasswordCredentials() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPasswordCredentials())\n err = writer.WriteCollectionOfObjectValues(\"passwordCredentials\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"publicClient\", m.GetPublicClient())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"publisherDomain\", m.GetPublisherDomain())\n if err != nil {\n return err\n }\n }\n if m.GetRequiredResourceAccess() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetRequiredResourceAccess())\n err = writer.WriteCollectionOfObjectValues(\"requiredResourceAccess\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"samlMetadataUrl\", m.GetSamlMetadataUrl())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"serviceManagementReference\", m.GetServiceManagementReference())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"signInAudience\", m.GetSignInAudience())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"spa\", m.GetSpa())\n if err != nil {\n return err\n }\n }\n if m.GetTags() != nil {\n err = writer.WriteCollectionOfStringValues(\"tags\", m.GetTags())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"tokenEncryptionKeyId\", m.GetTokenEncryptionKeyId())\n if err != nil {\n return err\n }\n }\n if m.GetTokenIssuancePolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTokenIssuancePolicies())\n err = writer.WriteCollectionOfObjectValues(\"tokenIssuancePolicies\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTokenLifetimePolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTokenLifetimePolicies())\n err = writer.WriteCollectionOfObjectValues(\"tokenLifetimePolicies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"verifiedPublisher\", m.GetVerifiedPublisher())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"web\", m.GetWeb())\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 *CommunicationsIdentitySet) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.IdentitySet.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"applicationInstance\", m.GetApplicationInstance())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"assertedIdentity\", m.GetAssertedIdentity())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"azureCommunicationServicesUser\", m.GetAzureCommunicationServicesUser())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"encrypted\", m.GetEncrypted())\n if err != nil {\n return err\n }\n }\n if m.GetEndpointType() != nil {\n cast := (*m.GetEndpointType()).String()\n err = writer.WriteStringValue(\"endpointType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"guest\", m.GetGuest())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"onPremises\", m.GetOnPremises())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"phone\", m.GetPhone())\n if err != nil {\n return err\n }\n }\n return nil\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 (self *ResTransaction)Serialize()[]byte{\n data, err := json.Marshal(self)\n if err != nil {\n fmt.Println(err)\n }\n return data\n}", "func (m *AssignPostRequestBody) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetMobileAppAssignments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMobileAppAssignments())\n err := writer.WriteCollectionOfObjectValues(\"mobileAppAssignments\", cast)\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 DelegateMap) Serialize() ([]byte, error) {\n\tl := make(DelegateList, 0, len(m))\n\tfor _, v := range m {\n\t\tl = append(l, v)\n\t}\n\tsort.Sort(l)\n\treturn proto.Marshal(l.toProto())\n}", "func (i Int) Serialize() ([]byte, error) {\n\treturn []byte(strconv.Itoa(int(i))), nil\n}", "func (m *DockerContainersMemory) ToJson() ([]byte, error) {\n\treturn json.Marshal(m.Data)\n}", "func (m *UpdateAllowedCombinationsResult) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"additionalInformation\", m.GetAdditionalInformation())\n if err != nil {\n return err\n }\n }\n if m.GetConditionalAccessReferences() != nil {\n err := writer.WriteCollectionOfStringValues(\"conditionalAccessReferences\", m.GetConditionalAccessReferences())\n if err != nil {\n return err\n }\n }\n if m.GetCurrentCombinations() != nil {\n err := writer.WriteCollectionOfStringValues(\"currentCombinations\", SerializeAuthenticationMethodModes(m.GetCurrentCombinations()))\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.GetPreviousCombinations() != nil {\n err := writer.WriteCollectionOfStringValues(\"previousCombinations\", SerializeAuthenticationMethodModes(m.GetPreviousCombinations()))\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 (rs *Restake) Serialize() []byte {\n\treturn byteutil.Must(proto.Marshal(rs.Proto()))\n}", "func (m *CloudCommunications) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetCalls() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCalls()))\n for i, v := range m.GetCalls() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"calls\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOnlineMeetings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetOnlineMeetings()))\n for i, v := range m.GetOnlineMeetings() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"onlineMeetings\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetPresences() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetPresences()))\n for i, v := range m.GetPresences() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"presences\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *Marshaler) JSON(v interface{}) ([]byte, error) {\n\tif _, ok := v.(proto.Message); ok {\n\t\tvar buf bytes.Buffer\n\t\tjm := &jsonpb.Marshaler{}\n\t\tjm.OrigName = true\n\t\tif err := jm.Marshal(&buf, v.(proto.Message)); err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\n\t\tif m.FilterProtoJson {\n\t\t\treturn m.FilterJsonWithStruct(buf.Bytes(), v)\n\t\t}\n\t\treturn buf.Bytes(), nil\n\t}\n\treturn json.Marshal(v)\n}", "func (m *Printer) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.PrinterBase.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetConnectors() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetConnectors()))\n for i, v := range m.GetConnectors() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"connectors\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hasPhysicalDevice\", m.GetHasPhysicalDevice())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isShared\", m.GetIsShared())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastSeenDateTime\", m.GetLastSeenDateTime())\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 if m.GetShares() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetShares()))\n for i, v := range m.GetShares() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"shares\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTaskTriggers() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTaskTriggers()))\n for i, v := range m.GetTaskTriggers() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"taskTriggers\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *MessageFromServer) Encode() []byte {\n\n\t// encode to json\n\tbytes, err := json.Marshal(m)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn []byte{}\n\t}\n\n\treturn bytes\n}", "func (m *ChatMessageAttachment) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"content\", m.GetContent())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"contentType\", m.GetContentType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"contentUrl\", m.GetContentUrl())\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(\"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.WriteStringValue(\"teamsAppId\", m.GetTeamsAppId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"thumbnailUrl\", m.GetThumbnailUrl())\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 toJSON(a interface{}) ([]byte, error) {\n\tbs, err := json.Marshal(a)\n\tif err != nil {\n\t\t// return []byte{}, errors.New(fmt.Sprintf(\"Can't create json with error: %v\", err))\n\t\treturn []byte{}, fmt.Errorf(\"Can't create json for person: %v error: %v\", a, err)\n\t}\n\treturn bs, nil\n}" ]
[ "0.69589114", "0.6374156", "0.63503855", "0.63293475", "0.62809575", "0.62227243", "0.60944897", "0.6069264", "0.604852", "0.6047298", "0.6029144", "0.6010156", "0.59961045", "0.59700155", "0.59660673", "0.58975554", "0.5865713", "0.5852372", "0.58185226", "0.57493746", "0.57183236", "0.5713082", "0.56923836", "0.568314", "0.5661845", "0.56431746", "0.5636496", "0.56331366", "0.5614332", "0.56037927", "0.5587247", "0.5585006", "0.55691475", "0.55659956", "0.5563944", "0.55460787", "0.5534823", "0.55291003", "0.5527905", "0.5526862", "0.55078816", "0.5485817", "0.54763174", "0.5469871", "0.5464439", "0.54627794", "0.545888", "0.5457855", "0.5452171", "0.54409856", "0.54302746", "0.5427981", "0.54245704", "0.5422141", "0.5414543", "0.54144645", "0.5410178", "0.5409455", "0.5404736", "0.54024464", "0.5394186", "0.53836054", "0.537439", "0.5373903", "0.53706527", "0.5368869", "0.5366384", "0.5363737", "0.536339", "0.53602654", "0.53574175", "0.53565013", "0.5355706", "0.5345822", "0.53374827", "0.532216", "0.5320934", "0.53197366", "0.53111786", "0.53109986", "0.53068566", "0.52955663", "0.52928215", "0.52727306", "0.52694446", "0.52673686", "0.5261993", "0.5260202", "0.52503484", "0.52489156", "0.52475464", "0.52456594", "0.52442545", "0.5242741", "0.5241949", "0.52412164", "0.5240483", "0.52403677", "0.5238787", "0.5238048" ]
0.6021478
11
NewSAMap creates an empty SAMap
func newSAMap() *saMap { t := make(map[ServiceAccount]GSAEmail) return &saMap{ ma: t, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New() *Map { return new(Map).Init() }", "func New() Map {\n\treturn empty\n}", "func newMapCache(dss map[string]rrd.DataSourcer) *mapCache {\n\tmc := &mapCache{make(map[string]int64), make(map[int64]rrd.DataSourcer)}\n\tvar n int64\n\tfor name, ds := range dss {\n\t\tmc.byName[name] = n\n\t\tmc.byId[n] = ds\n\t\tn++\n\t}\n\treturn mc\n}", "func NewNoGrowMap(initialSize int) *NoGrowMap {\n\t// make an iterator that has initialSize items left to go\n\titerator := make(chan struct{}, initialSize)\n\tfor i := 0; i < initialSize; i++ {\n\t\titerator <- struct{}{}\n\t}\n\treturn &NoGrowMap{\n\t\tSize: initialSize,\n\t\tIterator: iterator,\n\t}\n}", "func NewMap() Map {\n\treturn Map{NewSet()}\n}", "func newProgramMap() *programMap {\n\treturn &programMap{\n\t\tp: make(map[uint32]uint16),\n\t}\n}", "func newSimpleMapping(name string, m map[byte]rune) *simpleMapping {\n\treturn &simpleMapping{\n\t\tbaseName: name,\n\t\tdecode: m,\n\t}\n}", "func NewNaiveMap(size int) *NaiveMap {\n\tinitial := &NaiveMap{\n\t\tsync.Mutex{},\n\t\tmake([]string, size),\n\t\tmake([]interface{}, size),\n\t\tsize,\n\t\t0,\n\t}\n\treturn initial\n\n}", "func New() SharedMap {\n\tsm := sharedMap{\n\t\tm: make(map[string]interface{}),\n\t\tc: make(chan command),\n\t}\n\tgo sm.run()\n\treturn sm\n}", "func NewMap(size int) *Map {\n\tif size <= 0 {\n\t\tsize = runtime.GOMAXPROCS(0)\n\t}\n\tsplits := make([]Split, size)\n\tfor i := range splits {\n\t\tsplits[i].Map = make(map[interface{}]interface{})\n\t}\n\treturn &Map{splits}\n}", "func NewMap(store map[string]*rsa.PrivateKey) *KeyStore {\n\treturn &KeyStore{\n\t\tstore: store,\n\t}\n}", "func New() *OMap {\n\treturn &OMap{\n\t\tkeys: make([]string, 0),\n\t\tbaseMap: make(map[string]interface{}, 0),\n\t}\n}", "func newMap() map[interface{}]interface{} {\n\treturn map[interface{}]interface{}{}\n}", "func newMap(src *map[string]interface{}) map[string]interface{} {\n\tdst := make(map[string]interface{})\n\tif src == nil {\n\t\treturn dst\n\t}\n\tfor k, v := range *src {\n\t\tif strings.HasPrefix(k, \"_\") {\n\t\t\tcontinue\n\t\t}\n\t\tdst[k] = v\n\t}\n\treturn dst\n}", "func initMap(maxEntries int) *signalMap {\n\treturn &signalMap{\n\t\tmaxEntries: maxEntries,\n\t\toldBpfMap: bpf.NewMap(MapName,\n\t\t\tebpf.PerfEventArray,\n\t\t\t&Key{},\n\t\t\t&Value{},\n\t\t\tmaxEntries,\n\t\t\t0,\n\t\t),\n\t}\n}", "func New() hctx.Map {\n\treturn hctx.Map{\n\t\tPathForKey: PathFor,\n\t}\n}", "func ConstructorMap() MyHashMap {\n\to := MyHashMap{\n\t\tlist: [500]LinkNode{},\n\t}\n\tfor i := 0; i < len(o.list); i++ {\n\t\to.list[i].value = -1\n\t}\n\treturn o\n}", "func New() *S {\n\treturn &S{map[PType][]*A{}, map[string]*A{}}\n}", "func NewMap(concurrency int) *Map {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tm := &Map{\n\t\tconcurrency: concurrency,\n\t\tseed: uintptr(rand.Int63()),\n\t\tmutices: make([]sync.RWMutex, concurrency),\n\t\tducklings: make([]duckling, concurrency),\n\t}\n\tfor b := 0; b < concurrency; b++ {\n\t\tm.ducklings[b] = make(duckling, duckilingDefaultSize)\n\t}\n\treturn m\n}", "func NewMap() Map {\n\treturn &sortedMap{}\n}", "func newDesiredCESMap() *CESToCEPMapping {\n\treturn &CESToCEPMapping{\n\t\tdesiredCESs: make(map[CESName]*cesTracker),\n\t\tcepNametoCESName: make(map[CEPName]CESName),\n\t}\n}", "func (sm * SpaceMap) Init(cellsize Float, numcells int) (*SpaceMap) {\n sm.numcells = numcells\n sm.cellsize = cellsize\n sm.table = make(rawSpaceMap, sm.numcells)\n for i := 0; i < sm.numcells ; i++ {\n cell, ok := sm.table[SpaceMapKey(i)]\n if !ok {\n cell = SpaceMapCell{}\n cell.Init() \n sm.table[SpaceMapKey(i)] = cell \n }\n cell.Init()\n } \n return sm\n}", "func NewMap(r *goja.Runtime) *Map {\n\treturn &Map{runtime: r}\n}", "func (p *PersistentSyncMap) New() {\n\tp.storage = make(map[interface{}]interface{}, 100)\n}", "func Constructor() MyHashMap {\n\treturn MyHashMap{0, InitContainer, make([]*Node, InitContainer)}\n}", "func newLockMap() *lockMap {\n\treturn &lockMap{\n\t\tmutexMap: make(map[string]*sync.Mutex),\n\t}\n}", "func GenerateMap(game *Game) {\n\tgame.Locations = getEmptyMap()\n\n\tsetObjects(&game.Locations, \"CakeFactory\", CakeFactories)\n\tsetObjects(&game.Locations, \"CandyFactory\", CandyFactories)\n\tsetObjects(&game.Locations, \"Chest\", Chests)\n\tsetObjects(&game.Locations, \"CoffeePoint\", CoffeePoints)\n\tsetObjects(&game.Locations, \"Sign\", Signs)\n\tsetObjects(&game.Locations, \"Block\", Blocks)\n\tsetObjects(&game.Locations, \"Monster\", Monsters)\n\tfor column := 0; column < Width/ColumnWidth; column++ {\n\t\tcreateSweetHome(game, column)\n\t}\n}", "func NewStrMap() StrMap {\n\ts := make(map[string]interface{})\n\treturn &strMap{s: s}\n}", "func SpaceMapAllocate() (* SpaceMap) {\n return &SpaceMap{}\n}", "func Constructor() MyHashMap {\n\treturn MyHashMap{make([]*Node, 10000), 10000}\n}", "func newMapping(prof *profile.Profile, obj plugin.ObjTool, ui plugin.UI, force bool) (*mappingTable, error) {\n\tmt := &mappingTable{\n\t\tprof: prof,\n\t\tsegments: make(map[*profile.Mapping]plugin.ObjFile),\n\t}\n\n\t// Identify used mappings\n\tmappings := make(map[*profile.Mapping]bool)\n\tfor _, l := range prof.Location {\n\t\tmappings[l.Mapping] = true\n\t}\n\n\tmissingBinaries := false\n\tfor midx, m := range prof.Mapping {\n\t\tif !mappings[m] {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Do not attempt to re-symbolize a mapping that has already been symbolized.\n\t\tif !force && (m.HasFunctions || m.HasFilenames || m.HasLineNumbers) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif m.File == \"\" {\n\t\t\tif midx == 0 {\n\t\t\t\tui.PrintErr(\"Main binary filename not available.\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmissingBinaries = true\n\t\t\tcontinue\n\t\t}\n\n\t\t// Skip well-known system mappings\n\t\tif m.Unsymbolizable() {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Skip mappings pointing to a source URL\n\t\tif m.BuildID == \"\" {\n\t\t\tif u, err := url.Parse(m.File); err == nil && u.IsAbs() && strings.Contains(strings.ToLower(u.Scheme), \"http\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tname := filepath.Base(m.File)\n\t\tif m.BuildID != \"\" {\n\t\t\tname += fmt.Sprintf(\" (build ID %s)\", m.BuildID)\n\t\t}\n\t\tf, err := obj.Open(m.File, m.Start, m.Limit, m.Offset, m.KernelRelocationSymbol)\n\t\tif err != nil {\n\t\t\tui.PrintErr(\"Local symbolization failed for \", name, \": \", err)\n\t\t\tmissingBinaries = true\n\t\t\tcontinue\n\t\t}\n\t\tif fid := f.BuildID(); m.BuildID != \"\" && fid != \"\" && fid != m.BuildID {\n\t\t\tui.PrintErr(\"Local symbolization failed for \", name, \": build ID mismatch\")\n\t\t\tf.Close()\n\t\t\tcontinue\n\t\t}\n\n\t\tmt.segments[m] = f\n\t}\n\tif missingBinaries {\n\t\tui.PrintErr(\"Some binary filenames not available. Symbolization may be incomplete.\\n\" +\n\t\t\t\"Try setting PPROF_BINARY_PATH to the search path for local binaries.\")\n\t}\n\treturn mt, nil\n}", "func New() Hashmap {\n\treturn Hashmap{make([]node, defaultSize), defaultSize, 0}\n}", "func execNewMap(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := types.NewMap(args[0].(types.Type), args[1].(types.Type))\n\tp.Ret(2, ret)\n}", "func MakeMap(keys ...string) (m Map) {\n\tm = make(Map, len(keys))\n\tfor _, key := range keys {\n\t\tm.Set(key)\n\t}\n\n\treturn\n}", "func CreateMap(a ...[]string) (m map[string]struct{}) {\n\tm = make(map[string]struct{})\n\tfor _, aa := range a {\n\t\tfor _, val := range aa {\n\t\t\tm[val] = struct{}{}\n\t\t}\n\t}\n\treturn m\n}", "func (s InputSecureFileArray) FillMap(to map[int64]InputSecureFile) {\n\tfor _, value := range s {\n\t\tto[value.GetID()] = value\n\t}\n}", "func CreateMockMap() map[string]interface{} {\n\tm := make(map[string]interface{})\n\treturn m\n}", "func init() {\n\tstationsCache = make(map[string]Station)\n}", "func New(opts *Options) *Map {\n\tif opts == nil {\n\t\topts = &Options{}\n\t}\n\tstore := newStore(opts)\n\tm := &Map{\n\t\tstore: store,\n\t\tkeeper: newKeeper(store),\n\t}\n\tgo m.keeper.run()\n\treturn m\n}", "func (sm StringMap) InitEmptyWithCapacity(cap int) {\n\tif cap == 0 {\n\t\t*sm.orig = []otlpcommon.StringKeyValue(nil)\n\t\treturn\n\t}\n\t*sm.orig = make([]otlpcommon.StringKeyValue, 0, cap)\n}", "func NewFromMap(v map[string]interface{}) Object {\n\treturn v\n}", "func mapCreator2() {\n\n\tvar bootstrap2 = make(map[string]float64)\n\n\tbootstrap2[\"this is fun\"] = 123e9\n\n\tfmt.Println(bootstrap2)\n}", "func Constructor() TimeMap {\n\treturn TimeMap{\n\t\ttMap: make(map[string][]Pair),\n\t}\n}", "func Constructor() MyHashMap {\n\treturn MyHashMap{[10005][]Node{}}\n}", "func mapCreate(name, rollNo, height, weight, averageMarks, extraCurricularGrade string) map[string]string {\n\tvar mapRet = map[string]string{\n\t\t\"name\": name,\n\t\t\"roll_no\": rollNo,\n\t\t\"weight\": weight,\n\t\t\"height\": height,\n\t\t\"avg_marks\": averageMarks,\n\t\t\"extra_curr_grades\": extraCurricularGrade,\n\t}\n\treturn mapRet\n}", "func Constructor() MapSum {\n\treturn MapSum{\n\t\tm: map[string]int{},\n\t\tkeys: []string{},\n\t}\n}", "func NewMap(a Area) *Map {\n\tm := make([][]*unsafe.Pointer, a.height)\n\n\tfor y := uint8(0); y < a.height; y++ {\n\t\tm[y] = make([]*unsafe.Pointer, a.width)\n\n\t\tfor x := uint8(0); x < a.width; x++ {\n\t\t\tvar emptyFieldPointer = unsafe.Pointer(uintptr(0))\n\t\t\tm[y][x] = &emptyFieldPointer\n\t\t}\n\t}\n\n\treturn &Map{\n\t\tfields: m,\n\t\tarea: a,\n\t}\n}", "func MakeMap(kt *types.T, kvs ...T) *Map {\n\tif len(kvs)%2 != 0 {\n\t\tpanic(\"uneven makemap\")\n\t}\n\tm := new(Map)\n\tfor i := 0; i < len(kvs); i += 2 {\n\t\tm.Insert(Digest(kvs[i], kt), kvs[i], kvs[i+1])\n\t}\n\treturn m\n}", "func NewMap(Rows, Cols int) *Map {\n\tm := &Map{\n\t\tRows: Rows, \n\t\tCols: Cols,\n\t\tWater: make(map[Location]bool),\n\t\titemGrid: make([]Item, Rows * Cols),\n\t}\n\tm.Reset()\n\treturn m\n}", "func NewStringMap() StringMap {\n\torig := []otlpcommon.StringKeyValue(nil)\n\treturn StringMap{&orig}\n}", "func main() {\n\n\t// To create an empty map, use the builtin make: make(map[key-type]val-type).\t\n\n\tnew_map := make(map[string]int)\n\tnew_map[\"a\"] = 1\n\tnew_map[\"b\"] = 2\n\tnew_map[\"c\"] = 3\n\n\tfmt.Println(\"Map\", new_map)\n\n\tv1 := new_map[\"a\"]\n\tfmt.Println(\"v1 : \", v1)\n\tfmt.Println(\"len is: \", len(new_map))\n\n\t// Delete\n\n\tdelete(new_map, \"b\")\n\tfmt.Println(new_map)\n\n}", "func toMap(s *DefaultIDSetMap) map[int]*IDSet {\n\tif s.key != 0 {\n\t\treturn map[int]*IDSet{\n\t\t\ts.key: s.value,\n\t\t}\n\t}\n\n\tif s.m != nil {\n\t\tm := map[int]*IDSet{}\n\t\tfor k, v := range s.m {\n\t\t\tm[k] = v\n\t\t}\n\t\treturn m\n\t}\n\n\treturn nil\n}", "func Constructor() MapSum {\n\treturn MapSum{make(map[string]int)}\n}", "func New(_ string) (s *Store, err error) {\n\treturn &Store{xz.NewMap()}, nil\n}", "func (s EncryptedChatDiscardedArray) FillMap(to map[int]EncryptedChatDiscarded) {\n\tfor _, value := range s {\n\t\tto[value.GetID()] = value\n\t}\n}", "func (u *Unifi) StaMap() (StaMap, error) {\n\tsta, err := u.Sta()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm := make(StaMap)\n\tfor _, s := range sta {\n\t\tm[s.Mac] = s\n\t}\n\treturn m, nil\n}", "func Constructor() MapSum {\n \n}", "func createNewState(state int, at map[int]map[uint8]int) {\n at[state] = make(map[uint8]int)\n if debugMode==true {\n fmt.Printf(\"\\ncreated state %d\", state)\n }\n}", "func New() *DynMap {\n\treturn &DynMap{make(map[string]interface{})}\t\n}", "func Constructor() TimeMap {\n\treturn TimeMap{make(map[string][]int), make(map[string][]string)}\n}", "func MapPlayground() {\n\t// Create the map variable, but currently nil\n\tvar mapOne map[int]string\n\tfmt.Println(\"Created variable mapOne, before 'make'\")\n\tfmt.Printf(\"Value of mapOne: %v\\n\", mapOne)\n\tfmt.Printf(\"Value of mapOne, internal representation: %#v\\n\", mapOne)\n\tfmt.Printf(\"Getting anything from this un-inited map returns nothing: %v\\n\", mapOne[1])\n\tfmt.Printf(\"Getting anything from this un-inited map returns nothing (internal rep.): %#v\\n\", mapOne[1])\n\tres, ok := mapOne[1]\n\tfmt.Printf(\"var 'res' from getting an un-init map: %v\\n\", res)\n\tfmt.Printf(\"var 'res' from getting an un-init map (internal rep.): %#v\\n\", res)\n\tfmt.Printf(\"var 'ok' from getting an un-init map: %v\\n\", ok)\n\tfmt.Printf(\"var 'ok' from getting an un-init map (internal rep.): %#v\\n\", ok)\n\t// Using 'make' to init the map\n\tmapOne = make(map[int]string)\n\tfmt.Println(\"\\nInitialized map using make()\")\n\tfmt.Printf(\"Value of mapOne %v, internal rep. is %#v\\n\", mapOne, mapOne)\n\tres, ok = mapOne[1]\n\tfmt.Printf(\"var 'res' from getting an init but empty map: %v\\n\", res)\n\tfmt.Printf(\"var 'res' from getting an init but empty map (internal rep.): %#v\\n\", res)\n\tfmt.Printf(\"var 'ok' from getting an init but empty map: %v\\n\", ok)\n\tfmt.Printf(\"var 'ok' from getting an init but empty map (internal rep.): %#v\\n\", ok)\n\n\tfmt.Println(\"\\nFilling data\")\n\tmapOne[1] = \"hello\"\n\tres, ok = mapOne[1]\n\tfmt.Printf(\"var 'res' from getting a filled map: %v\\n\", res)\n\tfmt.Printf(\"var 'res' from getting a filled map (internal rep.): %#v\\n\", res)\n\tfmt.Printf(\"var 'ok' from getting a filled map: %v\\n\", ok)\n\tfmt.Printf(\"var 'ok' from getting a filled map (internal rep.): %#v\\n\", ok)\n}", "func Create() *MapUtil {\n\treturn &MapUtil{\n\t\tm: make(map[string]string),\n\t}\n}", "func newTestCache() *testCache {\n\tcache := new(testCache)\n\tcache.data = maps.New()\n\treturn cache\n}", "func New(cap int) (*HashMap, error) {\n\tif cap <= 0 {\n\t\treturn nil, errors.New(\"Capacity should be greater than 0\")\n\t}\n\n\treturn &HashMap{make([]*mapNode, cap), 0}, nil\n}", "func New() StringSet {\n\treturn &mapStringSet{\n\t\tstorage: make(map[string]uint64),\n\t}\n}", "func NewStrMapFrom(orig map[string]interface{}) StrMap {\n\treturn &strMap{s: orig}\n}", "func newStaticFilesMap(files ...string) staticFilesMap {\n\tm := staticFilesMap(make(map[string]struct{}, len(files)))\n\tfor _, k := range files {\n\t\tm[k] = struct{}{}\n\t}\n\treturn m\n}", "func createRandomMap(size int) Map {\n\tnewMap := mapArray\n\tfor tile := 0; tile < size*size; tile++ {\n\t\tif tile < size || tile > size*size-size {\n\t\t\tnewMap[tile] = 1 // top/bottom wall\n\t\t}\n\t\tif tile%size == 0 || tile%size == size-1 {\n\t\t\tnewMap[tile] = 1 // left/right wall\n\t\t}\n\t}\n\treturn Map{newMap, size}\n}", "func newConfigFromMap(cfgMap map[string]string) (*configstore, error) {\n\tdata, ok := cfgMap[configdatakey]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"config data not present\")\n\t}\n\treturn &configstore{data}, nil\n}", "func newSingle(slm *sunlightmap, timestamp time.Time) (sslm singleSunlightmap) {\n\n\tsslm = singleSunlightmap{}\n\n\tsslm.datetime = timestamp\n\tsslm.width = slm.Width\n\tsslm.height = slm.Height\n\t//daysinYear equals this year's February days minus 28, plus 365\n\tsslm.daysInYear = time.Date(timestamp.Year(),\n\t\ttime.February+1, 0, 0, 0, 0, 0,\n\t\ttime.UTC).Day() + 365 - 28\n\tsslm.dayOfYear = timestamp.YearDay()\n\tsslm.timeDayFraction = timeDayFraction(timestamp)\n\n\tsslm.tilt = 23.5 * math.Cos((2.0*math.Pi*(float64(sslm.dayOfYear)-173.0))/float64(sslm.daysInYear))\n\n\tsslm.pointingFromEarthToSun = vec3{\n\t\tmath.Sin((2.0 * math.Pi) * sslm.timeDayFraction),\n\t\tmath.Tan(math.Pi * 2.0 * (sslm.tilt / 360.0)),\n\t\tmath.Cos((2.0 * math.Pi) * sslm.timeDayFraction),\n\t}\n\tsslm.pointingFromEarthToSun.normalize(1)\n\n\treturn\n}", "func (s InputSecureFileUploadedArray) FillMap(to map[int64]InputSecureFileUploaded) {\n\tfor _, value := range s {\n\t\tto[value.GetID()] = value\n\t}\n}", "func NewMap(less func(a, b interface{}) bool) *Map {\n\treturn &Map{\n\t\tless: less,\n\t}\n}", "func NewScanMap() *ScanMap {\n\treturn &ScanMap{\n\t\thashMap: map[Hash][]File{},\n\t}\n}", "func NewTimeMap() TimeMap {\n\ttm := make(timemap, bucketConst)\n\tfor i := 0; i < bucketConst; i++ {\n\t\ttm[i] = &bucket{\n\t\t\tobjects: make(map[uintptr]*storeValue),\n\t\t}\n\t}\n\n\tgo tm.goroutine()\n\treturn tm\n}", "func newConfigMap(configMapName, namespace string, labels map[string]string,\n\tkibanaIndexMode, esUnicastHost, rootLogger, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount string) *v1.ConfigMap {\n\n\terr, data := renderData(kibanaIndexMode, esUnicastHost, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount, rootLogger)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &v1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: v1.SchemeGroupVersion.String(),\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configMapName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: data,\n\t}\n}", "func _dirtySeriesMapAlloc(opts _dirtySeriesMapOptions) *dirtySeriesMap {\n\tm := &dirtySeriesMap{_dirtySeriesMapOptions: opts}\n\tm.Reallocate()\n\treturn m\n}", "func (s EncryptedChatRequestedArray) FillMap(to map[int]EncryptedChatRequested) {\n\tfor _, value := range s {\n\t\tto[value.GetID()] = value\n\t}\n}", "func Constructor() RandomizedSet {\n\tp := make(map[int]struct{})\n\treturn RandomizedSet{p}\n}", "func New() *ConcurrentMap {\n\treturn AdvanceNew(fnv.New32, SHARD_COUNT)\n}", "func New() *SafeMap {\n\treturn &SafeMap{\n\t\trw: &sync.RWMutex{},\n\t\tc: make(map[interface{}]interface{}),\n\t}\n}", "func InitMapStorage() *MapURLStorage {\n\treturn &MapURLStorage{\n\t\tStorage: make(map[string]string),\n\t}\n}", "func NewStringMap() StringMap {\n\torig := []*otlpcommon.StringKeyValue(nil)\n\treturn StringMap{&orig}\n}", "func Constructor() MapSum {\n\tobj := MapSum{}\n\tobj.Nodes = map[byte]*MapSum{}\n\treturn obj\n}", "func makemap(t unsafe.Pointer, cap int) unsafe.Pointer", "func PopulateTools() (tls map[string] tool.Tool){\n\n tls = make(map[string]tool.Tool,1)\n\n t := &tool.RemoveDuplicates{}\n tls[t.Name()] = t\n\n // Add another\n //t = tools.<Name of tool>{}\n //tls.put[t.Name()] = t\n return tls\n}", "func (s EncryptedChatEmptyArray) FillMap(to map[int]EncryptedChatEmpty) {\n\tfor _, value := range s {\n\t\tto[value.GetID()] = value\n\t}\n}", "func (suite *MapValueTestSuite) TestNewMapValue() {\n\tsuite.doMapValueTest(false)\n}", "func (t *Map) Init() *Map {\n\tt.entries = make(map[interface{}]Value)\n\tif t.keys == nil {\n\t\tt.keys = list.New()\n\t} else {\n\t\tt.keys.Init()\n\t}\n\treturn t\n}", "func Constructor() MapSum {\n\treturn MapSum{\n\t\troot: &TrieNode{},\n\t}\n}", "func ResetMaps() {\n\tresetMaps()\n}", "func (cmap *Map) InitMap(list *MapItem) {\n\tcmap.items = make(map[string]*MapItem)\n\tif nil != list {\n\t\tcmap.list = list\n\t} else {\n\t\tcmap._list.Empty()\n\t\tcmap.list = &cmap._list\n\t}\n}", "func New(c *character.Character) *Maps {\n\n\tlog.Info(\"Generating new maps\")\n\n\tm := new(Maps)\n\tm.monsters = make([][]*monster.Monster, MaxVolcano)\n\tfor i := uint(0); i < MaxVolcano; i++ {\n\n\t\tnm := newMap(i) // create the new map with items\n\n\t\tswitch i {\n\t\tcase homeLevel:\n\t\t\tm.entrance = append(m.entrance, walkToEmpty(randMapCoord(), nm)) // TODO change this to be next to the dungeon entrance\n\t\tcase 1: // dungeon 0 has an entrance\n\t\t\tnm[height-1][width/2] = (Empty{})\n\t\t\tm.entrance = append(m.entrance, types.Coordinate{X: width / 2, Y: height - 2})\n\t\t\tm.monsters[i] = spawnMonsters(nm, i, true) // spawn monsters onto the map\n\t\tdefault:\n\t\t\t// Set the entrace for the maze to a random location\n\t\t\tm.entrance = append(m.entrance, walkToEmpty(randMapCoord(), nm))\n\t\t\tm.monsters[i] = spawnMonsters(nm, i, true) // spawn monsters onto the map\n\t\t}\n\n\t\tm.mazes = append(m.mazes, nm)\n\t}\n\tm.active = m.mazes[homeLevel]\n\tm.SpawnCharacter(m.entrance[homeLevel], c)\n\treturn m\n}", "func Constructor() MapSum {\n\treturn MapSum{}\n}", "func NewStorage() SafeMap {\n\tsm := make(safeMap)\n\tgo sm.run()\n\treturn sm\n}", "func New(gcPercent uint64) *CacheMap {\n\tc := &CacheMap{\n\t\titems: make(map[string]item),\n\t\tgcPercent: gcPercent,\n\t\tnbytes: 0,\n\t}\n\tgo c.GC()\n\treturn c\n}", "func smapFromNode(primarySmap *meta.Smap, sid string, usejs bool) error {\n\tvar (\n\t\tsmap = primarySmap\n\t\terr error\n\t\textendedURLs bool\n\t)\n\tif sid != \"\" {\n\t\tsmap, err = api.GetNodeClusterMap(apiBP, sid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, m := range []meta.NodeMap{smap.Tmap, smap.Pmap} {\n\t\tfor _, v := range m {\n\t\t\tif v.PubNet != v.ControlNet || v.PubNet != v.DataNet {\n\t\t\t\textendedURLs = true\n\t\t\t}\n\t\t}\n\t}\n\tbody := teb.SmapHelper{\n\t\tSmap: smap,\n\t\tExtendedURLs: extendedURLs,\n\t}\n\treturn teb.Print(body, teb.SmapTmpl, teb.Jopts(usejs))\n}", "func Test_interface001(t *testing.T) {\n\ts1 := make([]int, 10, 20)\n\ttest1(&s1)\n\tfmt.Println(s1)\n\n\tfmt.Println(len(s1))\n\n\ts2 := make(map[string]int)\n\ttest2(s2)\n\tfmt.Println(s2)\n\tfmt.Println(s2[\"aaaaa\"])\n\n\ts3 := make(map[string]sample1)\n\ttest2(s3)\n\tfmt.Println(s3)\n\n\ttype1 := reflect.MapOf(reflect.TypeOf(\"\"), reflect.TypeOf(1))\n\tfmt.Println(type1)\n\tfmt.Println(type1.Elem().Kind())\n\ts4 := reflect.MakeMap(type1)\n\tfmt.Println(s4.Kind())\n\tfmt.Println(s4.Type().Key().Kind())\n\tfmt.Println(s4.Type().Elem().Kind())\n\n\ts4.SetMapIndex(reflect.ValueOf(\"ccccc\"), reflect.ValueOf(3333))\n\n\tfmt.Println(s4)\n\n}", "func newMapReact() *mapReact {\n\tma := mapReact{ma: make(map[SenderDetachCloser]bool)}\n\treturn &ma\n}", "func (sds *SiaDirSet) newSiaDirSetEntry(sd *SiaDir) *siaDirSetEntry {\n\tthreads := make(map[uint64]threadInfo)\n\treturn &siaDirSetEntry{\n\t\tSiaDir: sd,\n\t\tsiaDirSet: sds,\n\t\tthreadMap: threads,\n\t}\n}", "func (c *Configmap) AsMapSI() map[string]interface{} {\n\treturn *c\n}" ]
[ "0.65439737", "0.6282135", "0.61550367", "0.60164434", "0.59804827", "0.59710264", "0.59459996", "0.5919371", "0.5913024", "0.5909943", "0.5902754", "0.5862311", "0.58337903", "0.57940173", "0.5659288", "0.5649941", "0.5599958", "0.55991834", "0.5569663", "0.5558988", "0.5546349", "0.5468053", "0.54631746", "0.5450785", "0.5409648", "0.5403175", "0.53933847", "0.539103", "0.5388081", "0.53849435", "0.5379576", "0.53784084", "0.53779763", "0.5370361", "0.53650326", "0.5357659", "0.5347748", "0.53475684", "0.53470796", "0.5345431", "0.5327519", "0.53266007", "0.5317041", "0.53141886", "0.5311025", "0.53029615", "0.5291183", "0.52861226", "0.5283056", "0.5282653", "0.52755827", "0.5268317", "0.52677315", "0.5266314", "0.52630913", "0.5263028", "0.5261189", "0.52605826", "0.5259429", "0.5256671", "0.5251997", "0.52502406", "0.5246465", "0.52419066", "0.52334684", "0.5231436", "0.5218524", "0.52114284", "0.5204226", "0.51975197", "0.5196822", "0.5189784", "0.51879627", "0.51833606", "0.5183132", "0.5174878", "0.51738715", "0.5173263", "0.51640654", "0.5162126", "0.5156554", "0.51556456", "0.5153687", "0.51530755", "0.5143522", "0.5141026", "0.5140452", "0.5135733", "0.5133148", "0.51252896", "0.51216805", "0.5120221", "0.51177716", "0.5105466", "0.5088923", "0.5072763", "0.50701857", "0.5069212", "0.50568324", "0.5055543" ]
0.83328515
0
get looks up sa from m and returns its gsa if sa exists.
func (m *saMap) get(sa ServiceAccount) (GSAEmail, bool) { m.RLock() defer m.RUnlock() gsa, ok := m.ma[sa] return gsa, ok }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o KubernetesClusterWindowsProfileOutput) Gmsa() KubernetesClusterWindowsProfileGmsaPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterWindowsProfile) *KubernetesClusterWindowsProfileGmsa { return v.Gmsa }).(KubernetesClusterWindowsProfileGmsaPtrOutput)\n}", "func (o KubernetesClusterWindowsProfilePtrOutput) Gmsa() KubernetesClusterWindowsProfileGmsaPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterWindowsProfile) *KubernetesClusterWindowsProfileGmsa {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Gmsa\n\t}).(KubernetesClusterWindowsProfileGmsaPtrOutput)\n}", "func (c *gateways) get(mac lorawan.EUI64) (gateway, error) {\n\tc.RLock()\n\tdefer c.RUnlock()\n\n\tgw, ok := c.gateways[mac]\n\tif !ok {\n\t\treturn gw, errGatewayDoesNotExist\n\t}\n\n\treturn gw, nil\n}", "func (m *mgr) get(ref *collaboration.ShareReference) (idx int, s *collaboration.Share, err error) {\n\tswitch {\n\tcase ref.GetId() != nil:\n\t\tidx, s, err = m.getByID(ref.GetId())\n\tcase ref.GetKey() != nil:\n\t\tidx, s, err = m.getByKey(ref.GetKey())\n\tdefault:\n\t\terr = errtypes.NotFound(ref.String())\n\t}\n\treturn\n}", "func (m *Message) MSA() (*MSA, error) {\n\tps, err := m.Parse(\"MSA\")\n\tpst, ok := ps.(*MSA)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func (m *Application) GetSpa()(SpaApplicationable) {\n return m.spa\n}", "func (store *GSStore) Get(key string, form GSType) (interface{}, error) {\n\n}", "func (t *Token) get(sender [32]byte) *Balance {\n\tfor _, b := range t.Balances {\n\t\tif b.Sender == sender {\n\t\t\treturn &b\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *ReportRoot) GetSla()(ServiceLevelAgreementRootable) {\n val, err := m.GetBackingStore().Get(\"sla\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(ServiceLevelAgreementRootable)\n }\n return nil\n}", "func (c *MockApplicationSecurityGroupsClient) Get(ctx context.Context, resourceGroupName string, asgName string) (*network.ApplicationSecurityGroup, error) {\n\tasg, ok := c.ASGs[asgName]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\treturn &asg, nil\n}", "func (m *store) Get(s string) (ukjent.Word, error) {\n\treturn m.get(s)\n}", "func getOrCreateSA(clientset kubernetes.Interface, duration metav1.Duration) ([]byte, []byte, error) {\n\tclient := clientset.CoreV1().ServiceAccounts(corev1.NamespaceDefault)\n\n\t// Check SelfSubjectAccessReviews are allowed.\n\tif err := checkSAAuth(clientset); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Create ServiceAccount if not exists.\n\tif _, err := client.Get(context.TODO(), serviceAccountName, metav1.GetOptions{}); err != nil {\n\t\t// Generate a Kubernetes ServiceAccount object.\n\t\tsaObj := &corev1.ServiceAccount{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: serviceAccountName,\n\t\t\t},\n\t\t}\n\n\t\t// Create ServiceAccount.\n\t\t_, err := client.Create(context.TODO(), saObj, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"create SA: %w\", err)\n\t\t}\n\t}\n\n\t// Get/Create ClusterRoleBinding.\n\terr := getOrCreateCRB(clientset)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"get or create CRB: %w\", err)\n\t}\n\n\t// Get ServiceAccount.\n\tsaObj, err := client.Get(context.TODO(), serviceAccountName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"get SA: %w\", err)\n\t}\n\n\treturn getSASecrets(clientset, saObj, duration)\n}", "func (e *EncryptedChatRequested) GetGA() (value []byte) {\n\treturn e.GA\n}", "func (r *MessagesRequestEncryptionRequest) GetGA() (value []byte) {\n\tif r == nil {\n\t\treturn\n\t}\n\treturn r.GA\n}", "func (nm nodeMap) get(gn GraphNode) *aStarNode {\n\tnode, ok := nm[gn]\n\tif !ok {\n\t\tnode = &aStarNode{\n\t\t\tgraphNode: gn,\n\t\t}\n\t\tnm[gn] = node\n\t}\n\treturn node\n}", "func newSAMap() *saMap {\n\tt := make(map[ServiceAccount]GSAEmail)\n\treturn &saMap{\n\t\tma: t,\n\t}\n}", "func (sc *streamsCoordinator) getStream(name string) (string, *streamGroup, error) {\n\tsc.mu.Lock()\n\tdefer sc.mu.Unlock()\n\n\tgroup, ok := sc.groups[name]\n\tif !ok {\n\t\treturn \"\", nil, errors.Errorf(\"no group for '%s'\", name)\n\t}\n\n\tif len(group.availableStreams) == 0 {\n\t\treturn \"\", nil, errors.New(\"must register first\")\n\t}\n\tid := group.availableStreams[0]\n\tgroup.availableStreams = group.availableStreams[1:]\n\n\treturn id, group, nil\n}", "func MSA2GFA(msa *multi.Multi) (*GFA, error) {\n\t// create an empty GFA instance and then add version (1)\n\tmyGFA := NewGFA()\n\terr := myGFA.AddVersion(1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// clean the MSA to remove consensus seq\n\tmsaCleaner(msa)\n\t// create nodes for each unique base in every column of the alignment\n\tmsaNodes, _ := getNodes(msa)\n\t// draw edges between nodes\n\tif err := msaNodes.drawEdges(); err != nil {\n\t\treturn nil, err\n\t}\n\t// squash neighbouring nodes and update edges\n\tif err := msaNodes.squashNodes(); err != nil {\n\t\treturn nil, err\n\t}\n\t// populate the GFA instance\n\torderedList := msaNodes.getOrderedList()\n\tfor _, nodeID := range orderedList {\n\t\tnode := msaNodes.nodeHolder[nodeID]\n\t\t// create the segment(s)\n\t\tseg, err := NewSegment([]byte(strconv.Itoa(nodeID)), []byte(node.base))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tseg.Add(myGFA)\n\t\t// create link(s)\n\t\tfor outEdge := range node.outEdges {\n\t\t\tlink, err := NewLink([]byte(strconv.Itoa(nodeID)), []byte(\"+\"), []byte(strconv.Itoa(outEdge)), []byte(\"+\"), []byte(\"0M\"))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tlink.Add(myGFA)\n\t\t}\n\t}\n\t// get paths for each MSA entry\n\ttype pathHolder struct {\n\t\tseqID []byte\n\t\tsegments [][]byte\n\t\toverlaps [][]byte\n\t}\n\tfor _, seqID := range msaNodes.seqIDs {\n\t\ttmpPath := &pathHolder{seqID: []byte(seqID)}\n\t\tfor _, nodeID := range orderedList {\n\t\t\tnode := msaNodes.nodeHolder[nodeID]\n\t\t\tfor _, seq := range node.parentSeqIDs {\n\t\t\t\tif seq == seqID {\n\t\t\t\t\tsegment := strconv.Itoa(nodeID) + \"+\"\n\t\t\t\t\toverlap := strconv.Itoa(len(node.base)) + \"M\"\n\t\t\t\t\ttmpPath.segments = append(tmpPath.segments, []byte(segment))\n\t\t\t\t\ttmpPath.overlaps = append(tmpPath.overlaps, []byte(overlap))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// add the path\n\t\tpath, err := NewPath(tmpPath.seqID, tmpPath.segments, tmpPath.overlaps)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpath.Add(myGFA)\n\t}\n\treturn myGFA, nil\n}", "func (c *cache) get(roleID string) *settingsmsg.Bundle {\n\tif ce := c.sc.Load(roleID); ce != nil {\n\t\treturn ce.V.(*settingsmsg.Bundle)\n\t}\n\n\treturn nil\n}", "func (pa permAttr) get(attr string) string {\n\tif pa.attrs != nil {\n\t\tv := pa.attrs[attr]\n\t\tif len(v) != 0 {\n\t\t\treturn v[0]\n\t\t}\n\t\treturn \"\"\n\t}\n\n\tif pa.claims != nil {\n\t\treturn claimsIntfAttrValue(pa.claims, attr, pa.at, pa.signerFilter)\n\t}\n\n\treturn \"\"\n}", "func (m *MatchResult) Get(s string) (string, error) {\n\tif !m.matched {\n\t\treturn \"\", nil\n\t}\n\n\tgroupNums, err := m.getNamedGroupNums(s)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, groupNum := range groupNums {\n\t\tw := C.onigmo_helper_get(C.CString(m.input), m.region.beg, m.region.end, groupNum)\n\t\tword := C.GoString(w)\n\t\tif word != \"\" {\n\t\t\treturn word, nil\n\t\t}\n\t}\n\n\treturn \"\", nil\n}", "func (c *cache) get(roleID string) *settings.Bundle {\n\tif ce := c.sc.Load(roleID); ce != nil {\n\t\treturn ce.V.(*settings.Bundle)\n\t}\n\n\treturn nil\n}", "func (ss *SharedStrings) get(index int) *ml.StringItem {\n\tss.file.LoadIfRequired(ss.afterLoad)\n\n\tif index < len(ss.ml.StringItem) {\n\t\treturn ss.ml.StringItem[index]\n\t}\n\n\treturn nil\n}", "func (s *Shader) getUniformLocation(name string) (location int32) {\n\t// if we already saved the location, return it\n\tif location, ok := s.uniformLocs[name]; ok {\n\t\treturn location\n\t}\n\n\t// if it's not in our location cache, get it from opengl and save it in the cache\n\tlocation = gl.GetUniformLocation(s.Program, gl.Str(name+\"\\x00\"))\n\tif location == -1 {\n\t\tfmt.Println(\"ERROR: Could not find uniform:\", name)\n\t\treturn\n\t}\n\n\ts.uniformLocs[name] = location\n\treturn\n}", "func (s *PublicSfcAPI) GetStaker(ctx context.Context, stakerID hexutil.Uint, verbosity hexutil.Uint64) (map[string]interface{}, error) {\n\tstaker, err := s.b.GetStaker(ctx, idx.StakerID(stakerID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif staker == nil {\n\t\treturn nil, nil\n\t}\n\tit := sfctype.SfcStakerAndID{\n\t\tStakerID: idx.StakerID(stakerID),\n\t\tStaker: staker,\n\t}\n\tstakerRPC := RPCMarshalStaker(it)\n\tif verbosity <= 1 {\n\t\treturn stakerRPC, nil\n\t}\n\treturn s.addStakerMetricFields(ctx, stakerRPC, idx.StakerID(stakerID))\n}", "func (q *SimpleQueue) getStorage(name string) storage.Storage {\n\tif q.MetaStorage == nil {\n\t\treturn nil\n\t}\n\n\tif st, ok := q.MarkerBlockDataStorage[name]; ok {\n\t\treturn st\n\t}\n\treturn q.MetaStorage\n}", "func (client *XenClient) SMGetByUuid(uuid string) (result string, err error) {\n\tobj, err := client.APICall(\"SM.get_by_uuid\", uuid)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = obj.(string)\n\treturn\n}", "func (r *Registry) get(name string) (v []byte, err error) {\n\tpair, err := r.store.Get(r.getModelName(name))\n\tif err != nil {\n\t\treturn\n\t}\n\treturn pair.Value, nil\n}", "func (st *Store) get(key []byte, dbname string) []byte {\n\tif st == nil {\n\t\treturn nil\n\t}\n\tstore := st.store\n\tif store == nil {\n\t\treturn nil\n\t}\n\tif dbname != \"\" {\n\t\t//check db availability\n\t\tdbdata, ok := st.dbs[dbname]\n\t\tif !ok {\n\t\t\tlog.Fatal(fmt.Sprintf(\"db with name %s is not found\", dbname))\n\t\t} else if !dbdata.isactive {\n\t\t\tlog.Fatal(fmt.Sprintf(\"db with name %s is not active\", dbname))\n\t\t}\n\t}\n\n\tst.lock.RLock()\n\tdefer func() {\n\t\tst.lock.RUnlock()\n\t\tst.stat.NumReads++\n\t}()\n\tresult, err := store.Get(key)\n\tif err != nil {\n\t\tst.stat.NumFailedReads++\n\t\treturn nil\n\t}\n\n\tif st.compression {\n\t\tresult = decompress(result.([]byte))\n\t}\n\n\treturn result.([]byte)\n\n}", "func (m *EmbeddedSIMActivationCode) GetSmdpPlusServerAddress()(*string) {\n val, err := m.GetBackingStore().Get(\"smdpPlusServerAddress\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (a *Client) SMSCampaignBySMSCampaignIDGet(params *SMSCampaignBySMSCampaignIDGetParams, authInfo runtime.ClientAuthInfoWriter) (*SMSCampaignBySMSCampaignIDGetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewSMSCampaignBySMSCampaignIDGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"SmsCampaignBySmsCampaignIdGet\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/sms-campaigns/{sms_campaign_id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &SMSCampaignBySMSCampaignIDGetReader{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.(*SMSCampaignBySMSCampaignIDGetOK), nil\n\n}", "func (t *Task) getVSL() (*velero.VolumeSnapshotLocation, error) {\n\tclient, err := t.getSourceClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tplan := t.PlanResources.MigPlan\n\tlocation, err := plan.GetVSL(client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif location == nil {\n\t\treturn nil, errors.New(\"VSL not found\")\n\t}\n\n\treturn location, nil\n}", "func (t *Task) getBSL() (*velero.BackupStorageLocation, error) {\n\tclient, err := t.getSourceClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tplan := t.PlanResources.MigPlan\n\tlocation, err := plan.GetBSL(client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif location == nil {\n\t\treturn nil, errors.New(\"BSL not found\")\n\t}\n\n\treturn location, nil\n}", "func (gs *LocalConf) Get(name string) (g Group) {\n\tif gs == nil {\n\t\treturn\n\t}\n\n\tfor _, g := range gs.Groups {\n\t\tif name == g.Name {\n\t\t\treturn g\n\t\t}\n\t}\n\n\treturn\n}", "func (m *SecureScoreControlProfile) GetService()(*string) {\n return m.service\n}", "func (c *memoryExactMatcher) get(key string) (*event.SloClassification, error) {\n\ttimer := prometheus.NewTimer(matcherOperationDurationSeconds.WithLabelValues(\"get\", exactMatcherType))\n\tdefer timer.ObserveDuration()\n\tc.mtx.RLock()\n\tdefer c.mtx.RUnlock()\n\n\tvalue := c.exactMatches[key]\n\treturn value, nil\n}", "func GetStrmer(name string) (Strmer, bool) {\n\n\tstrmer, ok := globalStrmers[name] \n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\treturn strmer, true\n}", "func (tg *TradesGroup) get(chanID int64) (e event, err error) {\n\tvar ok bool\n\ttg.RLock()\n\tdefer tg.RUnlock()\n\tif e, ok = tg.subs[chanID]; ok {\n\t\treturn\n\t}\n\treturn e, errors.New(\"[BITFINEX] subscription not found\")\n}", "func (subChMap *subChannelMap) get(serviceName string) (*SubChannel, bool) {\n\tsubChMap.RLock()\n\tsc, ok := subChMap.subchannels[serviceName]\n\tsubChMap.RUnlock()\n\treturn sc, ok\n}", "func (m *Mutex) Get() (*apiv1.BackendItem, error) {\n\treturn m.s.Get(m.ctx, m.key)\n}", "func (h *DirectImageStreamMigrationHandler) getSAR() auth.SelfSubjectAccessReview {\n\treturn auth.SelfSubjectAccessReview{\n\t\tSpec: auth.SelfSubjectAccessReviewSpec{\n\t\t\tResourceAttributes: &auth.ResourceAttributes{\n\t\t\t\tGroup: \"apps\",\n\t\t\t\tResource: \"DirectImageStreamMigration\",\n\t\t\t\tNamespace: h.directImageStream.Namespace,\n\t\t\t\tName: h.directImageStream.Name,\n\t\t\t\tVerb: \"get\",\n\t\t\t},\n\t\t},\n\t}\n}", "func (ps *PgStore) GetGateway(ctx context.Context, mac lorawan.EUI64, forUpdate bool) (Gateway, error) {\n\tvar fu string\n\tif forUpdate {\n\t\tfu = \" for update\"\n\t}\n\n\tvar gw Gateway\n\terr := sqlx.GetContext(ctx, ps.db, &gw, \"select * from gateway where mac = $1\"+fu, mac[:])\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn gw, errHandler.ErrDoesNotExist\n\t\t}\n\t\treturn gw, err\n\t}\n\treturn gw, nil\n}", "func (m *StringMap) Get() interface{} {\n\treturn *m\n}", "func (self *BTrie) SGet(key string) (value interface{}) {\n\treturn self.Get([]byte(key))\n}", "func (mp *Provider) Get(sessionID []byte) (session.Storer, error) {\n\tcurrentStore := mp.memoryDB.GetBytes(sessionID)\n\tif currentStore != nil {\n\t\treturn currentStore.(*Store), nil\n\t}\n\n\tnewStore := mp.acquireStore(sessionID, mp.expiration)\n\tmp.memoryDB.SetBytes(sessionID, newStore)\n\n\treturn newStore, nil\n}", "func (self *SafeMap) Get(k interface{}) interface{} {\n\tself.lock.RLock()\n\tdefer self.lock.RUnlock()\n\n\tif val, ok := self.sm[k]; ok {\n\t\treturn val\n\t}\n\n\treturn nil\n}", "func (m *AzureManager) GetAsgForInstance(instance *azureRef) (cloudprovider.NodeGroup, error) {\n\treturn m.asgCache.FindForInstance(instance, m.config.VMType)\n}", "func (m *systrayMap) Get(id refId) (*systrayRef, bool) {\n\tm.lock.RLock()\n\tref, ok := m.m[id]\n\tm.lock.RUnlock()\n\treturn ref, ok\n}", "func (client ProviderShareSubscriptionsClient) GetByShareSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (a *abaImpl) AsGPA() gpa.GPA {\n\treturn a.asGPA\n}", "func (p PostgresStapleStorer) Get(email string, stapleID int) (*models.Staple, error) {\n\tconn, err := p.connect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), timeoutForTransactions)\n\tdefer cancel()\n\n\tdefer conn.Close(ctx)\n\ttx, err := conn.Begin(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer tx.Rollback(ctx)\n\tvar (\n\t\tid int\n\t\tname, content string\n\t\tarchived bool\n\t\tcreatedAt time.Time\n\t)\n\tif err := tx.QueryRow(ctx, \"select name, id, content, archived, created_at from staples where user_email = $1 and id = $2\", email, stapleID).Scan(\n\t\t&name,\n\t\t&id,\n\t\t&content,\n\t\t&archived,\n\t\t&createdAt); err != nil {\n\t\treturn nil, err\n\t}\n\tif err != nil {\n\t\tif err.Error() == \"no rows in result set\" {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tif err := tx.Commit(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &models.Staple{\n\t\tName: name,\n\t\tID: id,\n\t\tContent: content,\n\t\tArchived: archived,\n\t\tCreatedAt: createdAt,\n\t}, nil\n}", "func getInterfaceSm(ctx context.Context, client pb.GNMIClient, iface string) *interfaceSm {\n\tsm, ok := interfaces[iface]\n\tif !ok {\n\t\tsm = &interfaceSm{\n\t\t\tname: iface,\n\t\t\tctx: ctx,\n\t\t\tclient: client,\n\t\t}\n\t\tinterfaces[iface] = sm\n\t}\n\n\treturn sm\n}", "func (m *mgr) getByID(id *collaboration.ShareId) (int, *collaboration.Share, error) {\n\tfor i, s := range m.model.Shares {\n\t\tif s.GetId().OpaqueId == id.OpaqueId {\n\t\t\treturn i, s, nil\n\t\t}\n\t}\n\treturn -1, nil, errtypes.NotFound(id.String())\n}", "func (r *Registry) Get(name string) interface{} {\n\treturn r.registrants[name]\n}", "func (p *Participant) getMaster() (Member, bool) {\n\tm, ok := p.master[p.instance]\n\treturn m, ok\n}", "func (a *Client) SMSCampaignsGet(params *SMSCampaignsGetParams, authInfo runtime.ClientAuthInfoWriter) (*SMSCampaignsGetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewSMSCampaignsGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"SmsCampaignsGet\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/sms-campaigns\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &SMSCampaignsGetReader{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.(*SMSCampaignsGetOK), nil\n\n}", "func (s *sqlStore) getAccess(key string) (Access, error) {\n\taci, err := s.getACI(key)\n\tif err != nil {\n\t\tlog.Debugf(\"failed to get aci for key %s: %s\", key, err)\n\t\treturn DefaultAccess, err\n\t}\n\n\tuid := aci.Uid()\n\tgid := aci.Gid()\n\n\tif uid == -1 {\n\t\tuname, _ := aci.Uname()\n\t\tuid = int64(s.lookUpUser(uname))\n\t}\n\n\tif gid == -1 {\n\t\tgname, _ := aci.Gname()\n\t\tgid = int64(s.lookUpGroup(gname))\n\t}\n\n\tmode := uint32(aci.Mode())\n\treturn Access{\n\t\tMode: uint32(os.ModePerm) & mode,\n\t\tUID: uint32(uid),\n\t\tGID: uint32(gid),\n\t}, nil\n}", "func Get(keyS string) string {\n\n\tdb := Connect()\n\n\t//defer db.Close()\n\n\tkey := []byte(keyS)\n\n\tvar valbyte []byte\n\n\terr = db.View(func(tx *bolt.Tx) error {\n\n\t\tbucket := tx.Bucket(Database)\n\n\t\tif bucket == nil {\n\t\t\treturn fmt.Errorf(\"Bucket %q not found!\", Database)\n\t\t}\n\n\t\tvalbyte = bucket.Get(key)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\n\t\tlog.Fatal(\"Error open db, \", err)\n\t}\n\n\treturn string(valbyte)\n}", "func (k Keeper) getGasMeter(ctx sdk.Context) wasmGasMeter {\r\n\treturn wasmGasMeter{\r\n\t\toriginalMeter: ctx.GasMeter(),\r\n\t\tgasMultiplier: types.GasMultiplier,\r\n\t}\r\n}", "func (ma *markAllocator) get() (uint32, error) {\n\tma.lock.Lock()\n\tdefer ma.lock.Unlock()\n\tif len(ma.marks) == 0 {\n\t\treturn 0, errors.New(\"allocator exhausted\")\n\t}\n\tmark := ma.marks[0]\n\tma.marks = ma.marks[1:]\n\treturn mark, nil\n}", "func (k keys) get(region string) *encryptionKey {\n\tfor i := range k {\n\t\tif k[i].Region == region {\n\t\t\treturn &k[i]\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m RegistryMap) Get(name string) (component.Registration, bool) {\n\treg, ok := m[name]\n\treturn reg, ok\n}", "func (m *SecureScoreControlProfile) GetService()(*string) {\n val, err := m.GetBackingStore().Get(\"service\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (c *Compiler) getGlobal(g *ssa.Global) llvm.Value {\n\tinfo := c.getGlobalInfo(g)\n\tllvmGlobal := c.mod.NamedGlobal(info.linkName)\n\tif llvmGlobal.IsNil() {\n\t\tllvmType := c.getLLVMType(g.Type().(*types.Pointer).Elem())\n\t\tllvmGlobal = llvm.AddGlobal(c.mod, llvmType, info.linkName)\n\t\tif !info.extern {\n\t\t\tllvmGlobal.SetInitializer(llvm.ConstNull(llvmType))\n\t\t\tllvmGlobal.SetLinkage(llvm.InternalLinkage)\n\t\t}\n\t}\n\treturn llvmGlobal\n}", "func (m *OMap) Get(s string) interface{} {\n\tif n, ok := m.baseMap[s]; ok {\n\t\treturn n\n\t}\n\treturn nil\n}", "func (o *TransactionSplit) GetSepaDb() string {\n\tif o == nil || o.SepaDb.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SepaDb.Get()\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 (c *cache) get(name string) *cacheItem {\n\tc.itemMu.Lock()\n\titem := c._get(name)\n\tc.itemMu.Unlock()\n\treturn item\n}", "func (m *Member) Get(account string) (bool, error) {\r\n\treturn isFound(DBConn.Where(\"ecosystem=? and account = ?\", m.ecosystem, account).First(m))\r\n}", "func (a Ave) Grasna() string {\n\treturn \"Quack\"\n\n}", "func (gm *GasMgrV1) GetGas() common.Gas {\n\treturn gm.gas\n}", "func (u *User) GetScam() (value bool) {\n\tif u == nil {\n\t\treturn\n\t}\n\treturn u.Flags.Has(24)\n}", "func (self Source) GetGain() (gain float32) {\n\treturn self.Getf(AlGain)\n}", "func getStore() (storage.Store, error) {\n\topts, err := storage.DefaultStoreOptions(unshare.IsRootless(), unshare.GetRootlessUID())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstore, err := storage.GetStore(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif store == nil {\n\t\treturn nil, fmt.Errorf(\"unable to instantiate storage\")\n\t}\n\tis.Transport.SetStore(store)\n\treturn store, nil\n}", "func (repo GymRepository) GetGymByName(name string) models.GymProfile {\n\tvar gyms models.GymProfile\n\trepo.db.First(&gyms, \"name = ?\", name)\n\n\treturn gyms\n}", "func (c *MockNetworkSecurityGroupsClient) Get(ctx context.Context, resourceGroupName string, nsgName string) (*network.SecurityGroup, error) {\n\tasg, ok := c.NSGs[nsgName]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\treturn &asg, nil\n}", "func Get(name string) Generator {\n\treturn Generators[name]\n}", "func (sks *SQLSKUStore) Get(id string) (*model.SKU, error) {\n\ts, err := sks.SQLStore.Tx.Get(model.SKU{}, id)\n\treturn s.(*model.SKU), err\n}", "func (m MafsaMapper) Get(key string) (value string, ok bool) {\n\t_, pos := m.mt.IndexedTraverse([]rune(key))\n\tif pos < 0 {\n\t\treturn // returns zero values for value (\"\") and ok (false)\n\t}\n\tok = true\n\tvalue = m.vals[pos-1]\n\treturn\n}", "func getString(m map[string]string, key string, alts ...string) (string, bool) {\n\tif m == nil {\n\t\treturn \"\", false\n\t}\n\tkeys := append([]string{key}, alts...)\n\tfor _, k := range keys {\n\t\tif v, ok := m[k]; ok {\n\t\t\treturn v, true\n\t\t}\n\t}\n\treturn \"\", false\n}", "func (m *Manager) GetSound(name string) (s *Sound, err error) {\n\ts, ok := m.sounds[name]\n\tif !ok {\n\t\ts, err = newSound(name + \".wav\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tm.sounds[name] = s\n\t}\n\treturn s, nil\n}", "func (Phosphorus) GetGroup() string {\n\tvar g groupType = a5\n\treturn g.get()\n}", "func (s *Scms) GetSCM(accessToken string) (sc scm.SCM, ok bool) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tsc, ok = s.scms[accessToken]\n\treturn\n}", "func (m *Group) GetOnPremisesSamAccountName()(*string) {\n return m.onPremisesSamAccountName\n}", "func (m *TokenManager) Get(key string) (token Token) {\n\tstmt := Tokens.Select().Where(Tokens.C[\"key\"].Equals(key))\n\tm.conn.MustQueryOne(stmt, &token)\n\treturn\n}", "func (et *ewmaThrottler) getSpender(validatorID ids.ShortID) *spender {\n\tvalidatorKey := validatorID.Key()\n\tif sp, exists := et.spenders[validatorKey]; exists {\n\t\treturn sp\n\t}\n\n\t// If this validator did not exist in spenders, create it and return\n\tsp := &spender{\n\t\tmaxMessages: et.maxNonStakerPendingMsgs,\n\t\texpectedCPU: defaultMinimumCPUAllotment,\n\t}\n\tet.spenders[validatorKey] = sp\n\treturn sp\n}", "func (m *Manager) GetAudio(audioID StringID) (*Audio, error) {\n\tif _, ok := m.audio[audioID]; ok {\n\t\treturn m.audio[audioID], nil\n\t}\n\treturn nil, errors.New(\"Audio does not exist\")\n}", "func (q *SimpleQueue) getStorageLock(ctx context.Context, name string) (st storage.Storage, err *mft.Error) {\n\tif !q.mx.RTryLock(ctx) {\n\t\treturn nil, GenerateError(10016000)\n\t}\n\n\tst = q.getStorage(name)\n\tq.mx.RUnlock()\n\n\treturn st, nil\n}", "func (m *SmsLogRow) GetUserCountryCode()(*string) {\n val, err := m.GetBackingStore().Get(\"userCountryCode\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (kvstore *KVStore) get(key string) []byte {\n\tv, _ := kvstore.kvstore[key]\n\treturn v\n}", "func (sp *ScrambleProvider) Get(event string) string {\n\tevent = trimSuffix(event)\n\tsp.mx.RLock()\n\tdefer sp.mx.RUnlock()\n\treturn sp.scrambles[event]\n}", "func (d *dao) GetByCode(code string) (oauth2.TokenInfo, error) {\n\tm, err := d.GetSsoToken(context.TODO(), &model.SsoToken{Code: code})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &m, nil\n}", "func (ps *PgStore) GetMulticastGroup(ctx context.Context, id uuid.UUID, forUpdate bool) (MulticastGroup, error) {\n\tvar fu string\n\tif forUpdate {\n\t\tfu = \" for update\"\n\t}\n\n\tvar mg MulticastGroup\n\n\terr := sqlx.GetContext(ctx, ps.db, &mg, `\n\t\tselect\n\t\t\tcreated_at,\n\t\t\tupdated_at,\n\t\t\tname,\n\t\t\tservice_profile_id,\n\t\t\tmc_app_s_key,\n\t\t\tmc_key\n\t\tfrom\n\t\t\tmulticast_group\n\t\twhere\n\t\t\tid = $1\n\t`+fu, id)\n\tif err != nil {\n\t\treturn mg, handlePSQLError(Select, err, \"select error\")\n\t}\n\n\treturn mg, nil\n}", "func (m *manager) Get(name, zone string) (*compute.InstanceGroup, error) {\n\tig, err := m.cloud.GetInstanceGroup(name, zone)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ig, nil\n}", "func getMulticastACLIgrMatch(nsInfo *namespaceInfo) string {\n\tvar ipv4Match, ipv6Match string\n\taddrSetNameV4, addrSetNameV6 := nsInfo.addressSet.GetASHashNames()\n\tif config.IPv4Mode {\n\t\tipv4Match = getMulticastACLIgrMatchV4(addrSetNameV4)\n\t}\n\tif config.IPv6Mode {\n\t\tipv6Match = getMulticastACLIgrMatchV6(addrSetNameV6)\n\t}\n\treturn getACLMatchAF(ipv4Match, ipv6Match)\n}", "func (m NumSeriesDistribution) Get(index int) *NumSeries {\n\tif index > -1 {\n\t\tif s, ok := m[index]; ok {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn nil\n}", "func (gc *GceCache) GetMig(migRef GceRef) (Mig, bool) {\n\tgc.cacheMutex.Lock()\n\tdefer gc.cacheMutex.Unlock()\n\n\tmig, found := gc.migs[migRef]\n\treturn mig, found\n}", "func (c Claims) Get(name string) (interface{}, error) {\n\tif !c.Has(name) {\n\t\treturn nil, ErrNotFound\n\t}\n\n\treturn c[name], nil\n}", "func (e *env) get(key string) (*object, error) {\n\tee, err := e.find(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ee.m[key], nil\n}", "func GetS(name string, defvals ...string) string {\n\tif global == nil {\n\t\tif len(defvals) == 0 {\n\t\t\treturn \"\"\n\t\t}\n\n\t\treturn defvals[0]\n\t}\n\n\treturn global.GetS(name, defvals...)\n}" ]
[ "0.59688526", "0.5825662", "0.5687476", "0.5570388", "0.55646", "0.5548485", "0.5404135", "0.52392215", "0.5225401", "0.5161567", "0.5112643", "0.50869906", "0.5049648", "0.50431406", "0.50244594", "0.50233185", "0.4935734", "0.49334112", "0.49163225", "0.4898356", "0.48868906", "0.48768598", "0.48724952", "0.48415118", "0.48308313", "0.4820003", "0.48107126", "0.47928765", "0.47902006", "0.47673717", "0.4762201", "0.47318062", "0.4709896", "0.4705363", "0.47032028", "0.46878102", "0.46820748", "0.4673029", "0.46673295", "0.4661472", "0.4660619", "0.46452057", "0.46411303", "0.46384448", "0.46319607", "0.46280074", "0.46277946", "0.4627768", "0.46248314", "0.46188775", "0.46117267", "0.45970917", "0.45897934", "0.45849967", "0.45848766", "0.4584645", "0.45771238", "0.4572961", "0.45691532", "0.4551338", "0.45512798", "0.45505896", "0.45493504", "0.45481616", "0.45393962", "0.45366865", "0.45222047", "0.45159683", "0.45132297", "0.45103058", "0.45082694", "0.45068276", "0.4505594", "0.45045754", "0.45036516", "0.44969216", "0.44965076", "0.4490572", "0.4483085", "0.4480549", "0.44725156", "0.44691512", "0.44674343", "0.44615135", "0.44579232", "0.44560307", "0.4454269", "0.44524977", "0.4449989", "0.44498345", "0.4446486", "0.44424433", "0.44387308", "0.4438372", "0.44367495", "0.4430267", "0.44302067", "0.44251338", "0.4420909", "0.44184965" ]
0.78783107
0
Serialize returns m in its JSON encoded format or error if serialization had failed.
func (m *saMap) serialize() ([]byte, error) { m.RLock() defer m.RUnlock() return json.Marshal(m.ma) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (em Message) Serialize() ([]byte, error) {\n\tmsg, err := json.Marshal(em)\n\treturn msg, err\n}", "func (s *Serializer) Serialize(m telegraf.Metric) ([]byte, error) {\n\ts.buf.Reset()\n\terr := s.writeMetric(&s.buf, m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := make([]byte, 0, s.buf.Len())\n\treturn append(out, s.buf.Bytes()...), nil\n}", "func (e *InvalidPageSizeError) Serialize() []byte {\n\tg, _ := json.Marshal(map[string]interface{}{\n\t\t\"code\": \"ERR-008\",\n\t\t\"error\": \"InvalidPageSizeError\",\n\t\t\"description\": e.Error(),\n\t\t\"success\": false,\n\t})\n\n\treturn g\n}", "func (cm Message) Serialize() ([]byte, error) {\n\treturn []byte(cm.Content), nil\n}", "func (e *InvalidPageError) Serialize() []byte {\n\tg, _ := json.Marshal(map[string]interface{}{\n\t\t\"code\": \"ERR-007\",\n\t\t\"error\": \"InvalidPageError\",\n\t\t\"description\": e.Error(),\n\t\t\"success\": false,\n\t})\n\n\treturn g\n}", "func Serialize(msg Message) ([]byte, error) {\n\tvar b bytes.Buffer\n\tencoder := json.NewEncoder(&b)\n\terr := encoder.Encode(msg)\n\treturn b.Bytes(), err\n}", "func (m Message) Marshal() ([]byte, error) {\n\treturn jsoniter.Marshal(m)\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 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 (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 (m *Media) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteObjectValue(\"calleeDevice\", m.GetCalleeDevice())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"calleeNetwork\", m.GetCalleeNetwork())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"callerDevice\", m.GetCallerDevice())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"callerNetwork\", m.GetCallerNetwork())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"label\", m.GetLabel())\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.GetStreams() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetStreams())\n err := writer.WriteCollectionOfObjectValues(\"streams\", cast)\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 *SAMap) Serialize() ([]byte, error) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\treturn json.Marshal(m.ma)\n}", "func (e *NonAllowedEmailDomainError) Serialize() []byte {\n\tg, _ := json.Marshal(map[string]interface{}{\n\t\t\"code\": \"ERR-002\",\n\t\t\"error\": \"NonAllowedEmailDomainError\",\n\t\t\"description\": e.Error(),\n\t\t\"success\": false,\n\t})\n\n\treturn g\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 (m *MatrixMessage) Marshal() ([]byte, error) {\n\tj, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn j, nil\n}", "func (m Message) Serialize() []byte {\n\tbuff := make([]byte, 0, 512)\n\n\t// fix header counts before serialization\n\tm.Header.QuestionCount = uint16(len(m.Questions))\n\tm.Header.AnswerRecordCount = uint16(len(m.AnswerRecords))\n\tm.Header.AuthorityRecordCount = uint16(len(m.AuthorityRecords))\n\tm.Header.AdditionalRecordCount = uint16(len(m.AdditionalRecords))\n\n\tbuff = append(buff, m.Header.Serialize()...)\n\tfor _, question := range m.Questions {\n\t\tbuff = append(buff, question.Serialize()...)\n\t}\n\tfor _, rr := range m.AnswerRecords {\n\t\tbuff = append(buff, rr.Serialize()...)\n\t}\n\tfor _, rr := range m.AuthorityRecords {\n\t\tbuff = append(buff, rr.Serialize()...)\n\t}\n\tfor _, rr := range m.AdditionalRecords {\n\t\tbuff = append(buff, rr.Serialize()...)\n\t}\n\treturn buff\n}", "func (m *MSPManaged) ToJSON() (string, error) {\n\treturn codec.ToJSON(m)\n}", "func (mu *MuHash) Serialize() *SerializedMuHash {\n\tvar out SerializedMuHash\n\tmu.serializeInner(&out)\n\treturn &out\n}", "func (m *NumaMem) ToJSON() (string, error) {\n\treturn codec.ToJSON(m)\n}", "func (l *Layer) Serialize() ([]byte, error) {\n\treturn json.Marshal(l)\n}", "func Serialize(data interface{}) string {\n\tval, _ := json.Marshal(data)\n\treturn string(val);\n}", "func (o *A_2) SerializeJSON() ([]byte, error) {\r\n\treturn json.Marshal(o)\r\n}", "func (pd *pymtData) Serialize() ([]byte, error) {\n\tb, err := json.Marshal(pd)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, payment.ErrUnexpectedSysError)\n\t}\n\n\treturn 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 Serialize(o interface{}) ([]byte, error) {\n\tautil.TODO(\"CBOR-serialization\")\n\treturn nil, nil\n}", "func (m Message) String() string {\n\tjm, _ := json.Marshal(m)\n\treturn string(jm)\n}", "func (m *Meta) JSON() string {\n\tj, _ := json.MarshalIndent(m, \"\", \" \")\n\treturn string(j)\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 (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 (s *WavefrontSerializer) Serialize(m telegraf.Metric) ([]byte, error) {\n\tout := []byte{}\n\tmetricSeparator := \".\"\n\n\tfor fieldName, value := range m.Fields() {\n\t\tvar name string\n\n\t\tif fieldName == \"value\" {\n\t\t\tname = fmt.Sprintf(\"%s%s\", s.Prefix, m.Name())\n\t\t} else {\n\t\t\tname = fmt.Sprintf(\"%s%s%s%s\", s.Prefix, m.Name(), metricSeparator, fieldName)\n\t\t}\n\n\t\tif s.UseStrict {\n\t\t\tname = strictSanitizedChars.Replace(name)\n\t\t} else {\n\t\t\tname = sanitizedChars.Replace(name)\n\t\t}\n\n\t\tname = pathReplacer.Replace(name)\n\n\t\tmetric := &wavefront.MetricPoint{\n\t\t\tMetric: name,\n\t\t\tTimestamp: m.Time().Unix(),\n\t\t}\n\n\t\tmetricValue, buildError := buildValue(value, metric.Metric)\n\t\tif buildError != nil {\n\t\t\t// bad value continue to next metric\n\t\t\tcontinue\n\t\t}\n\t\tmetric.Value = metricValue\n\n\t\tsource, tags := buildTags(m.Tags(), s)\n\t\tmetric.Source = source\n\t\tmetric.Tags = tags\n\n\t\tout = append(out, formatMetricPoint(metric, s)...)\n\t}\n\treturn out, nil\n}", "func (m Error) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(m.data)\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 (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 (h HMSketch) Serialize() ([]byte, error) {\n\tvar outbytes bytes.Buffer\n\tenc := gob.NewEncoder(&outbytes)\n\terr := enc.Encode(h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn outbytes.Bytes(), nil\n}", "func (m *ConnectedMessage) ToJson() string {\n\tvar msg, _ = json.Marshal(m)\n\treturn string(msg)\n}", "func GetJSON(m Model) ([]byte, error) {\n\tdata, err := json.MarshalIndent(m, \"\", \" \")\n\trtx.Must(err, \"ERROR: failed to marshal archive.Model to JSON. This should never happen\")\n\treturn data, err\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 *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 (m Mall) String() string {\n\ts, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn string(s)\n}", "func (m *Aws) ToJSON() (string, error) {\n\treturn codec.ToJSON(m)\n}", "func (m *ChatMessage) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAttachments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAttachments())\n err = writer.WriteCollectionOfObjectValues(\"attachments\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"body\", m.GetBody())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"channelIdentity\", m.GetChannelIdentity())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"chatId\", m.GetChatId())\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.WriteTimeValue(\"deletedDateTime\", m.GetDeletedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"etag\", m.GetEtag())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"eventDetail\", m.GetEventDetail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"from\", m.GetFrom())\n if err != nil {\n return err\n }\n }\n if m.GetHostedContents() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetHostedContents())\n err = writer.WriteCollectionOfObjectValues(\"hostedContents\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetImportance() != nil {\n cast := (*m.GetImportance()).String()\n err = writer.WriteStringValue(\"importance\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastEditedDateTime\", m.GetLastEditedDateTime())\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.WriteStringValue(\"locale\", m.GetLocale())\n if err != nil {\n return err\n }\n }\n if m.GetMentions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMentions())\n err = writer.WriteCollectionOfObjectValues(\"mentions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetMessageType() != nil {\n cast := (*m.GetMessageType()).String()\n err = writer.WriteStringValue(\"messageType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"policyViolation\", m.GetPolicyViolation())\n if err != nil {\n return err\n }\n }\n if m.GetReactions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetReactions())\n err = writer.WriteCollectionOfObjectValues(\"reactions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetReplies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetReplies())\n err = writer.WriteCollectionOfObjectValues(\"replies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"replyToId\", m.GetReplyToId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"subject\", m.GetSubject())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"summary\", m.GetSummary())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"webUrl\", m.GetWebUrl())\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 toJSON(a interface{}) ([]byte, error) {\n\tbs, err := json.Marshal(a)\n\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"there was an error: %v\", err)\n\t\t// return []byte{}, fmt.Println(\"there was an error: %v\", err)\n\t\t//does not work bc Println returns n int and err => we only need err\n\t\t//fatal does not work bec no error returned but we need to return here\n\n\t}\n\treturn bs, nil\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 (s *Serializer) Serialize(p svermaker.ProjectVersion) error {\n\ts.SerializerInvoked = true\n\treturn s.SerializerFn(p)\n}", "func serialize(toMarshal interface{}) *bytes.Buffer {\n\tjsonStr, _ := json.Marshal(toMarshal)\n\treturn bytes.NewBuffer(jsonStr)\n}", "func (store_m StoreModule) ToJSON() []byte {\n\tjsonStr, _ := json.Marshal(store_m)\n\treturn jsonStr\n}", "func (m *Message) Serialize() []byte {\n\tif m == nil {\n\t\treturn make([]byte, 4)\n\t}\n\tlength := uint32(len(m.Payload) + 1) // +1 for id\n\tbuf := make([]byte, 4+length)\n\tbinary.BigEndian.PutUint32(buf[0:4], length)\n\tbuf[4] = byte(m.ID)\n\tcopy(buf[5:], m.Payload)\n\treturn buf\n}", "func (m *ActionResultPart) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteObjectValue(\"error\", m.GetError())\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 (mp MassPayment) Serialize() (string, error) {\n\tdata := url.Values{}\n\tmassPaymentType := reflect.TypeOf(mp)\n\tmassPaymentValue := reflect.ValueOf(mp)\n\n\tfor i := 0; i < massPaymentType.NumField(); i++ {\n\t\tfield := massPaymentType.Field(i)\n\t\tif fieldTag, ok := field.Tag.Lookup(\"nvp_field\"); ok {\n\t\t\tvalueContents := massPaymentValue.Field(i).String()\n\t\t\tif valueContents != \"\" {\n\t\t\t\tdata.Set(fieldTag, massPaymentValue.Field(i).String())\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i, item := range mp.Items {\n\t\titem.Serialize(&data, i)\n\t}\n\n\tif len(mp.Items) == 0 {\n\t\treturn \"\", errors.New(\"Expected at least one mass payment item\")\n\t}\n\n\treturn data.Encode(), nil\n}", "func (m *Message) String() string {\n\tjsonBytes, err := json.MarshalIndent(m, \"\", \" \")\n\t// jsonBytes, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"message error - fail to marshal message to bytes, error: %v\", err)\n\t}\n\treturn string(jsonBytes)\n}", "func toJSON(a interface{}) ([]byte, error) {\n\tbs, err := json.Marshal(a)\n\tif err != nil {\n\t\t//return []byte{}, fmt.Errorf(\"Erro no json %v\", err)\n\t\treturn []byte{}, errors.New(fmt.Sprintf(\"Erro no json %v\", err))\n\t}\n\treturn bs, nil\n}", "func (m *Metrics) String() string {\n\tb, _ := json.Marshal(m)\n\treturn string(b)\n}", "func (m *ItemItemsItemWorkbookFunctionsComplexPostRequestBody) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteObjectValue(\"iNum\", m.GetINum())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"realNum\", m.GetRealNum())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"suffix\", m.GetSuffix())\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 *Free) ToJson() ([]byte, error) {\n\treturn json.Marshal(m.Data)\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 (g *Generic) Serialize() ([]byte, error) {\n\tlog.Println(\"DEPRECATED: MarshalBinary instead\")\n\treturn g.MarshalBinary()\n}", "func (m lockCmdMessage) JSON() string {\n\tmsgBytes, e := json.MarshalIndent(m, \"\", \" \")\n\tfatalIf(probe.NewError(e), \"Unable to marshal into JSON.\")\n\treturn string(msgBytes)\n}", "func toJSON(a interface{}) ([]byte, error) {\n\tbs, err := json.Marshal(a)\n\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"Error caught by Onur Gurel\")\n\t}\n\n\treturn bs, nil\n}", "func (mm *managedAnnotation) Encode(m map[string]interface{}) error {\n\tvar buf bytes.Buffer\n\tgz := gzip.NewWriter(&buf)\n\n\tactions := []serial.Action{\n\t\tfunc() error { return json.NewEncoder(gz).Encode(m) },\n\t\tgz.Flush,\n\t\tgz.Close,\n\t}\n\n\tif err := serial.RunActions(actions...); err != nil {\n\t\treturn err\n\t}\n\n\tmm.Pristine = base64.StdEncoding.EncodeToString(buf.Bytes())\n\treturn nil\n}", "func (m *Group) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DirectoryObject.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAcceptedSenders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAcceptedSenders())\n err = writer.WriteCollectionOfObjectValues(\"acceptedSenders\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"allowExternalSenders\", m.GetAllowExternalSenders())\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.GetAssignedLabels() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAssignedLabels())\n err = writer.WriteCollectionOfObjectValues(\"assignedLabels\", 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 {\n err = writer.WriteBoolValue(\"autoSubscribeNewMembers\", m.GetAutoSubscribeNewMembers())\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.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 {\n err = writer.WriteStringValue(\"classification\", m.GetClassification())\n if err != nil {\n return err\n }\n }\n if m.GetConversations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetConversations())\n err = writer.WriteCollectionOfObjectValues(\"conversations\", 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(\"createdOnBehalfOf\", m.GetCreatedOnBehalfOf())\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(\"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 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 {\n err = writer.WriteTimeValue(\"expirationDateTime\", m.GetExpirationDateTime())\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 if m.GetGroupLifecyclePolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetGroupLifecyclePolicies())\n err = writer.WriteCollectionOfObjectValues(\"groupLifecyclePolicies\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetGroupTypes() != nil {\n err = writer.WriteCollectionOfStringValues(\"groupTypes\", m.GetGroupTypes())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hasMembersWithLicenseErrors\", m.GetHasMembersWithLicenseErrors())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hideFromAddressLists\", m.GetHideFromAddressLists())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hideFromOutlookClients\", m.GetHideFromOutlookClients())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isArchived\", m.GetIsArchived())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isAssignableToRole\", m.GetIsAssignableToRole())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isSubscribedByMail\", m.GetIsSubscribedByMail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"licenseProcessingState\", m.GetLicenseProcessingState())\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.WriteBoolValue(\"mailEnabled\", m.GetMailEnabled())\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.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.GetMembers() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMembers())\n err = writer.WriteCollectionOfObjectValues(\"members\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"membershipRule\", m.GetMembershipRule())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"membershipRuleProcessingState\", m.GetMembershipRuleProcessingState())\n if err != nil {\n return err\n }\n }\n if m.GetMembersWithLicenseErrors() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMembersWithLicenseErrors())\n err = writer.WriteCollectionOfObjectValues(\"membersWithLicenseErrors\", cast)\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 {\n err = writer.WriteStringValue(\"onPremisesDomainName\", m.GetOnPremisesDomainName())\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 {\n err = writer.WriteStringValue(\"onPremisesNetBiosName\", m.GetOnPremisesNetBiosName())\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 if m.GetOwners() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwners())\n err = writer.WriteCollectionOfObjectValues(\"owners\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetPermissionGrants() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPermissionGrants())\n err = writer.WriteCollectionOfObjectValues(\"permissionGrants\", 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(\"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 if m.GetProxyAddresses() != nil {\n err = writer.WriteCollectionOfStringValues(\"proxyAddresses\", m.GetProxyAddresses())\n if err != nil {\n return err\n }\n }\n if m.GetRejectedSenders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetRejectedSenders())\n err = writer.WriteCollectionOfObjectValues(\"rejectedSenders\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"renewedDateTime\", m.GetRenewedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"securityEnabled\", m.GetSecurityEnabled())\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 if m.GetSettings() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSettings())\n err = writer.WriteCollectionOfObjectValues(\"settings\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSites() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSites())\n err = writer.WriteCollectionOfObjectValues(\"sites\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"team\", m.GetTeam())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"theme\", m.GetTheme())\n if err != nil {\n return err\n }\n }\n if m.GetThreads() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetThreads())\n err = writer.WriteCollectionOfObjectValues(\"threads\", cast)\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 if m.GetTransitiveMembers() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTransitiveMembers())\n err = writer.WriteCollectionOfObjectValues(\"transitiveMembers\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"unseenCount\", m.GetUnseenCount())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"visibility\", m.GetVisibility())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *Reminder) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"changeKey\", m.GetChangeKey())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"eventEndTime\", m.GetEventEndTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventId\", m.GetEventId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"eventLocation\", m.GetEventLocation())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"eventStartTime\", m.GetEventStartTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventSubject\", m.GetEventSubject())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventWebLink\", m.GetEventWebLink())\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(\"reminderFireTime\", m.GetReminderFireTime())\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 (message *Message) ToJson(writer io.Writer) error {\n\tencoder := json.NewEncoder(writer)\n\tencodedMessage := encoder.Encode(message)\n\treturn encodedMessage\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 *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 (m *CalendarGroup) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetCalendars() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCalendars()))\n for i, v := range m.GetCalendars() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"calendars\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"changeKey\", m.GetChangeKey())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteUUIDValue(\"classId\", m.GetClassId())\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 return nil\n}", "func (m *Empty) ToJSON() (string, error) {\n\treturn codec.ToJSON(m)\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 (m Messages) String() string {\n\tjm, _ := json.Marshal(m)\n\treturn string(jm)\n}", "func (msg *Error) JSON() any {\n\tjsonData := H{}\n\tif msg.Meta != nil {\n\t\tvalue := reflect.ValueOf(msg.Meta)\n\t\tswitch value.Kind() {\n\t\tcase reflect.Struct:\n\t\t\treturn msg.Meta\n\t\tcase reflect.Map:\n\t\t\tfor _, key := range value.MapKeys() {\n\t\t\t\tjsonData[key.String()] = value.MapIndex(key).Interface()\n\t\t\t}\n\t\tdefault:\n\t\t\tjsonData[\"meta\"] = msg.Meta\n\t\t}\n\t}\n\tif _, ok := jsonData[\"error\"]; !ok {\n\t\tjsonData[\"error\"] = msg.Error()\n\t}\n\treturn jsonData\n}", "func (m *Metadata) ToJSON() ([]byte, error) {\n\tjson, err := json.Marshal(m)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"err dumping JSON: %w\", err)\n\n\t\treturn []byte{}, err\n\t}\n\n\treturn json, nil\n}", "func (pg *ProblemGraph) Serialize() []byte {\n\tvar result bytes.Buffer\n\tencoder := gob.NewEncoder(&result)\n\n\terr := encoder.Encode(pg)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn result.Bytes()\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 *Membership) Serialize() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\n\t// Version (uint8)\n\t{\n\t\tif err := write(buf, m.Version); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// AgeRestriction (AgeRestriction)\n\t{\n\t\tif err := write(buf, m.AgeRestriction); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// ValidFrom (Timestamp)\n\t{\n\t\tif err := write(buf, m.ValidFrom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// ExpirationTimestamp (Timestamp)\n\t{\n\t\tif err := write(buf, m.ExpirationTimestamp); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// ID (string)\n\t{\n\t\tif err := WriteVarChar(buf, m.ID, 8); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// MembershipClass (string)\n\t{\n\t\tif err := WriteVarChar(buf, m.MembershipClass, 8); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// RoleType (string)\n\t{\n\t\tif err := WriteVarChar(buf, m.RoleType, 8); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// MembershipType (string)\n\t{\n\t\tif err := WriteVarChar(buf, m.MembershipType, 8); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Description (string)\n\t{\n\t\tif err := WriteVarChar(buf, m.Description, 16); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (m *Workbook) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"application\", m.GetApplication())\n if err != nil {\n return err\n }\n }\n if m.GetComments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetComments())\n err = writer.WriteCollectionOfObjectValues(\"comments\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"functions\", m.GetFunctions())\n if err != nil {\n return err\n }\n }\n if m.GetNames() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetNames())\n err = writer.WriteCollectionOfObjectValues(\"names\", cast)\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 if m.GetTables() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTables())\n err = writer.WriteCollectionOfObjectValues(\"tables\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetWorksheets() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetWorksheets())\n err = writer.WriteCollectionOfObjectValues(\"worksheets\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *TeamsAsyncOperation) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteInt32Value(\"attemptsCount\", m.GetAttemptsCount())\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(\"error\", m.GetError())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastActionDateTime\", m.GetLastActionDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetOperationType() != nil {\n cast := (*m.GetOperationType()).String()\n err = writer.WriteStringValue(\"operationType\", &cast)\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 {\n err = writer.WriteStringValue(\"targetResourceId\", m.GetTargetResourceId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"targetResourceLocation\", m.GetTargetResourceLocation())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *ConnectedOrganizationMembers) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.SubjectSet.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"connectedOrganizationId\", m.GetConnectedOrganizationId())\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 return nil\n}", "func (msssmto MigrateSQLServerSQLMITaskOutput) MarshalJSON() ([]byte, error) {\n\tmsssmto.ResultType = ResultTypeBasicMigrateSQLServerSQLMITaskOutputResultTypeMigrateSQLServerSQLMITaskOutput\n\tobjectMap := make(map[string]interface{})\n\tif msssmto.ID != nil {\n\t\tobjectMap[\"id\"] = msssmto.ID\n\t}\n\tif msssmto.ResultType != \"\" {\n\t\tobjectMap[\"resultType\"] = msssmto.ResultType\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (m *MqMessageKey) Encode() ([]byte, error) {\n\treturn json.Marshal(m)\n\n}", "func (m Message) MarshalJSON() ([]byte, error) {\n\ttype Message struct {\n\t\tSig hexutil.Bytes `json:\"sig,omitempty\"`\n\t\tTTL uint32 `json:\"ttl\"`\n\t\tTimestamp uint32 `json:\"timestamp\"`\n\t\tTopic TopicType `json:\"topic\"`\n\t\tPayload hexutil.Bytes `json:\"payload\"`\n\t\tPadding hexutil.Bytes `json:\"padding\"`\n\t\tPoW float64 `json:\"pow\"`\n\t\tHash hexutil.Bytes `json:\"hash\"`\n\t\tDst hexutil.Bytes `json:\"recipientPublicKey,omitempty\"`\n\t}\n\tvar enc Message\n\tenc.Sig = m.Sig\n\tenc.TTL = m.TTL\n\tenc.Timestamp = m.Timestamp\n\tenc.Topic = m.Topic\n\tenc.Payload = m.Payload\n\tenc.Padding = m.Padding\n\tenc.PoW = m.PoW\n\tenc.Hash = m.Hash\n\tenc.Dst = m.Dst\n\treturn json.Marshal(&enc)\n}", "func (b Bytes) Serialize() ([]byte, error) {\n\treturn b, nil\n}", "func (t Tweet) Serialize() *[]byte {\n\tb, err := json.Marshal(t)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn &b\n}", "func (s String) Serialize() ([]byte, error) {\n\treturn []byte(s), nil\n}", "func (m *Application) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DirectoryObject.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAddIns() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAddIns())\n err = writer.WriteCollectionOfObjectValues(\"addIns\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"api\", m.GetApi())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"appId\", m.GetAppId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"applicationTemplateId\", m.GetApplicationTemplateId())\n if err != nil {\n return err\n }\n }\n if m.GetAppRoles() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAppRoles())\n err = writer.WriteCollectionOfObjectValues(\"appRoles\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"certification\", m.GetCertification())\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(\"createdOnBehalfOf\", m.GetCreatedOnBehalfOf())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"defaultRedirectUri\", m.GetDefaultRedirectUri())\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(\"disabledByMicrosoftStatus\", m.GetDisabledByMicrosoftStatus())\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 if m.GetExtensionProperties() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetExtensionProperties())\n err = writer.WriteCollectionOfObjectValues(\"extensionProperties\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetFederatedIdentityCredentials() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetFederatedIdentityCredentials())\n err = writer.WriteCollectionOfObjectValues(\"federatedIdentityCredentials\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"groupMembershipClaims\", m.GetGroupMembershipClaims())\n if err != nil {\n return err\n }\n }\n if m.GetHomeRealmDiscoveryPolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetHomeRealmDiscoveryPolicies())\n err = writer.WriteCollectionOfObjectValues(\"homeRealmDiscoveryPolicies\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetIdentifierUris() != nil {\n err = writer.WriteCollectionOfStringValues(\"identifierUris\", m.GetIdentifierUris())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"info\", m.GetInfo())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isDeviceOnlyAuthSupported\", m.GetIsDeviceOnlyAuthSupported())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isFallbackPublicClient\", m.GetIsFallbackPublicClient())\n if err != nil {\n return err\n }\n }\n if m.GetKeyCredentials() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetKeyCredentials())\n err = writer.WriteCollectionOfObjectValues(\"keyCredentials\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteByteArrayValue(\"logo\", m.GetLogo())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"notes\", m.GetNotes())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"oauth2RequirePostResponse\", m.GetOauth2RequirePostResponse())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"optionalClaims\", m.GetOptionalClaims())\n if err != nil {\n return err\n }\n }\n if m.GetOwners() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwners())\n err = writer.WriteCollectionOfObjectValues(\"owners\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"parentalControlSettings\", m.GetParentalControlSettings())\n if err != nil {\n return err\n }\n }\n if m.GetPasswordCredentials() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPasswordCredentials())\n err = writer.WriteCollectionOfObjectValues(\"passwordCredentials\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"publicClient\", m.GetPublicClient())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"publisherDomain\", m.GetPublisherDomain())\n if err != nil {\n return err\n }\n }\n if m.GetRequiredResourceAccess() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetRequiredResourceAccess())\n err = writer.WriteCollectionOfObjectValues(\"requiredResourceAccess\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"samlMetadataUrl\", m.GetSamlMetadataUrl())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"serviceManagementReference\", m.GetServiceManagementReference())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"signInAudience\", m.GetSignInAudience())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"spa\", m.GetSpa())\n if err != nil {\n return err\n }\n }\n if m.GetTags() != nil {\n err = writer.WriteCollectionOfStringValues(\"tags\", m.GetTags())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"tokenEncryptionKeyId\", m.GetTokenEncryptionKeyId())\n if err != nil {\n return err\n }\n }\n if m.GetTokenIssuancePolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTokenIssuancePolicies())\n err = writer.WriteCollectionOfObjectValues(\"tokenIssuancePolicies\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTokenLifetimePolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTokenLifetimePolicies())\n err = writer.WriteCollectionOfObjectValues(\"tokenLifetimePolicies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"verifiedPublisher\", m.GetVerifiedPublisher())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"web\", m.GetWeb())\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 *CommunicationsIdentitySet) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.IdentitySet.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"applicationInstance\", m.GetApplicationInstance())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"assertedIdentity\", m.GetAssertedIdentity())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"azureCommunicationServicesUser\", m.GetAzureCommunicationServicesUser())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"encrypted\", m.GetEncrypted())\n if err != nil {\n return err\n }\n }\n if m.GetEndpointType() != nil {\n cast := (*m.GetEndpointType()).String()\n err = writer.WriteStringValue(\"endpointType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"guest\", m.GetGuest())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"onPremises\", m.GetOnPremises())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"phone\", m.GetPhone())\n if err != nil {\n return err\n }\n }\n return nil\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 (self *ResTransaction)Serialize()[]byte{\n data, err := json.Marshal(self)\n if err != nil {\n fmt.Println(err)\n }\n return data\n}", "func (m *AssignPostRequestBody) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetMobileAppAssignments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMobileAppAssignments())\n err := writer.WriteCollectionOfObjectValues(\"mobileAppAssignments\", cast)\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 DelegateMap) Serialize() ([]byte, error) {\n\tl := make(DelegateList, 0, len(m))\n\tfor _, v := range m {\n\t\tl = append(l, v)\n\t}\n\tsort.Sort(l)\n\treturn proto.Marshal(l.toProto())\n}", "func (i Int) Serialize() ([]byte, error) {\n\treturn []byte(strconv.Itoa(int(i))), nil\n}", "func (m *DockerContainersMemory) ToJson() ([]byte, error) {\n\treturn json.Marshal(m.Data)\n}", "func (m *UpdateAllowedCombinationsResult) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"additionalInformation\", m.GetAdditionalInformation())\n if err != nil {\n return err\n }\n }\n if m.GetConditionalAccessReferences() != nil {\n err := writer.WriteCollectionOfStringValues(\"conditionalAccessReferences\", m.GetConditionalAccessReferences())\n if err != nil {\n return err\n }\n }\n if m.GetCurrentCombinations() != nil {\n err := writer.WriteCollectionOfStringValues(\"currentCombinations\", SerializeAuthenticationMethodModes(m.GetCurrentCombinations()))\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.GetPreviousCombinations() != nil {\n err := writer.WriteCollectionOfStringValues(\"previousCombinations\", SerializeAuthenticationMethodModes(m.GetPreviousCombinations()))\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 (rs *Restake) Serialize() []byte {\n\treturn byteutil.Must(proto.Marshal(rs.Proto()))\n}", "func (m *CloudCommunications) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetCalls() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCalls()))\n for i, v := range m.GetCalls() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"calls\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOnlineMeetings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetOnlineMeetings()))\n for i, v := range m.GetOnlineMeetings() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"onlineMeetings\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetPresences() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetPresences()))\n for i, v := range m.GetPresences() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"presences\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *Marshaler) JSON(v interface{}) ([]byte, error) {\n\tif _, ok := v.(proto.Message); ok {\n\t\tvar buf bytes.Buffer\n\t\tjm := &jsonpb.Marshaler{}\n\t\tjm.OrigName = true\n\t\tif err := jm.Marshal(&buf, v.(proto.Message)); err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\n\t\tif m.FilterProtoJson {\n\t\t\treturn m.FilterJsonWithStruct(buf.Bytes(), v)\n\t\t}\n\t\treturn buf.Bytes(), nil\n\t}\n\treturn json.Marshal(v)\n}", "func (m *Printer) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.PrinterBase.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetConnectors() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetConnectors()))\n for i, v := range m.GetConnectors() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"connectors\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hasPhysicalDevice\", m.GetHasPhysicalDevice())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isShared\", m.GetIsShared())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastSeenDateTime\", m.GetLastSeenDateTime())\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 if m.GetShares() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetShares()))\n for i, v := range m.GetShares() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"shares\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTaskTriggers() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTaskTriggers()))\n for i, v := range m.GetTaskTriggers() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"taskTriggers\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *MessageFromServer) Encode() []byte {\n\n\t// encode to json\n\tbytes, err := json.Marshal(m)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn []byte{}\n\t}\n\n\treturn bytes\n}", "func (m *ChatMessageAttachment) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"content\", m.GetContent())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"contentType\", m.GetContentType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"contentUrl\", m.GetContentUrl())\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(\"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.WriteStringValue(\"teamsAppId\", m.GetTeamsAppId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"thumbnailUrl\", m.GetThumbnailUrl())\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 toJSON(a interface{}) ([]byte, error) {\n\tbs, err := json.Marshal(a)\n\tif err != nil {\n\t\t// return []byte{}, errors.New(fmt.Sprintf(\"Can't create json with error: %v\", err))\n\t\treturn []byte{}, fmt.Errorf(\"Can't create json for person: %v error: %v\", a, err)\n\t}\n\treturn bs, nil\n}" ]
[ "0.69589114", "0.6374156", "0.63503855", "0.63293475", "0.62809575", "0.62227243", "0.60944897", "0.6069264", "0.604852", "0.6047298", "0.6029144", "0.6021478", "0.6010156", "0.59700155", "0.59660673", "0.58975554", "0.5865713", "0.5852372", "0.58185226", "0.57493746", "0.57183236", "0.5713082", "0.56923836", "0.568314", "0.5661845", "0.56431746", "0.5636496", "0.56331366", "0.5614332", "0.56037927", "0.5587247", "0.5585006", "0.55691475", "0.55659956", "0.5563944", "0.55460787", "0.5534823", "0.55291003", "0.5527905", "0.5526862", "0.55078816", "0.5485817", "0.54763174", "0.5469871", "0.5464439", "0.54627794", "0.545888", "0.5457855", "0.5452171", "0.54409856", "0.54302746", "0.5427981", "0.54245704", "0.5422141", "0.5414543", "0.54144645", "0.5410178", "0.5409455", "0.5404736", "0.54024464", "0.5394186", "0.53836054", "0.537439", "0.5373903", "0.53706527", "0.5368869", "0.5366384", "0.5363737", "0.536339", "0.53602654", "0.53574175", "0.53565013", "0.5355706", "0.5345822", "0.53374827", "0.532216", "0.5320934", "0.53197366", "0.53111786", "0.53109986", "0.53068566", "0.52955663", "0.52928215", "0.52727306", "0.52694446", "0.52673686", "0.5261993", "0.5260202", "0.52503484", "0.52489156", "0.52475464", "0.52456594", "0.52442545", "0.5242741", "0.5241949", "0.52412164", "0.5240483", "0.52403677", "0.5238787", "0.5238048" ]
0.59961045
13
NewRunShellPlugin returns a new instance of the SHPlugin.
func NewRunShellPlugin(context context.T) (*runShellPlugin, error) { shplugin := runShellPlugin{ context: context, Plugin: Plugin{ Context: context, Name: appconfig.PluginNameAwsRunShellScript, ScriptName: shellScriptName, ShellCommand: shellCommand, ShellArguments: shellArgs, ByteOrderMark: fileutil.ByteOrderMarkSkip, CommandExecuter: executers.ShellCommandExecuter{}, IdentityRuntimeClient: runtimeconfig.NewIdentityRuntimeConfigClient(), }, } return &shplugin, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewRunPowerShellPlugin(context context.T) (*runPowerShellPlugin, error) {\n\tpsplugin := runPowerShellPlugin{\n\t\tPlugin{\n\t\t\tContext: context,\n\t\t\tName: appconfig.PluginNameAwsRunPowerShellScript,\n\t\t\tScriptName: powerShellScriptName,\n\t\t\tShellCommand: appconfig.PowerShellPluginCommandName,\n\t\t\tShellArguments: strings.Split(appconfig.PowerShellPluginCommandArgs, \" \"),\n\t\t\tByteOrderMark: fileutil.ByteOrderMarkEmit,\n\t\t\tCommandExecuter: executers.ShellCommandExecuter{},\n\t\t\tIdentityRuntimeClient: runtimeconfig.NewIdentityRuntimeConfigClient(),\n\t\t},\n\t}\n\n\treturn &psplugin, nil\n}", "func NewPlugin() (shared.Plugin, error) {\n\treturn instance, nil\n}", "func newPlugin() (p *slackscot.Plugin) {\n\tp = new(slackscot.Plugin)\n\tp.Name = \"tester\"\n\tp.Commands = []slackscot.ActionDefinition{{\n\t\tMatch: func(m *slackscot.IncomingMessage) bool {\n\t\t\treturn strings.HasPrefix(m.NormalizedText, \"make\")\n\t\t},\n\t\tUsage: \"make `<something>`\",\n\t\tDescription: \"Have the test bot make something for you\",\n\t\tAnswer: func(m *slackscot.IncomingMessage) *slackscot.Answer {\n\t\t\treturn &slackscot.Answer{Text: \"Ready\"}\n\t\t},\n\t}}\n\n\treturn p\n}", "func NewPluginCommand(cmd *cobra.Command, dockerCli *client.DockerCli) {\n}", "func New() *Plugin {\n\treturn &Plugin{}\n}", "func NewPlugin() container.Plugin {\n\treturn &plugin{}\n}", "func NewPlugin(name string, path string, args []string, config skyconfig.Configuration) Plugin {\n\tfactory := transportFactories[name]\n\tif factory == nil {\n\t\tpanic(fmt.Errorf(\"unable to find plugin transport '%v'\", name))\n\t}\n\tp := Plugin{\n\t\ttransport: factory.Open(path, args, config),\n\t\tgatewayMap: map[string]*router.Gateway{},\n\t}\n\treturn p\n}", "func New() *Goshell {\n\treturn &Goshell{\n\t\tpluginsDir: api.PluginsDir,\n\t\tcommands: make(map[string]api.Command),\n\t\tclosed: make(chan struct{}),\n\t}\n}", "func New(arguments framework.Arguments) framework.Plugin {\n\treturn &slaPlugin{\n\t\tpluginArguments: arguments,\n\t\tjobWaitingTime: nil,\n\t}\n}", "func NewPlugin(namespace string, dfn plugin.Definition, cfg *plugin.WorkerConfig) *Plugin {\n\treturn &Plugin{\n\t\tName: dfn.Name,\n\t\tUUID: gouuid.NewV4(),\n\t\tResultType: dfn.ResultType,\n\t\tPodSpec: &dfn.PodSpec,\n\t\tNamespace: namespace,\n\t\tConfig: cfg,\n\t}\n}", "func NewPlugin(name string, fn GenerateConfigsFunc) *Plugin {\n\treturn &Plugin{name: name, generate: fn}\n}", "func NewPlugin() (*Plugin, error) {\n\tstore := NewStore()\n\tdockerClient, err := NewDockerClient(store)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create a docker client: %v\", err)\n\t}\n\treporter := NewReporter(store)\n\tplugin := &Plugin{\n\t\treporter: reporter,\n\t\tclients: []containerClient{\n\t\t\tdockerClient,\n\t\t},\n\t}\n\tfor _, client := range plugin.clients {\n\t\tgo client.Start()\n\t}\n\treturn plugin, nil\n}", "func NewPlugin() *Auth {\n\tplugin := &Auth{\n\t\tname: PluginName,\n\t}\n\treturn plugin\n}", "func NewPlugin(next http.HandlerFunc) http.HandlerFunc {\n\tp, err := plugin.Open(\"plugin.so\")\n\tif err != nil {\n\t\tif strings.HasPrefix(err.Error(), \"plugin.Open\") {\n\t\t\tfmt.Printf(\"error: could not open plugin file 'plugin.so': %v\\n\", err)\n\t\t}\n\t\treturn next\n\t}\n\tf, err := p.Lookup(\"Handler\")\n\tif err != nil {\n\t\tfmt.Printf(\"error: could not find plugin Handler function %v\\n\", err)\n\t\treturn next\n\t}\n\tpluginFn, ok := f.(func(http.HandlerFunc) http.HandlerFunc)\n\tif !ok {\n\t\tfmt.Println(\"error: plugin Handler function should be 'func(http.HandlerFunc) http.HandlerFunc'\")\n\t\treturn next\n\t}\n\treturn pluginFn(next)\n}", "func NewPlugin(service Service) (*Plugin, error) {\n\tif service == nil {\n\t\treturn nil, fmt.Errorf(\"Service Interface Required.\")\n\t}\n\n\treturn &Plugin{\n\t\tService: service,\n\t}, nil\n}", "func NewPluginRunner(plugin interface{}, opts ...RunnerOption) *cobra.Command {\n\tk := &PluginRunner{\n\t\tplugin: plugin,\n\t\tconfig: func(*cobra.Command, []string) ([]byte, error) { return nil, nil },\n\t\tgenerate: func() (resmap.ResMap, error) { return resmap.New(), nil },\n\t\ttransform: func(resmap.ResMap) error { return nil },\n\t\tprint: asYaml,\n\t}\n\n\t// Setup the command run stages\n\tk.cmd = &cobra.Command{\n\t\tPreRunE: k.preRun,\n\t\tRunE: k.run,\n\t\tPostRunE: k.postRun,\n\t}\n\n\t// Establish generate and transform functions\n\tif p, ok := plugin.(resmap.Generator); ok {\n\t\tk.generate = p.Generate\n\t}\n\tif p, ok := plugin.(resmap.Transformer); ok {\n\t\tk.generate = k.newResMapFromStdin\n\t\tk.transform = p.Transform\n\t}\n\n\t// Apply the runner options\n\tfor _, opt := range opts {\n\t\topt(k)\n\t}\n\n\treturn k.cmd\n}", "func NewPlugin(proto, path string, params ...string) *Plugin {\n\tif proto != \"unix\" && proto != \"tcp\" {\n\t\tpanic(\"Invalid protocol. Specify 'unix' or 'tcp'.\")\n\t}\n\tp := &Plugin{\n\t\texe: path,\n\t\tproto: proto,\n\t\tparams: params,\n\t\tinitTimeout: 2 * time.Second,\n\t\texitTimeout: 2 * time.Second,\n\t\thandler: NewDefaultErrorHandler(),\n\t\tmeta: meta(\"pingo\" + randstr(5)),\n\t\tobjsCh: make(chan *objects),\n\t\tconnCh: make(chan *conn),\n\t\tkillCh: make(chan *waiter),\n\t\texitCh: make(chan struct{}),\n\t}\n\treturn p\n}", "func New() (*Plugin, error) {\n\treturn &Plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t}, nil\n}", "func New(cfg *Config, logger logger.Logger, registerer prometheus.Registerer) (*Plugin, error) {\n\tservice := &Plugin{\n\t\tcfg: cfg,\n\t\tregisterer: registerer,\n\t\tLogger: logger.NewLogger(\"simplePlugin\"),\n\t}\n\treturn service, nil\n}", "func NewPlugin(context context.T) (*Plugin, error) {\n\tvar plugin Plugin\n\n\tplugin.context = context\n\tplugin.birdwatcherfacade = facade.NewBirdwatcherFacade(context)\n\tplugin.localRepository = localpackages.NewRepository()\n\tplugin.packageServiceSelector = selectService\n\tplugin.isDocumentArchive = false\n\n\treturn &plugin, nil\n}", "func NewPlugin(plugins func() discovery.Plugins, choices selector.Options) instance.Plugin {\n\tbase := &internal.Base{\n\t\tPlugins: plugins,\n\t\tChoices: choices,\n\t\tSelectFunc: SelectOne,\n\t}\n\treturn &impl{\n\t\tPlugin: base.Init(),\n\t}\n}", "func NewPlugin(opts ...Option) *Plugin {\n\tp := &Plugin{}\n\n\tp.SetName(\"generator\")\n\tp.KVStore = &etcd.DefaultPlugin\n\tp.KVScheduler = &kvscheduler.DefaultPlugin\n\n\tfor _, o := range opts {\n\t\to(p)\n\t}\n\n\tp.Setup()\n\n\treturn p\n}", "func NewPlugin(name, version, endpointType string) (*Plugin, error) {\n\t// Setup base plugin.\n\tplugin, err := common.NewPlugin(name, version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Plugin{\n\t\tPlugin: plugin,\n\t\tEndpointType: endpointType,\n\t}, nil\n}", "func NewPlugin() (*Plugin, error) {\n\treporter := NewReporter()\n\tplugin := &Plugin{\n\t\treporter: reporter,\n\t}\n\treturn plugin, nil\n}", "func New(path string) (Plugin, error) {\n\tplugin, err := plugin.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp, err := plugin.Lookup(\"Plugin\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.(Plugin), nil\n}", "func NewPlugin() derive.Plugin {\n\treturn derive.NewPlugin(\"hash\", \"deriveHash\", New)\n}", "func New(c *sbi.Config) sbi.Plugin {\n\treturn &Plugin{\n\t\tc,\n\t}\n}", "func New(c *sbi.Config) sbi.Plugin {\n\treturn &Plugin{\n\t\tc,\n\t}\n}", "func NewSimplePlugin() *SimplePlugin {\n\treturn &SimplePlugin{}\n}", "func NewShell(stream io.ReadWriteCloser) (sh *Shell) {\n\n\tsh = &Shell{\n\t\tNewInteractive(stream), // The session is interactive.\n\t\t0, // The token is by default 0.\n\t\tfalse, // Not set yet, will be once only.\n\t\tfalse, // No tokens read yet.\n\t\t[]string{}, // No tokens to filter yet\n\t\t\"\", // No prompt on remote end\n\t\t&strings.Builder{}, // Used to build the output from conn\n\t}\n\n\tsh.Type = serverpb.SessionType_SHELL\n\n\treturn\n}", "func NewRegisterPluginCreated() *RegisterPluginCreated {\n\n\treturn &RegisterPluginCreated{}\n}", "func createPlugin(pkg parse.Package, errChan chan error) {\n\tcmd := exec.Command(\"go\", \"build\", \"-buildmode=plugin\",\n\t\t\"-o\", \"./\"+path.Join(PluginFolder, pkg.Name+\".so\"),\n\t\t\"./\"+path.Join(PluginFolder, pkg.Path))\n\n\t// create output buffer for error logging\n\tvar outBuf bytes.Buffer\n\tcmd.Stdout = &outBuf\n\tcmd.Stderr = &outBuf\n\n\t// copy env and turn off go modules\n\tcmd.Env = os.Environ()\n\tcmd.Env = append(cmd.Env, \"GO111MODULE=off\")\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to build plugin for package:%s\\n%s\", pkg.Name, outBuf.String())\n\t}\n\n\terrChan <- err\n}", "func NewShell(ip string) (Executor, error) {\n\tif ip == \"127.0.0.1\" || ip == \"localhost\" {\n\t\treturn NewLocal(), nil\n\t}\n\treturn NewRemoteFromIP(ip)\n}", "func NewPlugin(\n\tversion string,\n\tdependencies []bufpluginref.PluginReference,\n\tregistryConfig *bufpluginconfig.RegistryConfig,\n\timageDigest string,\n\tsourceURL string,\n\tdescription string,\n) (Plugin, error) {\n\treturn newPlugin(version, dependencies, registryConfig, imageDigest, sourceURL, description)\n}", "func CreatePlugin(dir, name string) error {\n\tsylog.Debugf(\"Create %q plugin directory %s\", name, dir)\n\treturn plugin.Create(dir, name)\n}", "func NewPlugin() plugin.Plugin {\n\tcaCertPool, err := x509.SystemCertPool()\n\tif err != nil {\n\t\tstsClientLog.Errorf(\"Failed to get SystemCertPool: %v\", err)\n\t\treturn nil\n\t}\n\treturn Plugin{\n\t\thTTPClient: &http.Client{\n\t\t\tTimeout: httpTimeOutInSec * time.Second,\n\t\t\tTransport: &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\tRootCAs: caCertPool,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func New() *WebHookPlugin {\n\treturn &WebHookPlugin{}\n}", "func New(qChan qtypes_qchannel.QChan, cfg *config.Config, name string) (Plugin, error) {\n\tp := Plugin{\n\t\tPlugin: qtypes_plugin.NewNamedPlugin(qChan, cfg, pluginTyp, pluginPkg, name, version),\n\t}\n\tp.Version = version\n\tp.Name = name\n\treturn p, nil\n}", "func New(tstore plugins.TstoreClient, settings []backend.PluginSetting, dataDir string) (*usermdPlugin, error) {\n\t// Create plugin data directory\n\tdataDir = filepath.Join(dataDir, usermd.PluginID)\n\terr := os.MkdirAll(dataDir, 0700)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &usermdPlugin{\n\t\ttstore: tstore,\n\t\tdataDir: dataDir,\n\t}, nil\n}", "func New() plugin.Plugin {\n\treturn &cronPlugin{}\n}", "func New(h kore.Interface, config Config) (identity.Plugin, error) {\n\t// @step: verify the configuration\n\tif err := config.IsValid(); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Info(\"initializing the jwt authentication plugin\")\n\n\treturn &authImpl{Interface: h, config: config}, nil\n}", "func NewShell(tb testing.TB, ctx *context.T) *Shell {\n\tsh := &Shell{\n\t\tShell: gosh.NewShell(tb),\n\t\ttb: tb,\n\t}\n\tif sh.Err != nil {\n\t\treturn sh\n\t}\n\tsh.ChildOutputDir = os.Getenv(envChildOutputDir)\n\n\t// Filter out any v23test or credentials-related env vars coming from outside.\n\t// Note, we intentionally retain envChildOutputDir (\"TMPDIR\") and\n\t// envShellTestProcess, as these should be propagated downstream.\n\tif envChildOutputDir != \"TMPDIR\" { // sanity check\n\t\tpanic(envChildOutputDir)\n\t}\n\tfor _, key := range []string{ref.EnvCredentials} {\n\t\tdelete(sh.Vars, key)\n\t}\n\tif sh.tb != nil {\n\t\tsh.Vars[envShellTestProcess] = \"1\"\n\t}\n\n\tcleanup := true\n\tdefer func() {\n\t\tif cleanup {\n\t\t\tsh.Cleanup()\n\t\t}\n\t}()\n\n\tif err := sh.initPrincipalManager(); err != nil {\n\t\tif _, ok := err.(errAlreadyHandled); !ok {\n\t\t\tsh.handleError(err)\n\t\t}\n\t\treturn sh\n\t}\n\tif err := sh.initCtx(ctx); err != nil {\n\t\tif _, ok := err.(errAlreadyHandled); !ok {\n\t\t\tsh.handleError(err)\n\t\t}\n\t\treturn sh\n\t}\n\n\tcleanup = false\n\treturn sh\n}", "func (o PluginDnsNsReg) NewPlugin(ctx *core.PluginCtx, initJson []byte) (*core.PluginBase, error) {\n\treturn NewDnsNs(ctx, initJson)\n}", "func New(next goproxy.Plugin, cache FileCache) goproxy.Plugin {\n\treturn &plugin{next: next, cache: cache}\n}", "func NewSimplePlugin(name string) *SimplePlugin {\n\treturn &SimplePlugin{name: name}\n}", "func (Factory) New(m *plugins.Manager, config interface{}) plugins.Plugin {\n\treturn istio_plugin.New(m, config.(*istio_plugin.Config))\n}", "func (rs *RunnerSuite) TestNewPluginInstance(c *C) {\n\tplugin := &Plugin{\n\t\tName: \"foo\",\n\t\tSources: []*PluginSource{{\n\t\t\tPrefix: ids.PluginID{Category: \"data\", Term: \"$prop1-data\"},\n\t\t}, {\n\t\t\tPrefix: ids.PluginID{Category: \"data\", Term: \"$prop1\"},\n\t\t}},\n\t\tProperties: []PluginProperty{{\n\t\t\tName: \"prop1\",\n\t\t}},\n\t}\n\n\tinstance := newPluginInstance(plugin, map[string]string{\n\t\t\"prop1\": \"bar\",\n\t})\n\n\tc.Assert(len(instance.sources), Equals, 2)\n\tc.Assert(instance.sources[0].dataPrefix.String(), Equals, \"data/bar-data\")\n\tc.Assert(instance.sources[1].dataPrefix, Equals, ids.PluginID{Category: \"data\", Term: \"bar\"})\n}", "func newPluginProvider(pluginBinDir string, provider kubeletconfig.CredentialProvider) (*pluginProvider, error) {\n\tmediaType := \"application/json\"\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tgv, ok := apiVersions[provider.APIVersion]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid apiVersion: %q\", provider.APIVersion)\n\t}\n\n\tclock := clock.RealClock{}\n\n\treturn &pluginProvider{\n\t\tclock: clock,\n\t\tmatchImages: provider.MatchImages,\n\t\tcache: cache.NewExpirationStore(cacheKeyFunc, &cacheExpirationPolicy{clock: clock}),\n\t\tdefaultCacheDuration: provider.DefaultCacheDuration.Duration,\n\t\tlastCachePurge: clock.Now(),\n\t\tplugin: &execPlugin{\n\t\t\tname: provider.Name,\n\t\t\tapiVersion: provider.APIVersion,\n\t\t\tencoder: codecs.EncoderForVersion(info.Serializer, gv),\n\t\t\tpluginBinDir: pluginBinDir,\n\t\t\targs: provider.Args,\n\t\t\tenvVars: provider.Env,\n\t\t\tenviron: os.Environ,\n\t\t},\n\t}, nil\n}", "func NewShell() *Shell {\n\treturn &Shell{\n\t\tinput: os.Stdin,\n\t\toutput: os.Stdout,\n\t\terrorOutput: os.Stdout,\n\t}\n}", "func New() *Plugin {\n\treturn &Plugin{metricsConfigs: make(map[string]configReader.Metric)}\n}", "func RunPlugin(request *plugin_go.CodeGeneratorRequest) (*plugin_go.CodeGeneratorResponse, error) {\n\toptions, err := ParseOptions(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := parser.ParseCodeRequest(request, options.ExcludePatterns)\n\ttemplate := NewTemplate(result)\n\n\tcustomTemplate := \"\"\n\n\tif options.TemplateFile != \"\" {\n\t\tdata, err := ioutil.ReadFile(options.TemplateFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcustomTemplate = string(data)\n\t}\n\n\toutput, err := RenderTemplate(options.Type, template, customTemplate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := new(plugin_go.CodeGeneratorResponse)\n\tresp.File = append(resp.File, &plugin_go.CodeGeneratorResponse_File{\n\t\tName: proto.String(options.OutputFile),\n\t\tContent: proto.String(string(output)),\n\t})\n\n\treturn resp, nil\n}", "func RunPlugin(name string, plugin interface{}) {\n\t_, stopped, err := rpc.StartPluginAtPath(path.Join(discovery.Dir(), name), plugin)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\t<-stopped // block until done\n}", "func newPluginWithErr(errorMsg string) (p *slackscot.Plugin, err error) {\n\tif errorMsg != \"\" {\n\t\treturn nil, fmt.Errorf(errorMsg)\n\t}\n\n\treturn newPlugin(), nil\n}", "func (p *PluginService) PluginCreate(ctx context.Context, createContext io.Reader, options types.PluginCreateOptions) error {\n\treturn nil\n}", "func newPluginContainer() PluginContainer {\n\treturn new(pluginContainer)\n}", "func newPluginContainer() PluginContainer {\n\treturn new(pluginContainer)\n}", "func NewPlugins(ps []Plugin, autoname bool, dedup bool) Plugins {\n\tsortPlugins(ps)\n\treturn &plugins{\n\t\tplugins: ps,\n\t\tautoname: autoname,\n\t\tdedup: dedup,\n\t}\n}", "func (p *Plugins) runPlugin(client github.Client, event *github.GenericRequestEvent, args []string) {\n\trunID, plugin, err := p.Get(args[0])\n\tif err != nil {\n\t\tp.log.Error(err, \"unable to get plugin for command\", \"command\", args[0])\n\t\treturn\n\t}\n\n\tif !client.IsAuthorized(plugin.Authorization(), event) {\n\t\tp.log.V(3).Info(\"user not authorized\", \"user\", event.GetAuthorName(), \"plugin\", plugin.Command())\n\t\t_, _ = client.Comment(context.TODO(), event, FormatUnauthorizedResponse(event.GetAuthorName(), args[0]))\n\t\treturn\n\t}\n\n\tp.initState(plugin, runID, event)\n\n\tfs := plugin.Flags()\n\tif err := fs.Parse(args[1:]); err != nil {\n\t\tp.RemoveState(plugin, runID)\n\t\t_ = p.Error(client, event, plugin, pluginerr.New(err.Error(), \"unable to parse flags\"))\n\t\treturn\n\t}\n\tif err := plugin.Run(fs, client, event); err != nil {\n\t\tif !pluginerr.IsRecoverable(err) {\n\t\t\tplugins.RemoveState(plugin, runID)\n\t\t\t_ = p.Error(client, event, plugin, err)\n\t\t}\n\t\treturn\n\t}\n\n\tplugins.RemoveState(plugin, runID)\n}", "func New(options ...func(*Plugin)) config.Plugin {\n\tp := &Plugin{\n\t\tcache: &configCache{},\n\t}\n\tfor _, opt := range options {\n\t\topt(p)\n\t}\n\n\treturn p\n}", "func New(handle interfaces.FrameworkHandle) (interfaces.Plugin, error) {\n\treturn &DefaultBinder{handle: handle}, nil\n}", "func New(_ context.Context, next http.Handler, config *TestConfiguration, name string) (http.Handler, error) {\n\ts := &SouinTraefikPlugin{\n\t\tname: name,\n\t\tnext: next,\n\t}\n\tc := parseConfiguration(*config)\n\n\ts.Retriever = DefaultSouinPluginInitializerFromConfiguration(&c)\n\treturn s, nil\n}", "func New(b bot.Bot) *LeftpadPlugin {\n\tp := &LeftpadPlugin{\n\t\tbot: b,\n\t\tconfig: b.Config(),\n\t}\n\tb.RegisterRegexCmd(p, bot.Message, leftpadRegex, p.leftpadCmd)\n\treturn p\n}", "func (o PluginDnsCReg) NewPlugin(ctx *core.PluginCtx, initJson []byte) (*core.PluginBase, error) {\n\treturn NewDnsClient(ctx, initJson)\n}", "func (s *pluginCRUD) Create(arg ...crud.Arg) (crud.Arg, error) {\n\tevent := eventFromArg(arg[0])\n\tplugin := pluginFromStuct(event)\n\n\tcreatedPlugin, err := s.client.Plugins.Create(nil, &plugin.Plugin)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &state.Plugin{Plugin: *createdPlugin}, nil\n}", "func New(_ runtime.Object, handle framework.Handle) (framework.Plugin, error) {\n\treturn &DefaultBinder{handle: handle}, nil\n}", "func NewPluginBuilder(ctx *runctx.RunContext) (shared.PluginBuilder, error) {\n\t// We're a host. Start by launching the plugin process.\n\tlogrus.SetOutput(os.Stdout)\n\n\tbuilders := map[string]shared.PluginBuilder{}\n\n\tfor _, a := range ctx.Cfg.Build.Artifacts {\n\t\tp := a.BuilderPlugin.Name\n\t\tif _, ok := builders[p]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tcmd := exec.Command(p)\n\t\tif _, ok := SkaffoldCorePluginExecutionMap[p]; ok {\n\t\t\texecutable, err := os.Executable()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"getting executable path\")\n\t\t\t}\n\t\t\tcmd = exec.Command(executable)\n\t\t\tcmd.Env = append(os.Environ(), []string{fmt.Sprintf(\"%s=%s\", constants.SkaffoldPluginKey, constants.SkaffoldPluginValue),\n\t\t\t\tfmt.Sprintf(\"%s=%s\", constants.SkaffoldPluginName, p)}...)\n\t\t}\n\n\t\tclient := plugin.NewClient(&plugin.ClientConfig{\n\t\t\tStderr: os.Stderr,\n\t\t\tSyncStderr: os.Stderr,\n\t\t\tSyncStdout: os.Stdout,\n\t\t\tManaged: true,\n\t\t\tHandshakeConfig: shared.Handshake,\n\t\t\tPlugins: shared.PluginMap,\n\t\t\tCmd: cmd,\n\t\t})\n\n\t\tlogrus.Debugf(\"Starting plugin with command: %+v\", cmd)\n\n\t\t// Connect via RPC\n\t\trpcClient, err := client.Client()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"connecting via rpc\")\n\t\t}\n\t\tlogrus.Debugf(\"plugin started.\")\n\t\t// Request the plugin\n\t\traw, err := rpcClient.Dispense(p)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"requesting rpc plugin\")\n\t\t}\n\t\tpluginBuilder := raw.(shared.PluginBuilder)\n\t\tbuilders[p] = pluginBuilder\n\t}\n\n\tb := &Builder{\n\t\tBuilders: builders,\n\t}\n\n\tlogrus.Debugf(\"Calling Init() for all plugins.\")\n\tif err := b.Init(ctx); err != nil {\n\t\tplugin.CleanupClients()\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func NewPlugin() derive.Plugin {\n\treturn derive.NewPlugin(\"compose\", \"deriveCompose\", New)\n}", "func Init() (*Plugin, error) {\n\tvar ex run.Info\n\treader := bufio.NewReader(os.Stdin)\n\tb, err := reader.ReadBytes('\\n')\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(b, &ex)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO: set log level from the config\n\tlog.SetLevel(log.DebugLevel)\n\n\treturn &Plugin{\n\t\tMeta: &ex,\n\t}, nil\n}", "func NewPlugin(opts ...Option) *Plugin {\n\tp := &Plugin{}\n\n\tp.PluginName = \"service-label\"\n\n\tfor _, o := range opts {\n\t\to(p)\n\t}\n\n\treturn p\n}", "func GetPlugin(name string, dockerCli command.Cli, rootcmd *cobra.Command) (*Plugin, error) {\n\tpluginDirs, err := getPluginDirs(dockerCli)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcandidates, err := listPluginCandidates(pluginDirs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif paths, ok := candidates[name]; ok {\n\t\tif len(paths) == 0 {\n\t\t\treturn nil, errPluginNotFound(name)\n\t\t}\n\t\tc := &candidate{paths[0]}\n\t\tp, err := newPlugin(c, rootcmd.Commands())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !IsNotFound(p.Err) {\n\t\t\tp.ShadowedPaths = paths[1:]\n\t\t}\n\t\treturn &p, nil\n\t}\n\n\treturn nil, errPluginNotFound(name)\n}", "func NewRemoteShell(opts RemoteShellOptions) (*RemoteShell, error) {\n\tvar err error\n\tvar auth goph.Auth\n\tshell := RemoteShell{opts: opts}\n\n\tif len(opts.KeyFile) > 0 {\n\t\tauth, err = goph.Key(opts.KeyFile, opts.KeyPassword)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tauth = goph.Password(opts.Password)\n\t}\n\n\tshell.conn, err = goph.NewConn(&goph.Config{\n\t\tAuth: auth,\n\t\tUser: opts.User,\n\t\tAddr: opts.Host,\n\t\tPort: opts.Port,\n\t\tTimeout: time.Second * 2,\n\t\tCallback: ssh.InsecureIgnoreHostKey(),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &shell, nil\n}", "func NewGotifyPluginInstance(ctx plugin.UserContext) plugin.Plugin {\n\treturn &MyPlugin{}\n}", "func (m *Mock) StartPlugin(name, configuration, orchestrationDir string, cancelFlag task.CancelFlag, out iohandler.IOHandler) (err error) {\n\treturn nil\n}", "func NewLanguage() language.Language {\n\tvar cmd *exec.Cmd\n\tvar err error\n\n\tplugin := GetPluginConfig()\n\taddress := plugin.Address\n\tif address == \"\" {\n\t\taddress = \"0.0.0.0:50051\"\n\t\tlog.Printf(\"Launching subprocess: %s (%s)\", plugin.Path, address)\n\t\tcmd, err = startPlugin(plugin.Root, plugin.Path, nil, []string{\n\t\t\tfmt.Sprintf(\"%sADDRESS=%s\", PluginEnvVarNamePrefix, address),\n\t\t})\n\t\tif err != nil {\n\t\t\tfatalError(fmt.Errorf(\"could not start plugin %q: %v\", plugin.Path, err))\n\t\t}\n\t}\n\n\tconn, err := grpc.Dial(address,\n\t\tgrpc.WithInsecure(),\n\t)\n\n\tif err != nil {\n\t\tfatalError(err)\n\t}\n\n\treturn &subzelle{\n\t\tplugin: plugin,\n\t\tclient: lpb.NewLanguageClient(conn),\n\t\tconn: conn,\n\t\tcmd: cmd,\n\t}\n}", "func Plugin() *node.Plugin {\n\tonce.Do(func() {\n\t\tplugin = node.NewPlugin(PluginName, node.Enabled, configure)\n\t})\n\treturn plugin\n}", "func New() bruxism.Plugin {\n\treturn &ReminderPlugin{\n\t\tReminders: []*Reminder{},\n\t}\n}", "func NewPlugin() derive.Plugin {\n\treturn derive.NewPlugin(\"keys\", \"deriveKeys\", New)\n}", "func (l *PluginLoader) Load(pluginType PluginTypeConfig) (interface{}, func(), error) {\n\terr := l.selectPlugin(pluginType)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tl.SelectedPluginKey.Interface = pluginType.Interface\n\n\tvar pluginCommand *exec.Cmd\n\tif l.SelectedPluginKey.IsInternal {\n\t\tporterPath, err := l.GetPorterPath()\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.Wrap(err, \"could not determine the path to the porter client\")\n\t\t}\n\n\t\tpluginCommand = l.NewCommand(porterPath, \"plugin\", \"run\", l.SelectedPluginKey.String())\n\t} else {\n\t\tpluginPath, err := l.GetPluginPath(l.SelectedPluginKey.Binary)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tpluginCommand = l.NewCommand(pluginPath, \"run\", l.SelectedPluginKey.String())\n\t}\n\tconfigReader, err := l.readPluginConfig()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpluginCommand.Stdin = configReader\n\n\t// Explicitly set PORTER_HOME for the plugin\n\tpluginCommand.Env = l.Environ()\n\n\tif l.DebugPlugins {\n\t\tfmt.Fprintf(l.Err, \"Resolved %s plugin to %s\\n\", pluginType.Interface, l.SelectedPluginKey)\n\t\tif l.SelectedPluginConfig != nil {\n\t\t\tfmt.Fprintf(l.Err, \"Resolved plugin config: \\n %#v\\n\", l.SelectedPluginConfig)\n\t\t}\n\t\tfmt.Fprintln(l.Err, strings.Join(pluginCommand.Args, \" \"))\n\t}\n\n\tpluginOutput := bytes.NewBufferString(\"\")\n\tlogger := hclog.New(&hclog.LoggerOptions{\n\t\tName: \"porter\",\n\t\tOutput: pluginOutput,\n\t\tLevel: hclog.Debug,\n\t\tJSONFormat: true,\n\t})\n\n\tif l.DebugPlugins {\n\t\tlogger.SetLevel(hclog.Info)\n\n\t\tgo l.logPluginMessages(pluginOutput)\n\t}\n\n\tpluginTypes := map[string]plugin.Plugin{\n\t\tpluginType.Interface: pluginType.Plugin,\n\t}\n\n\tvar errbuf bytes.Buffer\n\tclient := plugin.NewClient(&plugin.ClientConfig{\n\t\tHandshakeConfig: plugins.HandshakeConfig,\n\t\tPlugins: pluginTypes,\n\t\tCmd: pluginCommand,\n\t\tLogger: logger,\n\t\tStderr: &errbuf,\n\t})\n\tcleanup := func() {\n\t\tclient.Kill()\n\t}\n\n\t// Connect via RPC\n\trpcClient, err := client.Client()\n\tif err != nil {\n\t\tcleanup()\n\t\tif stderr := errbuf.String(); stderr != \"\" {\n\t\t\terr = errors.Wrap(errors.New(stderr), err.Error())\n\t\t}\n\t\treturn nil, nil, errors.Wrapf(err, \"could not connect to the %s plugin\", l.SelectedPluginKey)\n\t}\n\n\tcleanup, err = l.setUpDebugger(client, cleanup)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"could not set up debugger for plugin\")\n\t}\n\n\t// Request the plugin\n\traw, err := rpcClient.Dispense(pluginType.Interface)\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, errors.Wrapf(err, \"could not connect to the %s plugin\", l.SelectedPluginKey)\n\t}\n\n\treturn raw, cleanup, nil\n}", "func New() mmmorty.Plugin {\n\tp := &ColorPlugin{\n\t\tmanagedRoles: map[string]bool{},\n\t}\n\treturn p\n}", "func CreateHelmPlugin(version string) jenkinsv1.Plugin {\n\tbinaries := CreateBinaries(func(p Platform) string {\n\t\treturn fmt.Sprintf(\"https://get.helm.sh/helm-v%s-%s-%s.%s\", version, strings.ToLower(p.Goos), strings.ToLower(p.Goarch), p.Extension())\n\t})\n\n\tplugin := jenkinsv1.Plugin{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: HelmPluginName,\n\t\t},\n\t\tSpec: jenkinsv1.PluginSpec{\n\t\t\tSubCommand: \"helm\",\n\t\t\tBinaries: binaries,\n\t\t\tDescription: \"helm 3 binary\",\n\t\t\tName: HelmPluginName,\n\t\t\tVersion: version,\n\t\t},\n\t}\n\treturn plugin\n}", "func Plugin() *Auth {\n\tonce.Do(func() {\n\t\tplugin = NewPlugin()\n\t})\n\treturn plugin\n}", "func NewPlugin(name string, config *common.PluginConfig) (*ipamPlugin, error) {\n\t// Setup base plugin.\n\tplugin, err := cni.NewPlugin(name, config.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Setup address manager.\n\tam, err := ipam.NewAddressManager()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create IPAM plugin.\n\tipamPlg := &ipamPlugin{\n\t\tPlugin: plugin,\n\t\tam: am,\n\t}\n\n\tconfig.IpamApi = ipamPlg\n\n\treturn ipamPlg, nil\n}", "func StartPlugin(impl ComputationImplementation) {\n\tprovider := pie.NewProvider()\n\tcomputationPlugin := &ComputationPlugin{impl, sync.RWMutex{}}\n\tif err := provider.RegisterName(\"Computation\", computationPlugin); err != nil {\n\t\tlog.Fatalf(\"failed to register computation Plugin: %s\", err)\n\t}\n\tprovider.ServeCodec(jsonrpc.NewServerCodec)\n}", "func NewInvoker(exec execer.Execer, filer snapshot.Filer, output runner.OutputCreator, tmp *temp.TempDir) *Invoker {\n\treturn &Invoker{exec: exec, filer: filer, output: output, tmp: tmp}\n}", "func New() rikka.Plugin {\n\tp := rikka.NewSimplePlugin(\"Math\")\n\tp.MessageFunc = messageFunc\n\tp.HelpFunc = helpFunc\n\treturn p\n}", "func PluginRunCommand(dockerCli command.Cli, name string, rootcmd *cobra.Command) (*exec.Cmd, error) {\n\t// This uses the full original args, not the args which may\n\t// have been provided by cobra to our caller. This is because\n\t// they lack e.g. global options which we must propagate here.\n\targs := os.Args[1:]\n\tif !pluginNameRe.MatchString(name) {\n\t\t// We treat this as \"not found\" so that callers will\n\t\t// fallback to their \"invalid\" command path.\n\t\treturn nil, errPluginNotFound(name)\n\t}\n\texename := addExeSuffix(NamePrefix + name)\n\tpluginDirs, err := getPluginDirs(dockerCli)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, d := range pluginDirs {\n\t\tpath := filepath.Join(d, exename)\n\n\t\t// We stat here rather than letting the exec tell us\n\t\t// ENOENT because the latter does not distinguish a\n\t\t// file not existing from its dynamic loader or one of\n\t\t// its libraries not existing.\n\t\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\t\tcontinue\n\t\t}\n\n\t\tc := &candidate{path: path}\n\t\tplugin, err := newPlugin(c, rootcmd.Commands())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif plugin.Err != nil {\n\t\t\t// TODO: why are we not returning plugin.Err?\n\t\t\treturn nil, errPluginNotFound(name)\n\t\t}\n\t\tcmd := exec.Command(plugin.Path, args...)\n\t\t// Using dockerCli.{In,Out,Err}() here results in a hang until something is input.\n\t\t// See: - https://github.com/golang/go/issues/10338\n\t\t// - https://github.com/golang/go/commit/d000e8742a173aa0659584aa01b7ba2834ba28ab\n\t\t// os.Stdin is a *os.File which avoids this behaviour. We don't need the functionality\n\t\t// of the wrappers here anyway.\n\t\tcmd.Stdin = os.Stdin\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\n\t\tcmd.Env = os.Environ()\n\t\tcmd.Env = append(cmd.Env, ReexecEnvvar+\"=\"+os.Args[0])\n\n\t\treturn cmd, nil\n\t}\n\treturn nil, errPluginNotFound(name)\n}", "func NewTerraformInstancePlugin(dir string) instance.Plugin {\n\tlog.Debugln(\"terraform instance plugin. dir=\", dir)\n\tlock, err := lockfile.New(filepath.Join(dir, \"tf-apply.lck\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &plugin{\n\t\tDir: dir,\n\t\tfs: afero.NewOsFs(),\n\t\tlock: lock,\n\t}\n}", "func NewShellTask(name string, cmd string, args []string) *ShellTask {\n\treturn &ShellTask{name: name, cmd: cmd, args: args}\n}", "func Plugin(replayLayout *device.MemoryLayout) compiler.Plugin {\n\treturn &replayer{replayLayout: replayLayout}\n}", "func New(_ runtime.Object, h framework.Handle) (framework.Plugin, error) {\n\treturn &PodState{handle: h}, nil\n}", "func NewPluginHTTP() PluginHTTP {\n\tpf := PluginHTTP{}\n\n\treturn pf\n}", "func (o *EditorPlugin) GetScriptCreateDialog() ScriptCreateDialogImplementer {\n\t//log.Println(\"Calling EditorPlugin.GetScriptCreateDialog()\")\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(\"EditorPlugin\", \"get_script_create_dialog\")\n\n\t// Call the parent method.\n\t// ScriptCreateDialog\n\tretPtr := gdnative.NewEmptyObject()\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 := newScriptCreateDialogFromPointer(retPtr)\n\n\t// Check to see if we already have an instance of this object in our Go instance registry.\n\tif instance, ok := InstanceRegistry.Get(ret.GetBaseObject().ID()); ok {\n\t\treturn instance.(ScriptCreateDialogImplementer)\n\t}\n\n\t// Check to see what kind of class this is and create it. This is generally used with\n\t// GetNode().\n\tclassName := ret.GetClass()\n\tif className != \"ScriptCreateDialog\" {\n\t\tactualRet := getActualClass(className, ret.GetBaseObject())\n\t\treturn actualRet.(ScriptCreateDialogImplementer)\n\t}\n\n\treturn &ret\n}", "func New(name string, shortHelp string, longHelp string, flagFn func(*flag.FlagSet), runFn func(*flag.FlagSet) error) *Subcommand {\n\treturn defaultRegistry.new(name, shortHelp, longHelp, flagFn, runFn)\n}", "func New(config config.Config) Plugins {\n\tpkg := Plugins{\n\t\tclient: http.NewClient(config),\n\t\tpager: &http.LinkHeaderPager{},\n\t}\n\n\treturn pkg\n}", "func NewRemote(endpoint string) model.SecretService {\n\treturn &plugin{endpoint}\n}", "func New() *AttestorPlugin {\n\treturn &AttestorPlugin{}\n}", "func NewPluginMount(description string, destination string, name string, options []string, settable []string, source string, type_ string) *PluginMount {\n\tthis := PluginMount{}\n\tthis.Description = description\n\tthis.Destination = destination\n\tthis.Name = name\n\tthis.Options = options\n\tthis.Settable = settable\n\tthis.Source = source\n\tthis.Type = type_\n\treturn &this\n}", "func (p *Plugins) ParsePlugin(name, tag string) (*Plugin, error) {\n\tscript := `\n\tvar plugin = require('` + name + `')\n\tvar pjson = require('` + name + `/package.json')\n\n\tplugin.name = pjson.name\n\tplugin.version = pjson.version\n\n\tconsole.log(JSON.stringify(plugin))`\n\tcmd, done := p.RunScript(script)\n\tcmd.Stderr = Stderr\n\toutput, err := cmd.Output()\n\tdone()\n\n\tif err != nil {\n\t\treturn nil, merry.Errorf(\"Error installing plugin %s\", name)\n\t}\n\tvar plugin Plugin\n\tplugin.UpdatedAt = time.Now()\n\tplugin.Tag = tag\n\terr = json.Unmarshal(output, &plugin)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error parsing plugin: %s\\n%s\\n%s\\nIs this a real CLI plugin?\", name, err, string(output))\n\t}\n\tif len(plugin.Commands) == 0 {\n\t\treturn nil, fmt.Errorf(\"Invalid plugin. No commands found.\")\n\t}\n\tfor _, command := range plugin.Commands {\n\t\tif command == nil {\n\t\t\tcontinue\n\t\t}\n\t\tcommand.Plugin = plugin.Name\n\t\tcommand.Help = strings.TrimSpace(command.Help)\n\t}\n\tp.addToCache(&plugin)\n\treturn &plugin, nil\n}", "func (fe *fakeExec) ExecPlugin(_ context.Context, _ string, _ []byte, _ []string) ([]byte, error) {\n\treturn []byte(\"{}\"), nil\n}", "func NewConfigPluginCmd(opt *common.CommonOption) (cmd *cobra.Command) {\n\tcmd = &cobra.Command{\n\t\tUse: \"plugin\",\n\t\tShort: i18n.T(\"Manage plugins for jcli\"),\n\t\tLong: i18n.T(`Manage plugins for jcli\nIf you want to submit a plugin for jcli, please see also the following project.\nhttps://github.com/jenkins-zh/jcli-plugins`),\n\t\tAnnotations: map[string]string{\n\t\t\tcommon.Since: common.VersionSince0028,\n\t\t},\n\t}\n\n\tcmd.AddCommand(NewConfigPluginListCmd(opt),\n\t\tNewConfigPluginFetchCmd(opt),\n\t\tNewConfigPluginInstallCmd(opt),\n\t\tNewConfigPluginUninstallCmd(opt))\n\treturn\n}" ]
[ "0.6923861", "0.67561084", "0.6359121", "0.61285865", "0.6120209", "0.60953575", "0.6039016", "0.603275", "0.6027231", "0.5947812", "0.58890504", "0.58455384", "0.57837903", "0.57665294", "0.5712567", "0.57066154", "0.57032096", "0.569763", "0.5669368", "0.5662032", "0.56253535", "0.56097054", "0.56068695", "0.56017363", "0.55927765", "0.54480845", "0.5439048", "0.5439048", "0.5432084", "0.54320645", "0.53885067", "0.537175", "0.53716254", "0.53492785", "0.5334505", "0.53322965", "0.5328991", "0.5328877", "0.53238153", "0.5298432", "0.5292139", "0.529065", "0.52802247", "0.52665627", "0.5242141", "0.52418566", "0.5239994", "0.5228325", "0.5224806", "0.52093524", "0.5172298", "0.5161111", "0.51446176", "0.5144464", "0.5134146", "0.5134146", "0.509478", "0.50835544", "0.5077433", "0.5060913", "0.5055216", "0.50548387", "0.50459605", "0.5043772", "0.5043745", "0.5039934", "0.5027679", "0.5024225", "0.5008268", "0.50045353", "0.5001735", "0.49186376", "0.4905454", "0.4904314", "0.49012852", "0.48961458", "0.4884418", "0.4869787", "0.48595646", "0.48568055", "0.48526627", "0.48445818", "0.48052102", "0.4787707", "0.4783962", "0.4777129", "0.47721052", "0.47659644", "0.4753063", "0.47409284", "0.47407937", "0.47335935", "0.4724828", "0.47186738", "0.47165123", "0.47111273", "0.4702702", "0.46852177", "0.46775743", "0.46712273" ]
0.7514004
0
the service or tester wants to create a Raft server. the ports of all the Raft servers (including this one) are in peers[]. this server's port is peers[me]. all the servers' peers[] arrays have the same order. persister is a place for this server to save its persistent state, and also initially holds the most recent saved state, if any. applyCh is a channel on which the tester or service expects Raft to send ApplyMsg messages. Make() must return quickly, so it should start goroutines for any longrunning work.
func getSleepTime() time.Duration { return time.Duration(150+rand.Int31n(200)) * time.Millisecond }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 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\trf.applyChan = applyCh\n\n\t// Your initialization code here (2A, 2B, 2C).\n\tDPrintf(\"Peer-%d begins to initialize.\\n\", rf.me)\n\trf.currentTerm = 0\n\trf.voteFor = -1\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.state = Follower\n\ttimeout := RaftElectionTimeout\n\trf.heartbeatInterval = time.Duration(timeout / 2)\n\trf.electionTimeout = time.Duration(timeout)\n\trf.eventChan = make(chan Event, 1) // heartbeat should have 1 entry for message, this can void deadlock.\n\trf.log = make([]LogEntry, 1)\n\trf.nextIndex = make(map[int]int)\n\trf.matchIndex = make(map[int]int)\n\trf.maxAttempts = 3\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t// init nextIndex and matchIndex\n\tlogSize := len(rf.log)\n\tfor key, _ := range rf.peers {\n\t\trf.nextIndex[key] = logSize\n\t\trf.matchIndex[key] = 0\n\t}\n\n\tDPrintf(\"Peer-%d is initialized. log=%v, term=%d, leader=%d\\n\", rf.me, rf.log, rf.currentTerm, rf.state)\n\n\t// start services.\n\tDPrintf(\"Peer-%d start services\\n\", rf.me)\n\tgo rf.electionService()\n\tgo rf.applyService()\n\tgo rf.logSyncService()\n\n\t// for rf.state != End {\n\t// \tsleep(1000)\n\t// }\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n persister *Persister, applyCh chan ApplyMsg) *Raft {\n\n rf := &Raft{}\n rf.peers = peers\n rf.persister = persister\n rf.me = me\n rf.applyCh = applyCh\n\n const Log_CAPACITY int = 100\n rf.initRaftNodeToFollower(Log_CAPACITY)\n\n // initialize from state persisted before a crash\n rf.readPersist(persister.ReadRaftState())\n\n go rf.electionTimeoutListener()\n\n return rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\n\trf.peers = peers\n\trf.Persister = persister\n\trf.me = me\n\n\t// Your initialization code here (2A, 2B, 2C).\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.transitionToFollower(0, -1)\n\trf.applyCh = applyCh\n\n\trf.electionTimerReset = make(chan bool, 100)\n\n\trf.killCh = make(chan bool)\n\trf.ApplyCond = sync.NewCond(&rf.mu)\n\n\t// init persist fields (only for no raftState persist)\n\t// it should be ok not to init, but for consistency\n\trf.snapshotIndex = 0\n\trf.snapshotTerm = 0\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\trf.setCommitIndexAndApplyStateMachine(rf.snapshotIndex)\n\tPanicIfF(rf.snapshotIndex > rf.commitIndex, \"should not happen\")\n\tAssertF(rf.snapshotIndex <= rf.commitIndex,\n\t\t\"rf.snapshotIndex {%d} <= rf.commitIndex {%d}\",\n\t\trf.snapshotIndex, rf.commitIndex)\n\n\tRaftDebug(\"Started server\", rf)\n\n\t// debug only\n\trf.nanoSecCreated = time.Now().UnixNano()\n\n\tgo rf.electionDaemonProcess()\n\tgo rf.applyDaemonProcess()\n\tgo rf.periodicDump()\n\tgo rf.heartbeatDaemonProcess()\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\n\trf.mu.Lock()\n\n\t// default initial state for all servers\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\trf.state = Follower\n\trf.votedFor = -1\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\t// default initial state for leader\n\tfor range rf.peers {\n\t\trf.nextIndex = append(rf.nextIndex, 1)\n\t\trf.matchIndex = append(rf.matchIndex, 0)\n\t}\n\n\t// set election timeout randomly\n\trf.electionTimeout = GetRandomElectionTimeout()\n\n\t// for passing info about commits\n\trf.applyCh = applyCh\n\n\trf.mu.Unlock()\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t// start election timeout check - server can't be a leader when created\n\tgo rf.heartbeatTimeoutCheck()\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{\n\t\tmu: sync.Mutex{},\n\t\tpeers: peers,\n\t\tPersister: persister,\n\n\t\tme: me,\n\t\tdead: 0,\n\t\tVoteFor: -1,\n\t\tTerm: 0,\n\t\tCommitIndex: -1,\n\t\tappliedLast: -1,\n\t\tLog: nil,\n\t\tnextIndex: make([]int, len(peers)),\n\t\tmatchIndex: make([]int, len(peers)),\n\t\tlastReceiveHeartBeat: time.Now(),\n\t\tstate: Follower,\n\t\tapplyCh: applyCh,\n\t\tLastIncludedIndex: -1,\n\t\tLastIncludedTerm: 0,\n\t\tappendEntryCh: make(chan bool),\n\t\tfollowerTime: make(map[int]time.Time),\n\t}\n\tfor i, _ := range rf.peers {\n\t\tif i != rf.me {\n\t\t\trf.followerTime[i] = time.Now()\n\t\t}\n\t}\n\tserverNum := len(rf.peers)\n\tif serverNum%2 == 1 {\n\t\trf.majorityNum = serverNum/2 + 1\n\t} else {\n\t\trf.majorityNum = serverNum / 2\n\t}\n\trf.readPersist(persister.ReadRaftState()) // warn rf restart ,restore persistent\n\tDPrintf(\"rf [%v] restart detail : %v\", rf.me, rf)\n\tgo rf.initialServer()\n\tgo rf.doSendHeartBeat()\n\t// Your initialization code here (2A, 2B, 2C).\n\t//fmt.Printf(\"rf initialize begin\")\n\t// initialize from state persisted before a crash\n\n\treturn rf\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\n\trf.currentTerm = 0\n\trf.voteFor = VOTENULL\n\trf.logOfRaft = make([]LogOfRaft, 0)\n\trf.logOfRaft = append(rf.logOfRaft, LogOfRaft{0, 0, nil})\n\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\trf.state = Follower\n\n\trf.heartbeatInterval = time.Duration(HeartbeatInteval) * time.Millisecond\n\n\trf.grantVoteCh = make(chan bool, 1)\n\trf.appendEntryCh = make(chan bool, 1)\n\trf.leaderCh = make(chan bool, 1)\n\trf.exitCh = make(chan bool, 1)\n\n\trf.applyCh = applyCh\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t//log.Printf(\" %v is start, its currentTerm is %v, votefor is %v, log is %v\", rf.me, rf.currentTerm, rf.voteFor, rf.logOfRaft)\n\n\tgo func() {\n\t\tfor {\n\t\t\tDPrintf(\" %v is alive and its state is %v\", rf.me, rf.state)\n\t\t\tselect {\n\t\t\tcase <-rf.exitCh:\n\t\t\t\tDPrintf(\" Exit Server(%v)\", rf.me)\n\t\t\t\tlog.Printf(\" Exit Server(%v)\", rf.me)\n\t\t\t\treturn\n\n\t\t\t\t//break\n\t\t\tdefault:\n\t\t\t}\n\t\t\telectionTimeout := GetRandomElectionTimeout()\n\t\t\trf.mu.Lock()\n\t\t\tstate := rf.state\n\t\t\t//log.Printf(\" Server(%d) state:%v, electionTimeout:%v\", rf.me, state, electionTimeout)\n\t\t\trf.mu.Unlock()\n\n\t\t\tswitch state {\n\t\t\tcase Follower:\n\t\t\t\tselect {\n\t\t\t\tcase <-rf.appendEntryCh:\n\t\t\t\tcase <-rf.grantVoteCh:\n\t\t\t\tcase <-time.After(electionTimeout):\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\trf.convertToCandidate()\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t}\n\t\t\tcase Candidate:\n\t\t\t\tgo rf.leaderElection()\n\t\t\t\tselect {\n\t\t\t\tcase <-rf.appendEntryCh:\n\t\t\t\tcase <-rf.grantVoteCh:\n\t\t\t\tcase <-rf.leaderCh:\n\t\t\t\tcase <-time.After(electionTimeout):\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\trf.convertToCandidate()\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t}\n\t\t\tcase Leader:\n\t\t\t\trf.startAppendEntries()\n\t\t\t\ttime.Sleep(rf.heartbeatInterval)\n\t\t\t}\n\n\t\t}\n\t}()\n\n\treturn rf\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.\n\trf.state = STATE_FOLLOWER\n\trf.currentTerm = 0\n\trf.voteFor = -1\n\trf.log = append(rf.log, logEntries{Term: 0})\n\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\trf.chanBecomeLeader = make(chan int, 100)\n\trf.chanCommit = make(chan int, 100)\n\trf.chanHeartBeat = make(chan int, 100)\n\trf.chanVoteOther = make(chan int, 100)\n\trf.chanApply = applyCh\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\tgo rf.working()\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-rf.chanCommit:\n\t\t\t\trf.mtx.Lock()\n\t\t\t\tcommitIndex := rf.commitIndex\n\t\t\t\tfor i := rf.lastApplied + 1; i <= commitIndex; i++ {\n\t\t\t\t\tmsg := ApplyMsg{CommandIndex: i, Command: rf.log[i].Log, CommandValid: true}\n\t\t\t\t\tapplyCh <- msg\n\t\t\t\t\trf.lastApplied = i\n\t\t\t\t}\n\t\t\t\trf.mtx.Unlock()\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn rf\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 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\trf.applyCh = applyCh\n\n\t// Initialize from state persisted before a crash.\n\trf.readPersist(persister.ReadRaftState())\n\n\t// Initialize the other state values.\n\trf.commitIndex = -1\n\trf.lastApplied = -1\n\trf.nextIndex = make([]int, len(rf.peers))\n\trf.matchIndex = make([]int, len(rf.peers))\n\trf.isLeader = false\n\n\t// Heartbeat to be sent every 150 ms (since no more than 10 per second)\n\t// Thus, eleaction timout should be randomly chosen each time between\n\t// (200-900 ms); need to elect a leader within 5 secs.\n\trand.Seed(int64(rf.me*100000 + 10000))\n\trf.electionTimeoutVal = 200 + rand.Intn(700)\n\trf.electionTimeout = time.NewTimer(time.Millisecond *\n\t\ttime.Duration(rf.electionTimeoutVal))\n\n\trf.killAllGoRoutines = false\n\tgo rf.sendHeartbeat()\n\tgo rf.electLeader()\n\tgo rf.applyMsg()\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\n\trf := &Raft{}\n\trf.peers = peers\n\n\trf.persister = persister\n\trf.me = me\n\n\t// Your initialization code here (2A, 2B, 2C).\n\trf.state = FOLLOWER\n\trf.votedFor = -1\n\trf.log = make([]LogEntry, 1) //[]LogEntry{{0, nil}} // first index is 1, first term is also 1 , {LogTerm, Command}\n\trf.currentTerm = 0\n\n\t//rf.leaderCh = make(chan interface{})\n\t//rf.commitCh = make(chan interface{})\n\n\t//rf.electionTimerResetChan = make(chan bool)\n\t//rf.heartbeatResetChan = make(chan bool)\n\t// nextIndex和matchIndex只有leader用\n\trf.nextIndex = make([]int, len(peers))\n\tfor i := range rf.nextIndex {\n\t\trf.nextIndex[i] = rf.getLastIndex() + 1\n\t}\n\trf.matchIndex = make([]int, len(peers))\n\n\trf.applyCh = applyCh\n\n\trf.lastApplied = 0\n\trf.commitIndex = 0\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t// Modify Make() to create a background goroutine that will kick off leader election\n\t// periodically by sending out RequestVote RPCs when it hasn't heard from another peer for a while.\n\t// This way a peer will learn who is the leader, if there is already a leader, or become the leader itself.\n\n\trf.electionTimer = time.NewTimer(rf.getRandomElectionTimeOut())\n\trf.heartbeatTimer = time.NewTimer(HeartbeatInterval)\n\trf.stopCh = make(chan struct{})\n\trf.notifyApplyCh = make(chan struct{})\n\tgo func() {\n\n\t\tfor !rf.killed() {\n\n\t\t\tselect {\n\t\t\tcase <-rf.electionTimer.C:\n\t\t\t\trf.lock(\"electionTimer\")\n\n\t\t\t\tif rf.state == LEADER {\n\t\t\t\t\trf.unlock(\"electionTimer1\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif rf.state == FOLLOWER || rf.state == CANDIDATE {\n\t\t\t\t\t//DPrintf(\"ElectionTimer time out\")\n\t\t\t\t\trf.convertTo(CANDIDATE)\n\t\t\t\t\t// when the raft server becomes candidate\n\t\t\t\t\t// we should put the currentTerm update\n\t\t\t\t\t// and votedFor update in broadcastAppendEntries\n\t\t\t\t\t// or we have not time to win in the split vote\n\t\t\t\t\t// situation\n\n\n\t\t\t\t}\n\t\t\t\trf.unlock(\"electionTimer\")\n\n\t\t\tcase <-rf.heartbeatTimer.C:\n\t\t\t\trf.lock(\"heartbeatTimer\")\n\n\t\t\t\tif rf.state == LEADER {\n\t\t\t\t\t// rf.heartbeatTimer.Stop()\n\t\t\t\t\trf.stop(rf.heartbeatTimer)\n\t\t\t\t\trf.heartbeatTimer.Reset(HeartbeatInterval)\n\t\t\t\t\tgo rf.broadcastAppendEntries(rf.currentTerm)\n\t\t\t\t}\n\t\t\t\trf.unlock(\"heartbeatTimer\")\n\n\t\t\tcase <-rf.stopCh:\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor !rf.killed() {\n\t\t\tselect {\n\t\t\tcase <-rf.notifyApplyCh:\n\t\t\t\tgo rf.updateLastApplied()\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int, persister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\trf.lock() // i don't think this matters but i'm not taking chances\n\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\trf.isAlive = true\n\trf.applyCh = applyCh\n\n\trf.toApply = make(chan bool)\n\trf.becomeLeader = make(chan int)\n\trf.becomeFollower = make(chan bool)\n\n\trf.VotedFor = -1\n\trf.Log = makeEmptyLogOne()\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.CurrentElectionState = Follower\n\trf.candidateDeclareTime = time.Now().Add(getElectionTimeout())\n\trf.CurrentTerm = 0\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t// store the state in case we crash immediately\n\trf.writePersist()\n\n\tgo rf.ElectionThread()\n\tgo rf.HeartbeatThread()\n\tgo rf.ApplierThread()\n\n\trf.unlock()\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\n\trf := &Raft{\n\t\tpeers: peers,\n\t\tpersister: persister,\n\t\tme: me,\n\t\tstate: follower,\n\t\tcurrentTerm: 0,\n\t\tvotedFor: -1,\n\t\tlog: []LogEntry{{\n\t\t\tEntry: 0,\n\t\t\tTerm: 0,\n\t\t}},\n\t\tcommitIndex: 0,\n\t\tlastApplied: 0,\n\t\theartBeatTimer: time.Millisecond * 100,\n\t\tappendLogCh: make(chan struct{}),\n\t\tvoteCh: make(chan struct{}),\n\t\tkillChan: make(chan struct{}),\n\t\tapplyChan: applyCh,\n\t\tlastIncludedIndex: 0,\n\t\tlastIncludedTerm: 0,\n\t}\n\n\t// Your initialization code here (2A, 2B, 2C).\n\n\trand.Seed(time.Now().UnixNano())\n\trf.resetElectionTimer()\n\n\trf.readPersist(persister.ReadRaftState())\n\n\t// initialize from state persisted before a crash\n\tDPrintln(\"test is starting server \", me, \"log length\", rf.getLogLen(), \"last log entry\", rf.getLogEntry(rf.getLastLogIndex()),\n\t\t\"term\", rf.currentTerm, \" commitIndex\", rf.commitIndex,\n\t\t\"last applied\", rf.lastApplied, \"lastIncludedIndex\", rf.lastIncludedIndex,\n\t\t\"lastIncluded Term\", rf.lastIncludedTerm)\n\tgo rf.Run(me, peers)\n\n\treturn rf\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\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\trf.Cond = sync.NewCond(&rf.mu)\n\trf.currentTerm = 0\n\trf.votedFor = nil\n\trf.event = unknown\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.servers = len(peers)\n\trf.nextIndex = make([]int, rf.servers)\n\trf.matchIndex = make([]int, rf.servers)\n\trf.log = make([]Entry, 1)\n\trf.log[0] = Entry{0,0}\n\n\trf.stateChange = make(chan bool)\n\trf.rpcCh = make(chan int)\n\trf.expire = make(chan bool)\n\trf.voteCh = make(chan bool)\n\trf.eAppended = make(chan bool)\n\n\tgo func(applyCh chan ApplyMsg) {\n\t\tfor {\n\t\t\trf.state = follower\n\t\t\ttimer := rand.Intn(150) + 200\n\n\t\t\t/*default action for every server*/\n\t\t\tgo rf.handleLogEntries()\n\n\t\t\tgo rf.handlesignals()\n\t\t\t/*real raft life*/\n\t\t\trf.Run(timer)\n\t\t}\n\t}(applyCh)\n\treturn rf\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\trf.applyCh = applyCh\n\n\t// Your initialization code here (2A, 2B, 2C).\n\trf.isLeader = false\n\trf.VotedFor = -1\n\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\trf.Logs = make([]LogEntry, 1)\n\trf.Logs[0] = LogEntry{\n\t\tTerm:0,\n\t\tCommand:nil,\n\t}\n\trf.shutdown = make(chan struct{})\n\tfor i := 0; i < len(peers); i++ {\n\t\trf.nextIndex[i] = len(rf.Logs)\n\t}\n\trf.resetTimer = make(chan struct{})\n\trf.commitCond = sync.NewCond(&rf.mu)\n\trf.newEntryCond = make([]*sync.Cond, len(peers))\n\tfor i := 0; i < len(peers); i++ {\n\t\trf.newEntryCond[i] = sync.NewCond(&rf.mu)\n\t}\n\trf.electionTimeout = time.Millisecond * (400 +\n\t\ttime.Duration(rand.Int63() % 400))\n\trf.electionTimer = time.NewTimer(rf.electionTimeout)\n\n\trf.hearBeatInterval = time.Millisecond * 200\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\tgo rf.electionDaemon()\n\n\tgo rf.applyEntryDaemon()\n\treturn rf\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.\n\trf.appliedCond = sync.NewCond(&rf.mu)\n\n\trf.applyCh = applyCh\n\trf.currentTerm = 0\n\trf.votedFor = 0\n\trf.lastIncludedIndex = 0\n\trf.log = append(rf.log, LogEntry{Term: 0})\n\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\trf.serverState = Follower\n\trf.hasHeartbeat = false\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\trf.commitIndex = rf.lastIncludedIndex\n\trf.lastApplied = rf.lastIncludedIndex\n\n\tgo rf.elect()\n\n\tgo func() {\n\t\trf.mu.Lock()\n\t\tfor {\n\t\t\tfor rf.lastApplied+1 <= rf.commitIndex {\n\t\t\t\tlogEntry := rf.log[rf.lastApplied+1-rf.lastIncludedIndex]\n\t\t\t\tapplyMsg := ApplyMsg{\n\t\t\t\t\tIndex: rf.lastApplied + 1,\n\t\t\t\t\tCommand: logEntry.Command}\n\t\t\t\trf.lastApplied++\n\t\t\t\trf.mu.Unlock()\n\t\t\t\trf.applyCh <- applyMsg\n\t\t\t\trf.mu.Lock()\n\t\t\t}\n\t\t\trf.appliedCond.Wait()\n\t\t}\n\t}()\n\n\treturn rf\n}", "func Make(peers rpc.Peers, me int,\n\tpersister data.Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\trf.applyCh = applyCh\n\t// The server initialize as a Follower\n\trf.snapshotApplyChan = make(chan []byte)\n\trf.snapshotChan = make(chan bool)\n\trf.state = Follower\n\trf.stateCond = sync.NewCond(&rf.mu)\n\trf.commitCond = sync.NewCond(&rf.mu)\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister)\n\n\tgo rf.hearBeat()\n\tgo rf.electionTimeout()\n\tgo rf.commitLogs()\n\n\treturn rf\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\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.electionTimer = time.NewTimer(0)\n\t//first index is 1?\n\trf.applyCh = applyCh\n\trf.log = []LogEntries{LogEntries{0, 0}}\n\n\t//rf.applyCh <- ApplyMsg{true, 0, 0}\n\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\trf.nextIndex = make([]int, len(rf.peers))\n\trf.matchIndex = make([]int, len(rf.peers))\n\n\trf.resetLeaderNextIndex()\n\trf.resetLeaderMatchIndex()\n\n\trf.raftState = Follower\n\trf.killHeartBeatLoop = make(chan struct{}, 1)\n\trf.killElectionEventLoop = make(chan struct{}, 1)\n\n\t//may be need modification later\n\trf.lastIncludedIndex = 0\n\trf.lastIncludedTerm = 0\n\n\trf.notifyApplyCh = make(chan struct{}, 100)\n\trf.shutdownApply = make(chan struct{}, 1)\n\n\tgo rf.leaderElectionEventLoop()\n\tgo rf.heartbeatEventLoop()\n\tgo rf.apply()\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(rf.persister.ReadRaftState())\n\tDPrintf(\"after readPersist me is %v rf lastindex is %v commitindex is %v log is %v \",\n\t\trf.me, rf.lastIncludedIndex, rf.commitIndex, rf.log)\n\treturn rf\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\trf.mu = sync.Mutex{}\n\n\t// Your initialization code here (2A, 2B, 2C).\n\tstate := Follower\n\trf.state = &state\n\trf.currentTerm = 0\n\trf.votedFor = \"\"\n\t// init the log entries\n\trf.logEntries = []LogEntry{\n\t\t{\n\t\t\tIndex: 0,\n\t\t\tTerm: 0,\n\t\t},\n\t}\n\trf.heartBeatCh = make(chan bool)\n\trf.grantCh = make(chan bool)\n\trf.heartBeatInterval = time.Millisecond * 150\n\trf.electionTimeout = 2 * rf.heartBeatInterval\n\trf.electAsLeaderCh = make(chan bool)\n\trf.peerId = strconv.Itoa(rf.me)\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\trf.applyCh = applyCh\n\n\tgo rf.applyEntries()\n\n\t// start ticker goroutine to start elections\n\tgo rf.runServer()\n\n\treturn rf\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\trf.n = len(peers)\n\trf.currentState = StateFollower\n\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.logs = make([]LogEntry, 1)\n\trf.logs[0] = LogEntry{\n\t\tTerm: 0,\n\t\tType: NoOp,\n\t\tCommand: nil,\n\t}\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.resetElectionChan = make(chan int)\n\trf.numberOfGrantedVotes = 0\n\trf.nextIndex = make([]int, rf.n)\n\tfor i := range rf.nextIndex {\n\t\trf.nextIndex[i] = 1\n\t}\n\trf.matchIndex = make([]int, rf.n)\n\n\trf.appendEntriesReplyHandler = make(chan AppendEntriesReply)\n\trf.stopLeaderLogicHandler = make(chan int)\n\trf.requestVoteReplyHandler = make(chan RequestVoteReply)\n\n\t// Your initialization code here (2A, 2B, 2C).\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t// start ticker goroutine to start elections\n\tgo rf.ticker()\n\n\tDPrintf(\"Raft node (%v) starts up...\\n\", me)\n\treturn rf\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\t//rf.leaderId = -1\n\trf.cmtChan = make(chan bool, MAX_CHAN_DEPTH)\n\trf.applyChan = applyCh\n\t\n\t//initialization\n\trf.electTimer = time.NewTimer(TIMEOUT_MAX * time.Millisecond)\n\trf.state = FOLLOWER\n\trf.voteCnt = 0\n\trf.cmtIdx = 0\n\trf.applyIdx = 0\n\trf.nextIdx = make([]int, len(rf.peers)) //initialize when become leader\n\trf.matchIdx = make([]int, len(rf.peers))\n\tfor i := range rf.matchIdx {\n\t rf.matchIdx[i] = 0\n\t}\n\t// initialize from state persisted before a crash\n\trf.curTerm = 0\n\trf.votedFor = -1\n\trf.log = make([]LogEntry, 0)\n\trf.log = append(rf.log, LogEntry{Term: 0})\n\trf.readPersist(persister.ReadRaftState())\n\t\n\tgo rf.writeApplyCh()\n\tgo rf.run()\n\t\n\treturn rf\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\n\trf.votedFor = -1\n\trf.state = FOLLOWER\n\n\trf.logs = append(rf.logs, LogEntry{Term:0}) // add dummy\n\trf.currentTerm = 0\n\trf.heartBeatChan = make(chan bool, 100)\n\trf.leaderChan = make(chan bool, 100)\n\trf.voteChan = make(chan bool, 100)\n\trf.commitChan = make(chan bool, 100)\n\trf.chanApply = applyCh\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\trf.readSnapshot(persister.ReadSnapshot())\n\n\tDPrintf(\"[init] server %v(%p) initialization. %+v\", rf.me, rf, rf)\n\n\t// background go routine to track raft state\n\tgo func() {\n\t\tfor {\n\t\t\tswitch rf.state {\n\t\t\tcase FOLLOWER:\n\t\t\t\tselect {\n\t\t\t\tcase <- rf.heartBeatChan:\n\t\t\t\t\tDPrintf(\"[heartbeat]: server %v(%p) receive heartbeat. term: %v\", rf.me, rf, rf.currentTerm)\n\t\t\t\tcase <- rf.voteChan:\n\t\t\t\tcase <- time.After(time.Duration(rand.Int63() % 333 + 550) * time.Millisecond):\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\trf.state = CANDIDATE\n\t\t\t\t\tDPrintf(\"[state change]: server %v(%p), from FOLLOWER become a CANDIDATE. term: %v\", rf.me, rf, rf.currentTerm)\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t}\n\t\t\tcase CANDIDATE:\n\t\t\t\trf.mu.Lock()\n\t\t\t\trf.currentTerm++\n\t\t\t\trf.votedFor = me\n\t\t\t\trf.voteCounter = 1\n\t\t\t\trf.persist()\n\t\t\t\trf.mu.Unlock()\n\n\t\t\t\tDPrintf(\"[report]: server %v(%p) is CANDIDATE. term: %v\", rf.me, rf, rf.currentTerm)\n\n\t\t\t\tgo rf.broadcastVoteReq()\n\n\t\t\t\tselect {\n\t\t\t\tcase <- rf.heartBeatChan:\n\t\t\t\t\t//rf.mu.Lock()\n\t\t\t\t\trf.state = FOLLOWER\n\t\t\t\t\tDPrintf(\"[state change]: server %v(%p), CANDIDATE receive heartbeat, become a FOLLOWER. term: %v\", rf.me, rf, rf.currentTerm)\n\t\t\t\t\t//rf.mu.Unlock()\n\t\t\t\tcase <- rf.leaderChan:\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\trf.state = LEADER\n\t\t\t\t\trf.nextIndex = make([]int, len(rf.peers))\n\t\t\t\t\trf.matchIndex = make([]int, len(rf.peers))\n\t\t\t\t\t// 初始化每个follower的log匹配信息\n\t\t\t\t\tfor i := range rf.peers {\n\t\t\t\t\t\trf.nextIndex[i] = rf.getLastLogIndex() + 1\n\t\t\t\t\t\trf.matchIndex[i] = 0\n\t\t\t\t\t}\n\n\t\t\t\t\tDPrintf(\"[state change]: server %v(%p), from CANDIDATE become a LEADER. term: %v\", rf.me, rf, rf.currentTerm)\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\tcase <- time.After(time.Duration(rand.Int63() % 333 + 500) * time.Millisecond):\n\t\t\t\t}\n\n\t\t\tcase LEADER:\n\t\t\t\trf.broadcastAppendEntriesReq()\n\t\t\t\ttime.Sleep(50 * time.Millisecond) // 每秒20次\n\t\t\t}\n\t\t}\n\n\n\t}()\n\n\t// commit log\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <- rf.commitChan:\n\t\t\t\trf.mu.Lock()\n\t\t\t\tcommitIndex := rf.commitIndex\n\t\t\t\tbaseIndex := rf.logs[0].Index\n\n\t\t\t\tfor i := rf.lastApplied + 1; i <= commitIndex; i++ {\n\t\t\t\t\tmsg := ApplyMsg{CommandIndex:i, Command: rf.logs[i - baseIndex].Command, CommandValid: true}\n\t\t\t\t\tDPrintf(\"[commit log]: server %v, command: %v\", rf.me, msg.Command)\n\t\t\t\t\tapplyCh <- msg\n\t\t\t\t\trf.lastApplied = i\n\t\t\t\t}\n\n\t\t\t\trf.mu.Unlock()\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn rf\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\trf.currenctTerm = 0\n\trf.votedFor = -1\n\n\trf.applyCh = applyCh\n\trf.applyCond = sync.NewCond(&rf.mu)\n\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.nextIndex = make([]int, len(rf.peers))\n\trf.matchIndex = make([]int, len(rf.peers))\n\t//rf.log = append(rf.log, logEntry{Term: -1})\n\trf.Role = \"follower\"\n\trf.log = makeEmptyLog()\n\t//rf.commitCount=make(map[int]int)\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t// apply the message to client ( from lecture)\n\tgo rf.applier()\n\t// start ticker goroutine to start elections\n\tgo rf.ticker()\n\n\treturn rf\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\trf.currentTerm = 0\n\trf.votedFor = NULL\n\trf.logEntries = make([]LogEntry, 1)\n\n\trf.state = Follower\n\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\trf.nextIndex = make([]int, len(rf.peers))\n\trf.matchIndex = make([]int, len(rf.peers))\n\n\trf.applyCh = applyCh\n\trf.leaderElected = make(chan bool)\n\trf.appendEntry = make(chan bool)\n\theartBeat := time.Duration(100)*time.Millisecond\n\t// You'll need to write code that takes actions periodically or after delays in time.\n\t// The easiest way to do this is to create a goroutine with a loop that calls time.Sleep().\n\t// Don't use Go's time.Timer or time.Ticker, which are difficult to use correctly.\n\tgo func() {\n\t\tfor {\n\t\t\tdelay := time.Duration(rand.Intn(300) + 300)*time.Millisecond\n\t\t\ttimer := time.NewTimer(delay)\n\t\t\trf.mu.Lock()\n\t\t\tstate := rf.state\n\t\t\trf.mu.Unlock()\n\t\t\tswitch state {\n\t\t\tcase Follower, Candidate:\n\t\t\t\tselect {\n\t\t\t\tcase <- timer.C:\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\trf.BeCandidate()\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\trf.StartElection()\n\t\t\t\t\t}()\n\t\t\t\tcase <- rf.leaderElected:\n\t\t\t\tcase <- rf.appendEntry:\n\n\t\t\t\t}\n\t\t\tcase Leader:\n\t\t\t\trf.StartAppendLog()\n\t\t\t\ttime.Sleep(heartBeat)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\tnPeers := len(peers)\n\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\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.logs = make([]*LogEntry, 0)\n\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\trf.nextIndex = make([]int, nPeers)\n\trf.matchIndex = make([]int, nPeers)\n\n\trf.state = Follower\n\trf.hasHeartbeat = false\n\n\trf.replicateCount = make([]int, 0)\n\trf.replicateStart = 0\n\n\trf.appliedCond = sync.NewCond(&rf.mu)\n\n\t// goroutine that track leader's heartbeat\n\tgo func(){\n\t\t// as stated in the paper, BroadcastTime << electionTimeOut\n\t\t// the example value in the paper is\n\t\t// BroadcastTime: 0.5~20 ms, electionTimeOut 150~300ms\n\t\t// since we have BroadcastTime of 0.1s, and we need to constrain\n\t\t// multiple rounds to be less than 5s\n\t\t// electionTimeOut should be 1 second-ish, i.e. 0.8 ~ 1.2 s\n\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\tvar electionTimeOut time.Duration\n\t\tStateTransition:\n\t\tfor true {\n\t\t\telectionTimeOut = (time.Duration(rand.Intn(400) + 800)) * time.Millisecond\n\t\t\tif rf.state == Leader {\n\t\t\t\tfor i := 0; i < nPeers; i++{\n\t\t\t\t\tif i == me {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\t// parameters & reply\n\t\t\t\t\tlastLogIndex := len(rf.logs)\n\t\t\t\t\tprevLogIndex := rf.nextIndex[i] - 1\n\t\t\t\t\tvar prevLogTerm int\n\t\t\t\t\tif prevLogIndex >= 1 {\n\t\t\t\t\t\tprevLogTerm = rf.logs[prevLogIndex - 1].Term\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprevLogTerm = -1\n\t\t\t\t\t}\n\t\t\t\t\targs := &AppendEntriesArgs{\n\t\t\t\t\t\tTerm: rf.currentTerm,\n\t\t\t\t\t\tLeaderId: rf.me,\n\t\t\t\t\t\tPrevLogIndex: prevLogIndex,\n\t\t\t\t\t\tPrevLogTerm: prevLogTerm,\n\t\t\t\t\t\tLeaderCommit: rf.commitIndex,\n\t\t\t\t\t}\n\t\t\t\t\treply := &AppendEntriesReply{}\n\n\t\t\t\t\tif len(rf.logs) > 0 && len(rf.logs) >= rf.nextIndex[i] {\n\t\t\t\t\t\targs.Entries = rf.logs[prevLogIndex:]\n\t\t\t\t\t\t// send AppendEntries RPC with logs\n\t\t\t\t\t\tgo func(server int){\n\t\t\t\t\t\t\tDPrintf(\"Peer %d: Sending new entries(%d ~ %d) to Peer %d\\n\", rf.me, prevLogIndex + 1, len(rf.logs), server)\n\t\t\t\t\t\t\tif ok := rf.sendAppendEntriesRPC(server, args, reply); ok {\n\t\t\t\t\t\t\t\t// term, success\n\t\t\t\t\t\t\t\tif reply.Success {\n\t\t\t\t\t\t\t\t\trf.nextIndex[server] = lastLogIndex + 1\n\t\t\t\t\t\t\t\t\trf.matchIndex[server] = lastLogIndex\n\t\t\t\t\t\t\t\t\tfor index := prevLogIndex + 1; index <= lastLogIndex; index++ {\n\t\t\t\t\t\t\t\t\t\tDPrintf(\"Peer %d: access replicateCount[%d] (replicateStart = %d)\", rf.me, index - 1 -rf.replicateStart, rf.replicateStart)\n\t\t\t\t\t\t\t\t\t\taccessIndex := index - 1 -rf.replicateStart\n\t\t\t\t\t\t\t\t\t\tif accessIndex < 0 || rf.replicateCount[accessIndex] > len(rf.peers) / 2 {\n\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\trf.replicateCount[accessIndex]++;\n\t\t\t\t\t\t\t\t\t\tif rf.replicateCount[accessIndex] > len(rf.peers) / 2 {\n\t\t\t\t\t\t\t\t\t\t\trf.commitIndex = index\n\t\t\t\t\t\t\t\t\t\t\tDPrintf(\"Peer %d: entry %d has been replicated to majority, sending apply signal\\n\", me, index)\n\t\t\t\t\t\t\t\t\t\t\trf.appliedCond.Signal()\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} else {\n\t\t\t\t\t\t\t\t\tif updated := rf.updateTerm(reply.Term); !updated {\n\t\t\t\t\t\t\t\t\t\t// rejected because log consistency\n\t\t\t\t\t\t\t\t\t\trf.nextIndex[server]--;\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} else {\n\t\t\t\t\t\t\t\t// DPrintf(\"Peer %d: Can't reach Peer %d, AppendEntries RPC returned false!\\n\", me, server)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}(i)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Send Heartbeat\n\t\t\t\t\t\t// DPrintf(\"Peer %d: Sending heartbeat to Peer %d\", rf.me, i)\n\t\t\t\t\t\tgo rf.sendAppendEntriesRPC(i, args, reply)\n\t\t\t\t\t}\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t}\n\t\t\t\ttime.Sleep(BroadcastIntv)\n\t\t\t} else if rf.state == Candidate {\n\t\t\t\trf.currentTerm++\n\t\t\t\trf.votedFor = me\n\t\t\t\tvoteCount := 1\n\t\t\t\tvoteCh := make(chan int)\n\n\t\t\t\tfor i := 0; i < nPeers; i++ {\n\t\t\t\t\tif i == me {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tgo func(server int){\n\t\t\t\t\t\tlastLogIndex := len(rf.logs)\n\t\t\t\t\t\tvar lastLogTerm int\n\t\t\t\t\t\tif lastLogIndex > 0 {\n\t\t\t\t\t\t\tlastLogTerm = rf.logs[lastLogIndex - 1].Term\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlastLogTerm = -1\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\targs := &RequestVoteArgs{\n\t\t\t\t\t\t\tTerm: rf.currentTerm,\n\t\t\t\t\t\t\tCandidateId: me,\n\t\t\t\t\t\t\tLastLogIndex: lastLogIndex,\n\t\t\t\t\t\t\tLastLogTerm: lastLogTerm,\n\t\t\t\t\t\t}\n\t\t\t\t\t\treply := &RequestVoteReply{}\n\n\t\t\t\t\t\t// Send RequestVote RPC\n\t\t\t\t\t\t// DPrintf(\"Peer %d: Sending RequestVote RPC to peer %d.\\n\", me, server)\n\t\t\t\t\t\tok := rf.sendRequestVote(server, args, reply)\n\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\trf.updateTerm(reply.VotersTerm)\n\t\t\t\t\t\t\tif reply.VoteGranted {\n\t\t\t\t\t\t\t\t// DPrintf(\"Peer %d: Receive grant vote from Peer %d.\\n\", me, server)\n\t\t\t\t\t\t\t\tvoteCh <- 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// DPrintf(\"Peer %d: Can't reach Peer %d, RPC returned false!\\n\", me, server)\n\t\t\t\t\t\t}\n\t\t\t\t\t}(i)\n\t\t\t\t}\n\n\t\t\t\ttimeOutCh := time.After(electionTimeOut)\n\t\t\t\t// DPrintf(\"Peer %d(@%s state) will wait %v for votes.\\n\", me, rf.state, electionTimeOut)\n\t\t\t\tvoteLoop:\n\t\t\t\tfor {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <- voteCh:\n\t\t\t\t\t\tvoteCount++\n\t\t\t\t\t\tif rf.state == Candidate && voteCount > nPeers / 2 {\n\t\t\t\t\t\t\tDPrintf(\"Peer %d: Received majority votes, become leader now!\\n\", me)\n\t\t\t\t\t\t\trf.state = Leader\n\t\t\t\t\t\t\t// before become a leader, init nextIndex[] and matchIndex[]\n\t\t\t\t\t\t\tfor i := 0; i < nPeers; i++ {\n\t\t\t\t\t\t\t\tcurrentIndex := len(rf.logs)\n\t\t\t\t\t\t\t\trf.nextIndex[i] = currentIndex + 1\n\t\t\t\t\t\t\t\trf.matchIndex[i] = currentIndex // optimistic guessing\n\n\t\t\t\t\t\t\t\t// replicateCount\n\t\t\t\t\t\t\t\tuncommitedLogs := len(rf.logs) - rf.commitIndex\n\t\t\t\t\t\t\t\trf.replicateCount = make([]int, uncommitedLogs, 1)\n\t\t\t\t\t\t\t\trf.replicateStart = rf.commitIndex\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak voteLoop\n\t\t\t\t\t\t}\n\t\t\t\t\tcase <- timeOutCh:\n\t\t\t\t\t\tDPrintf(\"Peer %d(@%s): Election timed out.\\n\", me, rf.state)\n\t\t\t\t\t\tbreak voteLoop\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else if rf.state == Follower {\n\t\t\t\ttime.Sleep(BroadcastIntv)\n\t\t\t\tif !rf.hasHeartbeat {\n\t\t\t\t\t// DPrintf(\"Peer %d(@%s state) hasn't receive heartbeat, will wait heartbeat for %v!\\n\", me, rf.state, electionTimeOut)\n\t\t\t\t\ttimer := time.After(electionTimeOut)\n\t\t\t\t\tStartElectionTimer:\n\t\t\t\t\tfor {\n\t\t\t\t\t\tselect{\n\t\t\t\t\t\tcase <- timer:\n\t\t\t\t\t\t\tDPrintf(\"Peer %d: Leader timed Out!\\n\", me)\n\t\t\t\t\t\t\trf.state = Candidate\n\t\t\t\t\t\t\tcontinue StateTransition\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tif rf.hasHeartbeat {\n\t\t\t\t\t\t\t\tbreak StartElectionTimer\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\trf.hasHeartbeat = false\n\t\t\t}\n\t\t}\n\t}()\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\tgo func(){\n\t\trf.mu.Lock() // 不能放在for循环里,否则循环只能执行一遍\n\t\tfor {\n\t\t\tfor rf.lastApplied < rf.commitIndex {\n\t\t\t\tindex := rf.lastApplied + 1\n\t\t\t\tapplyMsg := ApplyMsg{\n\t\t\t\t\tCommandValid: true,\n\t\t\t\t\tCommand: rf.logs[index - 1].Command,\n\t\t\t\t\tCommandIndex: index,\n\t\t\t\t}\n\t\t\t\tapplyCh <- applyMsg\n\t\t\t\trf.lastApplied = index\n\t\t\t\tvar printlog []interface{}\n\t\t\t\tfor _, v := range rf.logs {\n\t\t\t\t\tprintlog = append(printlog, v.Command)\n\t\t\t\t}\n\t\t\t\tDPrintf(\"Peer %d: applied entry %d to local state machine. logs: %v\", rf.me, index, printlog)\n\t\t\t}\n\t\t\trf.appliedCond.Wait()\n\t\t}\n\t}()\n\n\treturn rf\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\trf.role = Follower\n\trf.votedFor = -1\n\trf.nextIndex = make([]int, len(rf.peers))\n\trf.matchIndex = make([]int, len(rf.peers))\n\trf.validRpcTimestamp = time.Now()\n\trf.applyCh = applyCh\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t// Your initialization code here (2A, 2B, 2C).\n\tgo func() {\n\t\tfor {\n\t\t\trf.mu.Lock()\n\t\t\trole := rf.role\n\n\t\t\tswitch role {\n\t\t\tcase Follower:\n\t\t\t\tts := rf.validRpcTimestamp\n\t\t\t\trf.mu.Unlock()\n\t\t\t\trf.runAsFollower(ts)\n\t\t\tcase Candidate:\n\t\t\t\tlastLogIndex := len(rf.log) + rf.compactIndex\n\t\t\t\targs := &RequestVoteArgs{\n\t\t\t\t\tTerm: rf.currentTerm,\n\t\t\t\t\tCandidateID: rf.me,\n\t\t\t\t\tLastLogIndex: lastLogIndex,\n\t\t\t\t}\n\t\t\t\tif lastLogIndex > rf.compactIndex {\n\t\t\t\t\targs.LastLogTerm = rf.log[lastLogIndex - rf.compactIndex -1].Term\n\t\t\t\t}\n\t\t\t\trf.mu.Unlock()\n\t\t\t\trf.runAsCandidate(args)\n\t\t\tcase Leader:\n\t\t\t\tterm := rf.currentTerm\n\t\t\t\trf.mu.Unlock()\n\t\t\t\trf.runAsLeader(term)\n\t\t\t}\n\n\t\t\tif rf.killed() {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Wait for commitIndex to be updated.\n\tgo func() {\n\t\trf.mu.Lock()\n\t\tif rf.compactIndex != 0 {\n\t\t\tapplyCh <- ApplyMsg{\n\t\t\t\tCommandValid: false,\n\t\t\t\tSnapshot: persister.ReadSnapshot(),\n\t\t\t}\n\t\t\trf.lastApplied = rf.compactIndex\n\t\t\tDPrintf(\"instance %d after restart rf.lastApplied is %d\", rf.me, rf.lastApplied)\n\t\t}\n\t\trf.mu.Unlock()\n\n\t\tfor {\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\n\t\t\tvar (\n\t\t\t\tentries []LogEntry\n\t\t\t\trecord int\n\t\t\t)\n\t\t\trf.mu.Lock()\n\t\t\tDPrintf(\"instance %d rf.commitIndex is %d, rf.lastApplied is %d, rf.compactIndex is %d, len(rf.log) is %d\", rf.me, rf.commitIndex, rf.lastApplied, rf.compactIndex, len(rf.log))\n\t\t\tif rf.commitIndex > rf.lastApplied {\n\t\t\t\tentries = rf.log[rf.lastApplied-rf.compactIndex : rf.commitIndex-rf.compactIndex]\n\t\t\t\trecord = rf.lastApplied\n\t\t\t\trf.lastApplied = rf.commitIndex\n\t\t\t}\n\t\t\trf.mu.Unlock()\n\n\t\t\tfor i := 0; i < len(entries); i++ {\n\t\t\t\trecord = record + 1\n\t\t\t\tapplyCh <- ApplyMsg{\n\t\t\t\t\tCommandValid: true,\n\t\t\t\t\tCommand: entries[i].Command,\n\t\t\t\t\tCommandIndex: record,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif rf.killed() {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\r\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\r\n\trf := &Raft{}\r\n\trf.peers = peers\r\n\trf.persister = persister\r\n\trf.me = me\r\n\r\n\t// Your initialization code here.\r\n\trf.state = FOLLOWER\r\n\trf.votedFor = -1\r\n\trf.voteCh = make(chan struct{}) //define the v of the channal is the size of an empty struct{}\r\n\trf.appendCh = make(chan struct{})\r\n\t\r\n\t// initialize from state persisted before a crash\r\n\trf.readPersist(persister.ReadRaftState())\r\n\t\r\n\tgo rf.startLoop() // start election\r\n\r\n\r\n\treturn rf\r\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\trf.applyCh = applyCh\n\n\t// Your initialization code here (2A, 2B, 2C).\n\trf.currentTerm = 0\n\trf.votedFor = LEADER_UNKNOWN\n\n\trf.voteCount = make([]bool, len(peers))\n\tfor i := range rf.voteCount {\n\t\trf.voteCount[i] = false\n\t}\n\n\trf.gotContacted = false\n\tatomic.StoreInt32(&rf.state, FOLLOWER)\n\n\trf.log = make([]JobEntry, 1)\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\trf.lastIncludedTerm = 0\n\trf.lastIncludedIndex = 0\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\trf.snapshot = persister.ReadSnapshot()\n\n\trf.canSend = false\n\n\t// start ticker goroutine to start elections\n\tgo rf.ticker()\n\tgo rf.apply()\n\tgo rf.send()\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int, persister *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\trf.stopCh = make(chan struct{})\n\trf.applyCh = applyCh\n\trf.electionTimer = time.NewTimer(rf.randElectionTimeout())\n\trf.appendEntryTimer = make([]*time.Timer, len(peers))\n\tfor i,_ := range rf.peers {\n\t\trf.appendEntryTimer[i] = time.NewTimer(HeartBeatTimeout)\n\t}\n\n\trf.state = Follower\n\trf.currentTerm = 0\n\trf.votedFor = -1\n\t// 初始时日志长度为1\n\trf.logs = make([]LogEntry, 1)\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.lastSnapshotIndex = 0\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\t// 发起投票\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <- rf.stopCh:\n\t\t\t\treturn\n\t\t\tcase <- rf.electionTimer.C:\n\t\t\t\tgo rf.startElection()\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\n\trf := &Raft{}\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\n\t//为了高可用需要存储在稳定介质中的数据\n\trf.votedFor = -1\n\trf.status = FOLLOWER\n\trf.currentTerm = 0\n\trf.logEntries = make([]LogEntry, 0, 10)\n\trf.logEntries = append(rf.logEntries, LogEntry{Term: 0})\n\n\t// failure发生以后重新计算的数据\n\trf.commitIndex = 0\n\trf.lastApplied = 0 //状态机丢失,从头开始计算得到状态机\n\n\t//成为leader后重新计算的数据\n\trf.nextIndex = make([]int, len(peers))\n\tfor i := range rf.nextIndex {\n\t\trf.nextIndex[i] = len(rf.logEntries)\n\t}\n\trf.matchIndex = make([]int, len(peers))\n\n\t//TODO: 学习Go time包中定时器的使用\n\tduration := rf.getElectionTimeout()\n\trf.electionTimer = time.NewTimer(duration)\n\n\trf.giveVoteCh = make(chan struct{}, 1)\n\trf.heartBeatCh = make(chan struct{}, 1)\n\n\trf.revCommand = make(chan struct{}, 1) //TODO:此处是否需要使用有缓存的channel\n\trf.stop = make(chan struct{}, 1)\n\trf.stateChangeCh = make(chan struct{}, 1)\n\trf.applyCh = applyCh\n\t// Your initialization code here (2A, 2B, 2C).\n\n\tgo func() {\n\t\trf.loop()\n\t}()\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\treturn rf\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\trf.applyCh = applyCh\n\trf.candidateId = me\n\trf.votedFor = NILVOTE \n\trf.role = FOLLOWER\n\trf.currentTerm = 0\n\trf.resetTimeoutEvent = makeTimestamp()\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\tif(len(rf.log) == 0) {\n\t\tentry := Entry {0, nil, 0}\n\t\trf.log = append(rf.log, entry)\n\t\trf.persist()\n\t}\n\n\tAssert(len(rf.log) >= 1, \"raft log not bigger than 0\")\n\n\trf.nextIndex = make([]int, len(rf.peers))\n\trf.matchIndex = make([]int, len(rf.peers))\n\n\t// start ticker goroutine to start elections\n\tgo rf.ticker()\n\n\t// have the leader send heartbeats out periodically\n\tgo rf.sendHeartbeats()\n\treturn rf\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\trf.mu = sync.Mutex{}\n\trf.state = FOLLOWER\n\n\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.log = []Log{}\n\t// log index counts from 1, index 0 is filled with a fake log with term 0\n\trf.log = append(rf.log, Log{0, nil})\n\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\trf.applyCond = sync.NewCond(&rf.mu)\n\n\trf.resetTimer()\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t// start as a follower\n\tgo rf.follower()\n\n\t// start apply check as a daemon\n\tgo rf.applier(applyCh)\n\n\treturn rf\n}", "func Make(peers []*rpc.Client, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\trf.peers = peers\n\trf.me = me\n\n\trf.votedFor = -1\n\trf.termElectState = make(map[int]chan interface{})\n\trf.rpcChan = make(chan interface{}, len(peers))\n\n\trf.logs = append(rf.logs, &LogEntry{0, -1})\n\trf.nextIndexes = make([]int, len(rf.peers))\n\trf.matchIndexes = make([]int, len(rf.peers))\n\n\trf.persister = persister\n\n\trf.applyCh = applyCh\n\n\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t// Your initialization code here.\n\t// create a background goroutine that will kick off leader election\n\t// periodically by sending out RequestVote RPCs when it hasn't heard from another peer for a while.\n\tgo rf.StartPeer()\n\n\treturn rf\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\trf.ConvertTo(Follower)\n\trf.CurrentTerm = 0\n\trf.Log = []LogEntry{}\n\n\trf.CommitIndex = 0\n\trf.LastApplied = 0\n\n\trf.NextIndex = []int{}\n\trf.MatchIndex = []int{}\n\t// Your initialization code here (2A, 2B, 2C).\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\tgo rf.ticker()\n\n\t// 每个结点应当检查自己的状态,\n\t// 如果是 leader 的话,就向其他节点发送心跳包\n\tgo rf.sendHeartBeats()\n\n\treturn rf\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\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.commitIndex = -1\n\trf.lastApplied = -1\n\trf.leaderId = -1\n\n\tfor i := 0; i < len(peers); i++ {\n\t\trf.nextIndex = append(rf.nextIndex, -1)\n\t\trf.matchIndex = append(rf.matchIndex, -1)\n\t}\n\n\trf.role = FOLLOWER\n\tgo rf.electionTimer()\n\n\t// Your initialization code here (2A, 2B, 2C).\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\treturn rf\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.\n\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.log = append(rf.log, LogEntry{Term: 0, Index: 0})\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\trf.role = FOLLOWER\n\trf.timer = time.NewTimer(rf.getRandomST() * time.Millisecond)\n\n\trf.chanApply = make(chan bool)\n\trf.applyCh = applyCh\n\n\trf.readSnapshot(persister.ReadSnapshot())\n\n\tgo rf.election()\n\tgo rf.apply(applyCh)\n\n\treturn rf\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\tn := len(peers)\n\trf.App = make([] chan bool, n)\n\tfor i := range rf.App{\n\t\trf.App[i] = make(chan bool, 1)\n\t\trf.App[i] <- true\n\t}\n\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.leader = -1\n\trf.role = 0\n\trf.log = append(rf.log, LogEntry{Term:0, Index:0})\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.nextIndex = make([]int, n)\n\trf.matchIndex = make([]int, n)\n\trf.Heartbeat = make(chan bool)\n\trf.GrantVote = make(chan bool)\n\trf.roleChan = make(chan int)\n\trf.applyCh = applyCh\n\t\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\trf.readSnapshot(persister.ReadSnapshot())\n\trf.randgene()\n\tgo rf.changestatus()\n\tgo rf.timeoutTimer()\n\n\treturn rf\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//rf.alive = true\n\trf.Log = append(rf.Log, LogEntry{Term: 0, Index: 0})\n\trf.CurrentTerm = 0\n\trf.VotedFor = -1\n\trf.CommitIndex = 0\n\trf.lastApplied = 0\n\trf.identity = FOLLOWER\n\n\trf.alive = true\n\trf.ApplyChan = applyCh\n\trf.hasVoted = make(chan bool, 10)\n\trf.hasAppended = make(chan bool, 10)\n\trf.hasBecomeLeader = make(chan bool, 10)\n\trf.commitNow = make(chan bool, 10)\n\trf.lastIncludedIndex = -1\n\trf.lastIncludedTerm = -1\n\n\trf.readPersist(persister.ReadRaftState())\n\trf.readSnapshot(persister.ReadSnapshot())\n\n\tgo rf.eventloop()\n\tgo rf.commitloop()\n\n\t// initialize from state persisted before a crash\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{\n\t\tpeers: peers,\n\t\tpersister: persister,\n\t\tme: me,\n\t\tmajority: (len(peers) / 2) + 1,\n\t\tcurrentRole: Candidate,\n\t\tcurrentTerm: 0,\n\t\tvotedFor: -1,\n\t\tcommitIndex: 0,\n\t\tlastApplied: 0,\n\t\tapplyCh: applyCh,\n\t\tdebugVerbosity: getVerbosity(),\n\t\tdebugStart: time.Now(),\n\t}\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t// set log and debug details\n\tlog.SetFlags(log.Flags() &^ (log.Ldate | log.Ltime))\n\n\t// start elections after random timeout\n\tgo rf.electionTicker()\n\tgo rf.heartbeatTicker()\n\n\treturn rf\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\trf.applyCh = applyCh\n\trf.applyCond = sync.NewCond(&rf.mu)\n\trf.commitIndex = 0\n\trf.currentTerm = 0\n\trf.electionState = follower\n\trf.lastApplied = 0\n\trf.log = make([]LogEntry, 1)\n\trf.matchIndex = make([]int, len(peers))\n\trf.nextIndex = make([]int, len(peers))\n\trf.receivedHeartbeat = false\n\trf.replyCount = make(map[int]int)\n\trf.requiredReplies = int((math.Ceil(float64(len(rf.peers)) / 2)))\n\trf.timer = sync.NewCond(&rf.mu)\n\trf.votedFor = -1\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\trf.resetElectionTimer()\n\tgo rf.systemTick()\n\tgo rf.manageApply()\n\tgo rf.periodicallyCheckElectionState()\n\n\treturn rf\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 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\trf.applyCh = applyCh\n\t// Your initialization code here (2A, 2B, 2C).\n\trf.logs = []*Entry{{0, nil}}\n\n\trf.nextIndex = make([]int, len(rf.peers))\n\trf.matchIndex = make([]int, len(rf.peers))\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\trf.timer = time.NewTimer(randomTimeout())\n\trf.heartBeatsTimer = time.NewTimer(0)\n\tgo rf.electionWatcher()\n\tgo func() {\n\t\tfor range time.Tick(time.Second / 2) {\n\t\t\tif rf.killed() {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t//log.Println(rf, rf.lockLocation, \"\\t\", rf.persister.RaftStateSize())\n\t\t}\n\t}()\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{\n\t\tpeers: peers,\n\t\tpersister: persister,\n\t\tme: me,\n\t\tvotedFor: -1,\n\t\tlogs: make([]Log, 0, 10),\n\t\tapplyCh: applyCh,\n\t\tnextIndex: make([]int, len(peers)),\n\t\tmatchIndex: make([]int, len(peers)),\n\t\trpcCh: make(chan rpcCall, 10),\n\t\tcommitIndex: -1,\n\t\tlastApplied: -1,\n\t\tclose: make(chan struct{}),\n\t}\n\t// initialize from state persisted before a crash\n\trf.state.Store(follower)\n\trf.leader.Store(-1)\n\trf.currentTerm.Store(0)\n\trf.readPersist(persister.ReadRaftState())\n\tif snap := rf.persister.ReadSnapshot(); snap != nil {\n\t\trf.applyCh <- ApplyMsg{\n\t\t\tUseSnapshot: true,\n\t\t\tSnapshot: snap,\n\t\t}\n\t}\n\tgo rf.mainLoop()\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int, persister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := newRaft(peers, me, persister)\n\n\tgo rf.checkApplyLoop(applyCh)\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\treturn rf\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\trf.id = string(rune(me + 'A'))\n\n\t// Your initialization code here (2A, 2B, 2C).\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\tgo rf.startElectionProcess()\n\n\tgo rf.startLocalApplyProcess(applyCh)\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int, persister *Persister, applyCh chan ApplyMsg, gid ...int) *Raft {\n\trf := &Raft{}\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\trf.applyCh = applyCh\n\n\tif len(gid) != 0 {\n\t\trf.gid = gid[0]\n\t} else {\n\t\trf.gid = -1\n\t}\n\n\t// Your initialization code here (2A, 2B, 2C).\n\trf.currentTerm = 0\n\trf.voteFor = -1\n\trf.role = Follower\n\trf.logEntries = make([]LogEntry, 1)\n\trf.readPersist(persister.ReadRaftState())\n\n\trf.electionTimer = time.NewTimer(randElectionTimeout())\n\trf.appendEntriesTimers = make([]*time.Timer, len(rf.peers))\n\tfor i := range rf.peers {\n\t\trf.appendEntriesTimers[i] = time.NewTimer(HeartBeatTimeout)\n\t}\n\trf.applyTimer = time.NewTimer(ApplyInterval)\n\trf.notifyApplyCh = make(chan struct{}, 100)\n\n\t// apply log\n\tgo func() {\n\t\tfor !rf.killed() {\n\t\t\tselect {\n\t\t\tcase <-rf.applyTimer.C:\n\t\t\t\trf.notifyApplyCh <- struct{}{}\n\t\t\tcase <-rf.notifyApplyCh:\n\t\t\t\trf.startApplyLogs()\n\t\t\t}\n\t\t}\n\t}()\n\t// start election\n\tgo func() {\n\t\tfor !rf.killed() {\n\t\t\t<-rf.electionTimer.C\n\t\t\trf.startElection()\n\t\t}\n\t}()\n\t// leader send logs\n\tfor i := range peers {\n\t\tif i == rf.me {\n\t\t\tcontinue\n\t\t}\n\t\tgo func(index int) {\n\t\t\tfor !rf.killed() {\n\t\t\t\t<-rf.appendEntriesTimers[index].C\n\t\t\t\trf.sendAppendEntries(index)\n\t\t\t}\n\t\t}(i)\n\t}\n\n\treturn rf\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\t//rf.term=0\n\trf.me=me\n\trf.state=0//日踏大爷就是因为这个channel没有make 1卡了老子好久,不make一个数的话就在读或者写之后如果在本线程内不能写或者读就会阻塞\n\trf.last_heartbeat=make(chan int,1)//这里一定要注意!有缓冲的与有缓冲channel有着重大差别!有缓冲可以是异步的而无缓冲只能是同步的\n\trf.voted=make([]int,20000)\n\trf.log=[]Entry{}\n\trf.Last_log_index=-1\n\trf.Last_log_term=-1\n\trf.readPersist(persister.ReadRaftState())\n\trf.leaderID=-1\n\trf.applych=applyCh\n\trf.committed_index=-1\n\t//rf.chan_of_commit=make(chan bool,1)\n\tgo rf.running()\n\t//go rf.commit(applyCh)\n\treturn rf\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\trf.leader = -1\n\trf.hasLeader = false\n\n\t// Your initialization code here (2A, 2B, 2C).\n\n\trf.log = []logItem{logItem{-1, 0}} // fill in an empty log\n\n\trf.votedTerms = map[int]int{}\n\n\t// init heartbeat channel\n\trf.stopHeartbeatCh = make(chan bool)\n\n\trf.stopBroadcastLogCh = make(chan bool)\n\n\t// start election clock\n\tgo rf.startElectionTimer()\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\trf.applyCh = applyCh\n\n\treturn rf\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\trf.state = Follower\n\trf.currentTerm = 0\n\trf.votedFor = NULL\n\n\trf.log = make([]Log, 1)\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\trf.applyCh = applyCh\n\trf.voteCh = make(chan bool, 1)\n\trf.appendLogCh = make(chan bool, 1)\n\trf.killCh = make(chan bool, 1)\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\theartBeatTime := time.Duration(100) * time.Millisecond\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-rf.killCh:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t}\n\t\t\telectionTime := time.Duration(rand.Intn(200)+300) * time.Millisecond\n\t\t\trf.mu.Lock()\n\t\t\tstate := rf.state\n\t\t\trf.mu.Unlock()\n\t\t\tswitch state {\n\t\t\tcase Follower, Candidate:\n\t\t\t\tselect {\n\t\t\t\tcase <-rf.voteCh:\n\t\t\t\tcase <-rf.appendLogCh:\n\t\t\t\tcase <-time.After(electionTime):\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\trf.beCandidate()\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t}\n\t\t\tcase Leader:\n\t\t\t\trf.startAppendLog()\n\t\t\t\ttime.Sleep(heartBeatTime)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn rf\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\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\t/// Start as a follower.\n\trf.currentState = \"FOLLOWER\"\n\trf.commitIndex=1\n\trf.lastApplied=1 // Initializing this to 1 as we have added dummy 0th entry\n\trf.votedFor=-1\n\t//05/12\n\t//Let the leader start with 0. When a candidate transitions to the candidate state it increments this value.\n\trf.currentTerm=0\n\t//Initialize the log.\n\t//This is a dummy entry\n\trf.log = append(rf.log, LogEntry{LastLogTerm: 0})\n\trf.applyCh = applyCh\n\trf.debug(\"++++++++++++++++++++++++++Length of the log during initialization---> %d \\n\",len(rf.log))\n\trf.electionTimer = time.NewTimer((400 + time.Duration(rand.Intn(300))) * time.Millisecond)\n\t// Your initialization code here (2A, 2B, 2C).\n\tgo rf.conductElection()\n\t//Send heart beat to everybody else\n\treturn rf\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\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\trf.voteGranted = map[int]bool{}\n\trf.commitIndex = -1\n\trf.applyIndex = -1\n\n\trf.heartbeatTimeoutTicks = defaultHeartBeatTimeoutTicks\n\trf.becomeFollower()\n\trf.resetElectionTimeoutTicks()\n\n\trf.votedFor = -1\n\trf.term = 0\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\trf.applyCh = applyCh\n\trf.eventc = make(chan *raftEV, 1)\n\trf.quitc = make(chan struct{})\n\n\trf.routineGroup.Add(2)\n\tgo rf.loopEV()\n\tgo rf.loopTicks()\n\n\tDPrintf(\"%v raft.start\", rf.raftInfo())\n\treturn rf\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\trf.numVote = 0\n\trf.log = make([]LogItem, 0)\n\trf.votedFor = -1\n\trf.currentTerm = 0\n\trf.state = Follower\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\trf.commitIndex = -1\n\trf.lastApplied = -1\n\n\t// random generate a duration\n\t//randomTimeOut := rand.Intn(MAXELECTIONTIMEOUT - MINELECTIONTIMEOUT) + MINELECTIONTIMEOUT\n\n\t//rf.timer = time.NewTimer(time.Duration(randomTimeOut))\n\n\t// Your initialization code here (2A, 2B, 2C).\n\t// 触发一定时间内没有收到heartbeat进行选举\n\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\trf.resetTimer()\n\n\n\n\treturn rf\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.\n\n\t// -1 means no candidate you are voting for\n\trf.votedFor = -1\n\trf.state = Follower\n\trf.stateCh = make(chan int)\n\trf.currentTerm = 0\n\trf.log = make([]LogEntry, 1)\n\trf.log[0].Term = 0\n\trf.applyCh = applyCh\n\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\tgo rf.CreateCommitTimer()\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\tgo rf.CyclicStateMachine()\n\n\treturn rf\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\trf.role = Initial\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.heardFromLeader = 0\n\trf.electionTimeoutLbound = 300\n\trf.electionTimeoutUbound = 800\n\trf.heartbeatInterval = 50 * time.Millisecond\n\trf.appendEntriesInterval = 100\n\trf.applyCh = applyCh\n\trf.notifyLeaderCh = make(chan struct{}, 100)\n\trf.notifyFollowerCh = make(chan int64, 100)\n\trf.matchIndex = make([]int64, len(peers))\n\trf.nextIndex = make([]int64, len(peers))\n\trf.inflightGoroutines = 10\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\trf.switchToFollower()\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\trf.mu = sync.Mutex{}\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\n\t// Your initialization code here (2A, 2B, 2C).\n\n\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.log = []LogEntry{}\n\trf.committedIndex = -1\n\trf.lastApplied = -1\n\n\trf.state = Follower\n\trf.applyCh = applyCh\n\n\trf.grantVoteCh = make(chan bool)\n\trf.heartBeatCh = make(chan bool)\n\trf.leaderCh = make(chan bool)\n\n\trf.timer = time.NewTimer(time.Duration(rand.Intn(300)+300) * time.Millisecond)\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\tgo rf.heartBeat()\n\n\treturn rf\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\trf.stateMachine = applyCh\n\t// Your initialization code here (2A, 2B, 2C).\n\n\t// initialize from state persisted before a crash\n\trf.init()\n\trf.readPersist(persister.ReadRaftState())\n\tgo rf.run()\n\tDPrintf(\"Success make\")\n\treturn rf\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\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.log = make([]LogEntry, 1) //初始大小为1,因为开始大家都是follower,log[0]中存放默认值\n\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\trf.state = 2 //follower\n\trf.applyCh = applyCh\n\t// Your initialization code here.\n\t// initialize from state persisted before a crash\n\trf.readPersist(rf.persister.ReadRaftState())\n\trf.persist()\n\trf.RestartTime()\n\n\treturn rf\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.\n\trf.currentTerm = 0\n\t// -1 is nil for voteFor\n\trf.voteFor = -1\n\tlog := Log{0, nil}\n\t// log has at least one element, convenient for programming\n\trf.log = []Log{log}\n\n\t// volatile state on all server\n\trf.role = Follower\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\trf.applyChan = applyCh\n\n\t// volatile state on leader\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\trf.electionChan = make(chan bool)\n\trf.heartbeatChan = make(chan bool)\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\tgo rf.handle()\n\n\treturn rf\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 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.\n\trf.state = FOLLOWER\n\trf.applyChan = applyCh\n\n\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.log = make([]LogEntry, 0)\n\trf.commitIndex = -1\n\trf.lastApplied = -1\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\trf.timer = time.NewTimer(properTimeDuration(rf.state))\n\t//repeat\n\tgo func() {\n\t\tfor {\n\t\t\t<-rf.timer.C\n\t\t\trf.solveTimeOut()\n\t\t}\n\t}()\n\n\treturn rf\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\trf.logger = log.New(GetLoggerWriter(), fmt.Sprintf(\"[Node %v] \", me), log.LstdFlags)\n\n\t// Your initialization code here.\n\trf.state = FOLLOWER\n\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.logs = make([]interface{}, 0)\n\trf.logs_term = make([]int, 0)\n\trf.commitCount = 0\n\trf.appliedCount = 0\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchCount = make([]int, len(peers))\n\trf.applyCh = applyCh\n\n\t// initialize from state persisted before a crash\n\trf.readPersist()\n\trf.resetTimer()\n\n\treturn rf\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\trf.state = Follower\n\trf.currentTerm = 0\n\trf.votedFor = NULL\n\trf.logs = make([]Log, 1)\n\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\trf.applyCh = applyCh\n\trf.voteCh = make(chan bool, 1)\n\trf.appendCh = make(chan bool, 1)\n\trf.killCh = make(chan bool, 1)\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\tgo rf.service()\n\treturn rf\n}", "func NewPeer(peers []*rpc.ClientEnd, me int, applyCh chan ApplyCommand) *Raft {\n\trf := &Raft{\n\t\tpeers: peers,\n\t\tme: me, //default values\n\t\trole: Follower,\n\t\tcurrTerm: 0,\n\t\tvotedFor: -1,\n\t\tnumVotes: 0,\n\t}\n\n\tif kEnableDebugLogs {\n\t\t// peerName := peers[me].String()\n\t\tlogPrefix := fmt.Sprintf(\"%s \", strconv.Itoa(rf.me)+\" \")\n\t\tif kLogToStdout {\n\t\t\trf.logger = log.New(os.Stdout, strconv.Itoa(rf.me)+\" \", log.Lmicroseconds|log.Lshortfile)\n\t\t} else {\n\t\t\terr := os.MkdirAll(kLogOutputDir, os.ModePerm)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err.Error())\n\t\t\t}\n\t\t\tlogOutputFile, err := os.OpenFile(fmt.Sprintf(\"%s/%s.txt\", kLogOutputDir, logPrefix), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err.Error())\n\t\t\t}\n\t\t\trf.logger = log.New(logOutputFile, logPrefix, log.Lmicroseconds|log.Lshortfile)\n\t\t}\n\t\trf.logger.Println(\"logger initialized\")\n\t} else {\n\t\trf.logger = log.New(ioutil.Discard, \"\", 0)\n\t}\n\n\trf.elecTimer = time.NewTicker(time.Duration(rand.Intn(RANGE)+LOWER) * time.Millisecond)\n\n\t//Initialize Background goroutines\n\tgo rf.ElectionRoutine()\n\tgo rf.HeartBeatRoutine()\n\n\treturn rf\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\trf.applyCh = applyCh\n\n\trf.state = Follower\n\trf.CurrentTerm = 0\n\trf.VotedFor = NilCandidateID\n\trf.OpLog = []Log{Log{0, \"sentinel\"}}\n\trf.readPersist(persister.ReadRaftState())\n\trf.lastLogIndex = len(rf.OpLog) - 1\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.heartbeat = make(chan bool)\n\trf.nextIndex = make([]int, len(rf.peers))\n\trf.matchIndex = make([]int, len(rf.peers))\n\trf.init()\n\n\treturn rf\n}", "func (c *JoinCommand) Apply(raftServer *raft.Server) (interface{}, error) {\n\n\t// check if the join command is from a previous machine, who lost all its previous log.\n\tresponse, _ := etcdStore.RawGet(path.Join(\"_etcd/machines\", c.Name))\n\n\tb := make([]byte, 8)\n\tbinary.PutUvarint(b, raftServer.CommitIndex())\n\n\tif response != nil {\n\t\treturn b, nil\n\t}\n\n\t// check machine number in the cluster\n\tnum := machineNum()\n\tif num == maxClusterSize {\n\t\tdebug(\"Reject join request from \", c.Name)\n\t\treturn []byte{0}, etcdErr.NewError(103, \"\")\n\t}\n\n\taddNameToURL(c.Name, c.RaftVersion, c.RaftURL, c.EtcdURL)\n\n\t// add peer in raft\n\terr := raftServer.AddPeer(c.Name, \"\")\n\n\t// add machine in etcd storage\n\tkey := path.Join(\"_etcd/machines\", c.Name)\n\tvalue := fmt.Sprintf(\"raft=%s&etcd=%s&raftVersion=%s\", c.RaftURL, c.EtcdURL, c.RaftVersion)\n\tetcdStore.Set(key, value, time.Unix(0, 0), raftServer.CommitIndex())\n\n\t// add peer stats\n\tif c.Name != r.Name() {\n\t\tr.followersStats.Followers[c.Name] = &raftFollowerStats{}\n\t\tr.followersStats.Followers[c.Name].Latency.Minimum = 1 << 63\n\t}\n\n\treturn b, err\n}", "func startServer(\n\tstate *ServerState,\n\tvoteChannels *[ClusterSize]chan Vote,\n\tappendEntriesCom *[ClusterSize]AppendEntriesCom,\n\tclientCommunicationChannel chan KeyValue,\n\tpersister Persister,\n\tchannel ApplyChannel,\n\t) Raft {\n\n\tisElection := true\n\telectionThreadSleepTime := time.Millisecond * 1000\n\ttimeSinceLastUpdate := time.Now() //update includes election or message from leader\n\tserverStateLock := new(sync.Mutex)\n\tonWinChannel := make(chan bool)\n\n\tgo runElectionTimeoutThread(&timeSinceLastUpdate, &isElection, state, voteChannels, &onWinChannel, electionThreadSleepTime)\n\tgo startLeaderListener(appendEntriesCom, state, &timeSinceLastUpdate, &isElection, serverStateLock) //implements F1.\n\tgo onWinChannelListener(state, &onWinChannel, serverStateLock, appendEntriesCom, &clientCommunicationChannel, persister, channel) //in leader.go\n\n\t//creates raft object with closure\n\traft := Raft{}\n\traft.Start = func (logEntry LogEntry) (int, int, bool){ //implements\n\t\tgo func () { //non blocking sent through client (leader may not be choosen yet).\n\t\t\tclientCommunicationChannel <- logEntry.Content\n\t\t}()\n\t\treturn len(state.Log), state.CurrentTerm, state.Role == LeaderRole\n\t}\n\n\traft.GetState = func ()(int, bool) {\n\t\treturn state.CurrentTerm, state.Role == LeaderRole\n\t}\n\treturn raft\n}", "func newApplyManager(rf *Raft) *applyManager {\n\treturn &applyManager{rf: rf, indexChange: make(chan struct{}, 1)}\n}", "func New(IP, firstContact, ID string, OutputTo io.Writer) *RaftMember {\n\t//try to get the existing data from file\n\tos.Mkdir(\"/tmp/raft/\", 0777)\n\tR, PStore, success := readPersist()\n\t//build the stateMachine\n\tpwd := \"/tmp\"\n\tos.Mkdir(pwd+\"/machines\", 0777) //make the machines directory\n\n\tR.hrt = new(time.Timer) //initialize our timer.\n\tR.giveStatus = make(chan StatusBall)\n\tR.outputTo = OutputTo\n\tR.needStatus = make(chan bool)\n\tR.giveLog = make(chan string)\n\tR.needLog = make(chan bool)\n\tR.nextIndex = make(map[string]int)\n\tR.matchIndex = make(map[string]int)\n\tR.appendRequests = make(chan string, 100)\n\tR.needScoreBoard = make(chan bool)\n\tR.suspend = make(chan int)\n\tR.GiveScoreboard = make(chan map[string]int)\n\tif !success {\n\t\t//load failed or files dont exist\n\t\tfmt.Println(\"Creating New Member\")\n\t\ttid, err := makeID()\n\t\tR.VoteLog = append(R.VoteLog, VoteRecord{Votes: make(map[string]bool), VotedFor: \"NIL\"}) //bootstrap the vote record for the 0 term\n\t\tterr.BreakError(\"ID Creation\", err)\n\t\tR.ID = tid\n\t\tR.Log = append(R.Log, LogEntry{Term: 0, Entry: \"init\"}) // make the first entry an initialize for counting purposes.\n\t\tR.Target = 1\n\t}\n\tR.Machine = stateMachine.CreateStateMachine(pwd+\"/machines/\"+R.ID[:6]+\".sm\", contentionLevel) //build or recreate the state machine.\n\tterr.VerbPrint(R.outputTo, 1, verb, \"Target Set to:\", R.Target)\n\tR.Machine.SetTarget(R.Target) //restores a target after a reboot\n\tif ID != \"\" {\n\t\tR.ID = ID\n\t}\n\n\tR.CM = CM.New(R.ID, IP, R.outputTo)\n\tif firstContact != \"\" {\n\t\tterr.VerbPrint(R.outputTo, 3, verb, \"connecting to\", firstContact)\n\t\tR.Connect(firstContact)\n\t}\n\tR.writePersist(PStore)\n\tR.et = timers.NewElectionTimer()\n\tR.run(PStore) //spawns a go routine to handle incomming messages\n\treturn R\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\n\t// Your initialization code here.\n\tpx.dead = 0\n\tpx.unreliable = 0\n\tpx.offset = len(peers)\n\tpx.acceptor = make(map[int]*AcceptState)\n\tpx.prepareNum = make(map[int]int)\n\tpx.dones = make([]int, len(peers))\n\tfor i := 0; i < len(peers); i++ {\n\t\tpx.dones[i] = -1\n\t}\n\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// please do not change any of the following code,\n\t\t// or do anything to subvert it.\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.isdead() == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.isdead() == false {\n\t\t\t\t\tif px.isunreliable() && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.isunreliable() && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.isdead() == false {\n\t\t\t\t\tfmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn px\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\n\t// Your initialization code here.\n\tpx.doneSeq = make([]int, len(px.peers))\n\tfor i := 0; i < len(px.peers); i++ {\n\t\tpx.doneSeq[i] = -1\n\t}\n\tpx.maxSeq = -1\n\tpx.decidedVals = make(map[int]interface{})\n\taMgr := AcceptorManager{}\n\taMgr.acceptors = make(map[int]*Acceptor)\n\tpMgr := ProposerManager{}\n\tpMgr.proposers = make(map[int]*Proposer)\n\tpx.acceptorMgr = &aMgr\n\tpx.proposerMgr = &pMgr\n\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.isdead() == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.isdead() == false {\n\t\t\t\t\tif px.isunreliable() && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.isunreliable() && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.isdead() == false {\n\t\t\t\t\tfmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn px\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\n\t// Your initialization code here.\n\tpx.peerDones = make([]int, len(peers))\n\tfor i := range px.peerDones {\n\t\tpx.peerDones[i] = -1\n\t}\n\tpx.done = -1\n\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// please do not change any of the following code,\n\t\t// or do anything to subvert it.\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.isdead() == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.isdead() == false {\n\t\t\t\t\tif px.isunreliable() && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.isunreliable() && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.isdead() == false {\n\t\t\t\t\tfmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn px\n}", "func newServer(listenAddrs []string, notifier chainntnfs.ChainNotifier,\n\tbio lnwallet.BlockChainIO, fundingSigner lnwallet.MessageSigner,\n\twallet *lnwallet.LightningWallet, chanDB *channeldb.DB) (*server, error) {\n\n\tprivKey, err := wallet.GetIdentitykey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivKey.Curve = btcec.S256()\n\n\tlisteners := make([]net.Listener, len(listenAddrs))\n\tfor i, addr := range listenAddrs {\n\t\tlisteners[i], err = brontide.NewListener(privKey, addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tserializedPubKey := privKey.PubKey().SerializeCompressed()\n\ts := &server{\n\t\tlnwallet: wallet,\n\t\tbio: bio,\n\t\tchainNotifier: notifier,\n\t\tchanDB: chanDB,\n\n\t\tinvoices: newInvoiceRegistry(chanDB),\n\t\tutxoNursery: newUtxoNursery(chanDB, notifier, wallet),\n\t\thtlcSwitch: newHtlcSwitch(),\n\n\t\tidentityPriv: privKey,\n\t\tnodeSigner: newNodeSigner(privKey),\n\n\t\t// TODO(roasbeef): derive proper onion key based on rotation\n\t\t// schedule\n\t\tsphinx: sphinx.NewRouter(privKey, activeNetParams.Params),\n\t\tlightningID: sha256.Sum256(serializedPubKey),\n\n\t\tpersistentPeers: make(map[string]struct{}),\n\t\tpersistentConnReqs: make(map[string][]*connmgr.ConnReq),\n\n\t\tpeersByID: make(map[int32]*peer),\n\t\tpeersByPub: make(map[string]*peer),\n\t\tinboundPeers: make(map[string]*peer),\n\t\toutboundPeers: make(map[string]*peer),\n\n\t\tnewPeers: make(chan *peer, 10),\n\t\tdonePeers: make(chan *peer, 10),\n\n\t\tbroadcastRequests: make(chan *broadcastReq),\n\t\tsendRequests: make(chan *sendReq),\n\n\t\tglobalFeatures: globalFeatures,\n\t\tlocalFeatures: localFeatures,\n\n\t\tqueries: make(chan interface{}),\n\t\tquit: make(chan struct{}),\n\t}\n\n\t// If the debug HTLC flag is on, then we invoice a \"master debug\"\n\t// invoice which all outgoing payments will be sent and all incoming\n\t// HTLCs with the debug R-Hash immediately settled.\n\tif cfg.DebugHTLC {\n\t\tkiloCoin := btcutil.Amount(btcutil.SatoshiPerBitcoin * 1000)\n\t\ts.invoices.AddDebugInvoice(kiloCoin, *debugPre)\n\t\tsrvrLog.Debugf(\"Debug HTLC invoice inserted, preimage=%x, hash=%x\",\n\t\t\tdebugPre[:], debugHash[:])\n\t}\n\n\t// If external IP addresses have been specified, add those to the list\n\t// of this server's addresses.\n\tselfAddrs := make([]net.Addr, 0, len(cfg.ExternalIPs))\n\tfor _, ip := range cfg.ExternalIPs {\n\t\tvar addr string\n\t\t_, _, err = net.SplitHostPort(ip)\n\t\tif err != nil {\n\t\t\taddr = net.JoinHostPort(ip, strconv.Itoa(defaultPeerPort))\n\t\t} else {\n\t\t\taddr = ip\n\t\t}\n\n\t\tlnAddr, err := net.ResolveTCPAddr(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tselfAddrs = append(selfAddrs, lnAddr)\n\t}\n\n\tchanGraph := chanDB.ChannelGraph()\n\n\t// TODO(roasbeef): make alias configurable\n\talias := lnwire.NewAlias(hex.EncodeToString(serializedPubKey[:10]))\n\tself := &channeldb.LightningNode{\n\t\tLastUpdate: time.Now(),\n\t\tAddresses: selfAddrs,\n\t\tPubKey: privKey.PubKey(),\n\t\tAlias: alias.String(),\n\t\tFeatures: globalFeatures,\n\t}\n\n\t// If our information has changed since our last boot, then we'll\n\t// re-sign our node announcement so a fresh authenticated version of it\n\t// can be propagated throughout the network upon startup.\n\t// TODO(roasbeef): don't always set timestamp above to _now.\n\tself.AuthSig, err = discovery.SignAnnouncement(s.nodeSigner,\n\t\ts.identityPriv.PubKey(),\n\t\t&lnwire.NodeAnnouncement{\n\t\t\tTimestamp: uint32(self.LastUpdate.Unix()),\n\t\t\tAddresses: self.Addresses,\n\t\t\tNodeID: self.PubKey,\n\t\t\tAlias: alias,\n\t\t\tFeatures: self.Features,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to generate signature for \"+\n\t\t\t\"self node announcement: %v\", err)\n\t}\n\tif err := chanGraph.SetSourceNode(self); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't set self node: %v\", err)\n\t}\n\n\ts.chanRouter, err = routing.New(routing.Config{\n\t\tGraph: chanGraph,\n\t\tChain: bio,\n\t\tNotifier: notifier,\n\t\tSendToSwitch: func(firstHop *btcec.PublicKey,\n\t\t\thtlcAdd *lnwire.UpdateAddHTLC) ([32]byte, error) {\n\n\t\t\tfirstHopPub := firstHop.SerializeCompressed()\n\t\t\tdestInterface := chainhash.Hash(sha256.Sum256(firstHopPub))\n\n\t\t\treturn s.htlcSwitch.SendHTLC(&htlcPacket{\n\t\t\t\tdest: destInterface,\n\t\t\t\tmsg: htlcAdd,\n\t\t\t})\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't create router: %v\", err)\n\t}\n\n\ts.discoverSrv, err = discovery.New(discovery.Config{\n\t\tBroadcast: s.broadcastMessage,\n\t\tNotifier: s.chainNotifier,\n\t\tRouter: s.chanRouter,\n\t\tSendToPeer: s.sendToPeer,\n\t\tTrickleDelay: time.Millisecond * 300,\n\t\tProofMatureDelta: 0,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.rpcServer = newRPCServer(s)\n\ts.breachArbiter = newBreachArbiter(wallet, chanDB, notifier, s.htlcSwitch)\n\n\tvar chanIDSeed [32]byte\n\tif _, err := rand.Read(chanIDSeed[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.fundingMgr, err = newFundingManager(fundingConfig{\n\t\tIDKey: s.identityPriv.PubKey(),\n\t\tWallet: wallet,\n\t\tNotifier: s.chainNotifier,\n\t\tSignMessage: func(pubKey *btcec.PublicKey, msg []byte) (*btcec.Signature, error) {\n\t\t\tif pubKey.IsEqual(s.identityPriv.PubKey()) {\n\t\t\t\treturn s.nodeSigner.SignMessage(pubKey, msg)\n\t\t\t}\n\n\t\t\treturn fundingSigner.SignMessage(pubKey, msg)\n\t\t},\n\t\tSendAnnouncement: func(msg lnwire.Message) error {\n\t\t\ts.discoverSrv.ProcessLocalAnnouncement(msg,\n\t\t\t\ts.identityPriv.PubKey())\n\t\t\treturn nil\n\t\t},\n\t\tArbiterChan: s.breachArbiter.newContracts,\n\t\tSendToPeer: s.sendToPeer,\n\t\tFindPeer: s.findPeer,\n\t\tTempChanIDSeed: chanIDSeed,\n\t\tFindChannel: func(chanID lnwire.ChannelID) (*lnwallet.LightningChannel, error) {\n\t\t\tdbChannels, err := chanDB.FetchAllChannels()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfor _, channel := range dbChannels {\n\t\t\t\tif chanID.IsChanPoint(channel.ChanID) {\n\t\t\t\t\treturn lnwallet.NewLightningChannel(wallet.Signer,\n\t\t\t\t\t\tnotifier, channel)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil, fmt.Errorf(\"unable to find channel\")\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO(roasbeef): introduce closure and config system to decouple the\n\t// initialization above ^\n\n\t// Create the connection manager which will be responsible for\n\t// maintaining persistent outbound connections and also accepting new\n\t// incoming connections\n\tcmgr, err := connmgr.New(&connmgr.Config{\n\t\tListeners: listeners,\n\t\tOnAccept: s.inboundPeerConnected,\n\t\tRetryDuration: time.Second * 5,\n\t\tTargetOutbound: 100,\n\t\tGetNewAddress: nil,\n\t\tDial: noiseDial(s.identityPriv),\n\t\tOnConnection: s.outboundPeerConnected,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.connMgr = cmgr\n\n\treturn s, nil\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\n\t// Your initialization code here.\n\tpx.peersNum = len(peers)\n\tpx.proposerInfo = make(map[int]ProposerInfo)\n\tpx.acceptorInfo = make(map[int]AcceptorInfo)\n\tpx.maxProposalId = make(map[int]ProposalId)\n\tpx.maxSeq = 0\n\tpx.minSeq = 0\n\tpx.doneInfo = make(map[string]int)\n\tfor _, peer := range peers {\n\t\tpx.doneInfo[peer] = -1\n\t}\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// please do not change any of the following code,\n\t\t// or do anything to subvert it.\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.isdead() == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.isdead() == false {\n\t\t\t\t\tif px.isunreliable() && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.isunreliable() && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.isdead() == false {\n\t\t\t\t\tfmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn px\n}", "func (rf *Raft) applyMsg() {\n\tticker := time.NewTicker(time.Millisecond * 100)\n\tfor _ = range ticker.C {\n\t\trf.mu.Lock()\n\t\tif rf.killAllGoRoutines {\n\t\t\trf.mu.Unlock()\n\t\t\treturn\n\t\t}\n\t\t// Logic to increment commitIndex at the Leader.\n\t\tif rf.isLeader {\n\t\t\tfor i := rf.Log.Length() - 1; i > rf.commitIndex && i >= rf.Log.LastIncludedLength; i-- {\n\t\t\t\tif rf.Log.Entries[i-rf.Log.LastIncludedLength].Term != rf.CurrentTerm {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmajority := 1\n\t\t\t\tfor j := 0; j < len(rf.peers); j++ {\n\t\t\t\t\tif j == rf.me {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif rf.matchIndex[j] >= i {\n\t\t\t\t\t\tmajority++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif majority > len(rf.peers)/2 {\n\t\t\t\t\trf.commitIndex = i\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor rf.commitIndex > rf.lastApplied {\n\t\t\trf.lastApplied++\n\t\t\t// This check is required as lastApplied is not persisted, upon\n\t\t\t// crash, it would start applying from the beginning of the log.\n\t\t\tif rf.lastApplied < rf.Log.LastIncludedLength {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\targ := ApplyMsg{Index: rf.lastApplied + 1,\n\t\t\t\tCommand: rf.Log.Entries[rf.lastApplied-rf.Log.LastIncludedLength].Command}\n\t\t\trf.mu.Unlock()\n\t\t\trf.applyCh <- arg\n\t\t\trf.mu.Lock()\n\t\t}\n\t\trf.mu.Unlock()\n\t}\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\n\t// Your initialization code here.\n\tpx.prepareStatus = NewLinkedList()\n\tpx.localDoneMin = -1\n\tpx.doneMins = make([]int, len(peers))\n\tfor i := 0; i < len(peers); i++ {\n\t\tpx.doneMins[i] = -1\n\t}\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// please do not change any of the following code,\n\t\t// or do anything to subvert it.\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.isdead() == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.isdead() == false {\n\t\t\t\t\tif px.isunreliable() && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.isunreliable() && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.isdead() == false {\n\t\t\t\t\tfmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn px\n}", "func (rf *Raft) apply() {\n\tfor !rf.killed() {\n\t\ttime.Sleep(time.Duration(time.Millisecond * 10)) //50ms\n\t\trf.mu.Lock()\n\t\tkeepApplying := true\n\t\tfor keepApplying && rf.lastApplied < rf.commitIndex {\n\t\t\tmsg := ApplyMsg{CommandValid: true, Command: rf.index(rf.lastApplied + 1).Job, CommandIndex: rf.lastApplied + 1}\n\n\t\t\tselect {\n\t\t\tcase rf.applyCh <- msg:\n\t\t\t\t// message has been sent\n\t\t\t\trf.debug(\"Sent information about %v, content=%v, commitIndex=%v\\n\", rf.lastApplied+1, rf.index(rf.lastApplied+1).Job, rf.commitIndex)\n\t\t\t\trf.lastApplied++\n\t\t\tcase <-time.After(time.Millisecond * 5):\n\t\t\t\t// drop message\n\t\t\t\tkeepApplying = false\n\t\t\t}\n\t\t}\n\t\trf.debug(\"Finished committing stuff\")\n\t\trf.mu.Unlock()\n\t}\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\n\t// Your initialization code here.\n\tpx.prepareNum = make(map[string]int)\n\tpx.acceptedNum = make(map[string]int)\n\tpx.fate = make(map[string]Fate)\n\tpx.value = make(map[string]interface{})\n\tpx.peersMaxSeq = make([]int, len(px.peers))\n\tfor i, _ := range px.peersMaxSeq {\n\t\tpx.peersMaxSeq[i] = -1\n\t}\n\tpx.maxSeq = -1\n\tpx.doneSeq = -1\n\tpx.peerMinSeq = -1\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// please do not change any of the following code,\n\t\t// or do anything to subvert it.\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.isdead() == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.isdead() == false {\n\t\t\t\t\tif px.isunreliable() && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.isunreliable() && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.isdead() == false {\n\t\t\t\t\tfmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn px\n}", "func newRaft(c *Config) *Raft {\n\tif err := c.validate(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\t// Your Code Here (2A).\n\tl := newLog(c.Storage)\n\t// 恢复 hardState\n\thardState, confState, _ := c.Storage.InitialState()\n\tif hardState.Commit > 0 {\n\t\tl.committed = hardState.Commit\n\t}\n\tvar peers []uint64\n\tif len(confState.Nodes) > 0 {\n\t\tpeers = confState.Nodes\n\t} else {\n\t\tpeers = c.peers\n\t}\n\tr := &Raft{\n\t\tid: c.ID,\n\t\tTerm: hardState.Term,\n\t\tVote: hardState.Vote,\n\t\tRaftLog: l,\n\t\tPrs: make(map[uint64]*Progress),\n\t\tState: StateFollower,\n\t\tvotes: make(map[uint64]bool),\n\t\tmsgs: nil,\n\t\tLead: None,\n\t\theartbeatTimeout: c.HeartbeatTick,\n\t\telectionTimeout: c.ElectionTick,\n\t\theartbeatElapsed: 0,\n\t\telectionElapsed: 0,\n\t\tleadTransferee: 0,\n\t\tPendingConfIndex: 0,\n\t}\n\tif c.Applied > 0 {\n\t\tr.RaftLog.applied = c.Applied\n\t}\n\tfor _, v := range peers {\n\t\tif v == 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[v] = &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\tr.votes[v] = false\n\t}\n\tr.votes[r.Vote] = true\n\t// 此处不可以使用 becomeFollower,否则会丢失 Vote 变量\n\tr.actualElectionTimeout = rand.Intn(r.electionTimeout) + r.electionTimeout\n\tlog.DInfo(\"'Raft Created' %d=%+v\", r.id, r)\n\treturn r\n}", "func (kv *KVServer) ScanApplyCh() {\n\tfor !kv.killed() {\n\t\tmsg := <-kv.applyCh\n\t\tkv.Log(LogInfo, \"Received commit on applyCh:\", msg)\n\n\t\t// see what type of message is is and respond accordingly\n\t\tif op, ok := msg.Command.(Op); ok {\n\t\t\t// message is an applyable op. Apply it to kv state\n\t\t\t// ensure to cache response to prevent re-applications later on!\n\t\t\tappliedOp := kv.ApplyOp(op, msg.CommandIndex, msg.CommandTerm)\n\t\t\tkv.mu.Lock()\n\t\t\tkv.latestResponse[appliedOp.KVOp.ClientID] = appliedOp\n\t\t\tkv.mu.Unlock()\n\t\t\tkv.Log(LogDebug, \"New request processed for client\", appliedOp.KVOp.ClientID, \"\\n - appliedOp\", appliedOp)\n\t\t} else if len(msg.Snapshot) > 0 {\n\t\t\tr := bytes.NewBuffer(msg.Snapshot)\n\t\t\td := labgob.NewDecoder(r)\n\t\t\tvar s Snapshot\n\t\t\tif e := d.Decode(&s); e != nil {\n\t\t\t\tkv.Log(LogError, \"Saw an applyMsg with Snapshot but error reading it.\\n - error\", e)\n\t\t\t} else {\n\t\t\t\tkv.Log(LogInfo, \"InstallSnapshot found on applyMsg Ch.\\n - LastIncludedIndex\", s.LastIncludedIndex, \"\\n - LastIncludedTerm\", s.LastIncludedTerm, \"\\n - Store\", s.Store, \"\\n - LatestResponse\", s.LatestResponse)\n\n\t\t\t\t// only apply the update to state if it is a more recent snapshot\n\t\t\t\tkv.mu.Lock()\n\t\t\t\tif s.LastIncludedIndex > kv.lastIndexApplied {\n\t\t\t\t\tkv.Log(LogInfo, \"InstallSnapshot more up to date. Applying store and discarding log.\")\n\t\t\t\t\tkv.store = s.Store\n\t\t\t\t\tkv.latestResponse = s.LatestResponse\n\t\t\t\t\tstateBytes := kv.rf.TrimLog(s.LastIncludedIndex, s.LastIncludedTerm)\n\t\t\t\t\tkv.persister.SaveStateAndSnapshot(stateBytes, msg.Snapshot)\n\t\t\t\t\tkv.lastIncludedIndex = s.LastIncludedIndex\n\t\t\t\t\tkv.lastIndexApplied = kv.lastIncludedIndex\n\t\t\t\t\tkv.Log(LogDebug, \"Finished installing snapshot.\")\n\t\t\t\t} else {\n\t\t\t\t\tkv.Log(LogInfo, \"InstallSnapshot describes a prefix of our log. Ignoring.\")\n\t\t\t\t}\n\t\t\t\tkv.mu.Unlock()\n\t\t\t}\n\t\t}\n\t}\n}", "func StartKVServer(servers []*labrpc.ClientEnd, me int, persister *raft.Persister, maxraftstate int) *KVServer {\n\t// call labgob.Register on structures you want\n\t// Go's RPC library to marshall/unmarshall.\n\tlabgob.Register(Op{})\n\n\tkv := new(KVServer)\n\tkv.me = me\n\n\tkv.maxraftstate = maxraftstate\n\n\t//kv.GetChan = make(chan bool)\n\t//kv.PAChan = make(chan bool)\n\tkv.notify = make(map[int]chan Op) //->chan array\n\t// You may need initialization code here.\n\n\tkv.applyCh = make(chan raft.ApplyMsg)\n\tkv.storage = make(map[string]string)\n\n\tif Conservative > 0 {\n\t\tkv.commFilter = make(map[int64][]int)\n\t} else {\n\t\tkv.commFilterX = make(map[int64]int)\n\t}\n\tkv.rf = raft.Make(servers, me, persister, kv.applyCh)\n\n\tgo func() {\n\n\t\tfor { //m := range kv.applyCh {\n\t\t\tm := <-kv.applyCh\n\t\t\tif m.UseSnapshot {\n\t\t\t\tvar LastIncludedIndex int\n\t\t\t\tvar LastIncludedTerm int\n\n\t\t\t\tr := bytes.NewBuffer(m.Snapshot)\n\t\t\t\td := gob.NewDecoder(r)\n\n\t\t\t\tkv.mu.Lock()\n\t\t\t\td.Decode(&LastIncludedIndex)\n\t\t\t\td.Decode(&LastIncludedTerm)\n\t\t\t\tkv.storage = make(map[string]string)\n\t\t\t\tkv.commFilterX = make(map[int64]int)\n\t\t\t\td.Decode(&kv.storage)\n\t\t\t\td.Decode(&kv.commFilterX)\n\t\t\t\tkv.mu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif kv.rf.State == 1 {\n\t\t\t\tDPrintNew(\"I am the leader %d\", kv.me)\n\t\t\t}\n\t\t\t//do get / append / put\n\t\t\tDPrintf5(\"server %d received applych\", kv.me)\n\t\t\top := m.Command.(Op)\n\n\t\t\tkv.mu.Lock()\n\t\t\t//DPrintf5(\"%v will put %v %v with snum %d-----------------------------\", op.Cid, op.Key, op.Value, op.Snum)\n\t\t\tif Conservative > 0 {\n\t\t\t\tif op.Optype != \"Get\" && !kv.FilterSnum(op.Cid, op.Snum) {\n\n\t\t\t\t\tkv.ApplyOp(op)\n\n\t\t\t\t\tif kv.commFilter[op.Cid] == nil {\n\t\t\t\t\t\tkv.commFilter[op.Cid] = make([]int, 0)\n\t\t\t\t\t}\n\t\t\t\t\tkv.commFilter[op.Cid] = append(kv.commFilter[op.Cid], op.Snum)\n\n\t\t\t\t\t//kv.ApplyOp(op)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif op.Optype != \"Get\" {\n\t\t\t\t\tif snum, ok := kv.commFilterX[op.Cid]; !ok || op.Snum > snum {\n\t\t\t\t\t\tkv.ApplyOp(op)\n\t\t\t\t\t\tkv.commFilterX[op.Cid] = op.Snum\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnotifyChan, ok := kv.notify[m.CommandIndex]\n\t\t\tif ok {\n\t\t\t\tnotifyChan <- op\n\t\t\t}\n\t\t\tDPrintNew(\"cmdidx: %d, logsize %d\", m.CommandIndex, kv.rf.GetPersistSize())\n\t\t\tif kv.maxraftstate != -1 && kv.rf.GetPersistSize() > kv.maxraftstate {\n\t\t\t\t//only for non-conservative\n\n\t\t\t\tDPrintNew(\"KV side: me: %d, cmdidx: %d, logsize %d\", kv.me, m.CommandIndex, kv.rf.GetPersistSize())\n\t\t\t\tw := new(bytes.Buffer)\n\t\t\t\te := labgob.NewEncoder(w)\n\t\t\t\te.Encode(kv.storage)\n\t\t\t\te.Encode(kv.commFilterX)\n\t\t\t\tdata := w.Bytes()\n\n\t\t\t\tgo kv.rf.DoSnapshot(data, m.CommandIndex) //may use another index\n\n\t\t\t}\n\n\t\t\tkv.mu.Unlock()\n\t\t}\n\t}()\n\n\t// You may need initialization code here.\n\n\treturn kv\n}", "func (rf *Raft) sendAppendEntries(peerIdx int) {\n\tRPCTimer := time.NewTimer(RPCTimeout)\n\tdefer RPCTimer.Stop()\n\n\tfor !rf.killed() {\n\t\trf.mu.Lock()\n\t\tif rf.role != Leader { // 不是 Leader, 直接结束\n\t\t\trf.resetHeartBeatTimer(peerIdx)\n\t\t\trf.mu.Unlock()\n\t\t\treturn\n\t\t}\n\t\targs := rf.getAppendEntriesArgs(peerIdx)\n\t\trf.resetHeartBeatTimer(peerIdx)\n\t\trf.mu.Unlock()\n\n\t\tRPCTimer.Stop()\n\t\tRPCTimer.Reset(RPCTimeout)\n\t\treply := AppendEntriesReply{} // RPC 返回reply\n\t\tresCh := make(chan bool, 1) // call result\n\t\tgo func(args *AppendEntriesArgs, reply *AppendEntriesReply) {\n\t\t\tok := rf.peers[peerIdx].Call(\"Raft.AppendEntries\", args, reply)\n\t\t\tif !ok {\n\t\t\t\ttime.Sleep(time.Millisecond * 10)\n\t\t\t}\n\t\t\tresCh <- ok\n\t\t}(&args, &reply)\n\n\t\tselect {\n\t\tcase <-RPCTimer.C: // RPC 超时\n\t\t\tcontinue\n\t\tcase ok := <-resCh:\n\t\t\tif !ok { // RPC 失败\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// call ok, check reply\n\t\trf.mu.Lock()\n\t\tif rf.currentTerm != args.Term { // 不是 Leader, 或者 Term 不匹配\n\t\t\trf.mu.Unlock()\n\t\t\treturn\n\t\t} else if reply.Term > rf.currentTerm { // Election Restriction: 有更加新的 Term, 直接拒绝\n\t\t\trf.changeRole(Follower)\n\t\t\trf.resetElectionTimer()\n\t\t\trf.currentTerm = reply.Term\n\t\t\trf.persist()\n\t\t\trf.mu.Unlock()\n\t\t\treturn\n\t\t} else if reply.Success { // reply 成功\n\t\t\tif reply.NextIndex > rf.nextIndex[peerIdx] {\n\t\t\t\trf.nextIndex[peerIdx] = reply.NextIndex\n\t\t\t\trf.matchIndex[peerIdx] = reply.NextIndex - 1\n\t\t\t}\n\t\t\tif len(args.Entries) > 0 && args.Entries[len(args.Entries)-1].Term == rf.currentTerm {\n\t\t\t\t// 只 commit 自己 term 的 index\n\t\t\t\trf.updateCommitIndex()\n\t\t\t}\n\t\t\trf.persist()\n\t\t\trf.mu.Unlock()\n\t\t\treturn\n\t\t} else if reply.NextIndex != 0 { // reply 失败\n\t\t\tif reply.NextIndex > rf.lastSnapshotIndex {\n\t\t\t\t// need retry\n\t\t\t\trf.nextIndex[peerIdx] = reply.NextIndex\n\t\t\t\trf.mu.Unlock()\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\t// send snapshot rpc\n\t\t\t\tgo rf.sendInstallSnapshot(peerIdx)\n\t\t\t\trf.mu.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t// 乱序\n\t\t\trf.mu.Unlock()\n\t\t}\n\t}\n}", "func (rf *Raft) initialServer() {\n\tfor {\n\t\tif !rf.killed() {\n\t\t\ttimeOut := time.Millisecond * time.Duration(ElectionTimeOut+rand.Intn(ElectionTimeOut)) //warn 必须sleep timeOut,避免server在一个ElectionTimeOut结束后连续发起选举\n\t\t\ttime.Sleep(timeOut)\n\t\t\t//DPrintf(\"rf%v state%v\",rf.me,rf.state)\n\t\t\trf.mu.Lock()\n\t\t\tswitch rf.state {\n\t\t\tcase Candidate:\n\t\t\t\tDPrintf(\"candidate [%v] startElection detail:%v\", rf.me, rf)\n\t\t\t\tgo rf.startElection()\n\t\t\tcase Follower:\n\t\t\t\t//if time.Now().Sub(rf.lastReceiveHeartBeat) > (timeOut - time.Millisecond*time.Duration(10)) {\n\t\t\t\tif time.Now().Sub(rf.lastReceiveHeartBeat) > timeOut {\n\t\t\t\t\trf.state = Candidate\n\t\t\t\t\t//DPrintf(\"follower %v startElection\",rf)\n\t\t\t\t\tgo rf.startElection() // warn follower转为candidate后应立即startElection,不再等待新的ElectionTimeOUt\n\t\t\t\t}\n\t\t\t}\n\t\t\trf.mu.Unlock()\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\n\t// Your initialization code here.\n\tpx.numPeers = len(px.peers)\n\tpx.majorityCount = (px.numPeers)/2 + 1\n\tpx.maxSeq = -1\n\tpx.instances = make(map[int]*Instance)\n\tpx.peersDone = make([]int, px.numPeers)\n\tfor i := range px.peersDone {\n\t\tpx.peersDone[i] = -1\n\t}\n\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// please do not change any of the following code,\n\t\t// or do anything to subvert it.\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.isdead() == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.isdead() == false {\n\t\t\t\t\tif px.isunreliable() && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.isunreliable() && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.isdead() == false {\n\t\t\t\t\tfmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn px\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n px := &Paxos{}\n px.peers = peers\n px.me = me\n px.Instances = make(map[int]Instance)\n px.done = make(map[int]int)\n px.maxSeq = -1\n \n // instantiate all done[i] at -1\n for i, _ := range px.peers {\n px.done[i] = -1\n }\n\n if rpcs != nil {\n // caller will create socket &c\n rpcs.Register(px)\n } else {\n rpcs = rpc.NewServer()\n rpcs.Register(px)\n\n // prepare to receive connections from clients.\n // change \"unix\" to \"tcp\" to use over a network.\n os.Remove(peers[me]) // only needed for \"unix\"\n l, e := net.Listen(\"unix\", peers[me])\n if e != nil {\n log.Fatal(\"listen error: \", e)\n }\n px.l = l\n\n // please do not change any of the following code,\n // or do anything to subvert it.\n\n // create a thread to accept RPC connections\n go func() {\n for px.isdead() == false {\n conn, err := px.l.Accept()\n if err == nil && px.isdead() == false {\n if px.isunreliable() && (rand.Int63()%1000) < 100 {\n // discard the request.\n conn.Close()\n } else if px.isunreliable() && (rand.Int63()%1000) < 200 {\n // process the request but force discard of reply.\n c1 := conn.(*net.UnixConn)\n f, _ := c1.File()\n err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n if err != nil {\n fmt.Printf(\"shutdown: %v\\n\", err)\n }\n atomic.AddInt32(&px.rpcCount, 1)\n go rpcs.ServeConn(conn)\n } else {\n atomic.AddInt32(&px.rpcCount, 1)\n go rpcs.ServeConn(conn)\n }\n } else if err == nil {\n conn.Close()\n }\n if err != nil && px.isdead() == false {\n fmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n }\n }\n }()\n }\n\n return px\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\n\t// Your initialization code here.\n\tpx.min = 0\n\tpx.max = -1\n\tpx.instances = make(map[int]*Instance)\n\tpx.peerDones = make([]int, len(px.peers), len(px.peers))\n\tfor i := 0; i < len(px.peers); i++ {\n\t\tpx.peerDones[i] = -1\n\t}\n\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// please do not change any of the following code,\n\t\t// or do anything to subvert it.\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.isdead() == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.isdead() == false {\n\t\t\t\t\tif px.isunreliable() && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.isunreliable() && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tatomic.AddInt32(&px.rpcCount, 1)\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.isdead() == false {\n\t\t\t\t\tfmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn px\n}", "func (self *RRSMNode) Build(addr string, initState RRSMState, configuration *RRSMConfig,\n\tRPCListenPort string, electionTimeout time.Duration, heartbeatInterval time.Duration) error {\n\tself.InitState = initState\n\tself.CurrentState = initState\n\tself.nodes = make(map[string]*rpc.RPCClient)\n\tself.addr = addr\n\n\t// init timer\n\tself.electionTimeoutTicker = nil\n\tself.electionTimeout = electionTimeout\n\tself.heartbeatTimeTicker = nil\n\tself.heartbeatInterval = heartbeatInterval\n\n\t// become a follower at the beginning\n\tself.character = RaftFOLLOWER\n\tself.currentTerm = uint64(0)\n\tself.haveVoted = false\n\n\t// init channels\n\tself.newTermChan = make(chan int, 1)\n\tself.accessLeaderChan = make(chan int, 1)\n\n\t// init lock\n\tself.termChangingLock = &sync.Mutex{}\n\tself.leaderChangingLock = &sync.Mutex{}\n\n\t// init node configuration\n\tif configuration == nil {\n\t\treturn fmt.Errorf(\"configuration is needed!\")\n\t}\n\tif len(configuration.Nodes) <= 0 {\n\t\treturn fmt.Errorf(\"config err: amounts of nodes needed to be a positive number!\")\n\t}\n\tself.config = *configuration\n\tself.amountsOfNodes = uint32(len(self.config.Nodes))\n\n\t// register rpc service\n\traftRPC := RaftRPC{\n\t\tnode: self,\n\t}\n\terr := rpc.RPCRegister(RPCListenPort, &raftRPC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// build rpc connection with other nodes\n\tfor _, node := range self.config.Nodes {\n\t\tif node != addr {\n\t\t\tclient, err := rpc.RPCConnect(node)\n\t\t\tif err != nil {\n\t\t\t\t// need to connect with all the nodes at the period of building\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tself.nodes[node] = client\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *Raft) runFollower() {\n\tfor {\n\t\tselect {\n\t\tcase rpc := <-r.rpcCh:\n\t\t\t// Handle the command\n\t\t\tswitch cmd := rpc.Command.(type) {\n\t\t\tcase *AppendEntriesRequest:\n\t\t\t\tr.appendEntries(rpc, cmd)\n\t\t\tcase *RequestVoteRequest:\n\t\t\t\tr.requestVote(rpc, cmd)\n\t\t\tdefault:\n\t\t\t\tr.logE.Printf(\"In follower state, got unexpected command: %#v\", rpc.Command)\n\t\t\t\trpc.Respond(nil, fmt.Errorf(\"unexpected command\"))\n\t\t\t}\n\t\tcase a := <-r.applyCh:\n\t\t\t// Reject any operations since we are not the leader\n\t\t\ta.response = ErrNotLeader\n\t\t\ta.Response()\n\t\tcase <-randomTimeout(r.conf.HeartbeatTimeout, r.conf.ElectionTimeout):\n\t\t\t// Heartbeat failed! Go to the candidate state\n\t\t\tr.logW.Printf(\"Heartbeat timeout, start election process\")\n\t\t\tr.setState(Candidate)\n\t\t\treturn\n\n\t\tcase <-r.shutdownCh:\n\t\t\treturn\n\t\t}\n\t}\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\n\t// Your initialization code here.\n\tpx.instances = make(map[int]*PaxInst)\n\tpx.done = make(map[int]int)\n\tpx.majority = len(px.peers)/2 + 1\n\tpx.k = 0\n\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// please do not change any of the following code,\n\t\t// or do anything to subvert it.\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.dead == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.dead == false {\n\t\t\t\t\tif px.unreliable && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.unreliable && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t//fmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpx.rpcCount++\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpx.rpcCount++\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.dead == false {\n\t\t\t\t\t//fmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn px\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 Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n px := &Paxos{}\n px.peers = peers\n px.me = me\n\n // Your initialization code here.\n px.history = make(map[int]Proposal)\n px.decisions = make(map[int]int)\n for i := 0; i < len(px.peers); i++ {\n px.decisions[i] = -1\n }\n px.maxSeq = -1\n px.majorSize = len(px.peers)/2 + 1\n\n if rpcs != nil {\n // caller will create socket &c\n rpcs.Register(px)\n } else {\n rpcs = rpc.NewServer()\n rpcs.Register(px)\n\n // prepare to receive connections from clients.\n // change \"unix\" to \"tcp\" to use over a network.\n os.Remove(peers[me]) // only needed for \"unix\"\n l, e := net.Listen(\"unix\", peers[me]);\n if e != nil {\n log.Fatal(\"listen error: \", e);\n }\n px.l = l\n\n // please do not change any of the following code,\n // or do anything to subvert it.\n\n // create a thread to accept RPC connections\n go func() {\n for px.dead == false {\n conn, err := px.l.Accept()\n if err == nil && px.dead == false {\n if px.unreliable && (rand.Int63() % 1000) < 100 {\n // discard the request.\n conn.Close()\n } else if px.unreliable && (rand.Int63() % 1000) < 200 {\n // process the request but force discard of reply.\n c1 := conn.(*net.UnixConn)\n f, _ := c1.File()\n err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n if err != nil {\n fmt.Printf(\"shutdown: %v\\n\", err)\n }\n px.rpcCount++\n go rpcs.ServeConn(conn)\n } else {\n px.rpcCount++\n go rpcs.ServeConn(conn)\n }\n } else if err == nil {\n conn.Close()\n }\n if err != nil && px.dead == false {\n fmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n }\n }\n }()\n }\n\n\n return px\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\n\t// Your initialization code here.\n\tpx.instances = make(map[int]*Instance)\n\tpx.curMax = -1\n\tpx.doneValue = make([]int, len(px.peers))\n\tfor i := range px.doneValue {\n\t\tpx.doneValue[i] = -1\n\t}\n\tpx.majority = len(px.peers)/2 + 1\n\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// please do not change any of the following code,\n\t\t// or do anything to subvert it.\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.dead == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.dead == false {\n\t\t\t\t\tif px.unreliable && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.unreliable && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpx.rpcCount++\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpx.rpcCount++\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.dead == false {\n\t\t\t\t\tfmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn px\n}", "func Make(peers []string, me int, rpcs *rpc.Server, saveToDisk bool, dir string, restart bool) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\n\tgob.Register(PaxosInstance{})\n\tpx.dir = dir\n\n\t// Your initialization code here.\n\tpx.instances = make(map[int]PaxosInstance)\n\tpx.done = make(map[int]int)\n\tfor peer := 0; peer < len(px.peers); peer++ {\n\t\t// a peers z_i is -1 if it has never called Done()\n\t\tpx.done[peer] = -1\n\t}\n\tpx.nseq = -1\n\tpx.nmajority = len(px.peers)/2 + 1\n\tpx.saveToDisk = saveToDisk\n\n\tif saveToDisk && restart {\n\t\tpx.instances = px.fileRetrievePaxos()\n\t}\n\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// please do not change any of the following code,\n\t\t// or do anything to subvert it.\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.dead == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.dead == false {\n\t\t\t\t\tif px.unreliable && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.unreliable && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpx.rpcCount++\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpx.rpcCount++\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.dead == false {\n\t\t\t\t\tfmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t// garbage collector - cleans up forgotten instances\n\tgo func() {\n\t\tfor !px.dead {\n\t\t\tpx.mu.Lock()\n\t\t\tmin := px.Min()\n\t\t\tfor ninst := range px.instances {\n\t\t\t\tif ninst < min {\n\t\t\t\t\t//DPrintf(\"delete(%d)\\n\", ninst)\n\t\t\t\t\tdelete(px.instances, ninst)\n\t\t\t\t\tif px.saveToDisk {\n\t\t\t\t\t\tfullname := px.dir + \"/paxos-\" + strconv.Itoa(ninst)\n\t\t\t\t\t\ttempname := px.dir + \"/paxos-\" + strconv.Itoa(ninst)\n\t\t\t\t\t\tos.Remove(fullname)\n\t\t\t\t\t\tos.Remove(tempname)\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tpx.mu.Unlock()\n\t\t\ttime.Sleep(GCInterval)\n\t\t}\n\t}()\n\n\treturn px\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n px := &Paxos{}\n px.peers = peers\n px.me = me\n\n // Your initialization code here.\n px.instances = make(map[int]*Instance)\n px.doneMap = make([]int, len(px.peers))\n for i := 0; i < len(px.doneMap); i++ {\n px.doneMap[i] = -1\n }\n px.maxSeq = -1\n\n if rpcs != nil {\n // caller will create socket &c\n rpcs.Register(px)\n } else {\n rpcs = rpc.NewServer()\n rpcs.Register(px)\n\n // prepare to receive connections from clients.\n // change \"unix\" to \"tcp\" to use over a network.\n os.Remove(peers[me]) // only needed for \"unix\"\n l, e := net.Listen(\"unix\", peers[me])\n if e != nil {\n log.Fatal(\"listen error: \", e)\n }\n px.l = l\n\n // please do not change any of the following code,\n // or do anything to subvert it.\n\n // create a thread to accept RPC connections\n go func() {\n for px.dead == false {\n conn, err := px.l.Accept()\n if err == nil && px.dead == false {\n if px.unreliable && (rand.Int63()%1000) < 100 {\n // discard the request.\n conn.Close()\n } else if px.unreliable && (rand.Int63()%1000) < 200 {\n // process the request but force discard of reply.\n c1 := conn.(*net.UnixConn)\n f, _ := c1.File()\n err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n if err != nil {\n fmt.Printf(\"shutdown: %v\\n\", err)\n }\n px.rpcCount++\n go rpcs.ServeConn(conn)\n } else {\n px.rpcCount++\n go rpcs.ServeConn(conn)\n }\n } else if err == nil {\n conn.Close()\n }\n if err != nil && px.dead == false {\n fmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n }\n }\n }()\n }\n\n return px\n}", "func (r *RaftNode) doFollower() stateFunction {\n\n\tr.initFollowerState()\n\n\t// election timer for handling going into candidate state\n\telectionTimer := r.randomTimeout(r.config.ElectionTimeout)\n\n\tfor {\n\t\tselect {\n\t\tcase shutdown := <-r.gracefulExit:\n\t\t\tif shutdown {\n\t\t\t\tr.Out(\"Shutting down\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\tcase <-electionTimer:\n\t\t\t// if we timeout with no appendEntries heartbeats,\n\t\t\t// start election with this node\n\t\t\tr.Out(\"Election timeout\")\n\n\t\t\t// for debugging purposes:\n\t\t\tif r.debugCond != nil {\n\t\t\t\tr.debugCond.L.Lock()\n\t\t\t\tr.Out(\"Waiting for broadcast...\")\n\t\t\t\tr.debugCond.Wait()\n\t\t\t\tr.debugCond.L.Unlock()\n\t\t\t}\n\n\t\t\treturn r.doCandidate\n\n\t\tcase msg := <-r.requestVote:\n\t\t\tif votedFor, _ := r.handleRequestVote(msg); votedFor {\n\t\t\t\t// reset timeout if voted so not all (non-candidate-worthy) nodes become candidates at once\n\t\t\t\tr.Debug(\"Election timeout reset\")\n\t\t\t\telectionTimer = r.randomTimeout(r.config.ElectionTimeout)\n\t\t\t}\n\t\tcase msg := <-r.appendEntries:\n\t\t\tif resetTimeout, _ := r.handleAppendEntries(msg); resetTimeout {\n\t\t\t\telectionTimer = r.randomTimeout(r.config.ElectionTimeout)\n\t\t\t}\n\t\tcase msg := <-r.registerClient:\n\t\t\tr.Out(\"RegisterClient received\")\n\t\t\tr.handleRegisterClientAsNonLeader(msg)\n\n\t\tcase msg := <-r.clientRequest:\n\t\t\tr.handleClientRequestAsNonLeader(msg)\n\t\t}\n\t}\n}", "func StartKVServer(servers []*labrpc.ClientEnd, me int, persister *raft.Persister, maxraftstate int) *KVServer {\n\t// call labgob.Register on structures you want\n\t// Go's RPC library to marshall/unmarshall.\n\tlabgob.Register(Op{})\n\n\tkv := new(KVServer)\n\tkv.me = me\n\tkv.maxraftstate = maxraftstate\n\n\n\tkv.logger = logger.CreateLogContext(zap.Int(\"server\", kv.me)).GetSugarLogger()\n\n\n\t// You may need initialization code here.\n\n\tkv.applyCh = make(chan raft.ApplyMsg)\n\tkv.kv = xlnraft.NewStringKV()//make(map[string]string)\n\tkv.clientReqRecord = sync.Map{} // make(map[int64]*PutAppendRequestRecord)\n\tkv.curClientReqID = sync.Map{}\n\tkv.clientResultChan = sync.Map{}\n\tkv.getReqRecord = sync.Map{}\n\n\tkv.clientMutexMap = sync.Map{}\n\tkv.ticker = time.NewTicker(5000 * time.Millisecond)\n\n\tkv.rf = raft.Make(servers, me, persister, kv.applyCh)\n\n\t// You may need initialization code here.\n\tgo func(maxRaftState int) {\n\t\tfor !kv.killed() {\n\t\t\tselect {\n\t\t\t//case <- time.After(10 * time.Millisecond):\n\t\t\t//\tbreak\n\t\t\tcase applyMsg := <- kv.applyCh:\n\n\t\t\t\tif applyMsg.CommandValid {\n\t\t\t\t\top := applyMsg.Command.(Op)\n\t\t\t\t\tkv.logger.Debugf(\"apply start server: %d key:%s, value:%s\", kv.me, op.Key, op.Value)\n\t\t\t\t\tvar result interface{} = nil\n\t\t\t\t\tif op.OpType == GET {\n\t\t\t\t\t\tresult = kv.kv.KV[op.Key]\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\treqID, ok := kv.curClientReqID.Load(op.ClientID)\n\t\t\t\t\t\tduplicateFound := false\n\t\t\t\t\t\tif ok && reqID == op.ReqID {\n\t\t\t\t\t\t\tduplicateFound = true\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif !duplicateFound {\n\t\t\t\t\t\t\tif op.OpType == PUT {\n\t\t\t\t\t\t\t\tkv.kv.KV[op.Key] = op.Value\n\t\t\t\t\t\t\t\tresult = kv.kv.KV[op.Key]\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t//append(kv.kvState[op.Key].([]string), op.Value)\n\t\t\t\t\t\t\t\tkv.kv.KV[op.Key] += op.Value\n\t\t\t\t\t\t\t\tresult = kv.kv.KV[op.Key]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tkv.curClientReqID.Store(op.ClientID, op.ReqID)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\topResult := &OpResult{opType: op.OpType, result: result}\n\t\t\t\t\t//fmt.Printf(\"start result channel\")\n\n\t\t\t\t\tchannelMap, ok := kv.clientResultChan.Load(op.ClientID)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tchannel, ok := channelMap.(*sync.Map).Load(op.ReqID)\n\t\t\t\t\t\t//go func() {\n\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\tselect {\n\t\t\t\t\t\t\tcase channel.(chan *OpResult) <- opResult:\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tcase <-time.After(1000 * time.Millisecond):\n\t\t\t\t\t\t\t\tkv.logger.Warn(\"result wait too long, must be leader changed\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentSize := persister.RaftStateSize()\n\n\t\t\t\t\tif maxraftstate != -1 && currentSize >= maxRaftState {\n\n\t\t\t\t\t\tbytes := kv.kv.Encode()\n\t\t\t\t\t\tsnapShotIndex := applyMsg.CommandIndex\n\t\t\t\t\t\tkv.logger.Warnf(\"Start snapshot from index: %d Size: %d / %d\", snapShotIndex, currentSize, maxraftstate)\n\n\t\t\t\t\t\tdoneChannel := make(chan *raft.Message)\n\t\t\t\t\t\tkv.rf.Snapshot(bytes, snapShotIndex, doneChannel)\n\n\t\t\t\t\t\t_ = <-doneChannel\n\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t//apply snapshot\n\t\t\t\t\tsnapShot := applyMsg.Command.(*raft.Snapshot)\n\t\t\t\t\tkv.kv.Decode(snapShot.Snapshot)\n\n\t\t\t\t}\n\n\n\t\t\t\t//kv.logger.Debugf(\"apply end\")\n\t\t\t}\n\n\n\t\t}\n\t}(kv.maxraftstate)\n\n\treturn kv\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n lastLogIndex := 0\n isLeader := true\n \n // TODO WED: check corner cases with -1\n rf.mu.Lock()\n term := rf.currentTerm\n myId := rf.me\n if len(rf.log) > 0 {\n lastLogIndex = len(rf.log)\n //term = rf.log[index].Term \n }\n \n if rf.state != Leader || rf.killed() {\n return lastLogIndex-1, term, false\n }\n \n var oneEntry LogEntry\n oneEntry.Command = command\n oneEntry.Term = term\n \n rf.log = append(rf.log, oneEntry)\n rf.mu.Unlock()\n\n \n go func() {\n \n // Add a while loop. when successReply count greater than threhsold, commit. loop breaks when successReply is equal to peers\n // the for loop inside only iterates over the left peers.\n \n var localMu sync.Mutex\n \n isLeader := true\n committed := false\n successReplyCount := 0\n var receivedResponse []int\n receivedResponse = append(receivedResponse, myId)\n\n for isLeader {\n if rf.killed() {\n fmt.Printf(\"*** Peer %d term %d: Terminated. Closing all outstanding Append Entries calls to followers.\",myId, term)\n return \n }\n\n var args = AppendEntriesArgs {\n LeaderId: myId,\n }\n rf.mu.Lock()\n numPeers := len(rf.peers)\n rf.mu.Unlock()\n\n for id := 0; id < numPeers && isLeader; id++ {\n if (!find(receivedResponse,id)) {\n if lastLogIndex < rf.nextIndex[id] {\n successReplyCount++\n receivedResponse = append(receivedResponse,id)\n continue\n }\n var logEntries []LogEntry\n logEntries = append(logEntries,rf.log[(rf.nextIndex[id]):]...)\n args.LogEntries = logEntries\n args.PrevLogTerm = rf.log[rf.nextIndex[id]-1].Term\n args.PrevLogIndex = rf.nextIndex[id]-1\n args.LeaderTerm = rf.currentTerm\n args.LeaderCommitIndex = rf.commitIndex\n \n go func(serverId int) {\n var reply AppendEntriesReply\n ok:=rf.sendAppendEntries(serverId, &args, &reply)\n if !rf.CheckTerm(reply.CurrentTerm) {\n localMu.Lock()\n isLeader=false\n localMu.Unlock()\n } else if reply.Success && ok {\n localMu.Lock()\n successReplyCount++\n receivedResponse = append(receivedResponse,serverId)\n localMu.Unlock()\n rf.mu.Lock()\n if lastLogIndex >= rf.nextIndex[id] {\n rf.matchIndex[id]= lastLogIndex\n rf.nextIndex[id] = lastLogIndex + 1\n }\n rf.mu.Unlock()\n } else {\n rf.mu.Lock()\n rf.nextIndex[id]-- \n rf.mu.Unlock()\n }\n } (id)\n }\n }\n \n fmt.Printf(\"\\nsleeping before counting success replies\\n\")\n time.Sleep(time.Duration(RANDOM_TIMER_MIN*time.Millisecond))\n\n if !committed && isLeader {\n votesForIndex := 0\n N := math.MaxInt32\n rf.mu.Lock()\n for i := 0; i < numPeers; i++ {\n if rf.matchIndex[i] > rf.commitIndex {\n if rf.matchIndex[i] < N {\n N = rf.matchIndex[i]\n }\n votesForIndex++\n }\n }\n rf.mu.Unlock()\n\n\n if (votesForIndex > (numPeers/2)){ \n go func(){\n committed = true\n rf.mu.Lock()\n rf.commitIndex = N // Discuss: 3. should we use lock?\n rf.log[N].Term = rf.currentTerm\n if rf.commitIndex >= lastLogIndex {\n var oneApplyMsg ApplyMsg\n oneApplyMsg.CommandValid = true\n oneApplyMsg.CommandIndex = lastLogIndex\n oneApplyMsg.Command = command\n go func() {rf.applyCh <- oneApplyMsg} ()\n }\n rf.mu.Unlock()\n }()\n }\n } else if successReplyCount == numPeers {\n return\n } \n }\n } ()\n \n // Your code here (2B code).\n return lastLogIndex, term, isLeader\n}", "func (s *Server) raftApply(t structs.MessageType, msg interface{}) (interface{}, error) {\n\tbuf, err := structs.Encode(t, msg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to encode request: %v\", err)\n\t}\n\n\t// Warn if the command is very large\n\tif n := len(buf); n > raftWarnSize {\n\t\ts.logger.Printf(\"[WARN] consul: Attempting to apply large raft entry (%d bytes)\", n)\n\t}\n\n\tfuture := s.raft.Apply(buf, enqueueLimit)\n\tif err := future.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn future.Response(), nil\n}", "func (kv *KVServer) receiveApplyMsgAndApply() {\n\tfor {\n\t\t//get the op that commit by those rafts\n\t\tmsg := <-kv.applyCh\n\n\t\tkv.mu.Lock()\n\n\t\tif msg.UseSnapshot {\n\t\t\t//debug\n\t\t\tError1(\"kv-%v receiving a snapshot msg:%v\", kv.me, msg.Snapshot)\n\t\t\t//apply the snapshot on the kv-server\n\t\t\tkv.readSnapshot(msg.Snapshot)\n\t\t\t//apply the snapshot and update its maxIndex\n\t\t\tif kv.maxIndex < msg.CommandIndex {\n\t\t\t\tkv.maxIndex = msg.CommandIndex\n\t\t\t}\n\t\t\tkv.snapshotServer(msg.CommandIndex)\n\t\t\tkv.mu.Unlock()\n\t\t\tcontinue\n\t\t}\n\t\t//convert the command interface{} to Op\n\t\top := msg.Command.(Op)\n\n\t\tif op.Type != \"GET\" {\n\t\t\t//record the opNum of every clientId so that if the op.Opnum <= opNum, it means that this operation is executed before\n\t\t\tif opNum, ok := kv.detectDup[op.ClientId]; !ok || op.OpNum > opNum {\n\t\t\t\tkv.executeOpOnKvServer(op)\n\t\t\t\t// Trace(\"kv-%v receiving a op.OpNum:%v > opNum:%v from clientId:%v\", kv.me, op.OpNum, opNum, op.ClientId)\n\t\t\t\tkv.detectDup[op.ClientId] = op.OpNum\n\t\t\t}\n\t\t}\n\n\t\tch, ok := kv.result[msg.CommandIndex]\n\n\t\tif ok {\n\t\t\t//tell the RPC handler of kvserver that the agreement is done and the op is applied on storage\n\t\t\tch <- op\n\t\t\t// Error(\"kv-%v sending a op:%v to ch\", kv.me, op)\n\t\t}\n\n\t\t//record the max index for snapshotting and as a offset to update the raft log entries after deleting the previous log entries\n\t\tif msg.CommandIndex > kv.maxIndex {\n\t\t\tkv.maxIndex = msg.CommandIndex\n\t\t}\n\n\t\t//lab3B\n\t\t//if exceed the maxraftstate, do the snapshot\n\t\tif kv.maxraftstate != -1 && kv.rf.GetRaftSize() >= kv.maxraftstate {\n\t\t\tkv.snapshotServer(kv.maxIndex)\n\t\t}\n\t\tkv.mu.Unlock()\n\t}\n}", "func (r ApiGetEtherPortChannelListRequest) Apply(apply string) ApiGetEtherPortChannelListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {\n\tpx := &Paxos{}\n\tpx.peers = peers\n\tpx.me = me\n\t//fmt.Printf(\"#### Make %d/%d ####\\n\", me, len(peers))\n\n\t// Your initialization code here.\n\tpx.peers_count = len(peers)\n\tpx.majority = (px.peers_count + 1) / 2\n\tpx.max_seq = -1\n\tpx.global_done = -1\n\tpx.local_done = -1\n\n\tpx.APp = map[int]int{}\n\tpx.APa = map[int]Proposal{}\n\tpx.Lslots = map[int]Slot_t{}\n\n\tif rpcs != nil {\n\t\t// caller will create socket &c\n\t\trpcs.Register(px)\n\t} else {\n\t\trpcs = rpc.NewServer()\n\t\trpcs.Register(px)\n\n\t\t// prepare to receive connections from clients.\n\t\t// change \"unix\" to \"tcp\" to use over a network.\n\t\tos.Remove(peers[me]) // only needed for \"unix\"\n\t\tl, e := net.Listen(\"unix\", peers[me])\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error: \", e)\n\t\t}\n\t\tpx.l = l\n\n\t\t// please do not change any of the following code,\n\t\t// or do anything to subvert it.\n\n\t\t// create a thread to accept RPC connections\n\t\tgo func() {\n\t\t\tfor px.dead == false {\n\t\t\t\tconn, err := px.l.Accept()\n\t\t\t\tif err == nil && px.dead == false {\n\t\t\t\t\tif px.unreliable && (rand.Int63()%1000) < 100 {\n\t\t\t\t\t\t// discard the request.\n\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t} else if px.unreliable && (rand.Int63()%1000) < 200 {\n\t\t\t\t\t\t// process the request but force discard of reply.\n\t\t\t\t\t\tc1 := conn.(*net.UnixConn)\n\t\t\t\t\t\tf, _ := c1.File()\n\t\t\t\t\t\terr := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"shutdown: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpx.rpcCount++\n\t\t\t\t\t\tif DBG_RPCCOUNT {\n\t\t\t\t\t\t\tfmt.Println(\"*** RPC++ ***\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpx.rpcCount++\n\t\t\t\t\t\tif DBG_RPCCOUNT {\n\t\t\t\t\t\t\tfmt.Println(\"*** RPC++ ***\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgo rpcs.ServeConn(conn)\n\t\t\t\t\t}\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t}\n\t\t\t\tif err != nil && px.dead == false {\n\t\t\t\t\tfmt.Printf(\"Paxos(%v) accept: %v\\n\", me, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn px\n}", "func (rf *Raft) writeApplyCh() {// {{{\n for {\n <-rf.cmtChan \n rf.mu.Lock()\n for i := rf.applyIdx + 1; i <= rf.cmtIdx; i++ {\n var newApplyMsg ApplyMsg\n newApplyMsg.Index = i \n newApplyMsg.Command = rf.log[i].Cmd\n rf.applyChan<- newApplyMsg \n rf.applyIdx = i \n rf.debug(\"Applied committed msg: cmtIdx=%v, applyIdx=%v\\n\", rf.cmtIdx, rf.applyIdx)\n }\n rf.mu.Unlock()\n }\n}" ]
[ "0.7712334", "0.74356365", "0.741532", "0.7402304", "0.73939013", "0.72879225", "0.7238589", "0.7233324", "0.7218169", "0.72022396", "0.7174303", "0.7151774", "0.7134439", "0.71319026", "0.71256536", "0.71111095", "0.7102215", "0.7100773", "0.7074483", "0.70411783", "0.70386356", "0.70361143", "0.7017582", "0.6993661", "0.69631886", "0.694109", "0.691492", "0.6914683", "0.691238", "0.6900532", "0.6890531", "0.6871954", "0.68560165", "0.6855399", "0.68341017", "0.68275905", "0.6826712", "0.68161243", "0.68109155", "0.68076515", "0.680076", "0.6799263", "0.67811584", "0.6769558", "0.6760771", "0.6754314", "0.67334175", "0.67116106", "0.67041945", "0.66942704", "0.6685894", "0.666388", "0.66280144", "0.6624685", "0.6605545", "0.65977776", "0.6582483", "0.65611285", "0.6521476", "0.63935834", "0.6301074", "0.62913716", "0.6203262", "0.61706346", "0.5484842", "0.53910637", "0.5264983", "0.5145742", "0.51436025", "0.51221436", "0.5118241", "0.5114686", "0.50824064", "0.5069214", "0.5063199", "0.50589514", "0.50460345", "0.501252", "0.5003805", "0.4994119", "0.49925873", "0.4975589", "0.49445587", "0.4929504", "0.49255782", "0.49157974", "0.49127725", "0.4906693", "0.48994726", "0.48960447", "0.48905864", "0.48473093", "0.48458564", "0.48427844", "0.4840035", "0.48377636", "0.48257157", "0.48057675", "0.48014808", "0.4797263", "0.4794047" ]
0.0
-1
return currentTerm and whether this server believes it is the leader.
func (rf *Raft) GetState() (int, bool) { rf.mu.Lock() defer rf.mu.Unlock() var term int var isleader bool // Your code here (2A). term = rf.currentTerm if rf.state == LEADER { isleader = true } else { isleader = false } return term, isleader }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func IsLeader() bool {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\treturn leading\n}", "func (n *Ncd) IsLeader() bool {\n\treturn n.rtconf.Leader\n}", "func (c *Curator) isLeader() bool {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\treturn c.iAmLeader\n}", "func (rf *Raft) GetState() (int, bool) {\n var term int\n var isleader bool\n \n rf.mu.Lock()\n term = rf.currentTerm\n isleader = (rf.state == \"Leader\")\n rf.mu.Unlock()\n\n return term, isleader\n}", "func (s *store) isLeader() bool {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tif s.raftState == nil {\n\t\treturn false\n\t}\n\treturn s.raftState.raft.State() == raft.Leader\n}", "func (db *Ops) IsLeader() bool {\n\treturn db.metaDB.IsLeader()\n}", "func (r Replicator) Get_Isleader() bool {\n\treturn r.leader\n}", "func (r *Range) IsLeader() bool {\n\treturn true\n}", "func (t *Txn) IsLeader() bool {\n\treturn t.isLeader\n}", "func (s *Server) getLeader() (bool, *metadata.Server) {\n\t// Check if we are the leader\n\tif s.IsLeader() {\n\t\treturn true, nil\n\t}\n\n\t// Get the leader\n\tleader := s.raft.Leader()\n\tif leader == \"\" {\n\t\treturn false, nil\n\t}\n\n\t// Lookup the server\n\tserver := s.serverLookup.Server(leader)\n\n\t// Server could be nil\n\treturn false, server\n}", "func (rf *Raft) GetState() (int, bool) { //获取服务器的任期和他是否认为自己是leader\n\n\tterm := rf.currentTerm\n\tisLeader := rf.state == 1 //1 is leader\n\t// Your code here.\n\treturn term, isLeader\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 (s *Server) IsLeader() bool {\n\treturn atomic.LoadInt64(&s.isLeaderValue) == 1\n}", "func (c *Client) IsLeader() bool {\n\t// self node key\n\tself := c.dir.ElectionNode(c.address)\n\tif c.leader != nil && c.leader.Key == self {\n\t\treturn true\n\t}\n\treturn false\n}", "func (o *observer) CurrentLeader() (string, error) {\n\to.Lock()\n\tdefer o.Unlock()\n\tif o.running {\n\t\treturn o.leader, nil\n\t}\n\treturn \"\", errors.New(\"observer is not running\")\n}", "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 (s *server) Term() uint64 {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn s.currentTerm\n}", "func (c *Coordinator) IsLeader() bool {\n\n\treturn c.raft.State() == raft.Leader\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 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 (s *store) leader() string {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tif s.raftState == nil || s.raftState.raft == nil {\n\t\treturn \"\"\n\t}\n\n\ts.logger.Info(\"query leader. \" + string(s.raftState.raft.Leader()))\n\treturn string(s.raftState.raft.Leader())\n}", "func (c *context) CurrentTerm() uint64 {\n\treturn c.currentTerm\n}", "func (rf *Raft) GetState() (int, bool) {// {{{\n\trf.mu.Lock()\n\tterm := rf.curTerm\n\tisleader := (rf.state == LEADER)\n\trf.mu.Unlock() \n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\tvar term int\n\tvar isleader bool\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tterm = rf.currentTerm\n\tisleader = rf.electionState == leader\n\n\treturn term, isleader\n}", "func (n *Node) GetCurrentTerm() uint64 {\n\treturn n.StableStore.GetUint64([]byte(\"current_term\"))\n}", "func (rf *Raft) GetState() (int, bool) {\n\t// fmt.Printf(\"State for server %v... currentTerm: %v; state: %v; isLeader: %v\\n\", rf.me, rf.currentTerm, rf.state, rf.state == Leader)\n\treturn rf.currentTerm, (rf.state == Leader)\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tterm := rf.currentTerm\n\tisleader := (rf.role == Leader)\n\n\treturn term, isleader\n}", "func (mc *Client) Leader() string {\n\n\treturn mc.info.Leader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tterm = rf.currentTerm\n\treturn term, rf.state == Leader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\n\tterm = rf.currentTerm\n\tif rf.hasLeader && rf.leader == rf.me {\n\t\tisleader = true\n\t} else {\n\t\tisleader = false\n\t}\n\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\treturn rf.CurrentTerm, rf.state == Leader\n}", "func (dn *DNode) IsLeader() bool {\n\treturn dn.metaNode.IsLeader()\n}", "func (rf *Raft) GetState() (int, bool) {\n\t// Your code here (2A).\n\t// warn GetState不加锁,因为后续在处理请求时,会频繁调用GetState()函数,影响raft layer的performance,并且读操作此时不需要线程安全,data race is acceptable\n\tterm := rf.Term\n\tisLeader := rf.state == Leader\n\treturn term, isLeader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here.\n\n\trf.mu.Lock()\n\tterm = rf.currentTerm\n\tif rf.state == Leader {\n\t\tisleader = true\n\t} else {\n\t\tisleader = false\n\t}\n\trf.mu.Unlock()\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tterm = rf.currentTerm\n\tisleader = (rf.state == Leader)\n\trf.mu.Unlock()\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (term int, isleader bool) {\n\tterm = rf.currentTerm.Load().(int)\n\tisleader = rf.state.Load().(int) == leader\n\treturn\n}", "func (s *raftState) getTerm() int32 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\treturn s.CurrentTerm\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\n\t// Your code here (2A).\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tterm = rf.currentTerm\n\tisleader = rf.status == Leader\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isLeader bool\n\trf.stateCond.L.Lock()\n\tisLeader = rf.state == Leader\n\tterm = *rf.CurrentTerm\n\trf.stateCond.L.Unlock()\n\treturn term, isLeader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tterm = rf.currentTerm\n\tisleader = rf.state == leader\n\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tterm = rf.currentTerm\n\tisleader = rf.getState() == Leader\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tterm = rf.currentTerm\n\tif rf.state == leader {\n\t\tisleader = true\n\t} else {\n\t\tisleader = false\n\t}\n\trf.mu.Unlock()\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t{\n\t\trf.mu.Lock()\n\t\tterm = int(rf.currentTerm)\n\n\t\tif rf.leaderId == LEADER {\n\t\t\tisleader = true\n\t\t} else {\n\t\t\tisleader = false\n\t\t}\n\t\trf.mu.Unlock()\n\t}\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.state == Leader {\n\t\tisleader = true\n\t} else {\n\t\tisleader = false\n\t}\n\n\tterm = rf.currentTerm\n\treturn term, isleader\n}", "func (s *Status) Leader(args *structs.GenericRequest, reply *string) error {\n\tif args.Region == \"\" {\n\t\targs.Region = s.srv.config.Region\n\t}\n\tif done, err := s.srv.forward(\"Status.Leader\", args, args, reply); done {\n\t\treturn err\n\t}\n\n\tleader := string(s.srv.raft.Leader())\n\tif leader != \"\" {\n\t\t*reply = leader\n\t} else {\n\t\t*reply = \"\"\n\t}\n\treturn nil\n}", "func (rf *Raft) GetState() (int, bool) {\n\tvar term int\n\tvar isLeader bool\n\t// Your code here (2A).\n\trf.lock(\"GetState\")\n\tisLeader = rf.state == Leader\n\tterm = rf.currentTerm\n\tdefer rf.unlock(\"GetState\")\n\tif isLeader {\n\t\tDPrintf(\"Server %v get state is leader: %v\", rf.me, isLeader)\n\t}\n\treturn term, isLeader\n}", "func (rf *Raft) GetState() (int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\treturn rf.currentTerm, rf.currentRole == Leader\n}", "func (rf *Raft) GetState() (int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\t// Your code here.\n\treturn rf.currentTerm, rf.serverState == Leader\n}", "func (rf *Raft) GetState() (int, bool) {\n\tvar term int\n\tvar isleader bool\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tterm = rf.currentTerm\n\tisleader = rf.state == Leader\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\n//\trf.mu.Lock()\n\tterm = rf.currentTerm\n\tisleader = (rf.role == LEADER)\n//\trf.mu.Unlock()\n\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\t// Your code here (2A).\n\trf.stateLock.Lock()\n\tdefer rf.stateLock.Unlock()\n\treturn int(rf.currentTerm), atomic.LoadInt32(&rf.isLeader) == 1\n}", "func (rf *Raft) GetState() (int, bool) {\n\tvar term int\n\tvar isleader bool\n\trf.mu.Lock()\n\tterm = rf.CurrentTerm\n\tisleader = rf.isLeader\n\trf.mu.Unlock()\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\trf.Lock()\n\tdefer rf.Unlock()\n\tterm := rf.currentTerm\n\tisleader := rf.state == Leader\n\t// Your code here (2A).\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tterm = rf.currentTerm\n\tisleader = rf.state == Leader\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\tterm = rf.currentTerm\n\tif rf.state == \"leader\" {\n\t\tisleader = true\n\t} else {\n\t\tisleader = false\n\t}\n\t//DPrintf(\"GetState of %d, term=%d, isleader=%v\", rf.me, term, isleader)\n\treturn term, isleader\n}", "func (myRaft Raft) GetLeader() int {\n\tfor {\n\t\tfmt.Print(\"\")\n\t\tfor i := 0; i < PEERS; i++ {\n\t\t\tif myRaft.Cluster[i].SM.status == LEAD {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}", "func (rf *Raft) GetState() (int, bool) {\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tterm = rf.currentTerm\n\tisleader = rf.state == Leader\n\treturn term, isleader\n}", "func (m *MonLeaderDetector) Leader() int {\n\t// TODO(student): Implement\n\tif len(m.alive) == 0 {\n\t\tm.Allsuspected = true\n\t\treturn UnknownID\n\t}\n\n\tleader := -1\n\tfor key := range m.alive { //elect the node with highest id as a leader\n\t\tif key > leader {\n\t\t\tleader = key\n\t\t}\n\t}\n\n\tif leader < 0 { // if all suspected\n\t\treturn UnknownID\n\t}\n\n\tif m.CurrentLeader != leader { // if the leader changed\n\t\tm.LeaderChange = true\n\t} else {\n\t\tm.LeaderChange = false\n\t}\n\n\tm.CurrentLeader = leader //save the current elected leader\n\treturn leader\n\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\tswitch rf.State {\n\tcase Leader:\n\t\tDPrintf(\"[GetState] Server%v is Leader.\\n\", rf.me)\n\tcase Candidates:\n\t\tDPrintf(\"[GetState] Server%v is Candidate.\\n\", rf.me)\n\tcase Follower:\n\t\tDPrintf(\"[GetState] Server%v is Follower.\\n\", rf.me)\n\t}\n\n\tterm = rf.CurrentTerm\n\tif rf.State == Leader {\n\t\tisleader = true\n\t} else {\n\t\tisleader = false\n\t}\n\t// Your code here (2A).\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tterm = rf.currentTerm\n\tisleader = rf.IsLeader()\n\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tterm = rf.CurrentTerm\n\tisleader = rf.IsLeader\n\treturn term, isleader\n}", "func (actor *Actor) IsLeader() bool {\n\tif actor.Raft != nil {\n\t\treturn actor.Raft.State() == raft.Leader\n\t}\n\treturn false\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tterm = rf.currentTerm\n\tisleader = (rf.role == LEADER)\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tterm = rf.currentTerm\n\tisleader = rf.role == Leader\n\treturn term, isleader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := -1\n\tisLeader := true\n\n\trf.stateCond.L.Lock()\n\tif rf.state == Leader {\n\t\tisLeader = true\n\t\tindex = rf.lastNewEntryIndex + 1\n\t\tterm = *rf.CurrentTerm\n\t\trf.appendEntry(index, Entry{command, term, index})\n\t\trf.lastNewEntryIndex = index\n\t\trf.nextIndex[rf.me] = index + 1\n\t\trf.matchIndex[rf.me] = index\n\t\trf.persist()\n\t\trf.notifyReplica()\n\t\tlogger.Debugf(\"Client send command {%v} to %s[%d]. Success.Update nextIndex[%d] and matchIndex[%d]\",\n\t\t\tcommand, rf.state, rf.me, rf.nextIndex[rf.me], rf.matchIndex[rf.me])\n\t} else {\n\t\tlogger.Debugf(\"Client send command {%v} to %s[%d]. Fail.\", command, rf.state, rf.me)\n\t\tisLeader = false\n\t}\n\trf.stateCond.L.Unlock()\n\n\treturn index, term, isLeader\n}", "func (rf *Raft) GetState() (int, bool) {\n\trf.lock()\n\tdefer rf.unlock()\n\tisLeader := rf.CurrentElectionState == Leader\n\tterm := rf.CurrentTerm\n\treturn term, isLeader\n}", "func (rf *Raft) GetState() (int, bool) {\n\trf.mu.RLock()\n\tdefer rf.mu.RUnlock()\n\treturn int(rf.currentTerm), rf.IsLeader()\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\trf.lock(\"GetState()\")\n\tdefer rf.unlock(\"GetState()\")\n\tterm = rf.currentTerm\n\tisleader = rf.state == LEADER\n\t// DPrintf(\"the [%d]raft's term is [%d]\", rf.me, term)\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\t//var term int\n\t//var isleader bool\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\treturn rf.currentTerm, rf.currentState == StateLeader\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here.\n\tterm = rf.currentTerm\n\tisleader = (rf.state == LEADER)\n\treturn term, isleader\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\t//rf.readPersist(rf.persister.ReadRaftState())\n\n\trf.mu.Lock()\n\tif isLeader = rf.raftState == Leader; isLeader {\n\t\tterm = rf.currentTerm\n\t\tindex = rf.addLastIncludedIndex(len(rf.log))\n\t\trf.log = append(rf.log, LogEntries{rf.currentTerm, command})\n\t\trf.matchIndex[rf.me] = rf.addLastIncludedIndex(len(rf.log) - 1)\n\t}\n\trf.persist()\n\trf.mu.Unlock()\n\t//leader commit vs commitIndex\n\treturn index, term, isLeader\n}", "func (rf *Raft) GetState() (int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tvar term int\n\tvar isleader bool\n\n\tterm = rf.currentTerm\n\tisleader = rf.role == LEADER\n\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\tterm = rf.currentTerm\n\tif rf.state == Leader {\n\t\tisleader = true\n\t} else {\n\t\tisleader = false\n\t}\n\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\t// Your code here (2A).\n\tterm := rf.currentTerm\n\tisleader := rf.state == Leader\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\tisleader = false\n\tif rf.status == 2 {\n\t\tisleader = true\n\t}\n\tterm = rf.currentTerm\n\treturn term, isleader\n}", "func (m *MsgPing) Leader(state interfaces.IState) bool {\n\tswitch state.GetNetworkNumber() {\n\tcase 0: // Main Network\n\t\tpanic(\"Not implemented yet\")\n\tcase 1: // Test Network\n\t\tpanic(\"Not implemented yet\")\n\tcase 2: // Local Network\n\t\tpanic(\"Not implemented yet\")\n\tdefault:\n\t\tpanic(\"Not implemented yet\")\n\t}\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tterm = rf.currentTerm\n\tisleader = rf.state == LEADER\n\trf.mu.Unlock()\n\treturn term, isleader\n}", "func (rf *Raft) GetState() (int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\tterm = rf.currenctTerm\n\tisleader = rf.Role == \"leader\"\n\t// here just return the fields\n\treturn term, isleader\n}", "func (reply *GetReply) GetWrongLeader() bool {\n\treturn reply.WrongLeader\n}", "func (obj *instanceImpl) Leader() (*AppNode, error) {\n\tvar leaderID int64\n\tif obj.raft.State().Role == core.Leader {\n\t\tleaderID = obj.raft.Config().Node.ID\n\t}\n\n\tresult := obj.QueryRaftState()\n\tfor k, v := range result {\n\t\tif v != nil && v.State.Role == core.Leader {\n\t\t\tleaderID = k\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif leaderID < 1 {\n\t\treturn nil, fmt.Errorf(\"no leader!\")\n\t}\n\tfor _, node := range obj.nodes {\n\t\tif node.ID == leaderID {\n\t\t\treturn node, nil\n\t\t}\n\t}\n\tpanic(\"not found leader\")\n}", "func (a *DefaultApiService) GetIsLeader(ctx _context.Context) ApiGetIsLeaderRequest {\n\treturn ApiGetIsLeaderRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (rf *Raft) GetState() (int, bool) {\n\tvar term int\n\tvar isleader bool\n\t// Your code here (2A).\n\tterm = rf.currentTerm\n\tisleader = rf.role == Leader\n\n\treturn term, isleader\n}", "func (c *Client) Leader() *models.Leader {\n\tvar leader *models.Leader\n\tc.RLock()\n\tleader = c.leader\n\tc.RUnlock()\n\treturn leader\n}", "func (rf *Raft) GetState() (int, int, bool) {\n\trf.mux.Lock() //CS for accessing state variables\n\tdefer rf.mux.Unlock()\n\n\tme, term := rf.me, rf.currTerm\n\tisleader := rf.role == Leader\n\n\trf.logger.Printf(\"Showing current state of server. Role is %v \\n\", rf.role)\n\treturn me, term, isleader\n}", "func ExampleLeader() {\n\t// Init server\n\tsrv := redeo.NewServer(nil)\n\n\t// Start raft\n\trft, tsp, err := startRaft(srv)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer rft.Shutdown()\n\tdefer tsp.Close()\n\n\t// Report leader\n\tsrv.Handle(\"raftleader\", redeoraft.Leader(rft))\n\n\t// $ redis-cli -p 9736 raftleader\n\t// \"10.0.0.1:9736\"\n}", "func (a *RPC) VoteForLeader(args *RequestVoteRPCArgs,reply *bool) error{\n\t//r.ResetTimer()\n \t//fmt.Println(\"received Vote request parameter \",(*args).CandidateId,\" \",(*args).Term,\" \",(*args).LastLogTerm,\" \",(*args).LastLogIndex)\n \t//if len(r.Log)>1{\n \t//\tfmt.Println(\"Vote Request folloer parameter \",r.Id,\" \", r.CurrentTerm,\" \",r.Log[len(r.Log)-1].Term ,\" \",len(r.Log)-1)\n \t//}\n\tif r.IsLeader==2 { // if this server is follower\n\t\t//r.ResetTimer() //TODO\n\t\tif r.CurrentTerm > args.Term || r.VotedFor >-1 { // if follower has updated Term or already voted for other candidate in same term , reply nagative\n\t\t\t*reply = false\n\t\t} else if r.VotedFor== -1{ // if follower has not voted for anyone in current Term \n\t\t\tlastIndex:= len(r.Log) \n\t\t\tif lastIndex > 0 && args.LastLogIndex >0{ // if Candiate log and this server log is not empty. \n\t\t\t\tif r.Log[lastIndex-1].Term > args.LastLogTerm { // and Term of last log in follower is updated than Candidate, reject vote\n *reply=false\n }else if r.Log[lastIndex-1].Term == args.LastLogTerm{ // else if Terms of Follower and candidate is same\n \tif (lastIndex-1) >args.LastLogIndex { // but follower log is more updated, reject vote\n \t\t*reply = false\n \t} else {\n \t\t\t*reply = true // If last log terms is match and followe log is sync with candiate, vote for candidate\n \t\t}\n }else{ // if last log term is not updated and Term does not match, \n \t \t\t*reply=true//means follower is lagging behind candiate in log entries, vote for candidate\n \t\t}\n \t\n\t\t\t} else if lastIndex >args.LastLogIndex { // either of them is Zero\n\t\t\t\t*reply = false // if Follower has entries in Log, its more updated, reject vote\n\t\t\t}else{\n\t\t\t\t\t*reply = true // else Vote for candiate\n\t\t\t\t}\n\t\t}else{\n\t\t\t*reply=false\n\t\t}\n\t}else{\n\t\t*reply = false // This server is already a leader or candiate, reject vote\n\t}\n\n\tif(*reply) {\n r.VotedFor=args.CandidateId // Set Voted for to candiate Id if this server has voted positive\n }\n\t/*if(*reply) {\n\t\tfmt.Println(\"Follower \",r.Id,\" Voted for \",r.VotedFor)\n\t}else{\n\t\tfmt.Println(\"Follower \",r.Id,\" rejected vote for \",args.CandidateId)\n\t}*/\n\treturn nil\n}", "func (conn *Connection) Leader() (string, error) {\n\tif conn.hasBeenClosed {\n\t\treturn \"\", ErrClosed\n\t}\n\tif conn.disableClusterDiscovery {\n\t\treturn string(conn.cluster.leader), nil\n\t}\n\ttrace(\"%s: Leader(), calling updateClusterInfo()\", conn.ID)\n\terr := conn.updateClusterInfo()\n\tif err != nil {\n\t\ttrace(\"%s: Leader() got error from updateClusterInfo(): %s\", conn.ID, err.Error())\n\t\treturn \"\", err\n\t} else {\n\t\ttrace(\"%s: Leader(), updateClusterInfo() OK\", conn.ID)\n\t}\n\treturn string(conn.cluster.leader), nil\n}", "func (t *Txn) Leader() {\n\tif t.isLeader {\n\t\tpanic(\"transaction is already marked as leader\")\n\t}\n\tt.isLeader = true\n\tt.DryRun()\n}", "func (rf *Raft) GetState() (int, bool) {\n\n\t// Your code here.\n\treturn rf.currentTerm, rf.state == StateLeader\n}", "func (a *RPC) VoteForLeader(args *VoteInfo,reply *bool) error{\n\t\n\tse := r.GetServer(r.id)\n\tif ( (args.ElectionTerm >= r.currentTerm) && (args.LastCommit >= se.LsnToCommit) && (args.ElectionTerm != r.votedTerm) && se.isLeader==2){\n\t\tr.votedTerm=args.ElectionTerm\n\t\t*reply = true\n\t} else {\n\t\t*reply = false\n\t}\nreturn nil\n}", "func (reply *PutAppendReply) GetWrongLeader() bool {\n\treturn reply.WrongLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n rf.mu.Lock()\n defer rf.mu.Unlock()\n\n if rf.state != StateLeader {\n return nilIndex, nilIndex, false\n }\n\n // Your code here (2B).\n\n logLen := len(rf.log)\n index := logLen\n term := rf.currentTerm\n isLeader := true\n\n thisEntry := LogEntry{rf.currentTerm, command}\n rf.log = append(rf.log, thisEntry)\n rf.matchIndex[rf.me] = len(rf.log)\n\n rf.persist()\n\n // rf.print(\"Client start command %v\", command)\n\n return index, term, isLeader\n}", "func (proc *ConsensusProcess) currentRole() Role {\n\tif proc.oracle.Eligible(hashInstanceAndK(proc.instanceId, proc.k), proc.expectedCommitteeSize(proc.k), proc.signing.Verifier().String(), proc.roleProof()) {\n\t\tif proc.currentRound() == Round2 {\n\t\t\treturn Leader\n\t\t}\n\t\treturn Active\n\t}\n\n\treturn Passive\n}", "func (rf *Raft) GetState() (int, bool) {\n\t// Your code here (2A).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\treturn rf.currentTerm, rf.raftState == Leader\n\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\tfmt.Println(\"start cmd \", command)\n\t//mcommand := reflect.ValueOf(command)\n\tif rf.state != leader {\n\t\treturn index, term, !isLeader\n\t}\n\n\t/*here comes the leader*/\n\tfmt.Println(\"leader found!\")\n\tnewEntry := new(Entry)\n\tnewEntry.Term = rf.currentTerm\n\tnewEntry.Command = command\n\trf.mu.Lock()\n\tindex = len(rf.log)\n\trf.log = append(rf.log, *newEntry)\n\tterm = rf.currentTerm\n\trf.eAppended<-true\n\trf.mu.Unlock()\n\treturn index, term, isLeader\n}", "func (rp *RaftProcess) Leader() *RaftLeader {\n\tvar leader RaftLeader\n\n\tif rp.quorum == nil || rp.quorum.Member == false {\n\t\treturn nil\n\t}\n\n\tnoLeader := etf.Pid{}\n\tif rp.leader == noLeader {\n\t\treturn nil\n\t}\n\tleader.Leader = rp.leader\n\tleader.State = rp.quorum.State\n\tleader.Serial = rp.options.Serial\n\tif rp.leader != rp.Self() {\n\t\t// must be present among the peers\n\t\tc := rp.quorumCandidates.GetOnline(rp.leader)\n\t\tif c == nil {\n\t\t\tpanic(\"internal error. elected leader has been lost\")\n\t\t}\n\t\tleader.Serial = c.serial\n\t}\n\n\treturn &leader\n}", "func (s *server) updateCurrentTerm(term uint64, leaderName string) {\n\t//_assert(term > s.currentTerm,\n\t//\t\"upadteCurrentTerm: update is called when term is not larger than currentTerm\")\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\t// Store previous values temporarily.\n\t//prevTerm := s.currentTerm\n\t//prevLeader := s.leader\n\n\t// set currentTerm = T, convert to follower (§5.1)\n\t// stop heartbeats before step-down\n\tif s.state == Leader {\n\t\ts.mutex.Unlock()\n\t\tfor _, peer := range s.peers {\n\t\t\tpeer.stopHeartbeat(false)\n\t\t}\n\t\ts.mutex.Lock()\n\t}\n\t// update the term and clear vote for\n\tif s.state != Follower {\n\t\ts.mutex.Unlock()\n\t\ts.setState(Follower)\n\t\ts.mutex.Lock()\n\t}\n\ts.currentTerm = term\n\ts.leader = leaderName\n\ts.votedFor = \"\"\n}", "func (rf *Raft) GetState() (int, bool) {\n\trf.mu.Lock()\n\tvar term int\n\tvar isleader bool\n\tterm=rf.term\n\tif rf.state==2{\n\t\tisleader=true\n\t}else{\n\t\tisleader=false\n\t}\n\trf.mu.Unlock()\n\t// Your code here (2A).\n\treturn term, isleader\n}", "func (s *Store) LeaderCh() <-chan bool {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tassert(s.raft != nil, \"cannot retrieve leadership channel when closed\")\n\treturn s.raft.LeaderCh()\n}", "func (ReturnInst) isTerm() {}", "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}" ]
[ "0.65848434", "0.6578321", "0.64696634", "0.62550354", "0.6210325", "0.61630243", "0.61503905", "0.61364657", "0.60721785", "0.60605615", "0.6040155", "0.60323125", "0.5967074", "0.5937116", "0.59303606", "0.5888573", "0.5835713", "0.5816416", "0.5746628", "0.5691572", "0.56814516", "0.56455237", "0.5634406", "0.5616305", "0.56088036", "0.5555555", "0.55530334", "0.55415136", "0.5541279", "0.5520524", "0.5514832", "0.55142117", "0.550052", "0.5482139", "0.54783446", "0.5468967", "0.54565644", "0.5452383", "0.5451417", "0.54501486", "0.5416544", "0.54118514", "0.5411325", "0.5406948", "0.5402953", "0.53997225", "0.53977346", "0.5379648", "0.53782356", "0.5377984", "0.5377372", "0.5375754", "0.537328", "0.536958", "0.5358478", "0.53551805", "0.5351846", "0.534854", "0.53431535", "0.53379124", "0.5336803", "0.5336106", "0.5329487", "0.5311995", "0.52924424", "0.5287346", "0.52735984", "0.5269031", "0.5262324", "0.5242757", "0.52213323", "0.5209251", "0.51900196", "0.5173353", "0.51642483", "0.51609164", "0.51585877", "0.51545674", "0.515039", "0.5145943", "0.5145365", "0.5135294", "0.51224244", "0.51161075", "0.5100673", "0.50982475", "0.5081207", "0.5078703", "0.5069236", "0.5062197", "0.5050776", "0.50450575", "0.5042525", "0.5041722", "0.5036722", "0.5034083", "0.50331557", "0.5013603", "0.50114894", "0.500389" ]
0.5218591
71
save Raft's persistent state to stable storage, where it can later be retrieved after a crash and restart. see paper's Figure 2 for a description of what should be persistent.
func (rf *Raft) persist() { // Your code here (2C). // Example: // w := new(bytes.Buffer) // e := gob.NewEncoder(w) // e.Encode(rf.xxx) // e.Encode(rf.yyy) // data := w.Bytes() // rf.persister.SaveRaftState(data) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (rf *Raft) persist() {\n w := new(bytes.Buffer)\n e := labgob.NewEncoder(w)\n e.Encode(rf.currentTerm)\n e.Encode(rf.votedFor)\n e.Encode(rf.log)\n e.Encode(rf.snapshottedIndex)\n data := w.Bytes()\n rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\tp := persistentState{\n\t\tCurrentTerm: rf.currentTerm.Load().(int),\n\t\tVotedFor: rf.votedFor,\n\t\tLogs: rf.logs,\n\t\tState: rf.state.Load().(int),\n\t\tStartLogIndex: rf.startLogIndex,\n\t\tStartLogTerm: rf.startLogTerm,\n\t}\n\tbuf := bytes.NewBuffer(nil)\n\tgob.NewEncoder(buf).Encode(p)\n\trf.persister.SaveRaftState(buf.Bytes())\n}", "func (rf *Raft) persist() {\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\trf.mu.Lock()\n\te.Encode(rf.CurrentTerm)\n\te.Encode(rf.VotedFor)\n\te.Encode(rf.Log)\n\trf.mu.Unlock()\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\terr := e.Encode(rf.currentTerm)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = e.Encode(rf.votedFor)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = e.Encode(rf.logIndex)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = e.Encode(rf.logs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() { // {{{\n\twriteBuffer := new(bytes.Buffer)\n encoder := gob.NewEncoder(writeBuffer)\n encoder.Encode(rf.curTerm)\n encoder.Encode(rf.votedFor)\n encoder.Encode(rf.log)\n\tdata := writeBuffer.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.logs)\n\te.Encode(rf.lastIncludedIndex)\n\te.Encode(rf.lastIncludedTerm)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\tbuf := new(bytes.Buffer)\n\tenc := gob.NewEncoder(buf)\n\tenc.Encode(rf.snapshotedCount)\n\tenc.Encode(rf.currentTerm)\n\tenc.Encode(rf.votedFor)\n\n\tenc.Encode(rf.logs[rf.snapshotedCount:])\n\tenc.Encode(rf.logs_term[rf.snapshotedCount:])\n\tif rf.snapshotedCount > 0 {\n\t\tenc.Encode(rf.logs_term[rf.snapshotedCount-1])\n\t}\n\n\trf.persister.SaveRaftState(buf.Bytes())\n}", "func (rf *Raft) persist() {\n // Your code here (2C).\n // Example:\n // w := new(bytes.Buffer)\n // e := gob.NewEncoder(w)\n // e.Encode(rf.xxx)\n // e.Encode(rf.yyy)\n // data := w.Bytes()\n // rf.persister.SaveRaftState(data)\n buf := new(bytes.Buffer)\n encoder := gob.NewEncoder(buf)\n\n // rf.mu.Lock()\n encoder.Encode(rf.currentTerm)\n encoder.Encode(rf.votedFor)\n encoder.Encode(rf.log)\n encoder.Encode(rf.isKilled)\n // rf.mu.Unlock()\n \n rf.persister.SaveRaftState(buf.Bytes())\n}", "func (rf *Raft) persist() {\n\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.voteFor)\n\te.Encode(rf.logEntries)\n\te.Encode(rf.logEntryBeginIndex)\n\te.Encode(rf.lastSnapshotIndex)\n\te.Encode(rf.lastSnapshotTerm)\n\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.log)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\tstate := &StateInfo{\n\t\tCurrentTerm: rf.currentTerm,\n\t\tCommitIndex: rf.commitIndex,\n\t\tLastApplied: rf.lastApplied,\n\t\tLogs: rf.log,\n\t}\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(state)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n\t//DPrintf(\"rf [me %v] save stateInfo: %#v\", rf.me, state)\n}", "func (rf *Raft) persist() {\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.log)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\tdata := rf.getPersistState()\n\trf.persister.SaveRaftState(data)\n\t//\trf.persister.SaveRaftState(data)\n}", "func (bot *LeagueAnnouncerBot) persist() error {\n\tlog.Debug(\"Writing bot state to disk\")\n\t// Write the current state of the bot to disk, to load for next time\n\tstorageBytes, err := bot.storage.store()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(BOT_STATE, storageBytes, 0600)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.log)\n\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here.\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := gob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.voteFor)\n\te.Encode(rf.log)\n\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\tdata := rf.getStateBytes()\n\tDPrintf(\"[persist] raft %d persist data=%v\", rf.me, data)\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.log)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.lastIncludedIndex)\n\te.Encode(rf.lastIncludedTerm)\n\trf.persister.SaveRaftState(w.Bytes())\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.voteFor)\n\te.Encode(rf.log)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\tbuf := new(bytes.Buffer)\n\tenc := labgob.NewEncoder(buf)\n\tenc.Encode(rf.currentTerm)\n\tenc.Encode(rf.votedFor)\n\tenc.Encode(rf.log)\n\tdata := buf.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.commitIndex)\n\te.Encode(rf.compactIndex)\n\te.Encode(rf.compactTerm)\n\t// e.Encode(rf.lastApplied)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.log)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.voteFor)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.log)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.log)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.logs)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n\t// TODO uncomment when persist is less noisy\n\t//rf.Debug(dPersist, \"persisted state\")\n}", "func (rf *Raft) persist() {\n\t// Your code here.\n\t// Example:\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.log)\n\te.Encode(rf.lastIncludedIndex)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\tDPrintf(2, \"Server[%d] saving persist state: %d, %d, %+v\\n\", rf.me, rf.CurrentTerm, rf.VotedFor, rf.OpLog)\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.CurrentTerm)\n\te.Encode(rf.VotedFor)\n\te.Encode(rf.OpLog)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\trf.persistRaftStateAndSnapshot(nil)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.log)\n\te.Encode(rf.lastIncludedIndex)\n\te.Encode(rf.lastIncludedTerm)\n\t//e.Encode(rf.commitIndex)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here.\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := gob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.log)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here.\n\t// Example:\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.CurrentTerm)\n\te.Encode(rf.VotedFor)\n\te.Encode(rf.Log)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.log)\n\te.Encode(rf.voteGranted)\n\te.Encode(rf.voteNotGranted)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.logs)\n\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() { //\n\t// Your code here.\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := gob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\t//\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.log)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here.\n\t// Example:\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.voteFor)\n\te.Encode(rf.log)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n // Your code here (2C).\n // Example:\n // w := new(bytes.Buffer)\n // e := gob.NewEncoder(w)\n // e.Encode(rf.xxx)\n // e.Encode(rf.yyy)\n // data := w.Bytes()\n // rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\tbuf := new(bytes.Buffer)\n\traftPersistenceObj := RaftPersistence{\n\t\tCurrentTerm: rf.currentTerm,\n\t\tVotedFor: rf.voteForID,\n\t\tLastSnapshotIndex: rf.lastSnapshotIndex,\n\t\tLastSnapshotTerm: rf.lastSnapshotTerm,\n\t\t// LastApplied: rf.lastApplied,\n\t\t// CommitIndex: rf.commitIndex,\n\t}\n\traftPersistenceObj.Log = make([]LogEntry, len(rf.log))\n\tcopy(raftPersistenceObj.Log, rf.log)\n\n\tgob.NewEncoder(buf).Encode(raftPersistenceObj)\n\trf.persister.SaveRaftState(buf.Bytes())\n\t//RaftInfo(\"Saved persisted node data (%d bytes). log size is %d }\", rf, len(buf.Bytes()), len(raftPersistenceObj.Log))\n\n}", "func (rf *Raft) persist() {\n\t// Your code here.\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := gob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.log)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.raftData)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.commitIndex)\n\te.Encode(rf.lastApplied)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here.\n\t// Example:\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.logs)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\r\n\t// Your code here.\r\n\t// Example:\r\n\t// w := new(bytes.Buffer)\r\n\t// e := gob.NewEncoder(w)\r\n\t// e.Encode(rf.xxx)\r\n\t// e.Encode(rf.yyy)\r\n\t// data := w.Bytes()\r\n\t// rf.persister.SaveRaftState(data)\r\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t w := new(bytes.Buffer)\n\t e := gob.NewEncoder(w)\n\t e.Encode(rf.currentTerm)\n\t e.Encode(rf.votedFor)\n\t e.Encode(rf.log)\n\t data := w.Bytes()\n\t rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n // Your code here (2C).\n // Example:\n // w := new(bytes.Buffer)\n // e := labgob.NewEncoder(w)\n // e.Encode(rf.xxx)\n // e.Encode(rf.yyy)\n // data := w.Bytes()\n // rf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\terr := e.Encode(rf.currentTerm)\n\tif err!=nil {\n\t\tDPrintf(\"raft %d, encode currentTerm err: %v\",rf.currentTerm,err)\n\t}\n\terr = e.Encode(rf.votedFor)\n\tif err!=nil {\n\t\tDPrintf(\"raft %d, encode votedFor err: %v\",rf.currentTerm,err)\n\t}\n\n\terr = e.Encode(rf.log)\n\tif err!=nil {\n\t\tDPrintf(\"raft %d, encode log err: %v\",rf.currentTerm,err)\n\t}\n\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist(snapshot bool) {\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.log)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.lastIncludedIndex)\n\te.Encode(rf.lastIncludedTerm)\n\tdata := w.Bytes()\n\n\tif snapshot {\n\t\trf.persister.SaveStateAndSnapshot(data, rf.snapshot)\n\t} else {\n\t\trf.persister.SaveRaftState(data)\n\t}\n}", "func (rf *Raft) persistState() {\n\t// Your code here (2C).\n\t// Example:\n\tstate := rf.serializeState()\n\trf.persister.SaveRaftState(state)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\tt1 := time.Now()\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.currentTerm)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.log)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n\tduration := time.Now().Sub(t1)\n\tDPrintf(\"persist time finish in [%v]!!!\\n\", duration)\n}", "func (rf *Raft) persist() {\n\tw := new(bytes.Buffer)\n\te := gob.NewEncoder(w)\n\te.Encode(rf.CurrentTerm)\n\tif rf.VotedFor == nil {\n\t\trf.VotedFor = new(int)\n\t\t*rf.VotedFor = -1\n\t}\n\te.Encode(rf.VotedFor)\n\tif *rf.VotedFor == -1 {\n\t\trf.VotedFor = nil\n\t}\n\t*rf.Log = (*rf.Log)[:rf.lastNewEntryIndex+1-rf.lastSnapshotIndex]\n\te.Encode(rf.Log)\n\tcontent := w.Bytes()\n\trf.persister.SaveState(content)\n}", "func (rf *Raft) persist() {\n\trf.persister.SaveRaftState(rf.getRaftStateData())\n\tDebugPrint(\"%d save to %d, %d, %d, %d\\n\", rf.me, rf.term, rf.vote, rf.raftLog.commited, rf.raftLog.size)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\te.Encode(rf.term)\n\te.Encode(rf.votedFor)\n\te.Encode(rf.logEntries)\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n\n\t// DPrintf(\"%v persist term=%d voted-for=%d log-entries=%d\", rf.raftInfo(), rf.term, rf.votedFor, len(rf.logEntries))\n}", "func (rf *Raft) persist() {\n\tdata := rf.getPersistData()\n\trf.persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\tdefer DPrintf(\"rf [%v] persist term: %v len(log): %v \", rf.me, rf.Term, len(rf.Log))\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\t//rf.mu.Lock()\n\te.Encode(rf.Log)\n\te.Encode(rf.Term)\n\te.Encode(rf.VoteFor)\n\t//rf.mu.Unlock()\n\tdata := w.Bytes()\n\trf.Persister.SaveRaftState(data)\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\t// Example:\n\t// w := new(bytes.Buffer)\n\t// e := labgob.NewEncoder(w)\n\t// e.Encode(rf.xxx)\n\t// e.Encode(rf.yyy)\n\t// data := w.Bytes()\n\t// rf.persister.SaveRaftState(data)\n\n\tDPrintf(\" server %v persist success and current term is %v\", rf.me, rf.currentTerm)\n\n\tw := new(bytes.Buffer)\n\te := labgob.NewEncoder(w)\n\terr := e.Encode(rf.currentTerm)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = e.Encode(rf.voteFor)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = e.Encode(rf.logOfRaft)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdata := w.Bytes()\n\trf.persister.SaveRaftState(data)\n\n}", "func (s *ServiceState) save() {\n\tlog.Lvl3(\"Saving service\")\n\tb, err := network.Marshal(s.Storage)\n\tif err != nil {\n\t\tlog.Error(\"Couldn't marshal service:\", err)\n\t} else {\n\t\terr = ioutil.WriteFile(s.path+\"/prifi.bin\", b, 0660)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Couldn't save file:\", err)\n\t\t}\n\t}\n}", "func (m *stateManager) Save() (err error) {\n\terr = m.storage.Write(m.state)\n\n\tif err == nil {\n\t\tm.stateChanged = false\n\t\tm.stateLoaded = true\n\t}\n\n\treturn\n}", "func (rf *Raft) persist() {\n\t// Your code here (2C).\n\tdata := rf.getPersistData()\n\trf.persister.SaveRaftState(data)\n}", "func (fb *FileBackend) save(state *storage.State) error {\n\tout, err := proto.Marshal(state)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to encode state: %w\", err)\n\t}\n\ttmp := fmt.Sprintf(fb.path+\".%v\", time.Now())\n\tif err := ioutil.WriteFile(tmp, out, 0600); err != nil {\n\t\treturn fmt.Errorf(\"failed to write state: %w\", err)\n\t}\n\terr = os.Rename(tmp, fb.path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to move state: %w\", err)\n\t}\n\treturn nil\n}", "func (g *Gossiper) SaveState() {\n\tobj, e := json.MarshalIndent(g, \"\", \"\\t\")\n\tutils.HandleError(e)\n\t_ = os.Mkdir(utils.STATE_FOLDER, os.ModePerm)\n\tcwd, _ := os.Getwd()\n\te = ioutil.WriteFile(filepath.Join(cwd, utils.STATE_FOLDER, fmt.Sprint(g.Name, \".json\")), obj, 0644)\n\tutils.HandleError(e)\n}", "func (d *Database) Save() error {\n\tb, err := json.Marshal(d.State)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Save\n\tif err := ioutil.WriteFile(d.FilePath, b, os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (manager *basicStateManager) ForceSave() error {\n\tmanager.savingLock.Lock()\n\tdefer manager.savingLock.Unlock()\n\tseelog.Info(\"Saving state!\")\n\ts := manager.state\n\ts.Version = ECSDataVersion\n\n\tdata, err := json.Marshal(s)\n\tif err != nil {\n\t\tseelog.Error(\"Error saving state; could not marshal data; this is odd\", \"err\", err)\n\t\treturn err\n\t}\n\treturn manager.writeFile(data)\n}", "func (mw *ShardedRDB) SaveRaftState(updates []pb.Update,\n\tctx raftio.IContext) error {\n\tif len(updates) == 0 {\n\t\treturn nil\n\t}\n\tpid := mw.getParititionID(updates)\n\treturn mw.shards[pid].saveRaftState(updates, ctx)\n}", "func (p *Platform) PersistStateToFile(filename string) (*Platform, error) {\n\tif _, err := os.Stat(filename); !os.IsNotExist(err) {\n\t\t// If the file exists, read the state from the file and make it a backup of the file\n\t\tif _, err := p.ReadStateFromFile(filename); err != nil {\n\t\t\treturn p, err\n\t\t}\n\t\tos.Rename(filename, filename+\".bkp\")\n\t}\n\n\t// The files does not exists, create it with the current state: empty or loaded\n\tif _, err := p.WriteStateToFile(filename); err != nil {\n\t\treturn p, err\n\t}\n\n\tfsStateMgr := statemgr.NewFilesystem(filename)\n\tp.stateMgr = fsStateMgr\n\n\treturn p, nil\n}", "func (l *LogDB) SaveRaftState(updates []pb.Update, shardID uint64) error {\n\tif l.collection.multiplexedLog() {\n\t\treturn l.concurrentSaveState(updates, shardID)\n\t}\n\treturn l.sequentialSaveState(updates, shardID)\n}", "func (ms *MemoryStorage) PersistHardState(hs pb.HardState) {\n\tms.hardState.hs = hs\n\tms.hardState.set = true\n}", "func (t *turtle) persist() error {\n\treturn t.bdp.Persist(mesh.TORTOISE, t)\n}", "func (rf *Raft) readPersist(data []byte) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tif data == nil || len(data) < 1 { // bootstrap without any state?\n\t\treturn\n\t}\n\n\tr := bytes.NewBuffer(data)\n\td := labgob.NewDecoder(r)\n\tvar s PersistentState\n\tif e := d.Decode(&s); e != nil {\n\t\trf.Log(LogError, \"Error reading persistent state.\\n - error\", e)\n\t} else {\n\t\trf.currentTerm = s.CurrentTerm\n\t\trf.votedFor = s.VotedFor\n\t\trf.log = s.Log\n\t\trf.Log(LogDebug, \"Read persistent state on restart:\", \"\\nrf.currentTerm:\", rf.currentTerm, \"\\nrf.votedFor:\", rf.votedFor, \"\\nrf.log\", rf.log)\n\t}\n}", "func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error {\n\t// Create a temporary path for the state store\n\ttmpPath, err := ioutil.TempDir(os.TempDir(), \"state\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(tmpPath)\n\n\tdb, err := leveldb.OpenFile(tmpPath, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\titer := f.snapshot.NewIterator(nil, nil)\n\tfor iter.Next() {\n\t\terr = db.Put(iter.Key(), iter.Value(), nil)\n\t\tif err != nil {\n\t\t\tdb.Close()\n\t\t\tsink.Cancel()\n\t\t\treturn err\n\t\t}\n\t}\n\titer.Release()\n\tdb.Close()\n\n\t// make tar.gz\n\tw := gzip.NewWriter(sink)\n\terr = util.Tar(tmpPath, w)\n\tif err != nil {\n\t\tsink.Cancel()\n\t\treturn err\n\t}\n\n\terr = w.Close()\n\tif err != nil {\n\t\tsink.Cancel()\n\t\treturn err\n\t}\n\n\tsink.Close()\n\treturn nil\n}", "func saveStore(s dhtStore) {\n\tif s.path == \"\" {\n\t\treturn\n\t}\n\ttmp, err := ioutil.TempFile(s.path, \"marconi\")\n\tif err != nil {\n\t\tlog.Println(\"saveStore tempfile:\", err)\n\t\treturn\n\t}\n\terr = json.NewEncoder(tmp).Encode(s)\n\t// The file has to be closed already otherwise it can't be renamed on\n\t// Windows.\n\ttmp.Close()\n\tif err != nil {\n\t\tlog.Println(\"saveStore json encoding:\", err)\n\t\treturn\n\t}\n\n\t// Write worked, so replace the existing file. That's atomic in Linux, but\n\t// not on Windows.\n\tp := fmt.Sprintf(\"%v-%v\", s.path+\"/dht\", s.Port)\n\tif err := os.Rename(tmp.Name(), p); err != nil {\n\t\t// if os.IsExist(err) {\n\t\t// Not working for Windows:\n\t\t// http://code.google.com/p/go/issues/detail?id=3828\n\n\t\t// It's not possible to atomically rename files on Windows, so I\n\t\t// have to delete it and try again. If the program crashes between\n\t\t// the unlink and the rename operation, it loses the configuration,\n\t\t// unfortunately.\n\t\tif err := os.Remove(p); err != nil {\n\t\t\tlog.Println(\"saveStore failed to remove the existing config:\", err)\n\t\t\treturn\n\t\t}\n\t\tif err := os.Rename(tmp.Name(), p); err != nil {\n\t\t\tlog.Println(\"saveStore failed to rename file after deleting the original config:\", err)\n\t\t\treturn\n\t\t}\n\t\t// } else {\n\t\t// \tlog.Println(\"saveStore failed when replacing existing config:\", err)\n\t\t// }\n\t} else {\n\t\t// log.Println(\"Saved DHT routing table to the filesystem.\")\n\t}\n}", "func SaveState(backupFile string, noteAll *[]*notes.Note) {\n\tdat, err := json.Marshal(noteAll)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\terr = ioutil.WriteFile(backupFile, dat, 0644)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (c *Checkpoint) persist() bool {\n\tif c.numUpdates == 0 {\n\t\treturn false\n\t}\n\n\terr := c.flush()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tlogp.Debug(\"checkpoint\", \"Checkpoint saved to disk. numUpdates=%d\",\n\t\tc.numUpdates)\n\tc.numUpdates = 0\n\treturn true\n}", "func (r *LocalRegistry) save() {\n\tregBytes := core.ToJsonBytes(r)\n\tcore.CheckErr(ioutil.WriteFile(r.file(), regBytes, os.ModePerm), \"fail to update local registry metadata\")\n}", "func (service *HTTPRestService) saveState() error {\n\tlog.Printf(\"[Azure CNS] saveState\")\n\n\t// Skip if a store is not provided.\n\tif service.store == nil {\n\t\tlog.Printf(\"[Azure CNS] store not initialized.\")\n\t\treturn nil\n\t}\n\n\t// Update time stamp.\n\tservice.state.TimeStamp = time.Now()\n\terr := service.store.Write(storeKey, &service.state)\n\tif err == nil {\n\t\tlog.Printf(\"[Azure CNS] State saved successfully.\\n\")\n\t} else {\n\t\tlog.Errorf(\"[Azure CNS] Failed to save state., err:%v\\n\", err)\n\t}\n\n\treturn err\n}", "func (env *Solo) SaveSnapshot(fname string) {\n\tenv.glbMutex.Lock()\n\tdefer env.glbMutex.Unlock()\n\n\tsnapshot := soloSnapshot{\n\t\tUtxoDB: env.utxoDB.State(),\n\t}\n\n\tfor _, ch := range env.chains {\n\t\tchainSnapshot := soloChainSnapshot{\n\t\t\tName: ch.Name,\n\t\t\tStateControllerKeyPair: rwutil.WriteToBytes(ch.StateControllerKeyPair),\n\t\t\tChainID: ch.ChainID.Bytes(),\n\t\t\tOriginatorPrivateKey: rwutil.WriteToBytes(ch.OriginatorPrivateKey),\n\t\t\tValidatorFeeTarget: ch.ValidatorFeeTarget.Bytes(),\n\t\t}\n\n\t\terr := ch.db.Iterate(kvstore.EmptyPrefix, func(k, v []byte) bool {\n\t\t\tchainSnapshot.DB = append(chainSnapshot.DB, k, v)\n\t\t\treturn true\n\t\t})\n\t\trequire.NoError(env.T, err)\n\n\t\tsnapshot.Chains = append(snapshot.Chains, chainSnapshot)\n\t}\n\n\tb, err := json.Marshal(snapshot)\n\trequire.NoError(env.T, err)\n\terr = os.WriteFile(fname, b, 0o600)\n\trequire.NoError(env.T, err)\n}", "func (s store) Save() {\n\ts.writeToDisk()\n}", "func (c *Checkpoint) Persist(path, cursor string, realTs, monotonicTs uint64) {\n\tc.PersistState(JournalState{\n\t\tPath: path,\n\t\tCursor: cursor,\n\t\tRealtimeTimestamp: realTs,\n\t\tMonotonicTimestamp: monotonicTs,\n\t})\n}", "func (rf *Raft) readPersist(data []byte) {\n\tif len(data) == 0 {\n\t\treturn\n\t}\n\tvar p persistentState\n\tbuf := bytes.NewReader(data)\n\tgob.NewDecoder(buf).Decode(&p)\n\trf.currentTerm.Store(p.CurrentTerm)\n\trf.votedFor = p.VotedFor\n\trf.logs = p.Logs\n\trf.state.Store(p.State)\n\trf.startLogIndex = p.StartLogIndex\n\trf.startLogTerm = p.StartLogTerm\n\trf.lastApplied = p.StartLogIndex - 1\n\trf.commitIndex = p.StartLogIndex - 1\n}", "func (s *MapStorage) Persist() error {\n\tdataj, _ := json.Marshal(*s)\n\treturn ioutil.WriteFile(s.name+\".json\", dataj, 0644)\n}", "func (s *Store) SaveState() (err error) {\n\tif err = s.writePluginIDMap(); err != nil {\n\t\tslog.WithError(err).Error(\"can't write plugin id maps\")\n\t}\n\treturn\n}", "func (m *SynapsesPersist) Save() {\n\tif m.changed {\n\t\tfmt.Println(\"Saving synaptic data...\")\n\t\tindentedJSON, _ := json.MarshalIndent(m.Synapses, \"\", \" \")\n\n\t\tdataPath, err := filepath.Abs(m.relativePath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\terr = ioutil.WriteFile(dataPath+m.file, indentedJSON, 0644)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"ERROR:\", err)\n\t\t}\n\n\t\tm.Clean()\n\t\tfmt.Println(\"Synaptic data saved\")\n\t}\n}", "func saveState(ca *cauth.Ca) {\n\terr := ca.SavePrivateKey()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = ca.SaveCertificate()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (r *RadioStation) Save() error {\n\treturn nil\n}", "func (rs *RatchetServer) persist() error {\n\t// StoreTypeServerKeys\n\tif err := rs.persistence.Store(StoreTypeServerKeys, rs.keys.Marshall()); err != nil {\n\t\treturn err\n\t}\n\t// StoreTypeFountain\n\tif err := rs.persistence.Store(StoreTypeFountain, rs.fountain.Marshall()); err != nil {\n\t\treturn err\n\t}\n\t// StoreTypePregen\n\tif err := rs.persistence.Store(StoreTypePregen, rs.pregenerator.Marshall()); err != nil {\n\t\treturn err\n\t}\n\t// StoreTypeKeyList\n\tif rs.keylist != nil {\n\t\tif err := rs.persistence.Store(StoreTypeKeyList, rs.keylist); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func SaveLastRunState(lastRunState LastRunDownServers) {\n\t// write new last run state\n\tb, err := json.MarshalIndent(lastRunState, \"\", \" \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = ioutil.WriteFile(\"status.json\", b, 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (rf *Raft) readPersist(data []byte) {\n\tif data == nil || len(data) < 1 { // bootstrap without any state?\n\t\treturn\n\t}\n\tr := bytes.NewBuffer(data)\n\td := labgob.NewDecoder(r)\n\tvar currentTerm int\n\tvar votedFor \tint\n\tvar logs \t\t[]LogEntry\n\tvar commitIndex int\n\tvar lastSnapshotIndex int\n\tif d.Decode(&currentTerm) != nil || d.Decode(&votedFor) != nil || d.Decode(&logs) != nil ||\n\t\td.Decode(&commitIndex) != nil || d.Decode(&lastSnapshotIndex) != nil {\n\t\tpanic(\"fail to decode state\")\n\t} else {\n\t\trf.mu.Lock()\n\t\trf.currentTerm = currentTerm\n\t\trf.votedFor = votedFor\n\t\trf.logs = logs\n\t\trf.commitIndex = commitIndex\n\t\trf.lastSnapshotIndex = lastSnapshotIndex\n\t\t// bug修复: raft重启时要将rf.lastApplied初始化为lastSnapshotIndex,否则在commitLog时会报错(index为负数)\n\t\trf.lastApplied = lastSnapshotIndex\n\t\trf.mu.Unlock()\n\t}\n}", "func (s *LocalSnapStore) Save(snap brtypes.Snapshot, rc io.ReadCloser) error {\n\tdefer rc.Close()\n\terr := os.MkdirAll(path.Join(s.prefix, snap.SnapDir), 0700)\n\tif err != nil && !os.IsExist(err) {\n\t\treturn err\n\t}\n\tf, err := os.Create(path.Join(s.prefix, snap.SnapDir, snap.SnapName))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\t_, err = io.Copy(f, rc)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.Sync()\n}", "func (r GopassRepo) saveState(payload []byte) error {\n\tif err := r.prepare(); err != nil {\n\t\treturn err\n\t}\n\tcmd := exec.Command(\"gopass\", \"insert\", \"-f\", r.config.Repo.State)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tstdin, err := cmd.StdinPipe()\n\tif nil != err {\n\t\treturn fmt.Errorf(\"obtaining stdin: %s\", err.Error())\n\t}\n\tpayload = append(payload, []byte(\"\\n\")...)\n\tencoder := base64.NewEncoder(base64.StdEncoding, stdin)\n\tif _, err := encoder.Write(payload); nil != err {\n\t\treturn fmt.Errorf(\"encoding failed with %s\", err)\n\t}\n\n\tif err := cmd.Start(); nil != err {\n\t\treturn fmt.Errorf(\"gopass failed with %s\", err)\n\t}\n\tstdin.Close()\n\tencoder.Close()\n\tif err := cmd.Wait(); nil != err {\n\t\treturn fmt.Errorf(\"gopass failed with %s\", err)\n\t}\n\n\treturn nil\n}", "func (c *Contractor) saveSync() error {\n\treturn c.persist.saveSync(c.persistData())\n}", "func (c *Checkpoint) PersistState(st JournalState) {\n\tc.save <- st\n}", "func (rf *Raft) readPersist(data []byte) {\n\tif data == nil || len(data) < 1 { // bootstrap without any state?\n\t\treturn\n\t}\n\t// Your code here (2C).\n\t// Example:\n\t// r := bytes.NewBuffer(data)\n\t// d := labgob.NewDecoder(r)\n\t// var xxx\n\t// var yyy\n\t// if d.Decode(&xxx) != nil ||\n\t// d.Decode(&yyy) != nil {\n\t// error...\n\t// } else {\n\t// rf.xxx = xxx\n\t// rf.yyy = yyy\n\t// }\n\n\tbuf := bytes.NewBuffer(data)\n\ttempgob := gob.NewDecoder(buf)\n\ttempobj := RaftPersistence{}\n\ttempgob.Decode(&tempobj)\n\n\t//RaftInfo(\"Debug tempobj lastapplied = %d, commitIndex = %d, len(log) = %d\", rf, tempobj.LastApplied, tempobj.CommitIndex, len(tempobj.Log))\n\n\trf.currentTerm = tempobj.CurrentTerm\n\trf.log = tempobj.Log\n\trf.voteForID = tempobj.VotedFor\n\trf.lastSnapshotIndex = tempobj.LastSnapshotIndex\n\trf.lastSnapshotTerm = tempobj.LastSnapshotTerm\n\t// rf.lastApplied = tempobj.LastApplied\n\t// rf.commitIndex = tempobj.CommitIndex\n\n\t//RaftInfo(\"Loaded persisted node data (%d bytes). Last applied index: %d, log size is %d }\", rf, len(data), rf.lastApplied, len(rf.log))\n}" ]
[ "0.75167", "0.74272084", "0.7385772", "0.7351551", "0.732249", "0.7304177", "0.72780186", "0.72733635", "0.72732216", "0.7220507", "0.72022516", "0.72020787", "0.71884644", "0.71784896", "0.7176185", "0.71755075", "0.71626043", "0.71472174", "0.7138765", "0.7133676", "0.7133676", "0.7133676", "0.7133676", "0.7133676", "0.7133676", "0.7133676", "0.7133676", "0.7133676", "0.7133676", "0.71329325", "0.7132007", "0.71307105", "0.71273816", "0.71238554", "0.7115093", "0.7113032", "0.7100096", "0.7097758", "0.7093318", "0.7087399", "0.7084665", "0.7084358", "0.70702285", "0.70699185", "0.706986", "0.70576155", "0.7056425", "0.70537364", "0.7051346", "0.70232326", "0.70215344", "0.7011929", "0.70115775", "0.6991049", "0.69803375", "0.693074", "0.6875007", "0.6814168", "0.68007034", "0.6783676", "0.67659473", "0.6722533", "0.6633177", "0.65908", "0.64189595", "0.6265389", "0.6263995", "0.6262071", "0.6190921", "0.61312723", "0.6111332", "0.6108633", "0.6058927", "0.60483485", "0.6021651", "0.6017171", "0.6015332", "0.59978366", "0.5993777", "0.5987164", "0.59749454", "0.5969028", "0.5960696", "0.5931168", "0.59268576", "0.5922833", "0.5915132", "0.58814216", "0.58680695", "0.5866646", "0.58573383", "0.58530325", "0.58389646", "0.583545", "0.5827936", "0.58220285", "0.5813261" ]
0.71416587
20
restore previously persisted state.
func (rf *Raft) readPersist(data []byte) { // Your code here (2C). // Example: // r := bytes.NewBuffer(data) // d := gob.NewDecoder(r) // d.Decode(&rf.xxx) // d.Decode(&rf.yyy) if data == nil || len(data) < 1 { // bootstrap without any state? return } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *fsm) Restore(rc io.ReadCloser) error {\n\t//o := NewInMemDatastore()\n\t//if err := json.NewDecoder(rc).Decode(&o.m); err != nil {\n\t//\treturn err\n\t//}\n\n\t// Set the state from the snapshot, no lock required according to\n\t// Hashicorp docs.\n\t//f.m = o\n\n\treturn nil\n}", "func (s *Store) Restore(rc io.ReadCloser) error {\n\t// TODO\n\treturn nil\n}", "func (r Restorer) Restore() {\n\tr()\n}", "func (f *raftStore) Restore(rc io.ReadCloser) error {\n\tvar o state\n\tif err := json.NewDecoder(rc).Decode(&o); err != nil {\n\t\treturn err\n\t}\n\tf.mu.Lock()\n\tf.inFlight = nil\n\tf.mu.Unlock()\n\n\tf.m.setNewState(o)\n\treturn nil\n}", "func (f *fsm) Restore(closer io.ReadCloser) error {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\tdefer closer.Close()\n\tdecoder := gob.NewDecoder(closer)\n\tvar state State\n\tif err := decoder.Decode(&state); err != nil {\n\t\treturn err\n\t}\n\tf.state = state\n\treturn nil\n}", "func (c *Camera) Restore(state model.PlayerState) {\n\tc.pos = mgl32.Vec3{state.X, state.Y, state.Z}\n\tc.rotatex = state.Rx\n\tc.rotatey = state.Ry\n\tc.updateAngles()\n}", "func (s *Sandbox) Restore() error {\n\tss, _, err := s.newStore.FromDisk(s.id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.loadState(ss)\n\ts.loadDevices(ss.Devices)\n\treturn nil\n}", "func (f *fsm) Restore(rc io.ReadCloser) error {\n\treturn f.badger.Load(rc)\n}", "func (ft *factsTable) restore() {\n\tif ft.unsatDepth > 0 {\n\t\tft.unsatDepth--\n\t} else {\n\t\tft.unsat = false\n\t}\n\tfor {\n\t\told := ft.stack[len(ft.stack)-1]\n\t\tft.stack = ft.stack[:len(ft.stack)-1]\n\t\tif old == checkpointFact {\n\t\t\tbreak\n\t\t}\n\t\tif old.r == lt|eq|gt {\n\t\t\tdelete(ft.facts, old.p)\n\t\t} else {\n\t\t\tft.facts[old.p] = old.r\n\t\t}\n\t}\n\tfor {\n\t\told := ft.limitStack[len(ft.limitStack)-1]\n\t\tft.limitStack = ft.limitStack[:len(ft.limitStack)-1]\n\t\tif old.vid == 0 { // checkpointBound\n\t\t\tbreak\n\t\t}\n\t\tif old.limit == noLimit {\n\t\t\tdelete(ft.limits, old.vid)\n\t\t} else {\n\t\t\tft.limits[old.vid] = old.limit\n\t\t}\n\t}\n\tft.orderS.Undo()\n\tft.orderU.Undo()\n}", "func (d *digest) Restore(state []byte) error {\n\tdecoder := gob.NewDecoder(bytes.NewReader(state))\n\n\t// We decode this way so that we do not have\n\t// to export these fields of the digest struct.\n\tvals := []interface{}{\n\t\t&d.h, &d.x, &d.nx, &d.len, &d.is224,\n\t}\n\n\tfor _, val := range vals {\n\t\tif err := decoder.Decode(val); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (rf *Raft) restoreState() {\n\tstate := rf.persister.ReadRaftState()\n\tif state == nil || len(state) < 1 { // bootstrap without any state?\n\t\treturn\n\t}\n\t// Your code here (2C).\n\t// Example:\n\tr := bytes.NewBuffer(state)\n\td := labgob.NewDecoder(r)\n\tcurrentTerm := 0\n\tvotedFor := 0\n\traftLog := raftLog{}\n\tif d.Decode(&currentTerm) != nil ||\n\t\td.Decode(&votedFor) != nil ||\n\t\td.Decode(&raftLog) != nil {\n\t\tlog.Fatalln(\"Cannot decode persisted state\")\n\t} else {\n\t\trf.currentTerm = currentTerm\n\t\trf.votedFor = votedFor\n\t\trf.log = raftLog\n\t\trf.lastApplied = raftLog.LastIncludedIndex\n\t\trf.commitIndex = raftLog.LastIncludedIndex\n\t}\n}", "func (w *WorkerFSM) Restore(i io.ReadCloser) error {\n return nil\n}", "func (s *Surface) Restore() {\n\ts.Ctx.Call(\"restore\")\n}", "func (i *Item) Restore() {\n\ti.mu.Lock()\n\tdefer i.mu.Unlock()\n\n\tif i.closed {\n\t\tpanic(\"result: already closed\")\n\t}\n\n\ti.restore()\n\ti.closed = true\n}", "func restore() {\n\tfor _, dir := range []string{\n\t\t*restorePath,\n\t\tfmt.Sprintf(\"%s/remote\", *restorePath),\n\t\tfmt.Sprintf(\"%s/plain\", *restorePath),\n\t\tfmt.Sprintf(\"%s/remote/.git\", *restorePath),\n\t} {\n\t\tif _, err := os.Stat(dir); os.IsNotExist(err) {\n\t\t\tlog.Fatalf(\"restore req missing [%s]\", dir)\n\t\t}\n\t}\n\n\tlog.Info(\"store decrypt\")\n\tstore := fmt.Sprintf(\"%s/%s\", *restorePath, \"disposition-state.db\")\n\terr := crypto.Decrypt(\n\t\t[]byte(cfg.Secret.Key),\n\t\tstore,\n\t\tfmt.Sprintf(\"%s/%s/%s\", *restorePath, \"remote\", cfg.Secret.Obfuscated),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to decrypt state\")\n\t}\n\n\tlog.Debug(\"state init\")\n\tstorage, err := sqlite.New(store)\n\tif err != nil {\n\t\tlog.Fatalf(\"restore | sqlite.New [%s]\", err)\n\t}\n\n\tstoredFiles, err := storage.Files()\n\tif err != nil {\n\t\tlog.Fatalf(\"restore | storage.Files [%s]\", err)\n\t}\n\n\tfor _, storedFile := range storedFiles {\n\t\terr = crypto.Decrypt(\n\t\t\t[]byte(cfg.Secret.Key),\n\t\t\tfmt.Sprintf(\"%s/%s/%s\", *restorePath, \"plain\", storedFile.Name[1:]),\n\t\t\tfmt.Sprintf(\"%s/%s/%s\", *restorePath, \"remote\", storedFile.Obfuscated),\n\t\t)\n\t\tif err != nil {\n\t\t\tlog.Infof(\"failed to decrypt [%s -> %s]\", storedFile.Obfuscated, storedFile.Name)\n\t\t}\n\t}\n\n\tlog.Debug(\"state close\")\n\terr = storage.Close()\n\tif err != nil {\n\t\tlog.Fatalf(\"restore | storage.Close [%s]\", err)\n\t}\n}", "func (proc *Proc) Restore(p *os.Process) {\n\tproc.Pid = p.Pid\n\tproc.process = p\n\tproc.Status.SetStatus(\"restored\")\n}", "func (p *parser) restoreState(state storeDict) {\n\tif p.debug {\n\t\tdefer p.out(p.in(\"restoreState\"))\n\t}\n\tp.cur.state = state\n}", "func (p *parser) restore(pt savepoint) {\n\tif pt.offset == p.pt.offset {\n\t\treturn\n\t}\n\tp.pt = pt\n}", "func (p *parser) restoreState(state storeDict) {\n\tif p.debug {\n\t\tdefer p.out(p.in(\"restoreState\"))\n\t}\n\tp.cur.state.Discard()\n\tp.cur.state = state\n}", "func (p *parser) restoreState(state storeDict) {\n\tif p.debug {\n\t\tdefer p.out(p.in(\"restoreState\"))\n\t}\n\tp.cur.state.Discard()\n\tp.cur.state = state\n}", "func (s *SimpleFSM) Restore(kvMap io.ReadCloser) error {\n\n\tkvSnapshot := make(map[string]string)\n\tif err := json.NewDecoder(kvMap).Decode(&kvSnapshot); err != nil {\n\t\treturn err\n\t}\n\n\t// Set the state from the snapshot, no lock required according to\n\t// Hashicorp docs.\n\tfor k, v := range kvSnapshot {\n\t\ts.db.Update(func(tx *bolt.Tx) error {\n\t\t\tb := tx.Bucket(bucket)\n\t\t\terr := b.Put([]byte(k), []byte(v))\n\t\t\treturn err\n\t\t})\n\t}\n\treturn nil\n}", "func (strg *Storage) Restore(m map[storage.Key]*storage.Value) error {\n\tstrg.setItems(m)\n\treturn nil\n}", "func (builder *Builder) Restore() *Builder {\n\treturn builder.With(Restore)\n}", "func (t *TimeLine) Restore() {\n\tt.cursor = t.backup.cursor\n\tt.lastDelta = t.backup.lastDelta\n\tt.plannedCallbacks = t.backup.plannedCallbacks\n}", "func (c *Container) Restore() error {\n\t_, cs, err := c.sandbox.newStore.FromDisk(c.sandbox.id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, ok := cs[c.id]; !ok {\n\t\treturn errContainerPersistNotExist\n\t}\n\n\tc.state = types.ContainerState{\n\t\tState: types.StateString(cs[c.id].State),\n\t\tBlockDeviceID: cs[c.id].Rootfs.BlockDeviceID,\n\t\tFstype: cs[c.id].Rootfs.FsType,\n\t\tCgroupPath: cs[c.id].CgroupPath,\n\t}\n\n\treturn nil\n}", "func (s *Store) Restore(b block.Shape, start, numInputs int) {\n\tfor i := 0; i < numInputs && i < len(s.connections); i++ {\n\t\twsinput := b.Input(start + i)\n\t\tc := s.connections[i]\n\t\treconnect(b, wsinput, c)\n\t}\n}", "func (f *FSM) Restore(reader io.ReadCloser) error {\n\tf.registry.Lock()\n\tdefer f.registry.Unlock()\n\n\ttracer := f.registry.TracerFSM()\n\n\t// The first 8 bytes contain the FSM Raft log index.\n\tvar index uint64\n\tif err := binary.Read(reader, binary.LittleEndian, &index); err != nil {\n\t\treturn errors.Wrap(err, \"failed to read FSM index\")\n\t}\n\n\ttracer = tracer.With(trace.Integer(\"restore\", int64(index)))\n\ttracer.Message(\"start\")\n\n\tf.registry.IndexUpdate(index)\n\n\tfor {\n\t\tdone, err := f.restoreDatabase(tracer, reader)\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}\n\n\ttracer.Message(\"done\")\n\n\treturn nil\n}", "func (service *HTTPRestService) restoreState() error {\n\tlog.Printf(\"[Azure CNS] restoreState\")\n\n\t// Skip if a store is not provided.\n\tif service.store == nil {\n\t\tlog.Printf(\"[Azure CNS] store not initialized.\")\n\t\treturn nil\n\t}\n\n\t// Read any persisted state.\n\terr := service.store.Read(storeKey, &service.state)\n\tif err != nil {\n\t\tif err == store.ErrKeyNotFound {\n\t\t\t// Nothing to restore.\n\t\t\tlog.Printf(\"[Azure CNS] No state to restore.\\n\")\n\t\t\treturn nil\n\t\t}\n\n\t\tlog.Errorf(\"[Azure CNS] Failed to restore state, err:%v\\n\", err)\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[Azure CNS] Restored state, %+v\\n\", service.state)\n\treturn nil\n}", "func (p *parser) restore(pt savepoint) {\n\tif p.debug {\n\t\tdefer p.out(p.in(\"restore\"))\n\t}\n\tif pt.offset == p.pt.offset {\n\t\treturn\n\t}\n\tp.pt = pt\n}", "func (p *parser) restore(pt savepoint) {\n\tif p.debug {\n\t\tdefer p.out(p.in(\"restore\"))\n\t}\n\tif pt.offset == p.pt.offset {\n\t\treturn\n\t}\n\tp.pt = pt\n}", "func (p *parser) restore(pt savepoint) {\n\tif p.debug {\n\t\tdefer p.out(p.in(\"restore\"))\n\t}\n\tif pt.offset == p.pt.offset {\n\t\treturn\n\t}\n\tp.pt = pt\n}", "func (p *parser) restore(pt savepoint) {\n\tif p.debug {\n\t\tdefer p.out(p.in(\"restore\"))\n\t}\n\tif pt.offset == p.pt.offset {\n\t\treturn\n\t}\n\tp.pt = pt\n}", "func (o *ParamsReg) Restore(skipNotification bool) {\n\tcopy(o.theta, o.bkpTheta)\n\to.bias = o.bkpBias\n\to.lambda = o.bkpLambda\n\to.degree = o.bkpDegree\n\tif !skipNotification {\n\t\to.NotifyUpdate()\n\t}\n}", "func (kvm *Clone) Restore(rd io.Reader) error {\n\tkvm.mu.Lock()\n\tdefer kvm.mu.Unlock()\n\tdata, err := ioutil.ReadAll(rd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar keys map[string][]byte\n\tif err := json.Unmarshal(data, &keys); err != nil {\n\t\treturn err\n\t}\n\tkvm.keys = keys\n\treturn nil\n}", "func (s *KVStore) RestoreSnapshot(snapshot []byte) {\n\tlog.Printf(\"Restore all value from a snapshot\")\n\tread := bytes.NewBuffer(snapshot)\n\tdecoder := gob.NewDecoder(read)\n\tdecoder.Decode(&s.store)\n}", "func (l *Service) Restore(reader io.Reader) error {\n\tlength, err := util.ReadVarInt(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.values = make([]string, length)\n\treturn util.ReadSlice(reader, l.values, func(data []byte) (string, error) {\n\t\treturn string(data), nil\n\t})\n}", "func restoreTerminal() {\n\tif !stdoutIsTerminal() {\n\t\treturn\n\t}\n\n\tfd := int(os.Stdout.Fd())\n\tstate, err := terminal.GetState(fd)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"unable to get terminal state: %v\\n\", err)\n\t\treturn\n\t}\n\n\tAddCleanupHandler(func() error {\n\t\t// Restoring the terminal configuration while restic runs in the\n\t\t// background, causes restic to get stopped on unix systems with\n\t\t// a SIGTTOU signal. Thus only restore the terminal settings if\n\t\t// they might have been modified, which is the case while reading\n\t\t// a password.\n\t\tif !isReadingPassword {\n\t\t\treturn nil\n\t\t}\n\t\terr := checkErrno(terminal.Restore(fd, state))\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"unable to restore terminal state: %v\\n\", err)\n\t\t}\n\t\treturn err\n\t})\n}", "func Restore(fd uintptr, state *State) error {\n\tcmd := exec.Command(\"stty\", \"echo cooked\")\n\tcmd.Run()\n\treturn nil\n}", "func (v *NopObject) Restore(Snapshot string) (err error) {\n\treturn\n}", "func Restore(state State) {\n\triscv.EnableInterrupts(uintptr(state))\n}", "func termrestoreState(L *lua.LState) int {\n\terr := term.Restore(int(os.Stdin.Fd()), termState)\n\tif err != nil {\n\t\tL.RaiseError(err.Error())\n\t}\n\n\treturn 0\n}", "func (a *actuator) Restore(ctx context.Context, ex *extensionsv1alpha1.Extension) error {\n\treturn a.Reconcile(ctx, ex)\n}", "func (ipset *IPSet) Restore() error {\n\tstdin := bytes.NewBufferString(buildIPSetRestore(ipset))\n\terr := ipset.runWithStdin(stdin, \"restore\", \"-exist\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *UserModel) Restore(ctx context.Context, builders ...query.SQLBuilder) (int64, error) {\n\tm2 := m.WithTrashed()\n\treturn m2.UpdateFields(ctx, query.KV{\n\t\t\"deleted_at\": nil,\n\t}, builders...)\n}", "func (t *tempLogger) Restore() {\n\twrappedLogger.zap = &(t.previous)\n}", "func (w *Wrapper) Restore() error {\n\tif w.saved == nil {\n\t\treturn errors.New(\"attempted to restore without saving.\")\n\t}\n\tif !w32.SetConsoleTextAttribute(w.h, w.saved.WAttributes) {\n\t\treturn syscall.Errno(w32.GetLastError())\n\t}\n\treturn nil\n}", "func (rcr *RawRuneReader) Restore() error {\n\treturn terminal.Restore(syscall.Stdin, rcr.state)\n}", "func (g *Store) Rollback() error {\n\treturn g.ResetToHeadAll()\n}", "func (master *ProcMaster) restore(proc ProcContainer) error {\n\tif proc.IsAlive() {\n\t\tmaster.Watcher.AddProcWatcher(proc, true /*non-child*/)\n\t\tproc.SetStatus(\"restored\")\n\t\treturn nil\n\t}\n\treturn errors.New(fmt.Sprintf(\"Restore called on %s but process not running.\", proc.Identifier()))\n}", "func Recover() ElevatorState {\n\tvar state ElevatorState\n\tdataFile, err := os.Open(\"backup.gob\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tdataDecoder := gob.NewDecoder(dataFile)\n\terr = dataDecoder.Decode(&state)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\treturn state\n}", "func (msh *Mesh) revertState(ctx context.Context, layerID types.LayerID) error {\n\tlogger := msh.WithContext(ctx).WithFields(layerID)\n\tlogger.Info(\"attempting to roll back state to previous layer\")\n\tif err := msh.LoadState(layerID); err != nil {\n\t\treturn fmt.Errorf(\"failed to revert state to layer %v: %w\", layerID, err)\n\t}\n\treturn nil\n}", "func (this *RaidenService) restoreStateManager(isCrashed bool) {\n\tlog.Info(fmt.Sprintf(\"restore statemanager ,last close correct=%s\", !isCrashed))\n\tmgrs := this.db.GetAllStateManager()\n\tfor _, mgr := range mgrs {\n\t\t//log.Trace(fmt.Sprintf(\"unfinish manager %s\", utils.StringInterface(mgr, 7)))\n\t\tif mgr.ManagerState == transfer.StateManager_State_Init || mgr.ManagerState == transfer.StateManager_TransferComplete {\n\t\t\tcontinue\n\t\t}\n\t\tsetStateManagerFuncPointer(mgr)\n\t\tidmgrs := this.Identifier2StateManagers[mgr.Identifier]\n\t\tidmgrs = append(idmgrs, mgr)\n\t\tthis.Identifier2StateManagers[mgr.Identifier] = idmgrs\n\t\tthis.restoreDbPointer(mgr.CurrentState)\n\t}\n\tfor _, mgrs := range this.Identifier2StateManagers {\n\t\t//mannagers for the same channel should be order, otherwise, nonce error.\n\t\tfor _, mgr := range mgrs {\n\t\t\tlog.Trace(fmt.Sprintf(\"restore state manager:%s\\n\", utils.StringInterface(mgr, 7)))\n\t\t\tvar tag interface{}\n\t\t\tvar messageTag *transfer.MessageTag\n\t\t\tswitch mgr.ManagerState {\n\t\t\tcase transfer.StateManager_TransferComplete:\n\t\t\t\t//ignore\n\t\t\tcase transfer.StateManager_ReceivedMessage:\n\t\t\t\tst, ok := mgr.LastReceivedMessage.(mediated_transfer.ActionInitInitiatorStateChange)\n\t\t\t\tif ok {\n\t\t\t\t\tst.Db = this.db\n\t\t\t\t\tthis.StateMachineEventHandler.Dispatch(mgr, st)\n\t\t\t\t} else {\n\t\t\t\t\t//receive a message,and not handled\n\t\t\t\t\t//ignore ,partner will try\n\t\t\t\t}\n\t\t\t\tif mgr.LastSendMessage == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfallthrough\n\t\t\tcase transfer.StateManager_ReceivedMessageProcessComplete: //there may be message waiting for send\n\t\t\t\tif mgr.LastSendMessage == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfallthrough\n\t\t\tcase transfer.StateManager_SendMessage:\n\t\t\t\t/*\n\t\t\t\t\ttodo fix It should be detected whether it is out of date,\n\t\t\t\t\tsuch as ,MediatedTransfer, Secret, which are timeliness, and if it is expired after crash,discarding is more reasonable.\n\t\t\t\t*/\n\t\t\t\ttag = mgr.LastSendMessage.Tag()\n\t\t\t\tif tag == nil {\n\t\t\t\t\tpanic(fmt.Sprintf(\"statemanage state error, lastsendmessage has no tag :%s\", utils.StringInterface(mgr, 5)))\n\t\t\t\t}\n\t\t\t\tmessageTag = tag.(*transfer.MessageTag)\n\t\t\t\tif messageTag.SendingMessageComplete {\n\t\t\t\t\tcontinue // for receive secret message, no need sending any message but ack.\n\t\t\t\t}\n\t\t\t\tmessageTag.SetStateManager(mgr) //statemanager doesn't save\n\t\t\t\tthis.SendAsync(messageTag.Receiver, mgr.LastSendMessage.(encoding.SignedMessager))\n\t\t\tcase transfer.StateManager_SendMessageSuccesss:\n\t\t\t\t//do nothing right now.\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (stage *StageStruct) Restore(dirPath string) {\n\tif stage.BackRepo != nil {\n\t\tstage.BackRepo.Restore(stage, dirPath)\n\t}\n}", "func (stage *StageStruct) RestoreXL(dirPath string) {\n\tif stage.BackRepo != nil {\n\t\tstage.BackRepo.RestoreXL(stage, dirPath)\n\t}\n}", "func (backRepoFoo *BackRepoFooStruct) RestorePhaseTwo() {\n\n\tfor _, fooDB := range *backRepoFoo.Map_FooDBID_FooDB {\n\n\t\t// next line of code is to avert unused variable compilation error\n\t\t_ = fooDB\n\n\t\t// insertion point for reindexing pointers encoding\n\t\t// update databse with new index encoding\n\t\tquery := backRepoFoo.db.Model(fooDB).Updates(*fooDB)\n\t\tif query.Error != nil {\n\t\t\tlog.Panic(query.Error)\n\t\t}\n\t}\n\n}", "func (s *VolumeStore) restore() {\n\tvar entries []*dbEntry\n\ts.db.View(func(tx *bolt.Tx) error {\n\t\tentries = listEntries(tx)\n\t\treturn nil\n\t})\n\n\tchRemove := make(chan []byte, len(entries))\n\tvar wg sync.WaitGroup\n\tfor _, entry := range entries {\n\t\twg.Add(1)\n\t\t// this is potentially a very slow operation, so do it in a goroutine\n\t\tgo func(entry *dbEntry) {\n\t\t\tdefer wg.Done()\n\t\t\tvar meta volumeMetadata\n\t\t\tif len(entry.Value) != 0 {\n\t\t\t\tif err := json.Unmarshal(entry.Value, &meta); err != nil {\n\t\t\t\t\tlogrus.Errorf(\"Error while reading volume metadata for volume %q: %v\", string(entry.Key), err)\n\t\t\t\t\t// don't return here, we can try with `getVolume` below\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar v volume.Volume\n\t\t\tvar err error\n\t\t\tif meta.Driver != \"\" {\n\t\t\t\tv, err = lookupVolume(meta.Driver, string(entry.Key))\n\t\t\t\tif err != nil && err != errNoSuchVolume {\n\t\t\t\t\tlogrus.WithError(err).WithField(\"driver\", meta.Driver).WithField(\"volume\", string(entry.Key)).Warn(\"Error restoring volume\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif v == nil {\n\t\t\t\t\t// doesn't exist in the driver, remove it from the db\n\t\t\t\t\tchRemove <- entry.Key\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tv, err = s.getVolume(string(entry.Key))\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == errNoSuchVolume {\n\t\t\t\t\t\tchRemove <- entry.Key\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tmeta.Driver = v.DriverName()\n\t\t\t\tif err := s.setMeta(v.Name(), meta); err != nil {\n\t\t\t\t\tlogrus.WithError(err).WithField(\"driver\", meta.Driver).WithField(\"volume\", v.Name()).Warn(\"Error updating volume metadata on restore\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// increment driver refcount\n\t\t\tvolumedrivers.CreateDriver(meta.Driver)\n\n\t\t\t// cache the volume\n\t\t\ts.globalLock.Lock()\n\t\t\ts.options[v.Name()] = meta.Options\n\t\t\ts.labels[v.Name()] = meta.Labels\n\t\t\ts.names[v.Name()] = v\n\t\t\ts.globalLock.Unlock()\n\t\t}(entry)\n\t}\n\n\twg.Wait()\n\tclose(chRemove)\n\ts.db.Update(func(tx *bolt.Tx) error {\n\t\tfor k := range chRemove {\n\t\t\tif err := removeMeta(tx, string(k)); err != nil {\n\t\t\t\tlogrus.Warnf(\"Error removing stale entry from volume db: %v\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (sc *StateCheckpoint) Rollback() {\n\tif sc.ctx == nil {\n\t\treturn\n\t}\n\tsc.ctx.State().ImmutableTree = &sc.ImmutableTree\n}", "func (game *Game) Restore(turnNumber int) error {\n\tcurrent2hPath, err := game.Current2hFilepath()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcurrentTrnPath, err := game.CurrentTrnFilepath()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// It's fine if only the 2h or the trn file have backups we'll just restore the one that exists.\n\t// But if neither file exists, we error out.\n\tbackup2hPath, err := game.TwohFile.BackupFilepath(turnNumber)\n\tbackup2hExists := err == nil\n\n\tbackupTrnPath, err := game.TrnFile.BackupFilepath(turnNumber)\n\tbackupTrnExists := err == nil\n\n\tif !(backup2hExists || backupTrnExists) {\n\t\treturn errors.New(fmt.Sprintf(\"Neither trn nor 2h backups exist for turn %v in %v\", turnNumber, game.Directory))\n\t}\n\n\tif backup2hExists {\n\t\terr = utility.Cp(backup2hPath, current2hPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif backupTrnExists {\n\t\terr = utility.Cp(backupTrnPath, currentTrnPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (ctl Controller) Restore(name string) *pitr.Error {\n\terr := ctl.cluster.Stop()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ctl.cluster.Clear()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstdout, stderr, runErr := ctl.runner.Run(\"sudo --login --user postgres wal-g backup-fetch %s %s\", ctl.cluster.DataDirectory(), name)\n\n\tif runErr != nil {\n\t\treturn &pitr.Error{\n\t\t\tMessage: runErr.Error(),\n\t\t\tStdout: stdout,\n\t\t\tStderr: stderr,\n\t\t}\n\t}\n\n\tctl.createRecoveryConf(`restore_command = 'bash --login -c \\\"wal-g wal-fetch %f %p\\\"'`)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ctl.cluster.Start()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (i *Image) restore() error {\n\tw, h := i.image.Size()\n\tif i.screen {\n\t\t// The screen image should also be recreated because framebuffer might\n\t\t// be changed.\n\t\ti.image = graphics.NewScreenFramebufferImage(w, h)\n\t\ti.basePixels = nil\n\t\ti.drawImageHistory = nil\n\t\ti.stale = false\n\t\treturn nil\n\t}\n\tif i.volatile {\n\t\ti.image = graphics.NewImage(w, h)\n\t\ti.basePixels = nil\n\t\ti.drawImageHistory = nil\n\t\ti.stale = false\n\t\treturn nil\n\t}\n\tif i.stale {\n\t\t// TODO: panic here?\n\t\treturn errors.New(\"restorable: pixels must not be stale when restoring\")\n\t}\n\tgimg := graphics.NewImage(w, h)\n\tif i.basePixels != nil {\n\t\tgimg.ReplacePixels(i.basePixels, 0, 0, w, h)\n\t} else {\n\t\t// Clear the image explicitly.\n\t\tpix := make([]uint8, w*h*4)\n\t\tgimg.ReplacePixels(pix, 0, 0, w, h)\n\t}\n\tfor _, c := range i.drawImageHistory {\n\t\t// All dependencies must be already resolved.\n\t\tif c.image.hasDependency() {\n\t\t\tpanic(\"not reached\")\n\t\t}\n\t\tvs := []float32{}\n\t\tfor _, v := range c.vertices {\n\t\t\tvs = append(vs, v...)\n\t\t}\n\t\tgimg.DrawImage(c.image.image, vs, c.colorm, c.mode, c.filter)\n\t}\n\ti.image = gimg\n\n\tvar err error\n\ti.basePixels, err = gimg.Pixels()\n\tif err != nil {\n\t\treturn err\n\t}\n\ti.drawImageHistory = nil\n\ti.stale = false\n\treturn nil\n}", "func (r *Rule) Restore(ctx context.Context, q datasource.Querier, lookback time.Duration) error {\n\t// Get the last datapoint in range via MetricsQL `last_over_time`.\n\t// We don't use plain PromQL since Prometheus doesn't support\n\t// remote write protocol which is used for state persistence in vmalert.\n\texpr := fmt.Sprintf(\"last_over_time(%s{alertname=%q}[%ds])\",\n\t\talertForStateMetricName, r.Name, int(lookback.Seconds()))\n\tqMetrics, err := q.Query(ctx, expr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, m := range qMetrics {\n\t\tlabels := m.Labels\n\t\tm.Labels = make([]datasource.Label, 0)\n\t\t// drop all extra labels, so hash key will\n\t\t// be identical to timeseries received in Eval\n\t\tfor _, l := range labels {\n\t\t\tif l.Name == alertNameLabel {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// drop all overridden labels\n\t\t\tif _, ok := r.Labels[l.Name]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tm.Labels = append(m.Labels, l)\n\t\t}\n\n\t\ta, err := r.newAlert(m)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create alert: %s\", err)\n\t\t}\n\t\ta.ID = hash(m)\n\t\ta.State = notifier.StatePending\n\t\ta.Start = time.Unix(int64(m.Value), 0)\n\t\tr.alerts[a.ID] = a\n\t\tlogger.Infof(\"alert %q(%d) restored to state at %v\", a.Name, a.ID, a.Start)\n\t}\n\treturn nil\n}", "func (rf *Raft) recoverFromPersist(data []byte) {\n\tif data == nil || len(data) < 1 { // bootstrap without any state?\n\t\treturn\n\t}\n\tr := bytes.NewBuffer(data)\n\td := labgob.NewDecoder(r)\n\td.Decode(&rf.term)\n\td.Decode(&rf.vote)\n\td.Decode(&rf.raftLog.commited)\n\td.Decode(&rf.raftLog.size)\n\td.Decode(&rf.raftLog.Entries)\n\trf.prevState = HardState{rf.term, rf.vote, rf.raftLog.commited, rf.raftLog.Size()}\n\trf.raftLog.applied = 0\n\tDebugPrint(\"%d recover from %d, %d, %d, %d\\n\",\n\t\trf.me, rf.term, rf.vote, rf.raftLog.commited, rf.raftLog.size)\n}", "func Restore(output Output) func(cmd *cli.Cmd) {\n\treturn func(cmd *cli.Cmd) {\n\t\tconfigOpts := addConfigOptions(cmd)\n\t\tsilentOpt := cmd.BoolOpt(\"s silent\", false, \"If state already exists don't throw error\")\n\t\tfilename := cmd.StringArg(\"FILE\", \"\", \"Restore from this dump\")\n\t\tcmd.Spec += \"[--silent] [FILE]\"\n\n\t\tcmd.Action = func() {\n\t\t\tconf, err := configOpts.obtainBurrowConfig()\n\t\t\tif err != nil {\n\t\t\t\toutput.Fatalf(\"could not set up config: %v\", err)\n\t\t\t}\n\n\t\t\tif err := conf.Verify(); err != nil {\n\t\t\t\toutput.Fatalf(\"cannot continue with config: %v\", err)\n\t\t\t}\n\n\t\t\toutput.Logf(\"Using validator address: %s\", *conf.ValidatorAddress)\n\n\t\t\tkern, err := core.NewKernel(conf.HscDir)\n\t\t\tif err != nil {\n\t\t\t\toutput.Fatalf(\"could not create Hive Smart Chain kernel: %v\", err)\n\t\t\t}\n\n\t\t\tif err = kern.LoadLoggerFromConfig(conf.Logging); err != nil {\n\t\t\t\toutput.Fatalf(\"could not create Hive Smart Chain kernel: %v\", err)\n\t\t\t}\n\n\t\t\tif err = kern.LoadDump(conf.GenesisDoc, *filename, *silentOpt); err != nil {\n\t\t\t\toutput.Fatalf(\"could not create Hive Smart Chain kernel: %v\", err)\n\t\t\t}\n\n\t\t\tkern.ShutdownAndExit()\n\t\t}\n\t}\n}", "func (s *commonStream) RestoreTerminal() {\n\tif s.state != nil {\n\t\t_ = term.RestoreTerminal(s.fd, s.state)\n\t}\n}", "func (m *MonLeaderDetector) Restore(id int) {\n\t// TODO(student): Implement\n\t_, ok := m.suspected[id]\n\tif ok == true {\n\t\tdelete(m.suspected, id)\n\t\tm.alive[id] = true\n\t}\n\n\t//Publish to subscribers\n\tvar j int\n\tnewLeader := m.Leader()\n\tif m.LeaderChange || m.Allsuspected {\n\t\tfor j < len(m.Channels) {\n\t\t\tm.Channels[j] <- newLeader\n\t\t\tj++\n\t\t}\n\t}\n}", "func restoreEventHooks(m *sync.Map) {\n\t// Purge old event hooks\n\tpurgeEventHooks()\n\n\t// Restore event hooks\n\tm.Range(func(k, v interface{}) bool {\n\t\teventHooks.Store(k, v)\n\t\treturn true\n\t})\n}", "func (this *RaidenService) RestoreSnapshot() error {\n\tlog.Info(\"RestoreSnapshot...\")\n\tdefer func() {\n\t\tthis.db.MarkDbOpenedStatus()\n\t\tthis.db.SaveRegistryAddress(this.RegistryAddress)\n\t}()\n\t/*\n\t When debugging, the registry address may change constantly, Testing is to avoid unnecessary mistakes.\n\t*/\n\tregistryAddr := this.db.GetRegistryAddress()\n\tif registryAddr != this.RegistryAddress && registryAddr != utils.EmptyAddress {\n\t\terr := errors.New(fmt.Sprintf(\"db registry address not match db=%s,mine=%s\", registryAddr.String(), this.RegistryAddress.String()))\n\t\tlog.Error(err.Error())\n\t\treturn err\n\t}\n\t//never save before\n\t/*\n\t\tThe first step restore the channel state\n\t\tThe second step restore the hashlock in channel, so that hashlock changes during subsequent recovery, it can be reflected in the corresponding channel.\n\t\tThe third step restore stateManager. This step will send unfinished messages, which may change the channel state.\n\t\tThe fourth step recovery processing for unsent revealsecret and the unprocessed revealsecret.\n\t\tThe fifth step save the recovered channel state to the database.\n\t*/\n\tthis.restoreChannel(this.db.IsDbCrashedLastTime())\n\tthis.RestoreToken2Hash2Channels()\n\tthis.restoreStateManager(this.db.IsDbCrashedLastTime())\n\tthis.RestoreRevealSecret()\n\tthis.saveChannelStatusAfterStart()\n\treturn nil\n}", "func (c *Container) Restore(ctx context.Context, name string) error {\n\treturn c.client.ContainerStart(ctx, c.id, types.ContainerStartOptions{CheckpointID: name})\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 (strg *Storage) RestoreMeta(m map[storage.MetaKey]storage.MetaValue) error {\n\tstrg.metaMu.Lock()\n\tstrg.meta = m\n\tstrg.metaMu.Unlock()\n\treturn nil\n}", "func Restore() {\n\tprojects := read()\n\tproject := currentProject()\n\tbranch := projects[project]\n\t_, err := run(\"git\", \"checkout\", branch)\n\tif err != nil {\n\t\tfmt.Println(\"error: invalid branch\")\n\t\tos.Exit(1)\n\t}\n\tfmt.Printf(\"branch: restored `%s`\\n\", branch)\n}", "func (store KeyValue) Reopen() {\n}", "func (l *Lexer) backup() error {\n\treturn l.reader.UnreadRune()\n}", "func (s Secrets) Restore(ctx context.Context, value string) (Bundle, error) {\n\treturn s.Ops.Secrets().Restore(ctx, value)\n}", "func (c *container) Restore() bool {\n\treturn c.restore\n}", "func RestoreNow() {\n\tNow = time.Now\n}", "func (e *EntryManager) RestorePos(path string) {\n\tpos, ok := e.selectPos[path]\n\tif !ok {\n\t\tpos = selectPos{1, 0}\n\t}\n\n\te.Select(pos.row, pos.col)\n}", "func RestoreRaw(stack []byte) error {\n\ts := make([]map[string]interface{}, 0)\n\t_ = json.Unmarshal(stack, &s)\n\treturn Restore(s)\n}", "func (a *Agent) restoreCheckState(snap map[types.CheckID]*structs.HealthCheck) {\n\tfor id, check := range snap {\n\t\ta.State.UpdateCheck(id, check.Status, check.Output)\n\t}\n}", "func (b *raftBadger) Restore(rClose io.ReadCloser) error {\n\tdefer func() {\n\t\tif err := rClose.Close(); err != nil {\n\t\t\t_, _ = fmt.Fprintf(os.Stdout, \"[FINALLY RESTORE] close error %s\\n\", err.Error())\n\t\t}\n\t}()\n\n\t_, _ = fmt.Fprintf(os.Stdout, \"[START RESTORE] read all message from snapshot\\n\")\n\tvar totalRestored int\n\n\tdecoder := json.NewDecoder(rClose)\n\tfor decoder.More() {\n\t\tvar data = &command{}\n\t\terr := decoder.Decode(data)\n\t\tif err != nil {\n\t\t\tif !strings.Contains(err.Error(), \"EOF\") {\n\t\t\t\t_, _ = fmt.Fprintf(os.Stdout, \"[END RESTORE]snap skipped\\n\", totalRestored)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t_, _ = fmt.Fprintf(os.Stdout, \"[END RESTORE] error decode data %s\\n\", err.Error())\n\t\t\treturn err\n\t\t}\n\t\tvar key string\n\t\tif key, err = b.gs.Save(data.Key, data.Store, data.Value); err != nil {\n\t\t\t_, _ = fmt.Fprintf(os.Stdout, \"[END RESTORE] error persist data %s\\n\", err.Error())\n\t\t\treturn err\n\t\t}\n\t\tb.logger.Debug(\"restored key\", \"key\", hclog.Fmt(\"%v\", key))\n\n\t\ttotalRestored++\n\t}\n\n\t// read closing bracket\n\t_, err := decoder.Token()\n\tif err != nil && !strings.Contains(err.Error(), \"EOF\") {\n\t\t_, _ = fmt.Fprintf(os.Stdout, \"[END RESTORE] error %s\\n\", err.Error())\n\t\treturn err\n\t}\n\n\t_, _ = fmt.Fprintf(os.Stdout, \"[END RESTORE] success restore %d messages in snapshot\\n\", totalRestored)\n\treturn nil\n}", "func (t *State) resetChanges() {\n\tt.dirty = make(map[int]bool)\n\tt.changed = 0\n}", "func (bin unixRecycleBin) Restore(trashFilename string) error {\n\ttrashInfoPath := buildTrashInfoPath(bin.Path, trashFilename)\n\ttrashInfo, err := readTrashInfo(trashInfoPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdeletedFilePath := buildTrashFilePath(bin.Path, trashFilename)\n\tif err := fs.Rename(deletedFilePath, trashInfo.Path); err != nil {\n\t\treturn err\n\t}\n\terr = fs.Remove(buildTrashInfoPath(bin.Path, trashFilename))\n\treturn err\n}", "func (app *Application) reset() {\n\tapp.sandbox.Flush()\n}", "func Restore(stack []map[string]interface{}) error {\n\n\tvar err error\n\n\tfor i := len(stack) - 1; i >= 0; i-- {\n\n\t\te := restoreErrorFromStackItem(stack[i])\n\n\t\tif err != nil {\n\t\t\te.prev = err\n\t\t}\n\n\t\terr = e\n\t}\n\n\treturn err\n}", "func (ev Vars) Restore(key string) {\n\tev[key] = os.Getenv(key)\n}", "func (master *ProcMaster) Restore(proc ProcContainer) error {\n\tmaster.Lock()\n\tdefer master.Unlock()\n\tif _, ok := master.Procs[proc.Identifier()]; ok {\n\t\tlogger.Warningf(\"Proc %s already exist.\", proc.Identifier())\n\t\treturn errors.New(\"Trying to start a process that already exist.\")\n\t}\n\n\terr := master.restore(proc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmaster.Procs[proc.Identifier()] = proc\n\treturn nil\n}", "func (l *Loader) Restore(ctx context.Context) error {\n\tif err := putLoadTask(l.cli, l.cfg, l.workerName); err != nil {\n\t\treturn err\n\t}\n\n\tif err := l.prepare(); err != nil {\n\t\tl.logger.Error(\"scan directory failed\", zap.String(\"directory\", l.cfg.Dir), log.ShortError(err))\n\t\treturn err\n\t}\n\n\tfailpoint.Inject(\"WaitLoaderStopBeforeLoadCheckpoint\", func(v failpoint.Value) {\n\t\tt := v.(int)\n\t\tl.logger.Info(\"wait loader stop before load checkpoint\")\n\t\tl.wg.Add(1)\n\t\ttime.Sleep(time.Duration(t) * time.Second)\n\t\tl.wg.Done()\n\t})\n\n\t// not update checkpoint in memory when restoring, so when re-Restore, we need to load checkpoint from DB\n\terr := l.checkPoint.Load(tcontext.NewContext(ctx, l.logger))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = l.checkPoint.CalcProgress(l.db2Tables)\n\tif err != nil {\n\t\tl.logger.Error(\"calc load process\", log.ShortError(err))\n\t\treturn err\n\t}\n\tl.loadFinishedSize()\n\tif err2 := l.initAndStartWorkerPool(ctx); err2 != nil {\n\t\tl.logger.Error(\"initial and start worker pools failed\", log.ShortError(err))\n\t\treturn err2\n\t}\n\n\tbegin := time.Now()\n\terr = l.restoreData(ctx)\n\n\tfailpoint.Inject(\"dontWaitWorkerExit\", func(_ failpoint.Value) {\n\t\tl.logger.Info(\"\", zap.String(\"failpoint\", \"dontWaitWorkerExit\"))\n\t\tfailpoint.Return(nil)\n\t})\n\n\t// make sure all workers exit\n\tl.closeFileJobQueue() // all data file dispatched, close it\n\tl.workerWg.Wait()\n\n\tif err == nil {\n\t\tl.finish.Store(true)\n\t\tl.logger.Info(\"all data files have been finished\", zap.Duration(\"cost time\", time.Since(begin)))\n\t\tif l.checkPoint.AllFinished() {\n\t\t\tif l.cfg.Mode == config.ModeFull {\n\t\t\t\tif err = delLoadTask(l.cli, l.cfg, l.workerName); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif l.cfg.CleanDumpFile {\n\t\t\t\tcleanDumpFiles(l.cfg)\n\t\t\t}\n\t\t}\n\t} else if errors.Cause(err) != context.Canceled {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (backRepoFoo *BackRepoFooStruct) RestorePhaseOne(dirPath string) {\n\n\t// resets the map\n\tBackRepoFooid_atBckpTime_newID = make(map[uint]uint)\n\n\tfilename := filepath.Join(dirPath, \"FooDB.json\")\n\tjsonFile, err := os.Open(filename)\n\t// if we os.Open returns an error then handle it\n\tif err != nil {\n\t\tlog.Panic(\"Cannot restore/open the json Foo file\", filename, \" \", err.Error())\n\t}\n\n\t// read our opened jsonFile as a byte array.\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\n\tvar forRestore []*FooDB\n\n\terr = json.Unmarshal(byteValue, &forRestore)\n\n\t// fill up Map_FooDBID_FooDB\n\tfor _, fooDB := range forRestore {\n\n\t\tfooDB_ID_atBackupTime := fooDB.ID\n\t\tfooDB.ID = 0\n\t\tquery := backRepoFoo.db.Create(fooDB)\n\t\tif query.Error != nil {\n\t\t\tlog.Panic(query.Error)\n\t\t}\n\t\t(*backRepoFoo.Map_FooDBID_FooDB)[fooDB.ID] = fooDB\n\t\tBackRepoFooid_atBckpTime_newID[fooDB_ID_atBackupTime] = fooDB.ID\n\t}\n\n\tif err != nil {\n\t\tlog.Panic(\"Cannot restore/unmarshall json Foo file\", err.Error())\n\t}\n}", "func (s *Store) Reset() error {\n\treturn s.Storage.Reset()\n}", "func (s *trialWorkloadSequencer) snapshotState() {\n\ts.LatestSnapshot = s.trialWorkloadSequencerState.deepCopy()\n\ts.LatestSnapshot.LatestSnapshot = nil\n}", "func RestoreSnapshot(snap []byte, appConfig string) *StateMachine {\n\tsm := New(appConfig)\n\terr := json.Unmarshal(snap, sm)\n\tif err != nil {\n\t\tglog.Fatal(\"Unable to restore from snapshot: \", err)\n\t}\n\treturn sm\n}", "func (m *Model) recovered() {\n\tif m.IsSoftDelete() {\n\t\tm.DeletedAt = nil\n\t\tm.applyTimestamps()\n\t}\n}", "func restoreLists() {\n\tarticleList = tmpArticleList\n}", "func restore(ccmd *cobra.Command, args []string) error {\n\tkeyBytes, err := getPrivateKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar mdk types.MasterDerivationKey\n\tcopy(mdk[:], keyBytes)\n\tcwResponse, err := kmdClient.CreateWallet(WalletName, WalletPassword, kmd.DefaultWalletDriver, mdk)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating wallet - %s\", err)\n\t}\n\n\tfmt.Printf(\"Created wallet '%s' with ID: %s\\n\", cwResponse.Wallet.Name, cwResponse.Wallet.ID)\n\tif os.Getenv(\"GOTEST\") == \"true\" {\n\t\tccmd.Print(\"Created wallet successfully.\")\n\t}\n\n\treturn nil\n}", "func (fs *FileSystem) Restore(f *os.File, verbose bool, location string) error {\n\td := json.NewDecoder(f)\n\tstate := 0\n\tfor {\n\t\tswitch state {\n\t\tcase 0:\n\t\t\t// Type\n\t\t\tvar t backend.RecordType\n\t\t\terr := d.Decode(&t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Check version we understand\n\t\t\tif t.Version != backend.RecordTypeVersion {\n\t\t\t\treturn fmt.Errorf(\"unknown version %v\",\n\t\t\t\t\tt.Version)\n\t\t\t}\n\n\t\t\t// Determine record type\n\t\t\tswitch t.Type {\n\t\t\tcase backend.RecordTypeDigestReceived:\n\t\t\t\tstate = 1\n\t\t\tcase backend.RecordTypeFlushRecord:\n\t\t\t\tstate = 2\n\t\t\tcase backend.RecordTypeDigestReceivedGlobal:\n\t\t\t\tstate = 3\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"invalid record type: %v\",\n\t\t\t\t\tt.Type)\n\t\t\t}\n\t\tcase 1:\n\t\t\t// DigestReceived\n\t\t\tvar dr backend.DigestReceived\n\t\t\terr := d.Decode(&dr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = fs.restoreDigestReceived(dr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstate = 0\n\t\tcase 2:\n\t\t\t// Flushrecord\n\t\t\tvar fr backend.FlushRecordJSON\n\t\t\terr := d.Decode(&fr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = fs.restoreFlushRecord(verbose, fr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstate = 0\n\t\tcase 3:\n\t\t\t// Global timestamp\n\t\t\tvar dr backend.DigestReceived\n\t\t\terr := d.Decode(&dr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = fs.restoreDigestReceivedGlobal(dr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstate = 0\n\t\tdefault:\n\t\t\t// Illegal\n\t\t\treturn fmt.Errorf(\"invalid state %v\", state)\n\t\t}\n\t}\n}", "func (l *reader) backup() {\n\tif l.width > 0 {\n\t\terr := l.input.UnreadRune()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"err: \", err)\n\t\t}\n\t\tl.current.Truncate(l.current.Len() - l.width)\n\t}\n}", "func (b *blockEnc) reset(prev *blockEnc) {\n\tb.extraLits = 0\n\tb.literals = b.literals[:0]\n\tb.size = 0\n\tb.sequences = b.sequences[:0]\n\tb.output = b.output[:0]\n\tb.last = false\n\tif prev != nil {\n\t\tb.recentOffsets = prev.prevRecentOffsets\n\t}\n\tb.dictLitEnc = nil\n}", "func (e Environment) RestoreOriginalVars() {\n\tfor key, value := range e.backup {\n\t\terr := os.Setenv(key, value)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to restore env %s\", key))\n\t\t}\n\t}\n}", "func (l *Lexer) backup() {\n\tl.pos = l.start\n\t// log.Printf(\"[back] %s\", l.debugString())\n}", "func (file *File) UndoSaved() {\n\tif file.buffHist == nil {\n\t\treturn\n\t}\n\tbuffer, mc := file.buffHist.PrevSaved()\n\tfile.MultiCursor.ReplaceMC(mc)\n\tfile.buffer.ReplaceBuffer(buffer)\n}", "func (p *Process) Restore(r io.Reader) (*BackupInfo, error) {\n\tif err := p.writeConfig(configData{}); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := p.unpackXbstream(r); err != nil {\n\t\treturn nil, err\n\t}\n\tbackupInfo, err := p.extractBackupInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := p.restoreApplyLog(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn backupInfo, nil\n}" ]
[ "0.7321468", "0.6832732", "0.6766583", "0.6671123", "0.659835", "0.65958077", "0.6592788", "0.65480465", "0.6520159", "0.6459231", "0.6433336", "0.63779956", "0.63075215", "0.6301406", "0.6258902", "0.622341", "0.62129885", "0.6180124", "0.61749244", "0.61749244", "0.6154408", "0.613022", "0.6104019", "0.60699946", "0.6059884", "0.6053015", "0.60512227", "0.60396475", "0.6014667", "0.6014667", "0.6014667", "0.6014667", "0.589441", "0.5881232", "0.5871801", "0.586289", "0.58021307", "0.5779991", "0.5776714", "0.5767183", "0.5750954", "0.5745628", "0.5741252", "0.57248616", "0.57123184", "0.5702419", "0.5690292", "0.56504", "0.5612656", "0.5610264", "0.55790555", "0.5575288", "0.5572584", "0.55642104", "0.55477756", "0.55407524", "0.5538281", "0.5533619", "0.5510127", "0.5500512", "0.5470892", "0.54684734", "0.5464264", "0.54601693", "0.54527843", "0.5449753", "0.54444194", "0.5432883", "0.543065", "0.5423226", "0.54151124", "0.5379525", "0.5377019", "0.53700876", "0.5344895", "0.5334493", "0.53315073", "0.5328752", "0.53244627", "0.53096896", "0.53026336", "0.529681", "0.5296124", "0.52958757", "0.5295589", "0.52712196", "0.52572197", "0.5247997", "0.5246003", "0.52441627", "0.5232155", "0.52135885", "0.5212936", "0.51952684", "0.5177202", "0.51641494", "0.5137188", "0.51226956", "0.5121703", "0.5119685", "0.5115979" ]
0.0
-1
example RequestVote RPC handler.
func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) { // Your code here (2A, 2B). rf.mu.Lock() defer rf.mu.Unlock() // defer DPrintf("%d(%d|term%d|vote%d) replyed %d(%d) with %s", rf.me, rf.state, rf.currentTerm, rf.votedFor, args.CandidateId, args.Term, reply) if args.Term < rf.currentTerm { reply.VoteGranted = false return } if (rf.votedFor == -1 || rf.votedFor == args.CandidateId) && args.LastLogIndex >= rf.lastApplied { //rf.resetHeartBeatsTimer() reply.VoteGranted = true // rf.currentTerm += 1 rf.currentTerm = args.Term rf.votedFor = args.CandidateId rf.state = FOLLOWER return } else { reply.VoteGranted = false } reply.Term = rf.currentTerm }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\tresp := make(chan interface{})\n\trf.rpcCh <- rpcCall{command: args, reply: resp}\n\n\t*reply = (<-resp).(RequestVoteReply)\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\n\trf.mu.Lock()\n\trf.debug(\"***************Inside the RPC handler for sendRequestVote *********************\")\n\tdefer rf.mu.Unlock()\n\tvar lastIndex int\n\t//var lastTerm int\n\tif len(rf.log) > 0 {\n\t\tlastLogEntry := rf.log[len(rf.log)-1]\n\t\tlastIndex = lastLogEntry.LastLogIndex\n\t\t//lastTerm = lastLogEntry.lastLogTerm\n\t}else{\n\t\tlastIndex = 0\n\t\t//lastTerm = 0\n\t}\n\treply.Term = rf.currentTerm\n\t//rf.debug()\n\tif args.Term < rf.currentTerm {\n\t\treply.VoteGranted = false\n\t\trf.debug(\"My term is higher than candidate's term, myTerm = %d, candidate's term = %d\", rf.currentTerm,args.Term )\n\t} else if (rf.votedFor == -1 || rf.votedFor == args.CandidateId) && args.LastLogIndex >= lastIndex {\n\t\trf.votedFor = args.CandidateId\n\t\treply.VoteGranted = true\n\t\trf.currentTerm = args.Term\n\t\trf.resetElectionTimer()\n\t\t//rf.debug(\"I am setting my currentTerm to -->\",args.Term,\"I am \",rf.me)\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\t//fmt.Println(\"got vote request at server id: \", rf.me)\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tif rf.currentTerm > args.Term {\n\t\treply.VoteGranted = false\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t} else if rf.currentTerm < args.Term {\n\t\trf.currentTerm = args.Term\n\t\treply.Term = rf.currentTerm\n\t\trf.state = follower\n\t}\n\t\n\tgranted := false\n\tif rf.votedFor == nil {\n\t\tgranted = true\n\t} else if *rf.votedFor == args.CandidateId {\n\t\tgranted = true\n\t}\n\tif !granted {\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\n\tif args.LastLogIndex != len(rf.log)-1 {\n\t\tgranted = false\n\t} else {\n\t\tif args.LastLogTerm != rf.log[len(rf.log)-1].Term {\n\t\t\tgranted = false\n\t\t}\n\t}\n\t\n\tif !granted {\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\n\treply.VoteGranted = true\n\trf.rpcCh<-voteRpc\n\treturn\n}", "func (r *Raft) serviceRequestVote(request RequestVote, state int) {\n\t//fmt.Println(\"In service RV method of \", r.Myconfig.Id)\n\tresponse := RequestVoteResponse{}\n\tcandidateId := request.CandidateId\n\tresponse.Id = r.Myconfig.Id\n\tif r.isDeservingCandidate(request) {\n\t\tresponse.VoteGranted = true\n\t\tr.myCV.VotedFor = candidateId\n\t\tr.myCV.CurrentTerm = request.Term\n\t} else {\n\t\tif request.Term > r.myCV.CurrentTerm {\n\t\t\tr.myCV.CurrentTerm = request.Term\n\t\t\tr.myCV.VotedFor = -1\n\t\t}\n\t\tresponse.VoteGranted = false\n\t}\n\tif request.Term > r.myCV.CurrentTerm {\n\t\tr.WriteCVToDisk()\n\t}\n\tresponse.Term = r.myCV.CurrentTerm\n\tr.send(candidateId, response) //send to sender using send(sender,response)\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\tev := newRaftEV(args)\n\tselect {\n\tcase <-rf.quitc:\n\t\treturn\n\tcase rf.eventc <- ev:\n\t}\n\n\t<-ev.c\n\tif ev.result == nil {\n\t\tpanic(\"unexpected nil result\")\n\t}\n\t*reply = *(ev.result.(*RequestVoteReply))\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// TODO: fail this rpc when killed\n\n\t// Your code here (2A, 2B).\n\tisGoodRequestVote := false\n\trf.mu.Lock()\n\n\tdefer func() {\n\t\tAssertF(reply.Term >= args.Term, \"reply.Term {%d} >= args.Term {%d}\", reply.Term, args.Term)\n\t\trf.mu.Unlock()\n\t\trf.resetElectionTimerIf(isGoodRequestVote)\n\t}()\n\n\tif args.Term < rf.currentTerm {\n\t\t*reply = RequestVoteReply{Term: rf.currentTerm, VoteGranted: false}\n\t\treturn\n\t}\n\n\tif args.Term > rf.currentTerm {\n\t\trf.transitionToFollower(args.Term, -1)\n\t}\n\n\tAssertF(args.Term == rf.currentTerm, \"\")\n\n\tif (rf.votedFor == -1 || rf.votedFor == args.CandidateId) && rf.isUptoDate(args.LastLogIndex, args.LastLogTerm) {\n\t\tisGoodRequestVote = true\n\t\trf.votedFor = args.CandidateId\n\t\t*reply = RequestVoteReply{Term: args.Term, VoteGranted: true}\n\t} else {\n\t\t*reply = RequestVoteReply{Term: args.Term, VoteGranted: false}\n\t}\n\n\trf.persist()\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\tgrantVote := false\n\trf.updateTerm(args.Term) // All servers: if args.Term > rf.currentTerm, set currentTerm, convert to follower\n\n\tswitch rf.state {\n\tcase Follower:\n\t\tif args.Term < rf.currentTerm {\n\t\t\tgrantVote = false\n\t\t} else if rf.votedFor == -1 || rf.votedFor == args.CandidateId {\n\t\t\tif len(rf.logs) == 0 {\n\t\t\t\tgrantVote = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlastLogTerm := rf.logs[len(rf.logs) - 1].Term\n\t\t\tif (lastLogTerm == args.LastLogTerm && len(rf.logs) <= args.LastLogIndex) || lastLogTerm < args.LastLogTerm {\n\t\t\t\tgrantVote = true\n\t\t\t}\n\t\t}\n\tcase Leader:\n\t\t// may need extra operation since the sender might be out-dated\n\tcase Candidate:\n\t\t// reject because rf has already voted for itself since it's in\n\t\t// Candidate state\n\t}\n\n\tif grantVote {\n\t\t// DPrintf(\"Peer %d: Granted RequestVote RPC from %d.(@%s state)\\n\", rf.me, args.CandidateId, rf.state)\n\t\treply.VoteGranted = true\n\t\trf.votedFor = args.CandidateId\n\t\t// reset election timeout\n\t\trf.hasHeartbeat = true\n\t} else {\n\t\t// DPrintf(\"Peer %d: Rejected RequestVote RPC from %d.(@%s state)\\n\", rf.me, args.CandidateId, rf.state)\n\t\treply.VoteGranted = false\n\t}\n\treply.VotersTerm = rf.currentTerm\n\n\t// when deal with cluster member changes, may also need to reject Request\n\t// within MINIMUM ELECTION TIMEOUT\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tlastLogIndex, lastLogTerm := len(rf.log) + rf.compactIndex , 0\n\tif lastLogIndex > rf.compactIndex {\n\t\tlastLogTerm = rf.log[lastLogIndex - rf.compactIndex -1].Term\n\t} else if lastLogIndex == rf.compactIndex {\n\t\tlastLogTerm = rf.compactTerm\n\t}\n\n\tif args.Term < rf.currentTerm || (args.Term == rf.currentTerm && args.CandidateID != rf.votedFor) || args.LastLogTerm < lastLogTerm || (args.LastLogTerm == lastLogTerm && lastLogIndex > args.LastLogIndex) {\n\t\t// 1. The Term of RequestVote is out of date.\n\t\t// 2. The instance vote for other peer in this term.\n\t\t// 3. The log of Candidate is not the most update.\n\t\treply.VoteGranted = false\n\t\treply.Term = rf.currentTerm\n\t} else {\n\t\t// DPrintf(\"instance %d vote for %d, Term is %d, lastLogTerm is %d, args.LastLogTerm is %d, lastLogIndex is %d, args.LastLogIndex is %d, original votedFor is %d\", rf.me, args.CandidateID, args.Term, lastLogTerm, args.LastLogTerm, lastLogIndex, args.LastLogIndex, rf.votedFor)\n\t\trf.votedFor = args.CandidateID\n\t\trf.currentTerm = args.Term\n\n\t\treply.VoteGranted = true\n\t\treply.Term = rf.currentTerm\n\n\t\tif rf.role == Follower {\n\t\t\trf.validRpcTimestamp = time.Now()\n\t\t} else {\n\t\t\t// Notify the change of the role of instance.\n\t\t\tclose(rf.rollback)\n\t\t\trf.role = Follower\n\t\t}\n\t}\n\n\treturn\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tif args.Term < rf.currentTerm {\n\t\treply.Term = rf.currentTerm\n\t\treply.VoteGranted = false\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\t// follow the second rule in \"Rules for Servers\" in figure 2 before handling an incoming RPC\n\tif args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\trf.state = FOLLOWER\n\t\trf.votedFor = -1\n\t\trf.persist()\n\t}\n\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = true\n\t// deny vote if already voted\n\tif rf.votedFor != -1 {\n\t\treply.VoteGranted = false\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\t// deny vote if consistency check fails (candidate is less up-to-date)\n\tlastLog := rf.log[len(rf.log)-1]\n\tif args.LastLogTerm < lastLog.Term || (args.LastLogTerm == lastLog.Term && args.LastLogIndex < len(rf.log)-1) {\n\t\treply.VoteGranted = false\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\t// now this peer must vote for the candidate\n\trf.votedFor = args.CandidateID\n\trf.mu.Unlock()\n\n\trf.resetTimer()\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.Lock()\n\tdefer rf.Unlock()\n\tRaftInfo(\"Get Request from %s\", rf, args.CandidateId)\n\tlastIndex, lastTerm := rf.getLastEntryInfo()\n\tisLogUpToDate := func() bool {\n\t\tif lastTerm == args.LastLogTerm {\n\t\t\treturn lastIndex <= args.LastLogIndex\n\t\t} else {\n\t\t\treturn lastTerm < args.LastLogTerm\n\t\t}\n\t}()\n\n\treply.Term = rf.currentTerm\n\treply.Id = rf.id\n\n\tif args.Term < rf.currentTerm {\n\t\treply.VoteGranted = false\n\t} else if args.Term >= rf.currentTerm && isLogUpToDate {\n\t\trf.transitionToFollower(args.Term)\n\t\trf.voteForID = args.CandidateId\n\t\treply.VoteGranted = true\n\t} else if (rf.voteForID == \"\" || args.CandidateId == rf.voteForID) && isLogUpToDate {\n\t\trf.voteForID = args.CandidateId\n\t\treply.VoteGranted = true\n\t}\n\n\trf.persist()\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\tDPrintf(\"before voted reply is %v, me id is %d, votedFor is %d, candidateId is %d, current term is %v, \" +\n\t\t\"args term is %v args log is %v log is %v\", reply, rf.me, rf.votedFor, args.CandidateId,\n\t\trf.currentTerm, args.LastLogTerm, args.LastLogIndex, rf.addLastIncludedIndex(len(rf.log)-1))\n\n\tif rf.currentTerm < args.Term {\n\t\trf.votedFor = -1\n\t\trf.currentTerm = args.Term\n\t\trf.raftState = Follower\n\t\trf.resetTimer()\n\t}\n\tif rf.votedFor == args.CandidateId || rf.votedFor == -1 {\n\t\tlastIndex := len(rf.log) - 1\n\t\tlastLogTerm := rf.log[lastIndex].Term\n\t\tif (args.LastLogTerm > lastLogTerm) ||\n\t\t\t(args.LastLogTerm == lastLogTerm && args.LastLogIndex >= rf.addLastIncludedIndex(lastIndex)) {\n\t\t\trf.votedFor = args.CandidateId\n\t\t\trf.raftState = Follower\n\t\t\treply.VoteGranted = true\n\t\t\trf.resetTimer()\n\t\t}\n\t}\n\trf.persist()\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\trf.mu.Lock()\n\tdefer DPrintf(\"%d received RequestVote from %d, args.Term : %d, args.LastLogIndex: %d, args.LastLogTerm: %d, rf.log: %v, rf.voteFor: %d, \" +\n\t\t\"reply: %v\", rf.me, args.CandidatedId, args.Term, args.LastLogIndex, args.LastLogTerm, rf.log, rf.voteFor, reply)\n\t// Your code here (2A, 2B).\n\trf.resetElectionTimer()\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\tlastLogIndex := rf.log[len(rf.log)-1].Index\n\tlastLogTerm := rf.log[lastLogIndex].Term\n\n\tif lastLogTerm > args.LastLogTerm || (args.LastLogTerm == lastLogTerm && args.LastLogIndex < lastLogIndex) {\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\t// 5.1 Reply false if term < currentTerm\n\tif args.Term < rf.currentTerm {\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\tif (args.Term == rf.currentTerm && rf.state == \"leader\") || (args.Term == rf.currentTerm && rf.voteFor != -1){\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\tif args.Term == rf.currentTerm && rf.voteFor == args.CandidatedId {\n\t\treply.VoteGranted = true\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\t// Rules for Servers\n\t// All Servers\n\t// If RPC request or response contains term T > currentTerm: set currentTerm = T, convert to follower\n\tif args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\trf.voteFor = -1\n\t\trf.mu.Unlock()\n\t\trf.changeState(\"follower\")\n\t\trf.mu.Lock()\n\t}\n\n\trf.voteFor = args.CandidatedId\n\treply.VoteGranted = true\n\t//rf.persist()\n\trf.mu.Unlock()\n\treturn\n}", "func (m *Member) RequestVote(ctx context.Context, leader string, term uint64, logSize uint64) (*raftapi.RequestVoteResponse, error) {\n\tlog.WithFields(log.Fields{\"member_name\": m.Name}).Debugln(\"Requesting vote from\")\n\tvar conn *grpc.ClientConn\n\tconn, err := grpc.Dial(m.Address(), grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\tapi := raftapi.NewRaftServiceClient(conn)\n\tresponse, err := api.RequestVote(ctx, &raftapi.RequestVoteMessage{\n\t\tTerm: term,\n\t\tCandidate: leader,\n\t\tLogSize: logSize,\n\t\tLastLogTerm: 0,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response, nil\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tcurrentTerm := rf.currentTerm\n\n\t//If RPC request or response contains term T > currentTerm:\n\t//set currentTerm = T, convert to follower\n\tif (args.Term > currentTerm) {\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = NILVOTE\n\n\t\tif rf.role == LEADER {\n\t\t\tDPrintf(\"LeaderCondition sorry server %d term %d not a leader, logs %v, commitIndex %d\\n\",rf.me, rf.currentTerm, rf.log, rf.commitIndex) \n\t\t} \n\t\trf.role = FOLLOWER\n\t\trf.persist()\n\t}\n\n\tif args.Term < currentTerm {\n\t\t// Reply false if term < currentTerm \n\t\treply.VoteGranted = false\n\t\treply.Term = currentTerm \n\t}else {\n\t\t//If votedFor is null or candidateId,\n\t\t//and candidate’s log is at least as up-to-date as receiver’s log,\n\t\t//&& rf.atLeastUptodate(args.LastLogIndex, args.LastLogTerm)\n\t\tif (rf.votedFor == NILVOTE || rf.votedFor == args.CandidateId) && rf.atLeastUptodate(args.LastLogIndex, args.LastLogTerm) {\n\t\t\ti , t := rf.lastLogIdxAndTerm()\n\t\t\tPrefixDPrintf(rf, \"voted to candidate %d, args %v, lastlogIndex %d, lastlogTerm %d\\n\", args.CandidateId, args, i, t)\n\t\t\trf.votedFor = args.CandidateId\n\t\t\trf.persist()\t\n\t\t\treply.VoteGranted = true\n\t\t\treply.Term = rf.currentTerm\n\t\t\t//you grant a vote to another peer.\n\t\t\trf.resetTimeoutEvent = makeTimestamp()\n\t\t}else {\n\t\t\treply.VoteGranted = false\n\t\t\treply.Term = rf.currentTerm\n\t\t}\t\n\t}\n}", "func (r *Raft) serviceRequestVote(request RequestVote) {\n\t//fmt.Println(\"In service RV method of \", r.Myconfig.Id)\n\tresponse := RequestVoteResponse{} //prep response object,for responding back to requester\n\tcandidateId := request.candidateId\n\tresponse.id = r.Myconfig.Id\n\t//fmt.Println(\"Follower\", r.Myconfig.Id, \"log as complete?\", r.logAsGoodAsMine(request))\n\tif r.isDeservingCandidate(request) {\n\t\tresponse.voteGranted = true\n\t\tr.votedFor = candidateId\n\t\tr.currentTerm = request.term\n\n\t\t//Writing current term and voteFor to disk\n\t\tr.WriteCVToDisk()\n\n\t} else {\n\t\tresponse.voteGranted = false\n\t}\n\tresponse.term = r.currentTerm //to return self's term too\n\n\t//fmt.Println(\"Follower\", r.Myconfig.Id, \"voting\", response.voteGranted) //\"because votefor is\", r.votedFor, \"my and request terms are:\", r.currentTerm, request.term)\n\t//fmt.Println(\"Follower\", r.Myconfig.Id, \"Current term,request.term is\", r.currentTerm, request.term, \"Self lastLogIndex is\", r.myMetaData.lastLogIndex, \"VotedFor,request.lastLogTerm\", r.votedFor, request.lastLogTerm)\n\t//fmt.Println(\"VotedFor,request.lastLogTerm\", r.votedFor, request.lastLogTerm)\n\n\t//fmt.Printf(\"In serviceRV of %v, obj prep is %v \\n\", r.Myconfig.Id, response)\n\tsend(candidateId, response) //send to sender using send(sender,response)\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) { //RequestVote handdler\r\n\t// Your code here.\r\n\trf.mu.Lock() //get the lock\r\n\tdefer rf.mu.Unlock()\r\n\tif args.Term < rf.currentTerm {\r\n\t\treply.VoteGranted = false\r\n\t\treply.Term = rf.currentTerm\r\n\t}else if args.Term > rf.currentTerm {\r\n\t\trf.currentTerm = args.Term\r\n\t\trf.updateStateTo(FOLLOWER)\r\n\t\trf.votedFor = args.CandidateId\r\n\t\treply.VoteGranted = true\r\n\t}else {\r\n\t\tif rf.votedFor == -1 {//haven't vote for anyone\r\n\t\t\trf.votedFor = args.CandidateId\r\n\t\t\treply.VoteGranted = true\r\n\t\t}else {\r\n\t\t\treply.VoteGranted = false\r\n\t\t}\r\n\t}\r\n\tif reply.VoteGranted == true { // vote for current requester\r\n\t\tgo func() { rf.voteCh <- struct{}{} }() //send the struct{}{} to the voteCh channel\r\n\t}\t\r\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\n\tif args.Term < rf.currentTerm {\n\t\t\treply.Term = rf.currentTerm\n\t\t\treply.VoteGranted = false\n\t\t\treturn\n\t\t}\n\tif args.Term > rf.currentTerm{\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = -1\n\t\trf.role = 0\n\t\trf.roleChan <- 0\n\t\t}\n\treply.Term = args.Term\n\tfmt.Printf(\"LastLogTerm:%v rf.log:%v sever:%v \\n\", args.LastLogTerm, rf.log[len(rf.log)-1].Term, rf.me)\n\tif rf.votedFor != -1 && rf.votedFor != args.CandidateId {\n\t reply.VoteGranted = false \n\t }else if rf.log[len(rf.log)-1].Term > args.LastLogTerm{\n\t \treply.VoteGranted = false\n\t }else if rf.log[len(rf.log)-1].Index > args.LastLogIndex && rf.log[len(rf.log)-1].Term == args.LastLogTerm{\n\t \treply.VoteGranted = false\n\t }else{\n\t fmt.Printf(\"Server %v vote for server %v \\n\", rf.me, args.CandidateId)\n\t reply.VoteGranted = true\n\t rf.votedFor = args.CandidateId\n\t rf.GrantVote <- true\n\t }\n\n\t}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.executeLock.Lock()\n\tdefer rf.executeLock.Unlock()\n\n\t//DPrintf(\"[ReceiveRequestVote] [me %v] from [peer %v] start\", rf.me, args.CandidateId)\n\trf.stateLock.Lock()\n\n\tdebugVoteArgs := &RequestVoteArgs{\n\t\tTerm: rf.currentTerm,\n\t\tCandidateId: rf.votedFor,\n\t\tLastLogIndex: int32(len(rf.log) - 1),\n\t\tLastLogTerm: rf.log[len(rf.log)-1].Term,\n\t}\n\tDPrintf(\"[ReceiveRequestVote] [me %#v] self info: %#v from [peer %#v] start\", rf.me, debugVoteArgs, args)\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\treply.LastLog = int32(len(rf.log) - 1)\n\treply.LastLogTerm = rf.log[reply.LastLog].Term\n\tif args.Term < rf.currentTerm {\n\t\tDPrintf(\"[ReceiveRequestVote] [me %v] from %v Term :%v <= currentTerm: %v, return\", rf.me, args.CandidateId, args.Term, rf.currentTerm)\n\t\trf.stateLock.Unlock()\n\t\treturn\n\t}\n\n\tconvrt2Follower := false\n\tif args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = -1\n\t\tconvrt2Follower = true\n\t\trf.persist()\n\t}\n\n\tif rf.votedFor == -1 || rf.votedFor == args.CandidateId {\n\t\tlastLogIndex := int32(len(rf.log) - 1)\n\t\tlastLogTerm := rf.log[lastLogIndex].Term\n\n\t\tif args.LastLogTerm < lastLogTerm || (args.LastLogTerm == lastLogTerm && args.LastLogIndex < lastLogIndex) {\n\t\t\trf.votedFor = -1\n\t\t\trf.lastHeartbeat = time.Now()\n\t\t\tDPrintf(\"[ReceiveRequestVote] [me %v] index from [%v] is oldest, return\", rf.me, args.CandidateId)\n\n\t\t\tif convrt2Follower && rf.role != _Follower {\n\t\t\t\tDPrintf(\"[ReceiveRequestVote] [me %v] from %v Term :%v (non-follower) > currentTerm: %v, return\", rf.me, args.CandidateId, args.Term, rf.currentTerm)\n\t\t\t\trf.role = _Unknown\n\t\t\t\trf.stateLock.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase <-rf.closeCh:\n\t\t\t\tcase rf.roleCh <- _Follower:\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\trf.stateLock.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\trf.votedFor = args.CandidateId\n\t\t// [WARNING] 一旦授权,应该重置超时\n\t\trf.lastHeartbeat = time.Now()\n\t\treply.VoteGranted = true\n\t\tDPrintf(\"[ReceiveRequestVote] [me %v] granted vote for %v\", rf.me, args.CandidateId)\n\t\tif rf.role != _Follower {\n\t\t\tDPrintf(\"[ReceiveRequestVote] [me %v] become follower\", rf.me)\n\t\t\trf.role = _Unknown\n\t\t\trf.stateLock.Unlock()\n\t\t\tselect {\n\t\t\tcase <-rf.closeCh:\n\t\t\t\treturn\n\t\t\tcase rf.roleCh <- _Follower:\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\trf.stateLock.Unlock()\n\t\treturn\n\t}\n\tDPrintf(\"[ReceiveRequestVote] [me %v] have voted: %v, return\", rf.me, rf.votedFor)\n\trf.stateLock.Unlock()\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\n\t// Your code here (2A, 2B).\n\n\tDPrintf(\" before %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\t//log.Printf(\" before %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\tlog.Printf(\" before %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\n\tDPrintf(\" %v's requesetvote args is %v, and the reciever %v currentTerm is %v\", args.CandidateId, *args, rf.me, rf.currentTerm)\n\t//log.Printf(\" %v's requesetvote args is %v, and the reciever %v currentTerm is %v\", args.CandidateId, *args, rf.me, rf.currentTerm)\n\n\t// all servers\n\tif rf.currentTerm < args.Term {\n\t\trf.convertToFollower(args.Term)\n\t}\n\n\t_voteGranted := false\n\tif rf.currentTerm == args.Term && (rf.voteFor == VOTENULL || rf.voteFor == args.CandidateId) && (rf.getLastLogTerm() < args.LastLogTerm || (rf.getLastLogTerm() == args.LastLogTerm && rf.getLastLogIndex() <= args.LastLogIndex)) {\n\t\trf.state = Follower\n\t\tdropAndSet(rf.grantVoteCh)\n\t\t_voteGranted = true\n\t\trf.voteFor = args.CandidateId\n\t}\n\n\treply.VoteGranted = _voteGranted\n\treply.Term = rf.currentTerm\n\n\tDPrintf(\" after %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\tlog.Printf(\" after %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\n\t//fmt.Printf(\"Server %d: log is %v\\n\", rf.me, rf.log)\n\n\tvar newer bool\n\n\tif args.Term > rf.currentTerm {\n\t\trf.votedFor = -1\n\t}\n\n\tif len(rf.log) == 0 || args.LastLogTerm > rf.log[len(rf.log)-1].Term {\n\t\tnewer = true\n\t} else if args.LastLogTerm == rf.log[len(rf.log)-1].Term && len(rf.log) <= args.LastLogIndex+1 {\n\t\tnewer = true\n\t}\n\n\tif newer == true && (rf.votedFor == -1 || rf.votedFor == args.CandidateID) {\n\t\treply.VoteGranted = true\n\t} else {\n\t\treply.VoteGranted = false\n\t}\n\n\tvar votedFor int\n\tif reply.VoteGranted {\n\t\tvotedFor = args.CandidateID\n\t} else {\n\t\tvotedFor = -1\n\t}\n\trf.votedFor = votedFor\n\n\tif args.Term < rf.currentTerm {\n\t\treply.VoteGranted = false\n\t} else if args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\tif rf.state != Follower {\n\t\t\trf.convertToFollower(rf.currentTerm, votedFor)\n\t\t}\n\t}\n\n\treply.Term = rf.currentTerm\n\n\trf.persist()\n\n\tif reply.VoteGranted == true {\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase <-rf.grantVoteCh:\n\t\t\tdefault:\n\t\t\t}\n\t\t\trf.grantVoteCh <- true\n\t\t}()\n\t}\n}", "func (rf *Raft) RequestVoteHandler(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.lock(\"RVHandler lock\")\n\treply.Term = rf.currentTerm // update requester to follower (if currentTerm > args.CTerm)\n\n\tif args.CTerm < rf.currentTerm {\n\t\treply.VoteGranted = false\n\t\trf.unlock(\"RVHandler lock\")\n\t\treturn\n\t}\n\n\tif args.CTerm > rf.currentTerm {\n\t\trf.receivedLargerTerm(args.CTerm)\n\t}\n\n\tif (rf.votedFor == -1 || rf.votedFor == args.CID) && rf.isCandidateMoreUTD(args) {\n\t\treply.VoteGranted = true\n\t\trf.votedFor = args.CID\n\t\trf.persist()\n\t} else {\n\t\treply.VoteGranted = false\n\t}\n\trf.unlock(\"RVHandler lock\")\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\n\treply.VoteGranted = false\n\n\tif args.Term < rf.currentTerm {\n\t\treply.Term = rf.currentTerm\n\t\tDPrintf(\"[reject] %v currentTerm:%v vote reject for:%v term:%v\",rf.me,rf.currentTerm,args.CandidateId,args.Term)\n\t\treturn\n\t}\n\n\tif args.Term > rf.currentTerm {\n\t\trf.state = FOLLOWER\n\t\trf.votedFor = -1\n\t\trf.currentTerm = args.Term\n\t}\n\n\treply.Term = rf.currentTerm\n\n\tlastLogTerm := rf.getLastLogTerm()\n\tlastLogIndex := rf.getLastLogIndex()\n\n\tlogFlag := false\n\tif (args.LastLogTerm > lastLogTerm) || (args.LastLogTerm == lastLogTerm && args.LastLogIndex >= lastLogIndex) {\n\t\tlogFlag = true\n\t}\n\n\tif (-1 == rf.votedFor || args.CandidateId == rf.votedFor) && logFlag {\n\t\treply.VoteGranted = true\n\t\trf.votedFor = args.CandidateId\n\t\trf.voteChan <- true\n\t\trf.state = FOLLOWER\n\t}\n\t//DPrintf(\"[RequestVote]: server %v send %v\", rf.me, args.CandidateId)\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\n\n\t//fmt.Printf(\"成功调用RequestVote!\\n\")\n\t// Your code here (2A, 2B).\n\t//rf.mu.Lock()\n\t//current_time:=time.Now().UnixNano()/1e6\n\t//&&current_time-rf.voted_time>800\n\trf.mu.Lock()\n\n\tif (rf.term>args.Candidate_term)&&((args.Last_log_term>rf.Last_log_term)||(args.Last_log_term==rf.Last_log_term&&args.Last_log_term_lenth>=rf.last_term_log_lenth)){\n\t\trf.term=args.Candidate_term\n\t\trf.state=0\n\t}\n\n\n\t/*\n\t\tif args.Append==true&&((args.Newest_log.Log_Term<rf.Last_log_term)||(args.Newest_log.Log_Term==rf.Last_log_term&&args.Last_log_term_lenth<rf.Last_log_term)){\n\t\t\treply.Term=args.Candidate_term+1\n\t\t\treply.Last_log_term=rf.Last_log_term\n\t\t\treply.Last_log_lenth=rf.last_term_log_lenth\n\t\t\treply.Append_success=false\n\t\t\trf.mu.Unlock()\n\t\t\treturn\n\t\t}\n\t*/\n\t//if args.Second==true{\n\t//\tfmt.Printf(\"!\\n!\\n!\\n!\\n!\\n编号为%d的raft实例收到编号为%d的leader的second请求!本机term是%d,leader term是%d,args.Append是%v\\n\",rf.me,args.From,rf.term,args.Candidate_term,args.Append)\n\t//}\n\n\tif rf.state==2&&((rf.term<args.Candidate_term)||(rf.term==args.Candidate_term&&args.Last_log_term<rf.Last_log_term))&&args.Votemsg==false{\n\t\t//fmt.Printf(\"分区恢复后编号为%d的raft实例的term是%d,发现自己已经不是leader!leader是%d,leader的term是%d\\n\",rf.me,rf.term,args.From,args.Candidate_term)\n\t\trf.state=0\n\t\trf.leaderID=args.From\n\t}\n\n\n\n\tif args.Candidate_term>=rf.term{\n\t\t//rf.term=args.Candidate_term\n\t\t//if args.Second==true{\n\t\t//\tfmt.Printf(\"服务器上的SECOND进入第一个大括号\\n\")\n\t\t//}\n\t\tif args.Append == false {\n\t\t\tif args.Votemsg == true && rf.voted[args.Candidate_term] == 0&&((args.Last_log_term>rf.Last_log_term)||(args.Last_log_term==rf.Last_log_term&&args.Last_log_term_lenth>=rf.last_term_log_lenth)) { //合法投票请求\n\t\t\t\t//fmt.Printf(\"编号为%d的raft实例对投票请求的回答为true,term统一更新为为%d\\n\",rf.me,rf.term)\n\n\t\t\t\t//rf.term = args.Candidate_term\n\t\t\t\trf.voted[args.Candidate_term] = 1\n\t\t\t\treply.Vote_sent = true\n\n\t\t\t\t//rf.voted_time=time.Now().UnixNano()/1e6\n\n\t\t\t}else if args.Votemsg==true{ //合法的纯heartbeat\n\t\t\t\tif rf.voted[args.Candidate_term]==1 {\n\t\t\t\t\treply.Voted = true\n\t\t\t\t}\n\t\t\t\t//fmt.Printf(\"请求方的term是%d,本机的term是%d,来自%d的投票请求被%d拒绝!rf.last_log_term是%d,rf.last_log_lenth是%d,本机的rf.last_log_term是%d,rf.last_log_lenth是%d\\n\",args.Candidate_term,rf.term,args.From,rf.me,args.Last_log_term,args.Last_log_term_lenth,rf.Last_log_term,rf.last_term_log_lenth)\n\t\t\t}\n\t\t\treply.Term=rf.term\n\n\t\t\t//rf.term=args.Candidate_term//!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\t\t\t//if args.Votemsg==true{//!!!!!!!!!!!!!!\n\t\t\t//\trf.term=args.Candidate_term//!!!!!!!!!!!!\n\t\t\t//}//!!!!!!!!!!!!!!!!!\n\n\t\t} else { //这条是关于日志的\n\t\t\t//这个请求是日志同步请求,接收方需要将自己的日志最后一条和leader发过来的声称的进行比较,如果leader的更新且leader的PREV和自己的LAST相同就接受\n\t\t\t//还得找到最后一个一致的日志位置,然后将后面的全部更新为和leader一致的,这意味着中间多次的RPC通信\n\n\t\t\t/*\n\t\t\tif args.Newest_log.Log_Term<rf.Last_log_term{\n\t\t\t\treply.Wrong_leader=true\n\t\t\t\treply.Term=rf.term\n\t\t\t\treply.Append_success=false\n\t\t\t\treply.Last_log_lenth=rf.last_term_log_lenth\n\t\t\t\treturn\n\t\t\t}\n*/\n\n\t\t\tif (rf.Last_log_term>args.Last_log_term)||(rf.Last_log_term==args.Last_log_term&&rf.last_term_log_lenth>args.Last_log_term_lenth){\n\t\t\t\treply.Append_success=false\n\t\t\t\treply.Last_log_term=rf.Last_log_term\n\t\t\t\treply.Last_log_lenth=rf.last_term_log_lenth\n\t\t\t\trf.mu.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\n\n\t\t\trf.term=args.Candidate_term\n\t\t\tif args.Second==true{\n\t\t\t\t//\tfmt.Printf(\"在服务器端进入second阶段!\\n\")\n\t\t\t\trf.log=rf.log[:args.Second_position]\n\t\t\t\trf.log=append(rf.log,args.Second_log...)\n\t\t\t\treply.Append_success=true\n\t\t\t\trf.Last_log_term=args.Last_log_term\n\t\t\t\trf.last_term_log_lenth=args.Last_log_term_lenth\n\t\t\t\trf.Last_log_index=len(rf.log)-1\n\t\t\t\trf.Log_Term=args.Log_Term\n\t\t\t\t//fmt.Printf(\"Second APPend在服务器端成功!现在编号为%d的raft实例的log是%v, last_log_term是%d,term是%d\\n\",rf.me,rf.log,rf.Last_log_term,rf.term)\n\t\t\t}else{\n\t\t\t\tif args.Append_Try == false {//try用于表示是否是第一次append失败了现在正在沟通\n\t\t\t\t\trf.append_try_log_index = rf.Last_log_index\n\t\t\t\t\trf.append_try_log_term=rf.Last_log_term\n\t\t\t\t}\n\t\t\t\tif args.Prev_log_index != rf.append_try_log_index || args.Prev_log_term != rf.append_try_log_term{\n\t\t\t\t\t//fmt.Printf(\"匹配失败!!!%d号leader发过来的PREV_log_index是%d,本机%d的last_log_index是%d,PREV_term是%d,本机的last_log_term是%d!\\n\",args.From,args.Prev_log_index,rf.me,rf.append_try_log_index,args.Prev_log_term,rf.append_try_log_term)\n\t\t\t\t\treply.Vote_sent = false//匹配失败后进入双方沟通try\n\t\t\t\t\treply.Append_success = false\n\n\t\t\t\t\treply.Log_Term=rf.Log_Term\n\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t} else { //说明没问题。可以更新\n\t\t\t\t\t//fmt.Printf(\"匹配成功!!!%d号是leader,发过来的PREV_log_index是%d,本机的last_log_index是%d,PREV_term是%d,本机的last_log_term是%d,准备更新本机日志!!\\n\", args.From, args.Prev_log_index, rf.append_try_log_index, args.Prev_log_term, rf.append_try_log_term)\n\t\t\t\t\t//rf.Last_log_term = args.Last_log_term\n\t\t\t\t\trf.last_term_log_lenth=args.Last_log_term_lenth\n\t\t\t\t\trf.log = append(rf.log, args.Newest_log)\n\t\t\t\t\trf.Last_log_index += 1\n\t\t\t\t\trf.Log_Term = args.Log_Term\n\t\t\t\t\trf.Last_log_term=args.Newest_log.Log_Term\n\t\t\t\t\treply.Append_success = true\n\t\t\t\t\t//fmt.Printf(\"APPend成功,现在编号为%d的raft实例的log是%v,last_log_term是%d,term是%d\\n\",rf.me,rf.log,rf.Last_log_term,rf.term)\n\t\t\t\t}\n\t\t\t}\n\t\t\trf.log_added_content = args.Newest_log\n\t\t\trf.last_term_log_lenth=0\n\n\t\t\tfor cc:=len(rf.log)-1;cc>-1;cc--{\n\t\t\t\tif rf.log[cc].Log_Term!=rf.Last_log_term{\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\trf.last_term_log_lenth+=1\n\t\t\t}\n\n\n\t\t}\n\n\t\t//fmt.Printf(\"在更新heartbeat之前\\n\")\n\t\tif args.Votemsg==false {//加上个约束条件更严谨,加上了表示是在heartbeat开始之后认同了这个是leader,否则在投票阶段就认同了\n\t\t\t//fmt.Printf(\"rf.last_log_term %d, args.last_log_term %d\\n\",rf.Last_log_term,args.Last_log_term)\n\t\t\tif args.Last_log_term==rf.Last_log_term {//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\t\t\t\tif args.Commit_MSG == true {\n\t\t\t\t\t//if len(rf.Log_Term)==len(args.Log_Term)&&rf.Log_Term[len(rf.Log_Term)-1]==args.Log_Term[len(args.Log_Term)-1]{\n\t\t\t\t\t//if len(args.Log_Term)==len(rf.Log_Term)&&args.Last_log_term==rf.Last_log_term {\n\t\t\t\t\tfor cc := rf.committed_index + 1; cc <= rf.Last_log_index; cc++ {\n\t\t\t\t\t\trf.committed_index = cc\n\t\t\t\t\t\t//!-------------------------fmt.Printf(\"在follower %d 上进行commit,commit_index是%d,commit的内容是%v,commit的term是%d,last_log_term是%d, rf.log是太长暂时鸽了\\n\", rf.me, cc, rf.log[cc].Log_Command, rf.log[cc].Log_Term, rf.Last_log_term)\n\t\t\t\t\t\trf.applych <- ApplyMsg{true, rf.log[rf.committed_index].Log_Command, rf.committed_index}\n\t\t\t\t\t}\n\n\t\t\t\t\treply.Commit_finished = true\n\t\t\t\t\t//}else{\n\t\t\t\t\t//}\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t}//!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\t\t\trf.leaderID = args.From\n\t\t\trf.term = args.Candidate_term\n\t\t\trf.leaderID=args.From\n\n\n\t\t}\n\t\treply.Last_log_lenth=rf.last_term_log_lenth\n\t\treply.Last_log_term=rf.Last_log_term\n\n\t\tif args.Votemsg==false {\n\t\t\tif rf.state == 0 {\n\t\t\t\trf.last_heartbeat <- 1\n\t\t\t}\n\t\t}\n\n\t}else{\n\t\t//fmt.Printf(\"term都不符,明显是非法的!\\n\")\n\t\treply.Vote_sent = false\n\t\treply.Append_success = false\n\t\treply.Term=rf.term\n\t\treply.Last_log_lenth=rf.last_term_log_lenth\n\t\treply.Last_log_term=rf.Last_log_term\n\t\t//-------------------if (args.Last_log_term>rf.Last_log_term)||(args.Last_log_term==rf.Last_log_term&&args.Last_log_term_lenth>=rf.last_term_log_lenth){\n\t\t//----------------------\treply.You_are_true=true\n\t\t//------------------------}\n\t}\n\trf.mu.Unlock()\n\t//fmt.Printf(\"编号为%d的raft实例通过RequestVote()收到了heartbeat\\n\",rf.me)\n\t//reply.voted<-true\n\t//rf.mu.Unlock()\n}", "func (s *RaftServer) RequestVote(_ context.Context, request *raftapi.RequestVoteMessage) (*raftapi.RequestVoteResponse, error) {\n\tlog.WithFields(s.LogFields()).Debugln(\"Received RequestVote\")\n\ts.lastHeartbeat = time.Now()\n\tterm := s.getTerm()\n\tif votedFor, has := s.votedOn[term]; !has || votedFor == request.Candidate {\n\t\tlogSize, _ := s.logRepo.LogSize()\n\t\tif term < request.Term || (term == request.Term && logSize < request.LogSize) {\n\t\t\ts.votedOn[term] = request.Candidate\n\t\t\treturn &raftapi.RequestVoteResponse{\n\t\t\t\tTerm: term,\n\t\t\t\tApproved: true,\n\t\t\t}, nil\n\t\t}\n\t}\n\treturn &raftapi.RequestVoteResponse{Term: term}, nil\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tcurrentTerm := rf.currentTerm\n\tif args == nil {\n\t\tDPrintf(\"Peer-%d received a null vote request.\", rf.me)\n\t\treturn\n\t}\n\tcandidateTerm := args.Term\n\tcandidateId := args.Candidate\n\tDPrintf(\"Peer-%d received a vote request %v from peer-%d.\", rf.me, *args, candidateId)\n\tif candidateTerm < currentTerm {\n\t\tDPrintf(\"Peer-%d's term=%d > candidate's term=%d.\\n\", rf.me, currentTerm, candidateTerm)\n\t\treply.Term = currentTerm\n\t\treply.VoteGrant = false\n\t\treturn\n\t} else if candidateTerm == currentTerm {\n\t\tif rf.voteFor != -1 && rf.voteFor != candidateId {\n\t\t\tDPrintf(\"Peer-%d has grant to peer-%d before this request from peer-%d.\", rf.me, rf.voteFor, candidateId)\n\t\t\treply.Term = currentTerm\n\t\t\treply.VoteGrant = false\n\t\t\treturn\n\t\t}\n\t\tDPrintf(\"Peer-%d's term=%d == candidate's term=%d, to check index.\\n\", rf.me, currentTerm, candidateTerm)\n\t} else {\n\t\tDPrintf(\"Peer-%d's term=%d < candidate's term=%d.\\n\", rf.me, currentTerm, candidateTerm)\n\t\t// begin to update status\n\t\trf.currentTerm = candidateTerm // find larger term, up to date\n\t\trf.transitionState(NewTerm) // transition to Follower.\n\t\tgo func() {\n\t\t\trf.eventChan <- NewTerm // tell the electionService to change state.\n\t\t}()\n\t}\n\t// check whose log is up-to-date\n\tcandiLastLogIndex := args.LastLogIndex\n\tcandiLastLogTerm := args.LastLogTerm\n\tlocalLastLogIndex := len(rf.log) - 1\n\tlocalLastLogTerm := -1\n\tif localLastLogIndex >= 0 {\n\t\tlocalLastLogTerm = rf.log[localLastLogIndex].Term\n\t}\n\t// check term first, if term is the same, then check the index.\n\tDPrintf(\"Peer-%d try to check last entry, loacl: index=%d;term=%d, candi: index=%d,term=%d.\", rf.me, localLastLogIndex, localLastLogTerm, candiLastLogIndex, candiLastLogTerm)\n\tif localLastLogTerm > candiLastLogTerm {\n\t\treply.Term = rf.currentTerm\n\t\treply.VoteGrant = false\n\t\treturn\n\t} else if localLastLogTerm == candiLastLogTerm {\n\t\tif localLastLogIndex > candiLastLogIndex {\n\t\t\treply.Term = rf.currentTerm\n\t\t\treply.VoteGrant = false\n\t\t\treturn\n\t\t}\n\t} else {\n\t}\n\t// heartbeat.\n\tgo func() {\n\t\trf.eventChan <- HeartBeat\n\t}()\n\t// local log are up-to-date, grant\n\t// before grant to candidate, we should reset ourselves state.\n\trf.transitionState(NewLeader)\n\trf.voteFor = candidateId\n\treply.Term = rf.currentTerm\n\treply.VoteGrant = true\n\tDPrintf(\"Peer-%d grant to peer-%d.\", rf.me, candidateId)\n\trf.persist()\n\treturn\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here.\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\trf.updateTerm(args.Term)\n\treply.Term = rf.currentTerm\n\tlastLogIndex := rf.lastIncludedIndex + len(rf.log) - 1\n\tlastLogTerm := rf.log[len(rf.log)-1].Term\n\treply.VoteGranted = (rf.votedFor == -1 || rf.votedFor == args.CandidateId) && (lastLogTerm < args.LastLogTerm || lastLogTerm == args.LastLogTerm && lastLogIndex <= args.LastLogIndex)\n\tif reply.VoteGranted {\n\t\trf.votedFor = args.CandidateId\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\tDPrintf(\"peer-%d gets a RequestVote RPC.\", rf.me)\n\t// Your code here (2A, 2B).\n\t// First, we need to detect obsolete information\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif args.Term < rf.currentTerm {\n\t\treply.VoteGranted = false\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t}\n\n\tstepdown := false\n\t// step down and convert to follower, adopt the args.Term\n\tif args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\told_state := rf.state\n\t\trf.state = Follower\n\t\tif old_state == Leader {\n\t\t\trf.nonleaderCh <- true\n\t\t}\n\t\trf.votedFor = -1\n\t\trf.persist()\n\t\tstepdown = true\n\t}\n\n\t// 5.4.1 Election restriction : if the requester's log isn't more up-to-date than this peer's, don't vote for it.\n\t// check whether the requester's log is more up-to-date.(5.4.1 last paragraph)\n\tif len(rf.log) > 0 { // At first, there's no log entry in rf.log\n\t\tif rf.log[len(rf.log)-1].Term > args.LastLogTerm {\n\t\t\t// this peer's log is more up-to-date than requester's.\n\t\t\treply.VoteGranted = false\n\t\t\treply.Term = rf.currentTerm\n\t\t\treturn\n\t\t} else if rf.log[len(rf.log)-1].Term == args.LastLogTerm {\n\t\t\tif len(rf.log) > args.LastLogIndex {\n\t\t\t\t// this peer's log is more up-to-date than requester's.\n\t\t\t\treply.VoteGranted = false\n\t\t\t\treply.Term = rf.currentTerm\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// requester's log is more up-to-date than requester's.\n\t// Then, we should check whether this server has voted for another server in the same term\n\tif stepdown {\n\t\trf.resetElectionTimeout()\n\t\t// now we need to reset the election timer.\n\t\trf.votedFor = args.CandidateId // First-come-first-served\n\t\trf.persist()\n\t\treply.VoteGranted = true\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t}\n\n\t/* Section 5.5 :\n\t * The server may crash after it completing an RPC but before responsing, then it will receive the same RPC again after it restarts.\n\t * Raft RPCs are idempotent, so this causes no harm.\n\t */\n\tif rf.votedFor == -1 || rf.votedFor == args.CandidateId {\n\t\trf.votedFor = args.CandidateId\n\t\trf.persist()\n\t\treply.VoteGranted = true\n\t} else {\n\t\treply.VoteGranted = false // First-come-first-served, this server has voted for another server before.\n\t}\n\treply.Term = rf.currentTerm\n\treturn\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here.\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tbbit := true\n\tif len(rf.log) > 0 {\n\t\tlastLogTerm := rf.log[len(rf.log)-1].Term\n\t\tif lastLogTerm > args.LastLogTerm {\n\t\t\tbbit = false\n\t\t} else if lastLogTerm == args.LastLogTerm &&\n\t\t\tlen(rf.log)-1 > args.LastLogIndex {\n\t\t\tbbit = false\n\t\t}\n\t}\n\n\tif args.Term < rf.currentTerm {\n\t\treply.Term = rf.currentTerm\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\tif args.Term == rf.currentTerm {\n\t\treply.Term = rf.currentTerm\n\t\tif rf.votedFor == -1 && bbit {\n\t\t\trf.votedFor = args.CandidateId\n\t\t\trf.persist()\n\t\t\treply.VoteGranted = true\n\t\t} else {\n\t\t\treply.VoteGranted = false\n\t\t}\n\t\treturn\n\t}\n\tif args.Term > rf.currentTerm {\n\t\trf.state = FOLLOWER\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = -1\n\t\trf.timer.Reset(properTimeDuration(rf.state))\n\t\treply.Term = args.Term\n\t\tif bbit {\n\t\t\trf.votedFor = args.CandidateId\n\t\t\trf.persist()\n\t\t\treply.VoteGranted = true\n\t\t} else {\n\t\t\treply.VoteGranted = false\n\t\t}\n\t\treturn\n\t}\n\treturn\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\t//fmt.Printf(\"[::RequestVote]\\n\")\n\t// Your code here.\n\trf.mtx.Lock()\n\tdefer rf.mtx.Unlock()\n\tdefer rf.persist()\n\n\treply.VoteGranted = false\n\n\t// case 1: check term\n\tif args.Term < rf.currentTerm {\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t}\n\n\tif args.Term > rf.currentTerm { // set term to max. and then maybe become leader.\n\t\trf.currentTerm = args.Term\n\t\trf.state = STATE_FOLLOWER\n\t\trf.voteFor = -1\n\t}\n\treply.Term = rf.currentTerm\n\n\t// case 2: check log\n\tisNewer := false\n\tif args.LastLogTerm == rf.log[len(rf.log)-1].Term {\n\t\tisNewer = args.LastLogIndex >= rf.log[len(rf.log)-1].LogIndex\n\t} else {\n\t\tisNewer = args.LastLogTerm > rf.log[len(rf.log)-1].Term\n\t}\n\n\tif (rf.voteFor == -1 || rf.voteFor == args.CandidateId) && isNewer {\n\t\trf.chanVoteOther <- 1\n\t\trf.state = STATE_FOLLOWER\n\t\treply.VoteGranted = true\n\t\trf.voteFor = args.CandidateId\n\t}\n\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here.\n\trf.mu.Lock()\n\tdefer rf.persist()\n\tdefer rf.mu.Unlock()\n\treply.Term = rf.CurrentTerm\n\n\tif args.Term < rf.CurrentTerm {\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\n\tif args.Term > rf.CurrentTerm {\n\t\trf.VotedFor = -1\n\t\trf.CurrentTerm = args.Term\n\t\trf.identity = FOLLOWER\n\t}\n\n\tif rf.VotedFor != -1 && rf.VotedFor != args.CandidateId {\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\tvar rfLogIndex int\n\tvar rfLogTerm int\n\tif len(rf.Log) > 0 {\n\t\trfLogIndex = rf.Log[len(rf.Log)-1].Index\n\t\trfLogTerm = rf.Log[len(rf.Log)-1].Term\n\t} else {\n\t\trfLogIndex = rf.lastIncludedIndex\n\t\trfLogTerm = rf.lastIncludedTerm\n\t}\n\n\tif args.LastLogTerm > rfLogTerm || args.LastLogTerm == rfLogTerm && args.LastLogIndex >= rfLogIndex {\n\t\treply.VoteGranted = true\n\t\trf.VotedFor = args.CandidateId\n\t\trf.identity = FOLLOWER\n\t\trf.hasVoted <- true\n\t} else {\n\t\treply.VoteGranted = false\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tif rf.currentTerm < args.Term {\n\t\trf.debug(\"Updating term to new term %v\\n\", args.Term)\n\t\trf.currentTerm = args.Term\n\t\tatomic.StoreInt32(&rf.state, FOLLOWER)\n\t\trf.votedFor = LEADER_UNKNOWN\n\t}\n\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\n\t// late candidates\n\tif args.Term < rf.currentTerm {\n\t\trf.debug(\"Rejecting candidate %v. Reason: late term=%v\\n\", args.CandidateId, args.Term)\n\t\treturn\n\t}\n\n\t// avoid double vote\n\tif rf.votedFor != LEADER_UNKNOWN && rf.votedFor != args.CandidateId {\n\t\trf.debug(\"Rejecting candidate %v. Reason: already voted\\n\", args.CandidateId)\n\t\treturn\n\t}\n\n\tlastLogIndex := rf.lastEntryIndex()\n\n\t// reject old logs\n\tif rf.index(lastLogIndex).Term > args.LastLogTerm {\n\t\trf.debug(\"Rejecting candidate %v. Reason: old log\\n\", args.CandidateId)\n\t\treturn\n\t}\n\n\t// log is smaller\n\tif rf.index(lastLogIndex).Term == args.LastLogTerm && args.LastLogIndex < lastLogIndex {\n\t\trf.debug(\"Rejecting candidate %v. Reason: small log\\n\", args.CandidateId)\n\t\treturn\n\t}\n\n\trf.votedFor = args.CandidateId\n\trf.gotContacted = true\n\n\trf.debug(\"Granting vote to %v. me=(%v,%v), candidate=(%v,%v)\\n\", args.CandidateId, lastLogIndex, rf.index(lastLogIndex).Term, args.LastLogIndex, args.LastLogTerm)\n\treply.VoteGranted = true\n\n\t// save state\n\trf.persist(false)\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here.\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tmay_grant_vote := true\n\tif len(rf.logs) > 0 {\n\t\t// rf.logs_term[len(rf.logs)-1] will always there, no matter snapshotedCount\n\t\tif rf.logs_term[len(rf.logs)-1] > args.LastLogTerm ||\n\t\t\t(rf.logs_term[len(rf.logs)-1] == args.LastLogTerm && len(rf.logs) > args.LogCount) {\n\t\t\tmay_grant_vote = false\n\t\t}\n\t}\n\trf.logger.Printf(\"Got vote request: %v, may grant vote: %v\\n\", args, may_grant_vote)\n\n\tif args.Term < rf.currentTerm {\n\t\trf.logger.Printf(\"Got vote request with term = %v, reject\\n\", args.Term)\n\t\treply.Term = rf.currentTerm\n\t\treply.Granted = false\n\t\treturn\n\t}\n\n\tif args.Term == rf.currentTerm {\n\t\trf.logger.Printf(\"Got vote request with current term, now voted for %v\\n\", rf.votedFor)\n\t\tif rf.votedFor == -1 && may_grant_vote {\n\t\t\trf.votedFor = args.CandidateID\n\t\t\trf.persist()\n\t\t}\n\t\treply.Granted = (rf.votedFor == args.CandidateID)\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t}\n\tif args.Term > rf.currentTerm {\n\t\trf.logger.Printf(\"Got vote request with term = %v, follow it\\n\", args.Term)\n\t\trf.state = FOLLOWER\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = -1\n\t\tif may_grant_vote {\n\t\t\trf.votedFor = args.CandidateID\n\t\t\trf.persist()\n\t\t}\n\t\trf.resetTimer()\n\n\t\treply.Granted = (rf.votedFor == args.CandidateID)\n\t\treply.Term = args.Term\n\t\treturn\n\t}\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n ok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n return ok\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\t//log.Println(\"Raft \", rf.me, \"term \", rf.currentTerm, \" receive vote request from Raft \", args.Me, \" term \", args.Term)\n\treply.Me = rf.me\n\n\tif args.Term == rf.currentTerm {\n\t\tif args.Me != rf.leader {\n\t\t\treply.Agree = false\n\t\t} else {\n\t\t\t// heartbeat, reset timer\n\t\t\treply.Agree = true\n\t\t\trf.resetElectionTimer()\n\t\t\t//log.Println(\"rf \", args.Me, \" -> rf \", rf.me)\n\t\t}\n\n\t} else if args.Term > rf.currentTerm {\n\t\t// vote request\n\t\t_, voted := rf.votedTerms[args.Term]\n\n\t\tif voted {\n\t\t\treply.Agree = false\n\n\t\t} else {\n\t\t\trf.stopElectionTimer()\n\n\t\t\t// new term start\n\t\t\tif rf.leader == rf.me {\n\t\t\t\trf.dethrone()\n\t\t\t}\n\n\t\t\treply.Agree = true\n\t\t\trf.leader = args.Me\n\t\t\trf.votedTerms[args.Term] = args.Me\n\t\t\trf.currentTerm = args.Term\n\t\t\trf.resetElectionTimer()\n\t\t\tlog.Println(\"Server \", rf.me, \" vote server \", args.Me, \" as leader in term \",\n\t\t\t\targs.Term)\n\t\t}\n\n\t} else {\n\t\treply.Agree = false\n\t}\n\t//log.Println(\"Raft \", rf.me, \" reply \", args.Me, \" reply: \", reply)\n}", "func (node *Node) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) error {\n\tnode.mu.Lock()\n\tdefer node.mu.Unlock()\n\tif node.state == dead {\n\t\treturn nil\n\t}\n\n\tlog.Printf(\"RequestVote args: %+v\\ncurrentTerm=%d\\nvotedFor=%d\", args, node.currentTerm, node.votedFor)\n\n\t// If the RPC term is less than the current term then we must reject the\n\t// vote request.\n\tif args.term < node.currentTerm {\n\t\treply.term = node.currentTerm\n\t\treply.voteGranted = false\n\t\tlog.Printf(\"RequestVote has been rejected by %d\", node.id)\n\t\treturn nil\n\t}\n\n\tif args.term > node.currentTerm {\n\t\t// Update the current node's state to follower.\n\t\tnode.updateStateToFollower(args.term)\n\t}\n\n\t// If the above condition was not true then we have to ensure that we have\n\t// not voted for some other node with the same term.\n\tif args.term == node.currentTerm && (node.votedFor == -1 || node.votedFor == args.candidateID) {\n\t\treply.voteGranted = true\n\t\tnode.votedFor = args.candidateID\n\t\tnode.timeSinceTillLastReset = time.Now()\n\t} else {\n\t\treply.voteGranted = false\n\t}\n\treply.term = node.currentTerm\n\tlog.Printf(\"RequestVote reply: %+v\", reply)\n\treturn nil\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\t/*\n\tIf votedFor is null or candidateId, and candidate’s\n\tlog is at least as up-to-date as receiver’s log, grant vote\n\t */\n\tif rf.isCandidateUpToDate(args) &&\n\t\t(rf.votedFor == -1 || rf.votedFor == args.CandidateId) {\n\t\t// grant vote and update rf's term.\n\t\trf.currentTerm = args.Term\n\n\t\treply.Term = args.Term\n\n\t\treply.VoteGranted = true\n\t} else {\n\t\t// don't grant vote to the candidate.\n\t\treply.Term = rf.currentTerm\n\n\t\treply.VoteGranted = false\n\t}\n\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n fmt.Printf(\"\\n -> I the Peer %d in got Vote Request from cadidate %d!\\n\",rf.me, args.CandidateId)\n \n rf.mu.Lock()\n defer rf.mu.Unlock() // TODO: ask professor/TA about this atomisitc and if mutex is needed.\n \n reply.FollowerTerm = rf.currentTerm\n \n rf.CheckTerm(args.CandidateTerm) \n \n // 2B code - fix if needed\n logUpToDate := false\n if len(rf.log) == 0 {\n logUpToDate = true\n } else if rf.log[len(rf.log)-1].Term < args.LastLogTerm {\n logUpToDate = true\n } else if rf.log[len(rf.log)-1].Term == args.LastLogTerm && \n len(rf.log) <= (args.LastLogIndex+1) {\n logUpToDate = true\n }\n // 2B code end\n \n reply.VoteGranted = (rf.currentTerm <= args.CandidateTerm && \n (rf.votedFor == -1 || rf.votedFor == args.CandidateId) &&\n logUpToDate) \n\n if reply.VoteGranted {\n rf.votedFor = args.CandidateId\n fmt.Printf(\"-> I the Peer %d say: Vote for cadidate %d Granted!\\n\",rf.me, args.CandidateId)\n } else {\n fmt.Printf(\"-> I the Peer %d say: Vote for cadidate %d Denied :/\\n\",rf.me, args.CandidateId)\n }\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n ok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n return ok\n}", "func Vote(w http.ResponseWriter, r *http.Request) {\n\tvar data voteRequest // Create struct to store data.\n\terr := json.NewDecoder(r.Body).Decode(&data) // Decode response to struct.\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\thelpers.ThrowErr(w, r, \"JSON decoding error\", err)\n\t\treturn\n\t}\n\n\t// Secure our request with reCAPTCHA v2 and v3.\n\tif !captcha.V3(data.CaptchaV2, data.Captcha, r.Header.Get(\"CF-Connecting-IP\"), \"vote\") {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvars := mux.Vars(r)\n\n\tpost, err := db.GetPost(vars[\"uuid\"])\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\thelpers.ThrowErr(w, r, \"Getting post from DB error\", err)\n\t\treturn\n\t}\n\n\tif post.Creation == 0 {\n\t\t// Post has been deleted.\n\t\tw.WriteHeader(http.StatusGone)\n\t\treturn\n\t}\n\n\tscore, err := db.SetVote(post, context.Get(r, \"uuid\").(string), data.Upvote)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\thelpers.ThrowErr(w, r, \"Setting vote error\", err)\n\t\treturn\n\t}\n\n\thelpers.JSONResponse(voteResponse{\n\t\tScore: score,\n\t}, w)\n\treturn\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\tDPrintf(\"Raft node (%d) handles with RequestVote, candidateId: %v\\n\", rf.me, args.CandidateId)\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\treply.Term = rf.currentTerm\n\treply.PeerId = rf.me\n\n\tif rf.currentTerm == args.Term && rf.votedFor != -1 && rf.votedFor != args.CandidateId {\n\t\tDPrintf(\"Raft node (%v) denied vote, votedFor: %v, candidateId: %v.\\n\", rf.me,\n\t\t\trf.votedFor, args.CandidateId)\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\n\tlastLogIndex := len(rf.logs) - 1\n\tlastLogEntry := rf.logs[lastLogIndex]\n\tif lastLogEntry.Term > args.LastLogTerm || lastLogIndex > args.LastLogIndex {\n\t\t// If this node is more up-to-date than candidate, then reject vote\n\t\t//DPrintf(\"Raft node (%v) LastLogIndex: %v, LastLogTerm: %v, args (%v, %v)\\n\", rf.me,\n\t\t//\tlastLogIndex, lastLogEntry.Term, args.LastLogIndex, args.LastLogTerm)\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\n\trf.tryEnterFollowState(args.Term)\n\n\trf.currentTerm = args.Term\n\trf.votedFor = args.CandidateId\n\treply.VoteGranted = true\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here.\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.state == Follower {\n\t\trf.ResetHeartBeatTimer()\n\t}\n\n\t// term in candidate old than this follower\n\tif args.Term < rf.currentTerm {\n\t\treply.Term = rf.currentTerm\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\n\tif args.Term > rf.currentTerm {\n\t\trf.UpdateNewTerm(args.Term)\n\t\trf.stateCh <- Follower\n\t}\n\n\tlogIndexSelf := len(rf.log) - 1\n\n\tvar isNew bool\n\t// the term is equal check the index\n\tif args.LastLogTerm == rf.log[logIndexSelf].Term {\n\t\tisNew = args.LastLogIndex >= logIndexSelf\n\t} else {\n\t\tisNew = args.LastLogTerm > rf.log[logIndexSelf].Term\n\t}\n\n\tif (rf.votedFor == -1 || rf.me == args.CandidateId) && isNew {\n\t\treply.Term = rf.currentTerm\n\t\treply.VoteGranted = true\n\t\trf.votedFor = args.CandidateId\n\t\trf.persist()\n\t\treturn\n\t} else {\n\t\treply.Term = rf.currentTerm\n\t\treply.VoteGranted = false\n\t}\n\n}", "func (r *RaftNode) Vote(rv RequestVoteStruct, response *RPCResponse) error {\n\tr.Lock()\n\tdefer r.Unlock()\n\tif r.verbose {\n\t\tlog.Println(\"Vote()\")\n\t}\n\n\tdefer r.persistState()\n\n\tresponse.Term = r.CurrentTerm\n\n\tmyLastLogTerm := r.getLastLogTerm()\n\tmyLastLogIdx := r.getLastLogIndex()\n\n\tif r.verbose {\n\t\tlog.Printf(\"RequestVoteStruct: %s. \\nMy node: term: %d, votedFor %d, lastLogTerm: %d, lastLogIdx: %d\",\n\t\t\trv.String(), r.CurrentTerm, r.VotedFor, myLastLogTerm, myLastLogIdx)\n\t}\n\n\tlooksEligible := r.CandidateLooksEligible(rv.LastLogIdx, rv.LastLogTerm)\n\n\tif rv.Term > r.CurrentTerm {\n\t\tr.shiftToFollower(rv.Term, HostID(-1)) // We do not yet know who is leader for this term\n\t}\n\n\tif rv.Term < r.CurrentTerm {\n\t\tif r.verbose {\n\t\t\tlog.Println(\"RV from prior term - do not grant vote\")\n\t\t}\n\t\tresponse.Success = false\n\t} else if (r.VotedFor == -1 || r.VotedFor == rv.CandidateID) && looksEligible {\n\t\tif r.verbose {\n\t\t\tlog.Println(\"Grant vote\")\n\t\t}\n\t\tr.resetTickers()\n\t\tresponse.Success = true\n\t\tr.VotedFor = rv.CandidateID\n\t} else {\n\t\tif r.verbose {\n\t\t\tlog.Println(\"Do not grant vote\")\n\t\t}\n\t\tresponse.Success = false\n\t}\n\n\treturn nil\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\n\t//defer rf.updateAppliedLock()\n\t//Your code here (2A, 2B).\n\tisALeader := rf.role == Leader\n\n\tif rf.updateTermLock(args.Term) && isALeader {\n\t\t//DPrintf(\"[DEBUG] Server %d from %d to Follower {requestVote : Term higher}\", rf.me, Leader)\n\t}\n\treply.VoteCranted = false\n\tvar votedFor interface{}\n\t//var isLeader bool\n\tvar candidateID, currentTerm, candidateTerm, currentLastLogIndex, candidateLastLogIndex, currentLastLogTerm, candidateLastLogTerm int\n\n\tcandidateID = args.CandidateID\n\tcandidateTerm = args.Term\n\tcandidateLastLogIndex = args.LastLogIndex\n\tcandidateLastLogTerm = args.LastLogTerm\n\n\trf.mu.Lock()\n\n\treply.Term = rf.currentTerm\n\tcurrentTerm = rf.currentTerm\n\tcurrentLastLogIndex = len(rf.logs) - 1 //TODO: fix the length corner case\n\tcurrentLastLogTerm = rf.logs[len(rf.logs)-1].Term\n\tvotedFor = rf.votedFor\n\tisFollower := rf.role == Follower\n\trf.mu.Unlock()\n\t//case 0 => I'm leader, so you must stop election\n\tif !isFollower {\n\t\tDPrintf(\"[DEBUG] Case0 I [%d] is Candidate than %d\", rf.me, args.CandidateID)\n\t\treturn\n\t}\n\n\t//case 1 => the candidate is not suit to be voted\n\tif currentTerm > candidateTerm {\n\t\tDPrintf(\"[DEBUG] Case1 Follower %d > Candidate %d \", rf.me, args.CandidateID)\n\t\treturn\n\t}\n\n\t//case 2 => the candidate's log is not lastest than the follwer\n\tif currentLastLogTerm > candidateLastLogTerm || (currentLastLogTerm == candidateLastLogTerm && currentLastLogIndex > candidateLastLogIndex) {\n\t\tDPrintf(\"[DEBUG] Case2 don't my[%d] newer than can[%d]\", rf.me, args.CandidateID)\n\t\treturn\n\t}\n\trf.mu.Lock()\n\t//case3 => I have voted and is not you\n\tif votedFor != nil && votedFor != candidateID {\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\t//now I will vote you\n\n\tvar notFollower bool\n\trf.votedFor = candidateID\n\tif rf.role != Follower {\n\t\tnotFollower = true\n\t}\n\tDPrintf(\"[Vote] Server[%d] vote to Can[%d]\", rf.me, args.CandidateID)\n\trf.role = Follower\n\treply.VoteCranted = true\n\trf.mu.Unlock()\n\trf.persist()\n\tif notFollower {\n\t\trf.msgChan <- RecivedVoteRequest\n\t} else {\n\t\trf.msgChan <- RecivedVoteRequest\n\t}\n\n\treturn\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\trf.lock()\n\tdefer rf.unLock()\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\tif args.Term < rf.currentTerm {\n\t\treturn\n\t} else if args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = -1\n\t\trf.myState = FollowerState\n\t\trf.persist()\n\t}\n\n\tif rf.votedFor < 0 || rf.votedFor == args.CandidateId {\n\t\t// candidate's logEntries is at least as up-to-date as receiver's logEntries, grant vote\n\t\tlastLogTerm := -1\n\t\tif len(rf.logEntries) != 0 {\n\t\t\tlastLogTerm = rf.logEntries[len(rf.logEntries)-1].Term\n\t\t} else {\n\t\t\tlastLogTerm = rf.lastIncludedTerm\n\t\t}\n\t\tif args.LastLogTerm < lastLogTerm || (args.LastLogTerm == lastLogTerm && args.LastLogIndex < rf.lastIncludedIndex+len(rf.logEntries)) {\n\t\t\treturn\n\t\t} else {\n\t\t\trf.votedFor = args.CandidateId\n\t\t\treply.VoteGranted = true\n\t\t\trf.timerReset = time.Now()\n\t\t\trf.persist()\n\t\t\treturn\n\t\t}\n\t}\n\t// Your code here (2A, 2B).\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n fmt.Printf(\"----> sendRequestProc: sendRequest to %d from %d\\n\", server, args.CandidateId)\n // Why is there no lock here? We are accessing a common variable.\n ok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n return ok\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\treply.VoterId = rf.peerId\n\tif args.Term < rf.currentTerm {\n\t\treply.Term = rf.currentTerm\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\tif args.Term > rf.currentTerm {\n\t\trf.stepDownToFollower(args.Term)\n\t}\n\tlastLog := rf.getLastLog()\n\tif (rf.votedFor == \"\" || rf.votedFor == args.CandidateId) && (lastLog.Term < args.LastLogTerm || (lastLog.Index <= args.LastLogIndex && lastLog.Term == args.LastLogTerm)) {\n\t\treply.Term = rf.currentTerm\n\t\trf.grantCh <- true\n\t\treply.VoteGranted = true\n\t\t// set voteFor\n\t\trf.votedFor = args.CandidateId\n\t\tlog.Printf(\"peer %v elect peer %v as leader\\n\", rf.peerId, args.CandidateId)\n\t}\n\treturn\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n DPrintf(\"%d: %d recieve RequestVote from %d:%d\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate)\n // Your code here (2A, 2B).\n rf.mu.Lock()\n defer rf.mu.Unlock()\n if args.Term < rf.currentTerm {\n \n reply.VoteGranted = false\n reply.Term = rf.currentTerm\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n return\n }\n\n if args.Term > rf.currentTerm {\n rf.votedFor = -1\n rf.currentTerm = args.Term\n }\n\n if rf.votedFor == -1 || rf.votedFor == args.Candidate {\n // election restriction\n if args.LastLogTerm < rf.log[len(rf.log) - 1].Term ||\n (args.LastLogTerm == rf.log[len(rf.log) - 1].Term &&\n args.LastLogIndex < len(rf.log) - 1) {\n rf.votedFor = -1\n reply.VoteGranted = false\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n return\n }\n\n \n if rf.state == FOLLOWER {\n rf.heartbeat <- true\n }\n rf.state = FOLLOWER\n rf.resetTimeout()\n rf.votedFor = args.Candidate\n\n \n reply.VoteGranted = true\n reply.Term = args.Term\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n return\n }\n reply.VoteGranted = false\n reply.Term = args.Term\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tdefer rf.persist()\n\n\treply.VoteGranted = false\n\n\tif args.Term < rf.currentTerm {\n\t\treply.Term = rf.currentTerm\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\n\tif args.Term == rf.currentTerm {\n\t\tif rf.voteFor == -1 || rf.voteFor == args.CandidateId {\n\t\t\tlastLogTerm, lastLogIdx := rf.getLastLogTermAndIdx()\n\t\t\tif lastLogTerm < args.LastLogTerm || lastLogTerm == args.LastLogTerm && lastLogIdx <= args.LastLogIdx {\n\t\t\t\treply.VoteGranted = true\n\t\t\t\trf.voteFor = args.CandidateId\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\treply.VoteGranted = false\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\treply.VoteGranted = false\n\t\t\treturn\n\t\t}\n\t}\n\n\tif args.Term > rf.currentTerm {\n\t\t//收到更大的term,先更新状态;再判断日志的新旧来投票\n\t\trf.changeToFollower(args.Term)\n\t\t//fixbug: 忘记在收到更大的term时更新votefor\n\t\trf.voteFor = -1\n\n\t\treply.Term = args.Term\n\n\t\tlastLogTerm, lastLogIdx := rf.getLastLogTermAndIdx()\n\t\tif lastLogTerm < args.LastLogTerm || lastLogTerm == args.LastLogTerm && lastLogIdx <= args.LastLogIdx {\n\t\t\treply.VoteGranted = true\n\t\t\trf.voteFor = args.CandidateId\n\t\t\treturn\n\t\t} else {\n\t\t\treply.VoteGranted = false\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.currentTerm > args.Term {\n\t\treply.VoteGranted = false\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t}\n\n\tif rf.currentTerm < args.Term {\n\t\trf.currentTerm = args.Term\n\t\trf.updateStateTo(FOLLOWER)\n\t\t//妈的咋突然少了段代码~~ 这里要变为follower状态\n\t\t//var wg sync.WaitGroup\n\t\t//wg.Add(1)\n\t\tgo func() {\n\t\t\t//\tdefer wg.Done()\n\t\t\trf.stateChangeCh <- struct{}{}\n\t\t}()\n\n\t\t//wg.Wait()\n\n\t\t//直接return,等待下一轮投票会导致活锁,比如node 1 ,2,3 。 node 1 加term为2,发请求给node2,3,term1。 node2,3更新term拒绝投票\n\t\t//return\n\t}\n\n\t//此处if 在 currentTerm < args.Term下必然成立,在currentTerm等于args.Term下不一定成立\n\n\tif rf.votedFor == -1 || rf.votedFor == args.CandidatedId {\n\t\t//if candidate的log 至少 as up-to-date as reveiver's log\n\t\tlastLogIndex := len(rf.logEntries) - 1\n\t\t//fmt.Println(lastLogIndex,rf.me,rf.logEntries )\n\t\tlastLogTerm := rf.logEntries[len(rf.logEntries)-1].Term\n\t\t//fmt.Println(lastLogIndex,lastLogTerm , args.LastLogIndex,args.LastLogTerm)\n\t\tif lastLogTerm < args.LastLogTerm || (lastLogTerm == args.LastLogTerm && lastLogIndex <= args.LastLogIndex) {\n\t\t\trf.votedFor = args.CandidatedId\n\t\t\treply.Term = rf.currentTerm\n\t\t\treply.VoteGranted = true\n\t\t\t//fmt.Printf(\"[Term %d],Node %d Reply 值为%v. Term= %d , lastIndex = %d <= args.lastLogIndex %d\\n\", rf.currentTerm, rf.me, reply, args.LastLogTerm, lastLogIndex, args.LastLogIndex)\n\t\t\tif rf.status == FOLLOWER {\n\t\t\t\tgo func() { rf.giveVoteCh <- struct{}{} }()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tfmt.Println(lastLogIndex, lastLogTerm, args.LastLogIndex, args.LastLogTerm)\n\t}\n\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\t//fmt.Printf(\"[Term %d] Node %d Reply 值为%v,rf.votefor=%d,\\n\", rf.currentTerm, rf.me, reply, rf.votedFor)\n\n}", "func Vote(stub shim.ChaincodeStubInterface, args []string) error {\n\tvar vote entities.Vote\n\terr := json.Unmarshal([]byte(args[0]), &vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"validating vote.\")\n\tpoll, err := validateVote(stub, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvotes, err := voteForDelegates(stub, &poll.Votes, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpoll.Votes = votes\n\n\terr = addVoteToPoll(stub, poll, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = util.StoreObjectInChain(stub, vote.ID(), util.VotesIndexName, []byte(args[0]))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"successfully submitted vote to poll!\")\n\treturn nil\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) error {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.state == Down {\n\t\treturn nil\n\t}\n\tlastLogIdx, lastLogTerm := rf.lastLogIdxAndTerm()\n\tlog.Printf(\"[%v] received RequestVote RPC: %+v [currentTerm=%d votedFor=%d lastLogIdx=%d lastLogTerm=%d]\",\n\t\trf.me, args, rf.currentTerm, rf.votedFor, lastLogIdx, lastLogTerm)\n\tif args.Term > rf.currentTerm {\n\t\t// Raft rfServer in past term, revert to follower (and reset its state)\n\t\tlog.Printf(\"[%v] RequestVoteArgs.Term=%d bigger than currentTerm=%d\",\n\t\t\trf.me, args.Term, rf.currentTerm)\n\t\trf.toFollower(args.Term)\n\t}\n\n\t// if hasn't voted or already voted for this candidate or\n\t// if the candidate has up-to-date log (section 5.4.1 from paper) ...\n\tif rf.currentTerm == args.Term &&\n\t\t(rf.votedFor == -1 || rf.votedFor == args.Candidate) &&\n\t\t(args.LastLogTerm > lastLogTerm ||\n\t\t\t(args.LastLogTerm == lastLogTerm && args.LastLogIndex >= lastLogIdx)) {\n\t\t// ... grant vote\n\t\treply.VoteGranted = true\n\t\trf.votedFor = args.Candidate\n\t\trf.resetElection = time.Now()\n\t} else {\n\t\treply.VoteGranted = false\n\t}\n\treply.Term = rf.currentTerm\n\trf.persist()\n\tlog.Printf(\"[%v] replying to RequestVote: %+v\", rf.me, reply)\n\treturn nil\n}", "func (rf *Raft) requestVote(req *opRequest) {\n\targs := req.args.(*pb.RequestVoteRequest)\n\treply := req.reply.(*pb.RequestVoteReply)\n\n\tif args.Term < rf.term {\n\t\treply.Term = rf.term\n\t\treply.Reject = true\n\t\treq.errorCh <- nil\n\t\treturn\n\t}\n\n\tif args.Term > rf.term {\n\t\trf.term = args.Term\n\t\trf.voteFor = 0\n\t}\n\tcanVote := rf.voteFor == args.Id ||\n\t\t(rf.voteFor == 0 && rf.raftLog.IsUptoDate(args.LastIndex, args.LastTerm))\n\tif canVote {\n\t\trf.voteFor = args.Id\n\t\trf.electionTimeoutCounter = 0\n\t\trf.becomeFollower(args.Term, 0)\n\t} else {\n\t\treply.Reject = true\n\t}\n\treply.Term = rf.term\n\treq.errorCh <- nil\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\n\tif args.Term > rf.currentTerm {\n\t\trf.convert2Follower(args.Term)\n\t}\n\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\n\tif args.Term < rf.currentTerm {\n\t\treturn\n\t}\n\n\tlastLogTerm := rf.getLastLogTerm()\n\tlastLogIndex := rf.getLastLogIndex()\n\t// voted-none && least-up-to-date\n\n\tup2Date := false\n\tif lastLogTerm < args.LastLogTerm {\n\t\tup2Date = true\n\t}\n\tif lastLogTerm == args.LastLogTerm && lastLogIndex <= args.LastLogIndex {\n\t\tup2Date = true\n\t}\n\n\tif up2Date && (rf.votedFor == -1 || rf.votedFor == args.CandidateId) {\n\t\treply.VoteGranted = true\n\t\trf.votedFor = args.CandidateId\n\t\t// DPrintf(\"Server [%v] vote [%v] for Term [%v]\", rf.me, args.CandidateId, rf.currentTerm)\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\n\t//All Server rule\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif args.Term > rf.currentTerm {\n\t\trf.beFollower(args.Term)\n\t\t// TODO check\n\t\t// send(rf.voteCh)\n\t}\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\tif (args.Term < rf.currentTerm) || (rf.votedFor != NULL && rf.votedFor != args.CandidateId) {\n\t\t// Reply false if term < currentTerm (§5.1) If votedFor is not null and not candidateId,\n\t} else if args.LastLogTerm < rf.getLastLogTerm() || (args.LastLogTerm == rf.getLastLogTerm() &&\n\t\targs.LastLogIndex < rf.getLastLogIndex()) {\n\t\t//If the logs have last entries with different terms, then the log with the later term is more up-to-date.\n\t\t// If the logs end with the same term, then whichever log is longer is more up-to-date.\n\t\t// Reply false if candidate’s log is at least as up-to-date as receiver’s log\n\t} else {\n\t\t//grant vote\n\t\trf.votedFor = args.CandidateId\n\t\treply.VoteGranted = true\n\t\trf.state = Follower\n\t\trf.persist()\n\t\tsend(rf.voteCh) //because If election timeout elapses without receiving granting vote to candidate, so wake up\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\n\treply.VoteGranted = false\n\treply.Term = rf.currentTerm\n\n\t// Rule for all servers: If RPC request or response contains term T > currentTerm: set currentTerm = T, convert to follower (§5.1)\n\tif args.Term > rf.currentTerm {\n\t\trf.convertToFollower(args.Term)\n\t}\n\n\t// 1. Reply false if term < currentTerm (§5.1)\n\tif args.Term < rf.currentTerm {\n\t\t_, _ = DPrintf(vote(\"[T%v] %v: Received RequestVote from %v | Discarded Vote | Received Lower Term \"), rf.currentTerm, rf.me, args.CandidateID, args.CandidateID)\n\t\treturn\n\t}\n\n\t/* 2. If\n\t *\t\t1. votedFor is null or candidateId\n\t *\t\t2. candidate’s log is at least as up-to-date as receiver’s log\n\t *\tgrant vote (§5.2, §5.4)\n\t */\n\n\t// Check 1 vote: should be able to vote or voted for candidate\n\tvoteCheck := rf.votedFor == noVote || rf.votedFor == args.CandidateID\n\t// Check 2 up-to-date = (same indices OR candidate's lastLogIndex > current peer's lastLogIndex)\n\tlastLogIndex, lastLogTerm := rf.lastLogEntryIndex(), rf.lastLogEntryTerm()\n\tlogCheck := lastLogTerm < args.LastLogTerm || (lastLogTerm == args.LastLogTerm && lastLogIndex <= args.LastLogIndex)\n\n\t// Both checks should be true to grant vote\n\tif voteCheck && logCheck {\n\t\treply.VoteGranted = true\n\t\t_, _ = DPrintf(vote(\"[T%v] %v: Received RequestVote from %v | Vote Successful\"), rf.currentTerm, rf.me, args.CandidateID)\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = args.CandidateID\n\t} else if !voteCheck {\n\t\t_, _ = DPrintf(vote(\"[T%v] %v: Received RequestVote from %v | Vote Failure | Already voted for %v\"), rf.currentTerm, rf.me, args.CandidateID, rf.votedFor)\n\t} else {\n\t\t_, _ = DPrintf(vote(\"[T%v] %v: Received RequestVote from %v | Vote Failure | No Up-To-Date Log | Received {LastLogTerm: %v, LastLogIndex: %v} | Current {LastLogTerm: %v, LastLogIndex: %v}\"),\n\t\t\trf.currentTerm, rf.me, args.CandidateID, args.LastLogTerm, args.LastLogIndex, lastLogTerm, lastLogIndex)\n\t}\n\trf.resetTTL()\n}", "func(rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply,signal chan bool) bool {\n\t//if args.Second==true {\n\t//fmt.Printf(\"开始Second调用sendRequestVote!在sendRequestVote可以看到args.Second的内容是%v,接续postion是%d\\n\",args.Second_log,args.Second_position)\n\t//}\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\t//if ok&&args.Second==true {\n\t//\tfmt.Printf(\"调用成功Second调用sendRequestVote!\\n\")\n\t//}\n\t//if !ok&&args.Second==true{\n\t//\tfmt.Printf(\"Second RPC调用失败!\\n\")\n\t//}\n\tif ok{\n\t\tsignal<-true\n\t}\n\treturn ok\n}", "func (r *Raft) requestVote(rpc RPC, req *RequestVoteRequest) (transition bool) {\n\tr.peerLock.Lock()\n\tdefer r.peerLock.Unlock()\n\t// Setup a response\n\tpeers := make([][]byte, 0, len(r.peers))\n\tfor _, p := range r.peers {\n\t\tpeers = append(peers, []byte(p.String()))\n\t}\n\tresp := &RequestVoteResponse{\n\t\tTerm: r.getCurrentTerm(),\n\t\tGranted: false,\n\t\tPeers: peers,\n\t}\n\tvar err error\n\tdefer rpc.Respond(resp, err)\n\n\t// Ignore an older term\n\tif req.Term < r.getCurrentTerm() {\n\t\terr = errors.New(\"obsolete term\")\n\t\treturn\n\t}\n\n\t// Increase the term if we see a newer one\n\tif req.Term > r.getCurrentTerm() {\n\t\tif err := r.setCurrentTerm(req.Term); err != nil {\n\t\t\tr.logE.Printf(\"Failed to update current term: %w\", err)\n\t\t\treturn\n\t\t}\n\t\tresp.Term = req.Term\n\n\t\t// Ensure transition to follower\n\t\ttransition = true\n\t\tr.setState(Follower)\n\t}\n\n\t// Check if we have voted yet\n\tlastVoteTerm, err := r.stable.GetUint64(keyLastVoteTerm)\n\tif err != nil && err.Error() != \"not found\" {\n\t\tr.logE.Printf(\"raft: Failed to get last vote term: %w\", err)\n\t\treturn\n\t}\n\tlastVoteCandyBytes, err := r.stable.Get(keyLastVoteCand)\n\tif err != nil && err.Error() != \"not found\" {\n\t\tr.logE.Printf(\"raft: Failed to get last vote candidate: %w\", err)\n\t\treturn\n\t}\n\n\t// Check if we've voted in this election before\n\tif lastVoteTerm == req.Term && lastVoteCandyBytes != nil {\n\t\tr.logW.Printf(\"raft: Duplicate RequestVote for same term: %d\", req.Term)\n\t\tif bytes.Compare(lastVoteCandyBytes, req.Candidate) == 0 {\n\t\t\tr.logW.Printf(\"raft: Duplicate RequestVote from candidate: %s\", req.Candidate)\n\t\t\tresp.Granted = true\n\t\t}\n\t\treturn\n\t}\n\n\t// Reject if their term is older\n\tif r.getLastLogIndex() > 0 {\n\t\tvar lastLog Log\n\t\tif err := r.logs.GetLog(r.getLastLogIndex(), &lastLog); err != nil {\n\t\t\tr.logE.Printf(\"Failed to get last log: %d %v\",\n\t\t\t\tr.getLastLogIndex(), err)\n\t\t\treturn\n\t\t}\n\t\tif lastLog.Term > req.LastLogTerm {\n\t\t\tr.logW.Printf(\"Rejecting vote since our last term is greater\")\n\t\t\treturn\n\t\t}\n\n\t\tif lastLog.Index > req.LastLogIndex {\n\t\t\tr.logW.Printf(\"Rejecting vote since our last index is greater\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Persist a vote for safety\n\tif err := r.persistVote(req.Term, req.Candidate); err != nil {\n\t\tr.logE.Printf(\"raft: Failed to persist vote: %w\", err)\n\t\treturn\n\t}\n\n\tresp.Granted = true\n\treturn\n}", "func (r *Raft) broadcastRequestVote(ctx context.Context) {\n\tr.stateMutex.RLock()\n\trequest := &pb.RequestVoteRequest{\n\t\tTerm: r.stateManager.GetCurrentTerm(),\n\t\tCandidateId: r.settings.ID,\n\t\tLastLogIndex: r.logManager.GetLastLogIndex(),\n\t\tLastLogTerm: r.logManager.GetLastLogTerm(),\n\t}\n\tr.stateMutex.RUnlock()\n\n\tresponses := r.cluster.BroadcastRequestVoteRPCs(ctx, request)\n\n\t// Count of votes starts at one because the server always votes for itself\n\tcountOfVotes := 1\n\n\tr.stateMutex.Lock()\n\tdefer r.stateMutex.Unlock()\n\n\t// Check if the state hasn't been changed in the meantime\n\tif r.stateManager.GetRole() != CANDIDATE {\n\t\treturn\n\t}\n\n\t// Count the number of votes\n\tfor _, response := range responses {\n\t\t// Server was unable to respond\n\t\tif response == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If the response contains higher term, we convert to follower\n\t\tif response.GetTerm() > r.stateManager.GetCurrentTerm() {\n\t\t\tr.stateManager.SwitchPersistentState(response.GetTerm(), nil, FOLLOWER)\n\t\t\treturn\n\t\t}\n\n\t\tif response.GetVoteGranted() {\n\t\t\tcountOfVotes++\n\t\t}\n\t}\n\n\t// Check if majority reached\n\tif r.checkClusterMajority(countOfVotes) {\n\t\tr.stateManager.SwitchPersistentState(r.stateManager.GetCurrentTerm(), nil, LEADER)\n\t}\n}", "func vote(w http.ResponseWriter, req *http.Request, upvote bool, isComment bool, t VoteRequest) error {\n\tif t.Id == \"\" {\n\t\treturn fmt.Errorf(\"missing post id\")\n\t}\n\ttable := \"posts\"\n\tif isComment {\n\t\ttable = \"comments\"\n\t}\n\trsp, err := client.DbService.Read(&db.ReadRequest{\n\t\tTable: table,\n\t\tId: t.Id,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(rsp.Records) == 0 {\n\t\treturn fmt.Errorf(\"post or comment not found\")\n\t}\n\n\t// auth\n\tsessionRsp, err := client.UserService.ReadSession(&user.ReadSessionRequest{\n\t\tSessionId: t.SessionID,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif sessionRsp.Session.UserId == \"\" {\n\t\treturn fmt.Errorf(\"user id not found\")\n\t}\n\n\t// prevent double votes\n\tcheckTable := table + \"votecheck\"\n\tcheckId := t.Id + sessionRsp.Session.UserId\n\tcheckRsp, err := client.DbService.Read(&db.ReadRequest{\n\t\tTable: checkTable,\n\t\tId: checkId,\n\t})\n\tmod := isMod(sessionRsp.Session.UserId, mods)\n\tif err == nil && (checkRsp != nil && len(checkRsp.Records) > 0) {\n\t\tif !mod {\n\t\t\treturn fmt.Errorf(\"already voted\")\n\t\t}\n\t}\n\tval := float64(1)\n\tif mod {\n\t\trand.Seed(time.Now().UnixNano())\n\t\tval = float64(rand.Intn(17-4) + 4)\n\t}\n\n\tif !mod {\n\t\t_, err = client.DbService.Create(&db.CreateRequest{\n\t\t\tTable: checkTable,\n\t\t\tRecord: map[string]interface{}{\n\t\t\t\t\"id\": checkId,\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tobj := rsp.Records[0]\n\tkey := \"upvotes\"\n\tif !upvote {\n\t\tkey = \"downvotes\"\n\t}\n\n\tif _, ok := obj[\"upvotes\"].(float64); !ok {\n\t\tobj[\"upvotes\"] = float64(0)\n\t}\n\tif _, ok := obj[\"downvotes\"].(float64); !ok {\n\t\tobj[\"downvotes\"] = float64(0)\n\t}\n\n\tobj[key] = obj[key].(float64) + val\n\tobj[\"score\"] = obj[\"upvotes\"].(float64) - obj[\"downvotes\"].(float64)\n\n\t_, err = client.DbService.Update(&db.UpdateRequest{\n\t\tTable: table,\n\t\tId: t.Id,\n\t\tRecord: obj,\n\t})\n\treturn err\n}", "func (a *RepoAPI) vote(params interface{}) (resp *rpc.Response) {\n\treturn rpc.Success(a.mods.Repo.Vote(cast.ToStringMap(params)))\n}", "func (r *Raft) sendVoteRequestRpc(value ServerConfig, VoteCount chan int) error {\n\n\tclient, err := rpc.Dial(\"tcp\", \"localhost:\"+strconv.Itoa(value.LogPort))\n\tlog.Println(\"Dialing vote request rpc from:\",r.Id,\" to:\",value.Id)\n\n\t if err != nil {\n\t\tlog.Print(\"Error Dialing sendVoteRequestRpc:\", err)\n\t\tVoteCount<-0\n\t\treturn err\n\t }\n\n\t logLen:= len(r.Log)\n\t var lastLogIndex int\n\t var lastLogTerm int\n\n\t if logLen >0 { // if log is not empty, send index and term of last log\n\t \tlastLogIndex=logLen-1\t \t\n\t \tlastLogTerm = r.Log[lastLogIndex].Term\n\t } else { // if log is empty, send index and term as 0\n\t \tlastLogIndex=0\n\t \tlastLogTerm=0\n\t }\n\n\t // Prepare argumenst to be sent to follower\n\t args:= RequestVoteRPCArgs{r.CurrentTerm,r.Id,lastLogTerm,lastLogIndex,}\n\n\tvar reply bool // reply variable will reciece the vote from other server, true is voted, false otherwise\n\tdefer client.Close()\n\terr1 := client.Call(\"RPC.VoteForLeader\", &args, &reply) \n\n\tif err1 != nil {\n\t\tlog.Print(\"Remote Method Invocation Error:Vote Request:\", err1)\n\t}\n\tif(reply) { // if reply is positive infrom the candiate \n\t\t//fmt.Println(\"Received reply of vote request from:\",value.Id,\" for:\",r.Id)\n\t\tVoteCount <-1\t\n\t}else{\n\t\tVoteCount <-0 // if reply is negative infrom the candiate \n\t\t//fmt.Println(\"Received Negative reply of vote request from:\",value.Id,\" for:\",r.Id)\n\t}\n\treturn nil\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\tswitch {\n\tcase args.Term < rf.currentTerm:\n\t\treply.VoteGranted = false\n\t\treturn\n\tcase args.Term > rf.currentTerm:\n\t\trf.setTerm(args.Term) // only reset term (and votedFor) if rf is behind\n\t}\n\n\treply.Term = rf.currentTerm\n\n\tif rf.votedFor == -1 || rf.votedFor == args.CandidateId && rf.AtLeastAsUpToDate(args) {\n\t\treply.VoteGranted = true\n\t\trf.votedFor = args.CandidateId\n\t} else {\n\t\treply.VoteGranted = false\n\t}\n\n\t// TODO move me somewhere else\n\tif reply.VoteGranted {\n\t\trf.requestVoteCh <- struct{}{}\n\t}\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tDPrintf(\"Serv[%d], SendRequestVote to %d\\n\", rf.me, server)\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\tDPrintf(\"Serv[%d], SendRequestVote rsp from %d\\n\", rf.me, server)\n\treturn ok\n}", "func (r *Raft) callRequestVote(server int, args requestVoteArgs, reply *requestVoteReply) bool {\n\t// When there are no peers, return a test response, if any.\n\tif len(r.peers) == 0 {\n\t\t// Under test, return injected reply.\n\t\tglog.V(2).Infof(\"Under test, returning injected reply %v\", reply)\n\t\tif r.testRequestvotesuccess {\n\t\t\t*reply = *r.testRequestvotereply\n\t\t}\n\t\treturn r.testRequestvotesuccess\n\t}\n\tok := r.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (remote *RemoteNode) RequestVoteRPC(local *RemoteNode, request *RequestVoteRequest) (*RequestVoteReply, error) {\n\t// if local.NetworkPolicy.IsDenied(*local.Self, *remote) {\n\t// \treturn nil, ErrorNetworkPolicyDenied\n\t// }\n\n\tcc, err := remote.RaftRPCClientConn()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treply, err := cc.RequestVoteCaller(context.Background(), request)\n\treturn reply, remote.connCheck(err)\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply, voteCount *int32) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\tlog.Printf(\"peer %v request vote to peer %v result %v\", rf.peerId, reply.VoterId, reply)\n\tif !ok {\n\t\treturn ok\n\t}\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.getState() != Candidate || args.Term != rf.currentTerm {\n\t\treturn ok\n\t}\n\tif reply.Term > rf.currentTerm {\n\t\trf.stepDownToFollower(reply.Term)\n\t}\n\tif reply.VoteGranted {\n\t\tatomic.AddInt32(voteCount, 1)\n\t}\n\tif int(atomic.LoadInt32(voteCount)) > len(rf.peers)/2 {\n\t\trf.setState(Leader)\n\t\trf.electAsLeaderCh <- true\n\t}\n\treturn ok\n}", "func (node *Node) ReceiveRequestVote(ctx context.Context, buffer []byte) (candidateAddress string, request RequestVote, err error) {\n candidateAddress, err = node.receive(ctx, buffer, &request)\n return\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tRV_RPCS++\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (app *Application) initVoteHandler(w http.ResponseWriter, r *http.Request) {\n\n\tvar v initVoteRequestBodyAPI\n\n\t// Decode HTTP request body and marshal into Vote struct.\n\t// If the bytes in the request body do not match the fields\n\t// of the Vote struct, the operation will fail.\n\terr := json.NewDecoder(r.Body).Decode(&v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Push vote data to IPFS\n\tcid, err := app.IpfsAdd(v.Content)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Call InitVoteSDK() to initialize a vote on the Fabric network\n\tresp, err := blockchain.InitVoteSDK(app.FabricSDK, v.PollID, v.VoterID, v.Sex, v.Age, cid)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write([]byte(resp))\n}", "func (rf *Raft) sendRequestVote(serverConn *labrpc.ClientEnd, server int, voteChan chan int, args *RequestVoteArgs, reply *RequestVoteReply) {\n\n\trequest := func() bool {\n\t\treturn serverConn.Call(\"Raft.RequestVote\", args, reply)\n\t}\n\n\tif ok := SendRPCRequest(\"Raft.RequestVote\", request); ok {\n\t\tvoteChan <- server\n\t}\n\n\t//ok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\t//return ok\n}", "func (q queryServer) Vote(ctx context.Context, req *v1.QueryVoteRequest) (*v1.QueryVoteResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid request\")\n\t}\n\n\tif req.ProposalId == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"proposal id can not be 0\")\n\t}\n\n\tif req.Voter == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty voter address\")\n\t}\n\n\tvoter, err := q.k.authKeeper.AddressCodec().StringToBytes(req.Voter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvote, err := q.k.Votes.Get(ctx, collections.Join(req.ProposalId, sdk.AccAddress(voter)))\n\tif err != nil {\n\t\tif errors.IsOf(err, collections.ErrNotFound) {\n\t\t\treturn nil, status.Errorf(codes.InvalidArgument,\n\t\t\t\t\"voter: %v not found for proposal: %v\", req.Voter, req.ProposalId)\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &v1.QueryVoteResponse{Vote: &vote}, nil\n}", "func (rf *Raft) sendRequestVote(server int, wg *sync.WaitGroup, req *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tdefer wg.Done()\n\tDPrintf(\"[sendRequestVote] Server%v向Server%v发送选举投票\\n\", rf.me, server)\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", req, reply)\n\treturn ok\n}", "func replyVote(stub shim.ChaincodeStubInterface, voteId string, reply string) peer.Response {\t\n\tMSPid, _ := shim.GetMSPID()\n\tvar OclToken int\n\t\n\t// Init vote receive list\n\tvotes_list := []Votes{}\n\tOperator_list := []Operators{}\n\n\t// Get all votes\n\tvotes, _ := stub.GetState(\"Votes\")\n\tjson.Unmarshal(votes, &votes_list)\n\n\t// Get Operator list\n\tvalue, _ := stub.GetState(\"Operators\")\n\tjson.Unmarshal(value, &Operator_list)\n\n\ti, _ := strconv.Atoi(voteId)\n\n\tfor i := 0; i < len(Operator_list); i++ {\n\t\tif(Operator_list[i].OperatorID == MSPid) {\n\t\t\tOclToken = Operator_list[i].OclToken\n\t\t}\n\t}\n\t\n\tvote_Operator := Operators{OperatorID: MSPid, OclToken: OclToken}\n\n\tif(reply == \"yes\") {\n\t\tvotes_list[i].Yes = append(votes_list[i].Yes, vote_Operator)\n\t\tvotesJson, _ := json.Marshal(votes_list)\n\t\tstub.PutState(\"Votes\", votesJson)\n\t} else if(reply == \"no\") {\n\t\tvotes_list[i].No = append(votes_list[i].No, vote_Operator)\n\t\tvotesJson, _ := json.Marshal(votes_list)\n\t\tstub.PutState(\"Votes\", votesJson)\n\t}\n\n\ttemp, _ := json.Marshal(votes_list[i])\n\tfmt.Println(\"tesstje: \" + string(temp))\n\t\n\treturn shim.Success([]byte(\"Replied on vote: \" + votes_list[i].Title))\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\t//log.Println(\"Rf \", rf.me, \" term \", rf.currentTerm, \" call Rf \", server, \" term \", args.Term)\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (t transporter) SendVoteRequest(server *raft.Server, peer *raft.Peer, req *raft.RequestVoteRequest) *raft.RequestVoteResponse {\n\tvar rvrsp *raft.RequestVoteResponse\n\tvar b bytes.Buffer\n\tjson.NewEncoder(&b).Encode(req)\n\n\tdebug(\"Send Vote to %s\", peer.Name())\n\n\tresp, err := t.Post(fmt.Sprintf(\"%s/vote\", peer.Name()), &b)\n\n\tif err != nil {\n\t\tdebug(\"Cannot send VoteRequest to %s : %s\", peer.Name(), err)\n\t}\n\n\tif resp != nil {\n\t\tdefer resp.Body.Close()\n\t\trvrsp := &raft.RequestVoteResponse{}\n\t\tif err := json.NewDecoder(resp.Body).Decode(&rvrsp); err == nil || err == io.EOF {\n\t\t\treturn rvrsp\n\t\t}\n\n\t}\n\treturn rvrsp\n}", "func (n *Node) handleRequestVote(msg RequestVoteMsg) (fallback bool) {\n\t// TODO: Students should implement this method\n\treturn true\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tch := make(chan bool)\n\tgo func() {\n\t\tch <- rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\t}()\n\n\tselect {\n\tcase <-time.After(100 * time.Millisecond):\n\t\treturn false\n\tcase r := <-ch:\n\t\treturn r\n\t}\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tDPrintf(\"[%v to %v]: RequestVote REQ: args: %+v\", rf.me, server, args)\n\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\n\tDPrintf(\"[%v to %v]: RequestVote ACK. result: %v, reply: %+v\", rf.me, server, ok, reply)\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tif ok {\n\t\tterm := rf.currentTerm\n\t\tif rf.state != CANDIDATE {\n\t\t\treturn ok\n\t\t}\n\n\t\tif args.Term != term {\n\t\t\treturn ok\n\t\t}\n\n\t\tif reply.Term > term {\n\t\t\trf.currentTerm = reply.Term\n\t\t\trf.state = FOLLOWER\n\t\t\trf.votedFor = -1\n\t\t\trf.persist()\n\t\t}\n\n\t\tif reply.VoteGranted {\n\t\t\trf.voteCounter++\n\t\t\tif rf.voteCounter > len(rf.peers) / 2 && rf.state == CANDIDATE {\n\t\t\t\t//\n\t\t\t\trf.state = FOLLOWER\n\t\t\t\trf.leaderChan <- true\n\t\t\t}\n\t\t}\n\n\t\t//rf.mu.Unlock()\n\t}\n\n\n\n\treturn ok\n}", "func (n *Node) requestVotes(currTerm uint64) (fallback, electionResult bool) {\n\t// TODO: Students should implement this method\n\treturn\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\t//DPrintf(\"%d sendRequestVote to %d\", rf.me, server)\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\t// DPrintf(\"%d send to Server %d\", args.CandidateId, server)\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\trequestBlock := func() bool { return rf.peers[server].Call(\"Raft.RequestVote\", args, reply) }\n\tok := SendRPCRequestWithRetry(\"Raft.RequestVote\", RaftRPCTimeout, 3, requestBlock)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\r\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\r\n\treturn ok\r\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply, once *sync.Once) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\tif ok {\n\t\tif rf.identity != CANDIDATE {\n\t\t\treturn ok\n\t\t}\n\t\tif reply.Term > rf.CurrentTerm {\n\t\t\trf.CurrentTerm = reply.Term\n\t\t\trf.identity = FOLLOWER\n\t\t\treturn ok\n\t\t}\n\t\tif reply.VoteGranted == true {\n\t\t\trf.votes++\n\t\t\t//fmt.Println(\"peer\", server, \"vote peer\", rf.me, \"at term\", rf.CurrentTerm)\n\t\t\tif rf.votes > len(rf.peers)/2 {\n\t\t\t\tonce.Do(func() {\n\t\t\t\t\trf.hasBecomeLeader <- true\n\t\t\t\t})\n\t\t\t\treturn ok\n\t\t\t}\n\t\t}\n\t}\n\treturn ok\n}", "func (_Contract *ContractTransactor) Vote(opts *bind.TransactOpts, delegatedTo common.Address, proposalID *big.Int, choices []*big.Int) (*types.Transaction, error) {\n\treturn _Contract.contract.Transact(opts, \"vote\", delegatedTo, proposalID, choices)\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\t// RPC Send Request\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\tif !ok {\n\t\trf.mu.Lock()\n\t\t_, _ = DPrintf(red(\"[T%v] %v: Network Error! RequestVote: No connection to Peer %v\"), rf.currentTerm, rf.me, server)\n\t\trf.mu.Unlock()\n\t\treturn false\n\t}\n\n\t// Evaluate RPC Result\n\trf.processRequestVoteReply(server, args, reply)\n\treturn true\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVoteHandler\", args, reply)\n\treturn ok\n}", "func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\trepo := secondary.NewDynamoRepository()\n\tservice := votes.NewService(repo)\n\tprimary := primary.NewAPIGatewayPrimaryAdapter(service)\n\n\treturn primary.HandleVote(request)\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) {\n\tif ok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply); !ok {\n\t\treturn\n\t}\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\t// drop old reply\n\tif reply.Term != args.Term {\n\t\treturn\n\t}\n\n\tif reply.Term > rf.currentTerm {\n\t\trf.currentTerm = reply.Term\n\t\trf.persist()\n\t\trf.state = FOLLOWER\n\t\treturn\n\t}\n\tif reply.VoteGranted {\n\t\trf.voteCount++\n\t}\n}", "func ajaxPollVote(w http.ResponseWriter, r *http.Request) {\n\tpr(\"ajaxPollVote\")\n\tprVal(\"r.Method\", r.Method)\n\n\tif r.Method != \"POST\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tuserId := GetSession(w, r)\n\tif userId == -1 { // Secure cookie not found. Either session expired, or someone is hacking.\n\t\t// So go to the register page.\n\t\tpr(\"Must be logged in to vote.\")\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tprVal(\"userId\", userId)\n\n //parse request to struct\n var vote struct {\n\t\tPollId\t\t\t\tint\n\t\tVoteData\t\t\t[]string\n\t\tNewVoteData\t\t\t[]string\n\t\tNewOptions\t\t\t[]string\n\t\tNumOriginalOptions\tint\n\t}\n\n err := json.NewDecoder(r.Body).Decode(&vote)\n if err != nil {\n\t\tprVal(\"Failed to decode json body\", r.Body)\n http.Error(w, err.Error(), http.StatusInternalServerError)\n return\n }\n\n prVal(\"=======>>>>> vote\", vote)\n\n // Convert voteDataJson into parallel arrays for more compact database storage.\n\t// 1) Voting for existing options:\n voteOptionIds := make([]int, 0)\n voteAmounts := make([]int, 0)\n for optionId, str := range vote.VoteData {\n\t\tif str != \"\" {\n\t\t\tvoteOptionIds = append(voteOptionIds, optionId)\n\n\t\t\tif str != \"x\" { // Ranked Voting\n\t\t\t\tvoteAmount, err := strconv.Atoi(str)\n\t\t\t\tcheck(err)\n\n\t\t\t\tvoteAmounts = append(voteAmounts, voteAmount)\n\t\t\t}\n\t\t}\n\t}\n\t// 2) Voting for new options the user just added, while remembering the new options added.\n\tnewOptions := make([]string, 0) // New options the user just added.\n\tnewOptionId := vote.NumOriginalOptions // Index of the next option the user might vote on.\n\tfor o, newOption := range vote.NewOptions {\n\t\tif newOption != \"\" { // Filter out empty options (they were probably mistakes), along with corresponding votes for them.\n\t\t\tnewOptions = append(newOptions, newOption) // Add new user-submitted option.\n\n\t\t\tstr := vote.NewVoteData[o]\n\t\t\tif str != \"\" {\n\t\t\t\tvoteOptionIds = append(voteOptionIds, newOptionId)\n\n\t\t\t\tif str != \"x\" { // Ranked Voting\n\t\t\t\t\tvoteAmount, err := strconv.Atoi(str)\n\t\t\t\t\tcheck(err)\n\n\t\t\t\t\tvoteAmounts = append(voteAmounts, voteAmount)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnewOptionId++\n\t\t}\n\t}\n\n\tpollId := int64(vote.PollId)\n\n\t// Fetch the pollOptionData for the poll.\n\tvar pollOptionData PollOptionData\n\trows := DbQuery(\"SELECT PollOptionData FROM $$PollPost WHERE Id = $1::bigint\", pollId)\n\tfor rows.Next() {\n\t\tvar pollOptionJson\tstring\n\t\terr := rows.Scan(&pollOptionJson)\n\t\tcheck(err)\n\n\t\tassert(len(pollOptionJson) > 0)\n\t\tcheck(json.Unmarshal([]byte(pollOptionJson), &pollOptionData))\n\n\t\t// If the user has added new options, add them to pollOptionData and the database.\n\t\tif len(newOptions) > 0 {\n\t\t\tpollOptionData.Options = append(pollOptionData.Options, newOptions...)\n\n\t\t\ta, err := json.Marshal(pollOptionData)\n\t\t\tcheck(err)\n\n\t\t\t// TODO: Fetching & updating PollOptionsData should be protected by a db transaction.\n\t\t\tDbExec(\"UPDATE $$PollPost SET PollOptionData = $1 WHERE Id = $2::bigint\", a, pollId)\n\t\t}\n\t}\n\tcheck(rows.Err())\n\trows.Close()\n\n\t// Send poll vote to the database, removing any prior vote.\n\t// TODO: make the code and database protect against duplicate names.\n\tDbExec(\n\t\t`INSERT INTO $$PollVote(PollId, UserId, VoteOptionIds, VoteAmounts)\n\t\t VALUES ($1::bigint, $2::bigint, $3::int[], $4::int[])\n\t\t ON CONFLICT (PollId, UserId) DO UPDATE\n\t\t SET (VoteOptionIds, VoteAmounts) = ($3::int[], $4::int[])`,\n\t\tpollId,\n\t\tuserId,\n\t\tpq.Array(voteOptionIds),\n\t\tpq.Array(voteAmounts))\n\n\t// Tally the poll tally results, and cache them in the db.\n\tpollTallyResults , _, _ := calcPollTally(pollId, pollOptionData, false, false, false, \"\", Article{})\n\n\t//prVal(\"pollTallyResults\", pollTallyResults)\n\n\tpollTallyResultsJson, err := json.Marshal(pollTallyResults)\n \tcheck(err)\n \t//prVal(\"pollTallyResultsJson\", pollTallyResultsJson)\n\n \tInvalidateCache(userId)\n\n\tDbExec(\n\t\t`UPDATE $$PollPost\n\t\t SET PollTallyResults = $1\n\t\t WHERE Id = $2::bigint`,\n\t\tpollTallyResultsJson,\n\t\tpollId)\n\n // create json response from struct\n a, err := json.Marshal(vote)\n\n if err != nil {\n serveError(w, err)\n return\n }\n w.Write(a)\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\trf.mu.Lock()\n\trf.persist()\n\trf.mu.Unlock()\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\tDPrintf(\"%s %d sent request vote args %v to %d, ok = %t, reply %v\\n\", rf.serverState, rf.me, args, server, ok, *reply)\n\treturn ok\n}", "func (raft *Raft) sendVoteRequest(server ServerConfig, ackChannel chan bool) {\n\t//Create args and reply\n\tlastLogTerm := raft.Log[raft.LastLsn()].Term\n\targs := RequestVoteArgs{raft.Term, uint64(raft.ServerID), raft.LastLsn(), lastLogTerm}\n\treply := RequestVoteResult{}\n\n\t//Request vote by RPC\n\t// err := raft.requestVote(server, args, &reply) //fake\n\terr := raft.voteRequestRPC(server, args, &reply) //\n\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tackChannel <- false\n\t\treturn\n\t}\n\n\t//Send ack\n\tackChannel <- reply.VoteGranted\n}", "func (rf *Raft) sendRequestVote(server int, args *VoteRequest, reply *VoteResponse) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (_Contract *ContractCaller) GetVote(opts *bind.CallOpts, from common.Address, delegatedTo common.Address, proposalID *big.Int) (struct {\n\tWeight *big.Int\n\tChoices []*big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"getVote\", from, delegatedTo, proposalID)\n\n\toutstruct := new(struct {\n\t\tWeight *big.Int\n\t\tChoices []*big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Weight = *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\toutstruct.Choices = *abi.ConvertType(out[1], new([]*big.Int)).(*[]*big.Int)\n\n\treturn *outstruct, err\n\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\trf.mtx.Lock()\n\tdefer rf.mtx.Unlock()\n\n\tif ok {\n\t\tif rf.state != STATE_CANDIDATE {\n\t\t\treturn ok\n\t\t}\n\t\tif args.Term != rf.currentTerm { // consider the current term's reply\n\t\t\treturn ok\n\t\t}\n\t\tif reply.Term > rf.currentTerm {\n\t\t\trf.currentTerm = reply.Term\n\t\t\trf.state = STATE_FOLLOWER\n\t\t\trf.voteFor = -1\n\t\t\trf.persist()\n\t\t}\n\t\tif reply.VoteGranted {\n\t\t\trf.beenVotedCount++\n\t\t\tif rf.state == STATE_CANDIDATE && rf.beenVotedCount > len(rf.peers)/2 {\n\t\t\t\trf.state = STATE_FOLLOWER // ...\n\t\t\t\trf.chanBecomeLeader <- 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ok\n}", "func (c *arbiterClient) Vote(sessionID ID) (Addr, ID, StatusCode) {\n\tclient, err := rpc.Dial(\"tcp\", c.remoteAddr.ToStr())\n\tif err != nil {\n\t\t*c.netErr = err\n\t\treturn Addr{}, ID(\"\"), StatusDefault\n\t}\n\tdefer client.Close()\n\tvar resp VoteResp\n\t*c.netErr = client.Call(\"ArbiterServer.Vote\", sessionID, &resp)\n\treturn resp.Addr, resp.ID, resp.Status\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (_Contract *ContractCallerSession) GetVote(from common.Address, delegatedTo common.Address, proposalID *big.Int) (struct {\n\tWeight *big.Int\n\tChoices []*big.Int\n}, error) {\n\treturn _Contract.Contract.GetVote(&_Contract.CallOpts, from, delegatedTo, proposalID)\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}" ]
[ "0.7755591", "0.7598429", "0.7428474", "0.7358386", "0.7318336", "0.7224504", "0.7216466", "0.72044766", "0.71909463", "0.7170334", "0.71627903", "0.7153472", "0.711499", "0.71020395", "0.7095982", "0.708936", "0.70887816", "0.70858073", "0.7078154", "0.70765084", "0.70429474", "0.70210314", "0.70075405", "0.7001527", "0.6988214", "0.6978752", "0.6965567", "0.6944827", "0.6939392", "0.6936741", "0.69228846", "0.691349", "0.6906194", "0.6902493", "0.6901255", "0.689531", "0.6826881", "0.6823714", "0.679227", "0.6791145", "0.67884994", "0.67851245", "0.67849666", "0.67704916", "0.6736788", "0.67345756", "0.6732248", "0.67265844", "0.6713634", "0.67040926", "0.6656432", "0.6651033", "0.6646976", "0.6627248", "0.66271204", "0.6620202", "0.66128004", "0.6591852", "0.65861666", "0.65803003", "0.65682954", "0.6540955", "0.65293777", "0.6490501", "0.64829314", "0.6479604", "0.64730895", "0.64691186", "0.6468026", "0.6447522", "0.6402135", "0.6359337", "0.6349653", "0.6341687", "0.62925947", "0.6286413", "0.6257937", "0.62543625", "0.6226385", "0.62245446", "0.6210897", "0.616899", "0.61687654", "0.6167153", "0.61558026", "0.61448294", "0.61313885", "0.6109033", "0.61061484", "0.6105216", "0.6103472", "0.6093189", "0.608285", "0.6075811", "0.60748196", "0.6058491", "0.6052798", "0.60264266", "0.6015099", "0.6015099" ]
0.7096627
14
example code to send a RequestVote RPC to a server. server is the index of the target server in rf.peers[]. expects RPC arguments in args. fills in reply with RPC reply, so caller should pass &reply. the types of the args and reply passed to Call() must be the same as the types of the arguments declared in the handler function (including whether they are pointers). The labrpc package simulates a lossy network, in which servers may be unreachable, and in which requests and replies may be lost. Call() sends a request and waits for a reply. If a reply arrives within a timeout interval, Call() returns true; otherwise Call() returns false. Thus Call() may not return for a while. A false return can be caused by a dead server, a live server that can't be reached, a lost request, or a lost reply. Call() is guaranteed to return (perhaps after a delay) except if the handler function on the server side does not return. Thus there is no need to implement your own timeouts around Call(). look at the comments in ../labrpc/labrpc.go for more details. if you're having trouble getting RPC to work, check that you've capitalized all field names in structs passed over RPC, and that the caller passes the address of the reply struct with &, not the struct itself.
func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool { // DPrintf("%d send to Server %d", args.CandidateId, server) ok := rf.peers[server].Call("Raft.RequestVote", args, reply) return ok }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Raft) sendVoteRequestRpc(value ServerConfig, VoteCount chan int) error {\n\n\tclient, err := rpc.Dial(\"tcp\", \"localhost:\"+strconv.Itoa(value.LogPort))\n\tlog.Println(\"Dialing vote request rpc from:\",r.Id,\" to:\",value.Id)\n\n\t if err != nil {\n\t\tlog.Print(\"Error Dialing sendVoteRequestRpc:\", err)\n\t\tVoteCount<-0\n\t\treturn err\n\t }\n\n\t logLen:= len(r.Log)\n\t var lastLogIndex int\n\t var lastLogTerm int\n\n\t if logLen >0 { // if log is not empty, send index and term of last log\n\t \tlastLogIndex=logLen-1\t \t\n\t \tlastLogTerm = r.Log[lastLogIndex].Term\n\t } else { // if log is empty, send index and term as 0\n\t \tlastLogIndex=0\n\t \tlastLogTerm=0\n\t }\n\n\t // Prepare argumenst to be sent to follower\n\t args:= RequestVoteRPCArgs{r.CurrentTerm,r.Id,lastLogTerm,lastLogIndex,}\n\n\tvar reply bool // reply variable will reciece the vote from other server, true is voted, false otherwise\n\tdefer client.Close()\n\terr1 := client.Call(\"RPC.VoteForLeader\", &args, &reply) \n\n\tif err1 != nil {\n\t\tlog.Print(\"Remote Method Invocation Error:Vote Request:\", err1)\n\t}\n\tif(reply) { // if reply is positive infrom the candiate \n\t\t//fmt.Println(\"Received reply of vote request from:\",value.Id,\" for:\",r.Id)\n\t\tVoteCount <-1\t\n\t}else{\n\t\tVoteCount <-0 // if reply is negative infrom the candiate \n\t\t//fmt.Println(\"Received Negative reply of vote request from:\",value.Id,\" for:\",r.Id)\n\t}\n\treturn nil\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n ok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n return ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n fmt.Printf(\"----> sendRequestProc: sendRequest to %d from %d\\n\", server, args.CandidateId)\n // Why is there no lock here? We are accessing a common variable.\n ok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n return ok\n}", "func (r *Raft) callRequestVote(server int, args requestVoteArgs, reply *requestVoteReply) bool {\n\t// When there are no peers, return a test response, if any.\n\tif len(r.peers) == 0 {\n\t\t// Under test, return injected reply.\n\t\tglog.V(2).Infof(\"Under test, returning injected reply %v\", reply)\n\t\tif r.testRequestvotesuccess {\n\t\t\t*reply = *r.testRequestvotereply\n\t\t}\n\t\treturn r.testRequestvotesuccess\n\t}\n\tok := r.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n ok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n return ok\n}", "func(rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply,signal chan bool) bool {\n\t//if args.Second==true {\n\t//fmt.Printf(\"开始Second调用sendRequestVote!在sendRequestVote可以看到args.Second的内容是%v,接续postion是%d\\n\",args.Second_log,args.Second_position)\n\t//}\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\t//if ok&&args.Second==true {\n\t//\tfmt.Printf(\"调用成功Second调用sendRequestVote!\\n\")\n\t//}\n\t//if !ok&&args.Second==true{\n\t//\tfmt.Printf(\"Second RPC调用失败!\\n\")\n\t//}\n\tif ok{\n\t\tsignal<-true\n\t}\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(serverConn *labrpc.ClientEnd, server int, voteChan chan int, args *RequestVoteArgs, reply *RequestVoteReply) {\n\n\trequest := func() bool {\n\t\treturn serverConn.Call(\"Raft.RequestVote\", args, reply)\n\t}\n\n\tif ok := SendRPCRequest(\"Raft.RequestVote\", request); ok {\n\t\tvoteChan <- server\n\t}\n\n\t//ok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\t//return ok\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\tgrantVote := false\n\trf.updateTerm(args.Term) // All servers: if args.Term > rf.currentTerm, set currentTerm, convert to follower\n\n\tswitch rf.state {\n\tcase Follower:\n\t\tif args.Term < rf.currentTerm {\n\t\t\tgrantVote = false\n\t\t} else if rf.votedFor == -1 || rf.votedFor == args.CandidateId {\n\t\t\tif len(rf.logs) == 0 {\n\t\t\t\tgrantVote = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlastLogTerm := rf.logs[len(rf.logs) - 1].Term\n\t\t\tif (lastLogTerm == args.LastLogTerm && len(rf.logs) <= args.LastLogIndex) || lastLogTerm < args.LastLogTerm {\n\t\t\t\tgrantVote = true\n\t\t\t}\n\t\t}\n\tcase Leader:\n\t\t// may need extra operation since the sender might be out-dated\n\tcase Candidate:\n\t\t// reject because rf has already voted for itself since it's in\n\t\t// Candidate state\n\t}\n\n\tif grantVote {\n\t\t// DPrintf(\"Peer %d: Granted RequestVote RPC from %d.(@%s state)\\n\", rf.me, args.CandidateId, rf.state)\n\t\treply.VoteGranted = true\n\t\trf.votedFor = args.CandidateId\n\t\t// reset election timeout\n\t\trf.hasHeartbeat = true\n\t} else {\n\t\t// DPrintf(\"Peer %d: Rejected RequestVote RPC from %d.(@%s state)\\n\", rf.me, args.CandidateId, rf.state)\n\t\treply.VoteGranted = false\n\t}\n\treply.VotersTerm = rf.currentTerm\n\n\t// when deal with cluster member changes, may also need to reject Request\n\t// within MINIMUM ELECTION TIMEOUT\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tcurrentTerm := rf.currentTerm\n\n\t//If RPC request or response contains term T > currentTerm:\n\t//set currentTerm = T, convert to follower\n\tif (args.Term > currentTerm) {\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = NILVOTE\n\n\t\tif rf.role == LEADER {\n\t\t\tDPrintf(\"LeaderCondition sorry server %d term %d not a leader, logs %v, commitIndex %d\\n\",rf.me, rf.currentTerm, rf.log, rf.commitIndex) \n\t\t} \n\t\trf.role = FOLLOWER\n\t\trf.persist()\n\t}\n\n\tif args.Term < currentTerm {\n\t\t// Reply false if term < currentTerm \n\t\treply.VoteGranted = false\n\t\treply.Term = currentTerm \n\t}else {\n\t\t//If votedFor is null or candidateId,\n\t\t//and candidate’s log is at least as up-to-date as receiver’s log,\n\t\t//&& rf.atLeastUptodate(args.LastLogIndex, args.LastLogTerm)\n\t\tif (rf.votedFor == NILVOTE || rf.votedFor == args.CandidateId) && rf.atLeastUptodate(args.LastLogIndex, args.LastLogTerm) {\n\t\t\ti , t := rf.lastLogIdxAndTerm()\n\t\t\tPrefixDPrintf(rf, \"voted to candidate %d, args %v, lastlogIndex %d, lastlogTerm %d\\n\", args.CandidateId, args, i, t)\n\t\t\trf.votedFor = args.CandidateId\n\t\t\trf.persist()\t\n\t\t\treply.VoteGranted = true\n\t\t\treply.Term = rf.currentTerm\n\t\t\t//you grant a vote to another peer.\n\t\t\trf.resetTimeoutEvent = makeTimestamp()\n\t\t}else {\n\t\t\treply.VoteGranted = false\n\t\t\treply.Term = rf.currentTerm\n\t\t}\t\n\t}\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\tresp := make(chan interface{})\n\trf.rpcCh <- rpcCall{command: args, reply: resp}\n\n\t*reply = (<-resp).(RequestVoteReply)\n}", "func (remote *RemoteNode) RequestVoteRPC(local *RemoteNode, request *RequestVoteRequest) (*RequestVoteReply, error) {\n\t// if local.NetworkPolicy.IsDenied(*local.Self, *remote) {\n\t// \treturn nil, ErrorNetworkPolicyDenied\n\t// }\n\n\tcc, err := remote.RaftRPCClientConn()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treply, err := cc.RequestVoteCaller(context.Background(), request)\n\treturn reply, remote.connCheck(err)\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\tDPrintf(\"peer-%d gets a RequestVote RPC.\", rf.me)\n\t// Your code here (2A, 2B).\n\t// First, we need to detect obsolete information\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif args.Term < rf.currentTerm {\n\t\treply.VoteGranted = false\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t}\n\n\tstepdown := false\n\t// step down and convert to follower, adopt the args.Term\n\tif args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\told_state := rf.state\n\t\trf.state = Follower\n\t\tif old_state == Leader {\n\t\t\trf.nonleaderCh <- true\n\t\t}\n\t\trf.votedFor = -1\n\t\trf.persist()\n\t\tstepdown = true\n\t}\n\n\t// 5.4.1 Election restriction : if the requester's log isn't more up-to-date than this peer's, don't vote for it.\n\t// check whether the requester's log is more up-to-date.(5.4.1 last paragraph)\n\tif len(rf.log) > 0 { // At first, there's no log entry in rf.log\n\t\tif rf.log[len(rf.log)-1].Term > args.LastLogTerm {\n\t\t\t// this peer's log is more up-to-date than requester's.\n\t\t\treply.VoteGranted = false\n\t\t\treply.Term = rf.currentTerm\n\t\t\treturn\n\t\t} else if rf.log[len(rf.log)-1].Term == args.LastLogTerm {\n\t\t\tif len(rf.log) > args.LastLogIndex {\n\t\t\t\t// this peer's log is more up-to-date than requester's.\n\t\t\t\treply.VoteGranted = false\n\t\t\t\treply.Term = rf.currentTerm\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// requester's log is more up-to-date than requester's.\n\t// Then, we should check whether this server has voted for another server in the same term\n\tif stepdown {\n\t\trf.resetElectionTimeout()\n\t\t// now we need to reset the election timer.\n\t\trf.votedFor = args.CandidateId // First-come-first-served\n\t\trf.persist()\n\t\treply.VoteGranted = true\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t}\n\n\t/* Section 5.5 :\n\t * The server may crash after it completing an RPC but before responsing, then it will receive the same RPC again after it restarts.\n\t * Raft RPCs are idempotent, so this causes no harm.\n\t */\n\tif rf.votedFor == -1 || rf.votedFor == args.CandidateId {\n\t\trf.votedFor = args.CandidateId\n\t\trf.persist()\n\t\treply.VoteGranted = true\n\t} else {\n\t\treply.VoteGranted = false // First-come-first-served, this server has voted for another server before.\n\t}\n\treply.Term = rf.currentTerm\n\treturn\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\trf.mu.Lock()\n\tdefer DPrintf(\"%d received RequestVote from %d, args.Term : %d, args.LastLogIndex: %d, args.LastLogTerm: %d, rf.log: %v, rf.voteFor: %d, \" +\n\t\t\"reply: %v\", rf.me, args.CandidatedId, args.Term, args.LastLogIndex, args.LastLogTerm, rf.log, rf.voteFor, reply)\n\t// Your code here (2A, 2B).\n\trf.resetElectionTimer()\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\tlastLogIndex := rf.log[len(rf.log)-1].Index\n\tlastLogTerm := rf.log[lastLogIndex].Term\n\n\tif lastLogTerm > args.LastLogTerm || (args.LastLogTerm == lastLogTerm && args.LastLogIndex < lastLogIndex) {\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\t// 5.1 Reply false if term < currentTerm\n\tif args.Term < rf.currentTerm {\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\tif (args.Term == rf.currentTerm && rf.state == \"leader\") || (args.Term == rf.currentTerm && rf.voteFor != -1){\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\tif args.Term == rf.currentTerm && rf.voteFor == args.CandidatedId {\n\t\treply.VoteGranted = true\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\t// Rules for Servers\n\t// All Servers\n\t// If RPC request or response contains term T > currentTerm: set currentTerm = T, convert to follower\n\tif args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\trf.voteFor = -1\n\t\trf.mu.Unlock()\n\t\trf.changeState(\"follower\")\n\t\trf.mu.Lock()\n\t}\n\n\trf.voteFor = args.CandidatedId\n\treply.VoteGranted = true\n\t//rf.persist()\n\trf.mu.Unlock()\n\treturn\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\n\t// Your code here (2A, 2B).\n\n\tDPrintf(\" before %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\t//log.Printf(\" before %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\tlog.Printf(\" before %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\n\tDPrintf(\" %v's requesetvote args is %v, and the reciever %v currentTerm is %v\", args.CandidateId, *args, rf.me, rf.currentTerm)\n\t//log.Printf(\" %v's requesetvote args is %v, and the reciever %v currentTerm is %v\", args.CandidateId, *args, rf.me, rf.currentTerm)\n\n\t// all servers\n\tif rf.currentTerm < args.Term {\n\t\trf.convertToFollower(args.Term)\n\t}\n\n\t_voteGranted := false\n\tif rf.currentTerm == args.Term && (rf.voteFor == VOTENULL || rf.voteFor == args.CandidateId) && (rf.getLastLogTerm() < args.LastLogTerm || (rf.getLastLogTerm() == args.LastLogTerm && rf.getLastLogIndex() <= args.LastLogIndex)) {\n\t\trf.state = Follower\n\t\tdropAndSet(rf.grantVoteCh)\n\t\t_voteGranted = true\n\t\trf.voteFor = args.CandidateId\n\t}\n\n\treply.VoteGranted = _voteGranted\n\treply.Term = rf.currentTerm\n\n\tDPrintf(\" after %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\tlog.Printf(\" after %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\n\trf.mu.Lock()\n\trf.debug(\"***************Inside the RPC handler for sendRequestVote *********************\")\n\tdefer rf.mu.Unlock()\n\tvar lastIndex int\n\t//var lastTerm int\n\tif len(rf.log) > 0 {\n\t\tlastLogEntry := rf.log[len(rf.log)-1]\n\t\tlastIndex = lastLogEntry.LastLogIndex\n\t\t//lastTerm = lastLogEntry.lastLogTerm\n\t}else{\n\t\tlastIndex = 0\n\t\t//lastTerm = 0\n\t}\n\treply.Term = rf.currentTerm\n\t//rf.debug()\n\tif args.Term < rf.currentTerm {\n\t\treply.VoteGranted = false\n\t\trf.debug(\"My term is higher than candidate's term, myTerm = %d, candidate's term = %d\", rf.currentTerm,args.Term )\n\t} else if (rf.votedFor == -1 || rf.votedFor == args.CandidateId) && args.LastLogIndex >= lastIndex {\n\t\trf.votedFor = args.CandidateId\n\t\treply.VoteGranted = true\n\t\trf.currentTerm = args.Term\n\t\trf.resetElectionTimer()\n\t\t//rf.debug(\"I am setting my currentTerm to -->\",args.Term,\"I am \",rf.me)\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.executeLock.Lock()\n\tdefer rf.executeLock.Unlock()\n\n\t//DPrintf(\"[ReceiveRequestVote] [me %v] from [peer %v] start\", rf.me, args.CandidateId)\n\trf.stateLock.Lock()\n\n\tdebugVoteArgs := &RequestVoteArgs{\n\t\tTerm: rf.currentTerm,\n\t\tCandidateId: rf.votedFor,\n\t\tLastLogIndex: int32(len(rf.log) - 1),\n\t\tLastLogTerm: rf.log[len(rf.log)-1].Term,\n\t}\n\tDPrintf(\"[ReceiveRequestVote] [me %#v] self info: %#v from [peer %#v] start\", rf.me, debugVoteArgs, args)\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\treply.LastLog = int32(len(rf.log) - 1)\n\treply.LastLogTerm = rf.log[reply.LastLog].Term\n\tif args.Term < rf.currentTerm {\n\t\tDPrintf(\"[ReceiveRequestVote] [me %v] from %v Term :%v <= currentTerm: %v, return\", rf.me, args.CandidateId, args.Term, rf.currentTerm)\n\t\trf.stateLock.Unlock()\n\t\treturn\n\t}\n\n\tconvrt2Follower := false\n\tif args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = -1\n\t\tconvrt2Follower = true\n\t\trf.persist()\n\t}\n\n\tif rf.votedFor == -1 || rf.votedFor == args.CandidateId {\n\t\tlastLogIndex := int32(len(rf.log) - 1)\n\t\tlastLogTerm := rf.log[lastLogIndex].Term\n\n\t\tif args.LastLogTerm < lastLogTerm || (args.LastLogTerm == lastLogTerm && args.LastLogIndex < lastLogIndex) {\n\t\t\trf.votedFor = -1\n\t\t\trf.lastHeartbeat = time.Now()\n\t\t\tDPrintf(\"[ReceiveRequestVote] [me %v] index from [%v] is oldest, return\", rf.me, args.CandidateId)\n\n\t\t\tif convrt2Follower && rf.role != _Follower {\n\t\t\t\tDPrintf(\"[ReceiveRequestVote] [me %v] from %v Term :%v (non-follower) > currentTerm: %v, return\", rf.me, args.CandidateId, args.Term, rf.currentTerm)\n\t\t\t\trf.role = _Unknown\n\t\t\t\trf.stateLock.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase <-rf.closeCh:\n\t\t\t\tcase rf.roleCh <- _Follower:\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\trf.stateLock.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\trf.votedFor = args.CandidateId\n\t\t// [WARNING] 一旦授权,应该重置超时\n\t\trf.lastHeartbeat = time.Now()\n\t\treply.VoteGranted = true\n\t\tDPrintf(\"[ReceiveRequestVote] [me %v] granted vote for %v\", rf.me, args.CandidateId)\n\t\tif rf.role != _Follower {\n\t\t\tDPrintf(\"[ReceiveRequestVote] [me %v] become follower\", rf.me)\n\t\t\trf.role = _Unknown\n\t\t\trf.stateLock.Unlock()\n\t\t\tselect {\n\t\t\tcase <-rf.closeCh:\n\t\t\t\treturn\n\t\t\tcase rf.roleCh <- _Follower:\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\trf.stateLock.Unlock()\n\t\treturn\n\t}\n\tDPrintf(\"[ReceiveRequestVote] [me %v] have voted: %v, return\", rf.me, rf.votedFor)\n\trf.stateLock.Unlock()\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tcurrentTerm := rf.currentTerm\n\tif args == nil {\n\t\tDPrintf(\"Peer-%d received a null vote request.\", rf.me)\n\t\treturn\n\t}\n\tcandidateTerm := args.Term\n\tcandidateId := args.Candidate\n\tDPrintf(\"Peer-%d received a vote request %v from peer-%d.\", rf.me, *args, candidateId)\n\tif candidateTerm < currentTerm {\n\t\tDPrintf(\"Peer-%d's term=%d > candidate's term=%d.\\n\", rf.me, currentTerm, candidateTerm)\n\t\treply.Term = currentTerm\n\t\treply.VoteGrant = false\n\t\treturn\n\t} else if candidateTerm == currentTerm {\n\t\tif rf.voteFor != -1 && rf.voteFor != candidateId {\n\t\t\tDPrintf(\"Peer-%d has grant to peer-%d before this request from peer-%d.\", rf.me, rf.voteFor, candidateId)\n\t\t\treply.Term = currentTerm\n\t\t\treply.VoteGrant = false\n\t\t\treturn\n\t\t}\n\t\tDPrintf(\"Peer-%d's term=%d == candidate's term=%d, to check index.\\n\", rf.me, currentTerm, candidateTerm)\n\t} else {\n\t\tDPrintf(\"Peer-%d's term=%d < candidate's term=%d.\\n\", rf.me, currentTerm, candidateTerm)\n\t\t// begin to update status\n\t\trf.currentTerm = candidateTerm // find larger term, up to date\n\t\trf.transitionState(NewTerm) // transition to Follower.\n\t\tgo func() {\n\t\t\trf.eventChan <- NewTerm // tell the electionService to change state.\n\t\t}()\n\t}\n\t// check whose log is up-to-date\n\tcandiLastLogIndex := args.LastLogIndex\n\tcandiLastLogTerm := args.LastLogTerm\n\tlocalLastLogIndex := len(rf.log) - 1\n\tlocalLastLogTerm := -1\n\tif localLastLogIndex >= 0 {\n\t\tlocalLastLogTerm = rf.log[localLastLogIndex].Term\n\t}\n\t// check term first, if term is the same, then check the index.\n\tDPrintf(\"Peer-%d try to check last entry, loacl: index=%d;term=%d, candi: index=%d,term=%d.\", rf.me, localLastLogIndex, localLastLogTerm, candiLastLogIndex, candiLastLogTerm)\n\tif localLastLogTerm > candiLastLogTerm {\n\t\treply.Term = rf.currentTerm\n\t\treply.VoteGrant = false\n\t\treturn\n\t} else if localLastLogTerm == candiLastLogTerm {\n\t\tif localLastLogIndex > candiLastLogIndex {\n\t\t\treply.Term = rf.currentTerm\n\t\t\treply.VoteGrant = false\n\t\t\treturn\n\t\t}\n\t} else {\n\t}\n\t// heartbeat.\n\tgo func() {\n\t\trf.eventChan <- HeartBeat\n\t}()\n\t// local log are up-to-date, grant\n\t// before grant to candidate, we should reset ourselves state.\n\trf.transitionState(NewLeader)\n\trf.voteFor = candidateId\n\treply.Term = rf.currentTerm\n\treply.VoteGrant = true\n\tDPrintf(\"Peer-%d grant to peer-%d.\", rf.me, candidateId)\n\trf.persist()\n\treturn\n}", "func (a *RPC) VoteForLeader(args *RequestVoteRPCArgs,reply *bool) error{\n\t//r.ResetTimer()\n \t//fmt.Println(\"received Vote request parameter \",(*args).CandidateId,\" \",(*args).Term,\" \",(*args).LastLogTerm,\" \",(*args).LastLogIndex)\n \t//if len(r.Log)>1{\n \t//\tfmt.Println(\"Vote Request folloer parameter \",r.Id,\" \", r.CurrentTerm,\" \",r.Log[len(r.Log)-1].Term ,\" \",len(r.Log)-1)\n \t//}\n\tif r.IsLeader==2 { // if this server is follower\n\t\t//r.ResetTimer() //TODO\n\t\tif r.CurrentTerm > args.Term || r.VotedFor >-1 { // if follower has updated Term or already voted for other candidate in same term , reply nagative\n\t\t\t*reply = false\n\t\t} else if r.VotedFor== -1{ // if follower has not voted for anyone in current Term \n\t\t\tlastIndex:= len(r.Log) \n\t\t\tif lastIndex > 0 && args.LastLogIndex >0{ // if Candiate log and this server log is not empty. \n\t\t\t\tif r.Log[lastIndex-1].Term > args.LastLogTerm { // and Term of last log in follower is updated than Candidate, reject vote\n *reply=false\n }else if r.Log[lastIndex-1].Term == args.LastLogTerm{ // else if Terms of Follower and candidate is same\n \tif (lastIndex-1) >args.LastLogIndex { // but follower log is more updated, reject vote\n \t\t*reply = false\n \t} else {\n \t\t\t*reply = true // If last log terms is match and followe log is sync with candiate, vote for candidate\n \t\t}\n }else{ // if last log term is not updated and Term does not match, \n \t \t\t*reply=true//means follower is lagging behind candiate in log entries, vote for candidate\n \t\t}\n \t\n\t\t\t} else if lastIndex >args.LastLogIndex { // either of them is Zero\n\t\t\t\t*reply = false // if Follower has entries in Log, its more updated, reject vote\n\t\t\t}else{\n\t\t\t\t\t*reply = true // else Vote for candiate\n\t\t\t\t}\n\t\t}else{\n\t\t\t*reply=false\n\t\t}\n\t}else{\n\t\t*reply = false // This server is already a leader or candiate, reject vote\n\t}\n\n\tif(*reply) {\n r.VotedFor=args.CandidateId // Set Voted for to candiate Id if this server has voted positive\n }\n\t/*if(*reply) {\n\t\tfmt.Println(\"Follower \",r.Id,\" Voted for \",r.VotedFor)\n\t}else{\n\t\tfmt.Println(\"Follower \",r.Id,\" rejected vote for \",args.CandidateId)\n\t}*/\n\treturn nil\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n fmt.Printf(\"\\n -> I the Peer %d in got Vote Request from cadidate %d!\\n\",rf.me, args.CandidateId)\n \n rf.mu.Lock()\n defer rf.mu.Unlock() // TODO: ask professor/TA about this atomisitc and if mutex is needed.\n \n reply.FollowerTerm = rf.currentTerm\n \n rf.CheckTerm(args.CandidateTerm) \n \n // 2B code - fix if needed\n logUpToDate := false\n if len(rf.log) == 0 {\n logUpToDate = true\n } else if rf.log[len(rf.log)-1].Term < args.LastLogTerm {\n logUpToDate = true\n } else if rf.log[len(rf.log)-1].Term == args.LastLogTerm && \n len(rf.log) <= (args.LastLogIndex+1) {\n logUpToDate = true\n }\n // 2B code end\n \n reply.VoteGranted = (rf.currentTerm <= args.CandidateTerm && \n (rf.votedFor == -1 || rf.votedFor == args.CandidateId) &&\n logUpToDate) \n\n if reply.VoteGranted {\n rf.votedFor = args.CandidateId\n fmt.Printf(\"-> I the Peer %d say: Vote for cadidate %d Granted!\\n\",rf.me, args.CandidateId)\n } else {\n fmt.Printf(\"-> I the Peer %d say: Vote for cadidate %d Denied :/\\n\",rf.me, args.CandidateId)\n }\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tDPrintf(\"Serv[%d], SendRequestVote to %d\\n\", rf.me, server)\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\tDPrintf(\"Serv[%d], SendRequestVote rsp from %d\\n\", rf.me, server)\n\treturn ok\n}", "func replyVote(stub shim.ChaincodeStubInterface, voteId string, reply string) peer.Response {\t\n\tMSPid, _ := shim.GetMSPID()\n\tvar OclToken int\n\t\n\t// Init vote receive list\n\tvotes_list := []Votes{}\n\tOperator_list := []Operators{}\n\n\t// Get all votes\n\tvotes, _ := stub.GetState(\"Votes\")\n\tjson.Unmarshal(votes, &votes_list)\n\n\t// Get Operator list\n\tvalue, _ := stub.GetState(\"Operators\")\n\tjson.Unmarshal(value, &Operator_list)\n\n\ti, _ := strconv.Atoi(voteId)\n\n\tfor i := 0; i < len(Operator_list); i++ {\n\t\tif(Operator_list[i].OperatorID == MSPid) {\n\t\t\tOclToken = Operator_list[i].OclToken\n\t\t}\n\t}\n\t\n\tvote_Operator := Operators{OperatorID: MSPid, OclToken: OclToken}\n\n\tif(reply == \"yes\") {\n\t\tvotes_list[i].Yes = append(votes_list[i].Yes, vote_Operator)\n\t\tvotesJson, _ := json.Marshal(votes_list)\n\t\tstub.PutState(\"Votes\", votesJson)\n\t} else if(reply == \"no\") {\n\t\tvotes_list[i].No = append(votes_list[i].No, vote_Operator)\n\t\tvotesJson, _ := json.Marshal(votes_list)\n\t\tstub.PutState(\"Votes\", votesJson)\n\t}\n\n\ttemp, _ := json.Marshal(votes_list[i])\n\tfmt.Println(\"tesstje: \" + string(temp))\n\t\n\treturn shim.Success([]byte(\"Replied on vote: \" + votes_list[i].Title))\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\t//log.Println(\"Rf \", rf.me, \" term \", rf.currentTerm, \" call Rf \", server, \" term \", args.Term)\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\n\n\t//fmt.Printf(\"成功调用RequestVote!\\n\")\n\t// Your code here (2A, 2B).\n\t//rf.mu.Lock()\n\t//current_time:=time.Now().UnixNano()/1e6\n\t//&&current_time-rf.voted_time>800\n\trf.mu.Lock()\n\n\tif (rf.term>args.Candidate_term)&&((args.Last_log_term>rf.Last_log_term)||(args.Last_log_term==rf.Last_log_term&&args.Last_log_term_lenth>=rf.last_term_log_lenth)){\n\t\trf.term=args.Candidate_term\n\t\trf.state=0\n\t}\n\n\n\t/*\n\t\tif args.Append==true&&((args.Newest_log.Log_Term<rf.Last_log_term)||(args.Newest_log.Log_Term==rf.Last_log_term&&args.Last_log_term_lenth<rf.Last_log_term)){\n\t\t\treply.Term=args.Candidate_term+1\n\t\t\treply.Last_log_term=rf.Last_log_term\n\t\t\treply.Last_log_lenth=rf.last_term_log_lenth\n\t\t\treply.Append_success=false\n\t\t\trf.mu.Unlock()\n\t\t\treturn\n\t\t}\n\t*/\n\t//if args.Second==true{\n\t//\tfmt.Printf(\"!\\n!\\n!\\n!\\n!\\n编号为%d的raft实例收到编号为%d的leader的second请求!本机term是%d,leader term是%d,args.Append是%v\\n\",rf.me,args.From,rf.term,args.Candidate_term,args.Append)\n\t//}\n\n\tif rf.state==2&&((rf.term<args.Candidate_term)||(rf.term==args.Candidate_term&&args.Last_log_term<rf.Last_log_term))&&args.Votemsg==false{\n\t\t//fmt.Printf(\"分区恢复后编号为%d的raft实例的term是%d,发现自己已经不是leader!leader是%d,leader的term是%d\\n\",rf.me,rf.term,args.From,args.Candidate_term)\n\t\trf.state=0\n\t\trf.leaderID=args.From\n\t}\n\n\n\n\tif args.Candidate_term>=rf.term{\n\t\t//rf.term=args.Candidate_term\n\t\t//if args.Second==true{\n\t\t//\tfmt.Printf(\"服务器上的SECOND进入第一个大括号\\n\")\n\t\t//}\n\t\tif args.Append == false {\n\t\t\tif args.Votemsg == true && rf.voted[args.Candidate_term] == 0&&((args.Last_log_term>rf.Last_log_term)||(args.Last_log_term==rf.Last_log_term&&args.Last_log_term_lenth>=rf.last_term_log_lenth)) { //合法投票请求\n\t\t\t\t//fmt.Printf(\"编号为%d的raft实例对投票请求的回答为true,term统一更新为为%d\\n\",rf.me,rf.term)\n\n\t\t\t\t//rf.term = args.Candidate_term\n\t\t\t\trf.voted[args.Candidate_term] = 1\n\t\t\t\treply.Vote_sent = true\n\n\t\t\t\t//rf.voted_time=time.Now().UnixNano()/1e6\n\n\t\t\t}else if args.Votemsg==true{ //合法的纯heartbeat\n\t\t\t\tif rf.voted[args.Candidate_term]==1 {\n\t\t\t\t\treply.Voted = true\n\t\t\t\t}\n\t\t\t\t//fmt.Printf(\"请求方的term是%d,本机的term是%d,来自%d的投票请求被%d拒绝!rf.last_log_term是%d,rf.last_log_lenth是%d,本机的rf.last_log_term是%d,rf.last_log_lenth是%d\\n\",args.Candidate_term,rf.term,args.From,rf.me,args.Last_log_term,args.Last_log_term_lenth,rf.Last_log_term,rf.last_term_log_lenth)\n\t\t\t}\n\t\t\treply.Term=rf.term\n\n\t\t\t//rf.term=args.Candidate_term//!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\t\t\t//if args.Votemsg==true{//!!!!!!!!!!!!!!\n\t\t\t//\trf.term=args.Candidate_term//!!!!!!!!!!!!\n\t\t\t//}//!!!!!!!!!!!!!!!!!\n\n\t\t} else { //这条是关于日志的\n\t\t\t//这个请求是日志同步请求,接收方需要将自己的日志最后一条和leader发过来的声称的进行比较,如果leader的更新且leader的PREV和自己的LAST相同就接受\n\t\t\t//还得找到最后一个一致的日志位置,然后将后面的全部更新为和leader一致的,这意味着中间多次的RPC通信\n\n\t\t\t/*\n\t\t\tif args.Newest_log.Log_Term<rf.Last_log_term{\n\t\t\t\treply.Wrong_leader=true\n\t\t\t\treply.Term=rf.term\n\t\t\t\treply.Append_success=false\n\t\t\t\treply.Last_log_lenth=rf.last_term_log_lenth\n\t\t\t\treturn\n\t\t\t}\n*/\n\n\t\t\tif (rf.Last_log_term>args.Last_log_term)||(rf.Last_log_term==args.Last_log_term&&rf.last_term_log_lenth>args.Last_log_term_lenth){\n\t\t\t\treply.Append_success=false\n\t\t\t\treply.Last_log_term=rf.Last_log_term\n\t\t\t\treply.Last_log_lenth=rf.last_term_log_lenth\n\t\t\t\trf.mu.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\n\n\t\t\trf.term=args.Candidate_term\n\t\t\tif args.Second==true{\n\t\t\t\t//\tfmt.Printf(\"在服务器端进入second阶段!\\n\")\n\t\t\t\trf.log=rf.log[:args.Second_position]\n\t\t\t\trf.log=append(rf.log,args.Second_log...)\n\t\t\t\treply.Append_success=true\n\t\t\t\trf.Last_log_term=args.Last_log_term\n\t\t\t\trf.last_term_log_lenth=args.Last_log_term_lenth\n\t\t\t\trf.Last_log_index=len(rf.log)-1\n\t\t\t\trf.Log_Term=args.Log_Term\n\t\t\t\t//fmt.Printf(\"Second APPend在服务器端成功!现在编号为%d的raft实例的log是%v, last_log_term是%d,term是%d\\n\",rf.me,rf.log,rf.Last_log_term,rf.term)\n\t\t\t}else{\n\t\t\t\tif args.Append_Try == false {//try用于表示是否是第一次append失败了现在正在沟通\n\t\t\t\t\trf.append_try_log_index = rf.Last_log_index\n\t\t\t\t\trf.append_try_log_term=rf.Last_log_term\n\t\t\t\t}\n\t\t\t\tif args.Prev_log_index != rf.append_try_log_index || args.Prev_log_term != rf.append_try_log_term{\n\t\t\t\t\t//fmt.Printf(\"匹配失败!!!%d号leader发过来的PREV_log_index是%d,本机%d的last_log_index是%d,PREV_term是%d,本机的last_log_term是%d!\\n\",args.From,args.Prev_log_index,rf.me,rf.append_try_log_index,args.Prev_log_term,rf.append_try_log_term)\n\t\t\t\t\treply.Vote_sent = false//匹配失败后进入双方沟通try\n\t\t\t\t\treply.Append_success = false\n\n\t\t\t\t\treply.Log_Term=rf.Log_Term\n\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t} else { //说明没问题。可以更新\n\t\t\t\t\t//fmt.Printf(\"匹配成功!!!%d号是leader,发过来的PREV_log_index是%d,本机的last_log_index是%d,PREV_term是%d,本机的last_log_term是%d,准备更新本机日志!!\\n\", args.From, args.Prev_log_index, rf.append_try_log_index, args.Prev_log_term, rf.append_try_log_term)\n\t\t\t\t\t//rf.Last_log_term = args.Last_log_term\n\t\t\t\t\trf.last_term_log_lenth=args.Last_log_term_lenth\n\t\t\t\t\trf.log = append(rf.log, args.Newest_log)\n\t\t\t\t\trf.Last_log_index += 1\n\t\t\t\t\trf.Log_Term = args.Log_Term\n\t\t\t\t\trf.Last_log_term=args.Newest_log.Log_Term\n\t\t\t\t\treply.Append_success = true\n\t\t\t\t\t//fmt.Printf(\"APPend成功,现在编号为%d的raft实例的log是%v,last_log_term是%d,term是%d\\n\",rf.me,rf.log,rf.Last_log_term,rf.term)\n\t\t\t\t}\n\t\t\t}\n\t\t\trf.log_added_content = args.Newest_log\n\t\t\trf.last_term_log_lenth=0\n\n\t\t\tfor cc:=len(rf.log)-1;cc>-1;cc--{\n\t\t\t\tif rf.log[cc].Log_Term!=rf.Last_log_term{\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\trf.last_term_log_lenth+=1\n\t\t\t}\n\n\n\t\t}\n\n\t\t//fmt.Printf(\"在更新heartbeat之前\\n\")\n\t\tif args.Votemsg==false {//加上个约束条件更严谨,加上了表示是在heartbeat开始之后认同了这个是leader,否则在投票阶段就认同了\n\t\t\t//fmt.Printf(\"rf.last_log_term %d, args.last_log_term %d\\n\",rf.Last_log_term,args.Last_log_term)\n\t\t\tif args.Last_log_term==rf.Last_log_term {//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\t\t\t\tif args.Commit_MSG == true {\n\t\t\t\t\t//if len(rf.Log_Term)==len(args.Log_Term)&&rf.Log_Term[len(rf.Log_Term)-1]==args.Log_Term[len(args.Log_Term)-1]{\n\t\t\t\t\t//if len(args.Log_Term)==len(rf.Log_Term)&&args.Last_log_term==rf.Last_log_term {\n\t\t\t\t\tfor cc := rf.committed_index + 1; cc <= rf.Last_log_index; cc++ {\n\t\t\t\t\t\trf.committed_index = cc\n\t\t\t\t\t\t//!-------------------------fmt.Printf(\"在follower %d 上进行commit,commit_index是%d,commit的内容是%v,commit的term是%d,last_log_term是%d, rf.log是太长暂时鸽了\\n\", rf.me, cc, rf.log[cc].Log_Command, rf.log[cc].Log_Term, rf.Last_log_term)\n\t\t\t\t\t\trf.applych <- ApplyMsg{true, rf.log[rf.committed_index].Log_Command, rf.committed_index}\n\t\t\t\t\t}\n\n\t\t\t\t\treply.Commit_finished = true\n\t\t\t\t\t//}else{\n\t\t\t\t\t//}\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t}//!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\t\t\trf.leaderID = args.From\n\t\t\trf.term = args.Candidate_term\n\t\t\trf.leaderID=args.From\n\n\n\t\t}\n\t\treply.Last_log_lenth=rf.last_term_log_lenth\n\t\treply.Last_log_term=rf.Last_log_term\n\n\t\tif args.Votemsg==false {\n\t\t\tif rf.state == 0 {\n\t\t\t\trf.last_heartbeat <- 1\n\t\t\t}\n\t\t}\n\n\t}else{\n\t\t//fmt.Printf(\"term都不符,明显是非法的!\\n\")\n\t\treply.Vote_sent = false\n\t\treply.Append_success = false\n\t\treply.Term=rf.term\n\t\treply.Last_log_lenth=rf.last_term_log_lenth\n\t\treply.Last_log_term=rf.Last_log_term\n\t\t//-------------------if (args.Last_log_term>rf.Last_log_term)||(args.Last_log_term==rf.Last_log_term&&args.Last_log_term_lenth>=rf.last_term_log_lenth){\n\t\t//----------------------\treply.You_are_true=true\n\t\t//------------------------}\n\t}\n\trf.mu.Unlock()\n\t//fmt.Printf(\"编号为%d的raft实例通过RequestVote()收到了heartbeat\\n\",rf.me)\n\t//reply.voted<-true\n\t//rf.mu.Unlock()\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\trequestBlock := func() bool { return rf.peers[server].Call(\"Raft.RequestVote\", args, reply) }\n\tok := SendRPCRequestWithRetry(\"Raft.RequestVote\", RaftRPCTimeout, 3, requestBlock)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply, voteCount *int32) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\tlog.Printf(\"peer %v request vote to peer %v result %v\", rf.peerId, reply.VoterId, reply)\n\tif !ok {\n\t\treturn ok\n\t}\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.getState() != Candidate || args.Term != rf.currentTerm {\n\t\treturn ok\n\t}\n\tif reply.Term > rf.currentTerm {\n\t\trf.stepDownToFollower(reply.Term)\n\t}\n\tif reply.VoteGranted {\n\t\tatomic.AddInt32(voteCount, 1)\n\t}\n\tif int(atomic.LoadInt32(voteCount)) > len(rf.peers)/2 {\n\t\trf.setState(Leader)\n\t\trf.electAsLeaderCh <- true\n\t}\n\treturn ok\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tif args.Term < rf.currentTerm {\n\t\treply.Term = rf.currentTerm\n\t\treply.VoteGranted = false\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\t// follow the second rule in \"Rules for Servers\" in figure 2 before handling an incoming RPC\n\tif args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\trf.state = FOLLOWER\n\t\trf.votedFor = -1\n\t\trf.persist()\n\t}\n\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = true\n\t// deny vote if already voted\n\tif rf.votedFor != -1 {\n\t\treply.VoteGranted = false\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\t// deny vote if consistency check fails (candidate is less up-to-date)\n\tlastLog := rf.log[len(rf.log)-1]\n\tif args.LastLogTerm < lastLog.Term || (args.LastLogTerm == lastLog.Term && args.LastLogIndex < len(rf.log)-1) {\n\t\treply.VoteGranted = false\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\t// now this peer must vote for the candidate\n\trf.votedFor = args.CandidateID\n\trf.mu.Unlock()\n\n\trf.resetTimer()\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tRV_RPCS++\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\t//DPrintf(\"%d sendRequestVote to %d\", rf.me, server)\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, wg *sync.WaitGroup, req *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tdefer wg.Done()\n\tDPrintf(\"[sendRequestVote] Server%v向Server%v发送选举投票\\n\", rf.me, server)\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", req, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tch := make(chan bool)\n\tgo func() {\n\t\tch <- rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\t}()\n\n\tselect {\n\tcase <-time.After(100 * time.Millisecond):\n\t\treturn false\n\tcase r := <-ch:\n\t\treturn r\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tlastLogIndex, lastLogTerm := len(rf.log) + rf.compactIndex , 0\n\tif lastLogIndex > rf.compactIndex {\n\t\tlastLogTerm = rf.log[lastLogIndex - rf.compactIndex -1].Term\n\t} else if lastLogIndex == rf.compactIndex {\n\t\tlastLogTerm = rf.compactTerm\n\t}\n\n\tif args.Term < rf.currentTerm || (args.Term == rf.currentTerm && args.CandidateID != rf.votedFor) || args.LastLogTerm < lastLogTerm || (args.LastLogTerm == lastLogTerm && lastLogIndex > args.LastLogIndex) {\n\t\t// 1. The Term of RequestVote is out of date.\n\t\t// 2. The instance vote for other peer in this term.\n\t\t// 3. The log of Candidate is not the most update.\n\t\treply.VoteGranted = false\n\t\treply.Term = rf.currentTerm\n\t} else {\n\t\t// DPrintf(\"instance %d vote for %d, Term is %d, lastLogTerm is %d, args.LastLogTerm is %d, lastLogIndex is %d, args.LastLogIndex is %d, original votedFor is %d\", rf.me, args.CandidateID, args.Term, lastLogTerm, args.LastLogTerm, lastLogIndex, args.LastLogIndex, rf.votedFor)\n\t\trf.votedFor = args.CandidateID\n\t\trf.currentTerm = args.Term\n\n\t\treply.VoteGranted = true\n\t\treply.Term = rf.currentTerm\n\n\t\tif rf.role == Follower {\n\t\t\trf.validRpcTimestamp = time.Now()\n\t\t} else {\n\t\t\t// Notify the change of the role of instance.\n\t\t\tclose(rf.rollback)\n\t\t\trf.role = Follower\n\t\t}\n\t}\n\n\treturn\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\n\t//defer rf.updateAppliedLock()\n\t//Your code here (2A, 2B).\n\tisALeader := rf.role == Leader\n\n\tif rf.updateTermLock(args.Term) && isALeader {\n\t\t//DPrintf(\"[DEBUG] Server %d from %d to Follower {requestVote : Term higher}\", rf.me, Leader)\n\t}\n\treply.VoteCranted = false\n\tvar votedFor interface{}\n\t//var isLeader bool\n\tvar candidateID, currentTerm, candidateTerm, currentLastLogIndex, candidateLastLogIndex, currentLastLogTerm, candidateLastLogTerm int\n\n\tcandidateID = args.CandidateID\n\tcandidateTerm = args.Term\n\tcandidateLastLogIndex = args.LastLogIndex\n\tcandidateLastLogTerm = args.LastLogTerm\n\n\trf.mu.Lock()\n\n\treply.Term = rf.currentTerm\n\tcurrentTerm = rf.currentTerm\n\tcurrentLastLogIndex = len(rf.logs) - 1 //TODO: fix the length corner case\n\tcurrentLastLogTerm = rf.logs[len(rf.logs)-1].Term\n\tvotedFor = rf.votedFor\n\tisFollower := rf.role == Follower\n\trf.mu.Unlock()\n\t//case 0 => I'm leader, so you must stop election\n\tif !isFollower {\n\t\tDPrintf(\"[DEBUG] Case0 I [%d] is Candidate than %d\", rf.me, args.CandidateID)\n\t\treturn\n\t}\n\n\t//case 1 => the candidate is not suit to be voted\n\tif currentTerm > candidateTerm {\n\t\tDPrintf(\"[DEBUG] Case1 Follower %d > Candidate %d \", rf.me, args.CandidateID)\n\t\treturn\n\t}\n\n\t//case 2 => the candidate's log is not lastest than the follwer\n\tif currentLastLogTerm > candidateLastLogTerm || (currentLastLogTerm == candidateLastLogTerm && currentLastLogIndex > candidateLastLogIndex) {\n\t\tDPrintf(\"[DEBUG] Case2 don't my[%d] newer than can[%d]\", rf.me, args.CandidateID)\n\t\treturn\n\t}\n\trf.mu.Lock()\n\t//case3 => I have voted and is not you\n\tif votedFor != nil && votedFor != candidateID {\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\t//now I will vote you\n\n\tvar notFollower bool\n\trf.votedFor = candidateID\n\tif rf.role != Follower {\n\t\tnotFollower = true\n\t}\n\tDPrintf(\"[Vote] Server[%d] vote to Can[%d]\", rf.me, args.CandidateID)\n\trf.role = Follower\n\treply.VoteCranted = true\n\trf.mu.Unlock()\n\trf.persist()\n\tif notFollower {\n\t\trf.msgChan <- RecivedVoteRequest\n\t} else {\n\t\trf.msgChan <- RecivedVoteRequest\n\t}\n\n\treturn\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\t//log.Println(\"Raft \", rf.me, \"term \", rf.currentTerm, \" receive vote request from Raft \", args.Me, \" term \", args.Term)\n\treply.Me = rf.me\n\n\tif args.Term == rf.currentTerm {\n\t\tif args.Me != rf.leader {\n\t\t\treply.Agree = false\n\t\t} else {\n\t\t\t// heartbeat, reset timer\n\t\t\treply.Agree = true\n\t\t\trf.resetElectionTimer()\n\t\t\t//log.Println(\"rf \", args.Me, \" -> rf \", rf.me)\n\t\t}\n\n\t} else if args.Term > rf.currentTerm {\n\t\t// vote request\n\t\t_, voted := rf.votedTerms[args.Term]\n\n\t\tif voted {\n\t\t\treply.Agree = false\n\n\t\t} else {\n\t\t\trf.stopElectionTimer()\n\n\t\t\t// new term start\n\t\t\tif rf.leader == rf.me {\n\t\t\t\trf.dethrone()\n\t\t\t}\n\n\t\t\treply.Agree = true\n\t\t\trf.leader = args.Me\n\t\t\trf.votedTerms[args.Term] = args.Me\n\t\t\trf.currentTerm = args.Term\n\t\t\trf.resetElectionTimer()\n\t\t\tlog.Println(\"Server \", rf.me, \" vote server \", args.Me, \" as leader in term \",\n\t\t\t\targs.Term)\n\t\t}\n\n\t} else {\n\t\treply.Agree = false\n\t}\n\t//log.Println(\"Raft \", rf.me, \" reply \", args.Me, \" reply: \", reply)\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\n\t//fmt.Printf(\"Server %d: log is %v\\n\", rf.me, rf.log)\n\n\tvar newer bool\n\n\tif args.Term > rf.currentTerm {\n\t\trf.votedFor = -1\n\t}\n\n\tif len(rf.log) == 0 || args.LastLogTerm > rf.log[len(rf.log)-1].Term {\n\t\tnewer = true\n\t} else if args.LastLogTerm == rf.log[len(rf.log)-1].Term && len(rf.log) <= args.LastLogIndex+1 {\n\t\tnewer = true\n\t}\n\n\tif newer == true && (rf.votedFor == -1 || rf.votedFor == args.CandidateID) {\n\t\treply.VoteGranted = true\n\t} else {\n\t\treply.VoteGranted = false\n\t}\n\n\tvar votedFor int\n\tif reply.VoteGranted {\n\t\tvotedFor = args.CandidateID\n\t} else {\n\t\tvotedFor = -1\n\t}\n\trf.votedFor = votedFor\n\n\tif args.Term < rf.currentTerm {\n\t\treply.VoteGranted = false\n\t} else if args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\tif rf.state != Follower {\n\t\t\trf.convertToFollower(rf.currentTerm, votedFor)\n\t\t}\n\t}\n\n\treply.Term = rf.currentTerm\n\n\trf.persist()\n\n\tif reply.VoteGranted == true {\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase <-rf.grantVoteCh:\n\t\t\tdefault:\n\t\t\t}\n\t\t\trf.grantVoteCh <- true\n\t\t}()\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\t//fmt.Println(\"got vote request at server id: \", rf.me)\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tif rf.currentTerm > args.Term {\n\t\treply.VoteGranted = false\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t} else if rf.currentTerm < args.Term {\n\t\trf.currentTerm = args.Term\n\t\treply.Term = rf.currentTerm\n\t\trf.state = follower\n\t}\n\t\n\tgranted := false\n\tif rf.votedFor == nil {\n\t\tgranted = true\n\t} else if *rf.votedFor == args.CandidateId {\n\t\tgranted = true\n\t}\n\tif !granted {\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\n\tif args.LastLogIndex != len(rf.log)-1 {\n\t\tgranted = false\n\t} else {\n\t\tif args.LastLogTerm != rf.log[len(rf.log)-1].Term {\n\t\t\tgranted = false\n\t\t}\n\t}\n\t\n\tif !granted {\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\n\treply.VoteGranted = true\n\trf.rpcCh<-voteRpc\n\treturn\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n DPrintf(\"%d: %d recieve RequestVote from %d:%d\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate)\n // Your code here (2A, 2B).\n rf.mu.Lock()\n defer rf.mu.Unlock()\n if args.Term < rf.currentTerm {\n \n reply.VoteGranted = false\n reply.Term = rf.currentTerm\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n return\n }\n\n if args.Term > rf.currentTerm {\n rf.votedFor = -1\n rf.currentTerm = args.Term\n }\n\n if rf.votedFor == -1 || rf.votedFor == args.Candidate {\n // election restriction\n if args.LastLogTerm < rf.log[len(rf.log) - 1].Term ||\n (args.LastLogTerm == rf.log[len(rf.log) - 1].Term &&\n args.LastLogIndex < len(rf.log) - 1) {\n rf.votedFor = -1\n reply.VoteGranted = false\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n return\n }\n\n \n if rf.state == FOLLOWER {\n rf.heartbeat <- true\n }\n rf.state = FOLLOWER\n rf.resetTimeout()\n rf.votedFor = args.Candidate\n\n \n reply.VoteGranted = true\n reply.Term = args.Term\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n return\n }\n reply.VoteGranted = false\n reply.Term = args.Term\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n}", "func (r *rpcClientService) Call(serviceMethod string, args interface{},\n reply interface{}) error {\n\n if r == nil {\n return fmt.Errorf(\"error in rpc: client is nil\")\n }\n if r.rpcCh == nil {\n return fmt.Errorf(\"error in rpc client setup: channel is nil\")\n }\n buf, errJSON := json.Marshal(args)\n if errJSON != nil {\n glog.Error(\"error in marshaling args:: \", errJSON)\n return fmt.Errorf(\"error in marshaling args:: %v\", errJSON)\n }\n\n replyCh := make(chan *httpRPCRsp)\n state := sendRPCState{Method: serviceMethod, Args: buf, ReplyCh: replyCh}\n\n // send it on the rpc channel to the startClient loop\n glog.V(2).Info(\"sending rpc on channel: \", serviceMethod)\n\n select {\n case r.rpcCh <- &state:\n glog.V(2).Info(\"queued rpc call\")\n case <-r.stopCh:\n glog.V(2).Info(\"abandoning rpc call\")\n return ErrClient\n }\n\n // Now block on the response channel. Timeouts are implemented per request\n // in the client so we do not need to check for timeouts here.\n var rsp *httpRPCRsp\n select {\n case rsp = <-replyCh:\n glog.V(2).Infof(\"received response for rpc Call\")\n case <-r.stopCh:\n glog.V(2).Info(\"abandoning rpc call after sending\")\n return ErrDisconnect\n }\n\n // This can happen when stopCh gets closed due to connection errors.\n if rsp == nil {\n glog.Error(\"error in rpc response\")\n reply = nil\n return ErrDisconnect\n }\n if rsp.Status != nil {\n return rsp.Status\n }\n glog.V(1).Infof(\"rpc response succeeded with size: %d\", len(rsp.Reply))\n glog.V(3).Infof(\"rpc response reply: %+v, size: %d\", rsp.Reply,\n len(rsp.Reply))\n // success, let's unmarshal\n errRsp := json.Unmarshal(rsp.Reply, reply)\n if errRsp != nil {\n glog.Error(\"error unmarshaling RPC reply: \", errRsp)\n return errRsp\n }\n return nil\n}", "func (r *Raft) serviceRequestVote(request RequestVote) {\n\t//fmt.Println(\"In service RV method of \", r.Myconfig.Id)\n\tresponse := RequestVoteResponse{} //prep response object,for responding back to requester\n\tcandidateId := request.candidateId\n\tresponse.id = r.Myconfig.Id\n\t//fmt.Println(\"Follower\", r.Myconfig.Id, \"log as complete?\", r.logAsGoodAsMine(request))\n\tif r.isDeservingCandidate(request) {\n\t\tresponse.voteGranted = true\n\t\tr.votedFor = candidateId\n\t\tr.currentTerm = request.term\n\n\t\t//Writing current term and voteFor to disk\n\t\tr.WriteCVToDisk()\n\n\t} else {\n\t\tresponse.voteGranted = false\n\t}\n\tresponse.term = r.currentTerm //to return self's term too\n\n\t//fmt.Println(\"Follower\", r.Myconfig.Id, \"voting\", response.voteGranted) //\"because votefor is\", r.votedFor, \"my and request terms are:\", r.currentTerm, request.term)\n\t//fmt.Println(\"Follower\", r.Myconfig.Id, \"Current term,request.term is\", r.currentTerm, request.term, \"Self lastLogIndex is\", r.myMetaData.lastLogIndex, \"VotedFor,request.lastLogTerm\", r.votedFor, request.lastLogTerm)\n\t//fmt.Println(\"VotedFor,request.lastLogTerm\", r.votedFor, request.lastLogTerm)\n\n\t//fmt.Printf(\"In serviceRV of %v, obj prep is %v \\n\", r.Myconfig.Id, response)\n\tsend(candidateId, response) //send to sender using send(sender,response)\n}", "func (rf *Raft) processRequestVoteReply(peerNum int, args *RequestVoteArgs, reply *RequestVoteReply) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\t// Rule for all servers: If RPC request or response contains term T > currentTerm: set currentTerm = T, convert to follower (§5.1)\n\tif reply.Term > rf.currentTerm {\n\t\trf.convertToFollower(reply.Term)\n\t\treturn\n\t}\n\n\tif reply.VoteGranted {\n\t\trf.votesReceived++\n\t\tif rf.state == leader {\n\t\t\treturn\n\t\t}\n\t\t// it wins the election\n\t\tif rf.votesReceived > len(rf.peers)/2 {\n\t\t\t_, _ = DPrintf(newLeader(\"[T%v] %v: New Leader! (%v/%v votes) (%v -> %v)\"), rf.currentTerm, rf.me, rf.votesReceived, len(rf.peers), rf.state, leader)\n\t\t\trf.state = leader\n\n\t\t\t// Initialize all nextIndex values to the index just after the last one in its log\n\t\t\trf.nextIndex = make([]int, len(rf.peers))\n\t\t\trf.matchIndex = make([]int, len(rf.peers))\n\t\t\tfor i := range rf.nextIndex {\n\t\t\t\trf.nextIndex[i] = len(rf.log)\n\t\t\t}\n\n\t\t\t// send heartbeat messages to all of the other servers to establish its authority (§5.2)\n\t\t\tgo rf.sendPeriodicHeartBeats()\n\t\t}\n\t}\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\t// RPC Send Request\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\tif !ok {\n\t\trf.mu.Lock()\n\t\t_, _ = DPrintf(red(\"[T%v] %v: Network Error! RequestVote: No connection to Peer %v\"), rf.currentTerm, rf.me, server)\n\t\trf.mu.Unlock()\n\t\treturn false\n\t}\n\n\t// Evaluate RPC Result\n\trf.processRequestVoteReply(server, args, reply)\n\treturn true\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) error {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.state == Down {\n\t\treturn nil\n\t}\n\tlastLogIdx, lastLogTerm := rf.lastLogIdxAndTerm()\n\tlog.Printf(\"[%v] received RequestVote RPC: %+v [currentTerm=%d votedFor=%d lastLogIdx=%d lastLogTerm=%d]\",\n\t\trf.me, args, rf.currentTerm, rf.votedFor, lastLogIdx, lastLogTerm)\n\tif args.Term > rf.currentTerm {\n\t\t// Raft rfServer in past term, revert to follower (and reset its state)\n\t\tlog.Printf(\"[%v] RequestVoteArgs.Term=%d bigger than currentTerm=%d\",\n\t\t\trf.me, args.Term, rf.currentTerm)\n\t\trf.toFollower(args.Term)\n\t}\n\n\t// if hasn't voted or already voted for this candidate or\n\t// if the candidate has up-to-date log (section 5.4.1 from paper) ...\n\tif rf.currentTerm == args.Term &&\n\t\t(rf.votedFor == -1 || rf.votedFor == args.Candidate) &&\n\t\t(args.LastLogTerm > lastLogTerm ||\n\t\t\t(args.LastLogTerm == lastLogTerm && args.LastLogIndex >= lastLogIdx)) {\n\t\t// ... grant vote\n\t\treply.VoteGranted = true\n\t\trf.votedFor = args.Candidate\n\t\trf.resetElection = time.Now()\n\t} else {\n\t\treply.VoteGranted = false\n\t}\n\treply.Term = rf.currentTerm\n\trf.persist()\n\tlog.Printf(\"[%v] replying to RequestVote: %+v\", rf.me, reply)\n\treturn nil\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\n\treply.VoteGranted = false\n\treply.Term = rf.currentTerm\n\n\t// Rule for all servers: If RPC request or response contains term T > currentTerm: set currentTerm = T, convert to follower (§5.1)\n\tif args.Term > rf.currentTerm {\n\t\trf.convertToFollower(args.Term)\n\t}\n\n\t// 1. Reply false if term < currentTerm (§5.1)\n\tif args.Term < rf.currentTerm {\n\t\t_, _ = DPrintf(vote(\"[T%v] %v: Received RequestVote from %v | Discarded Vote | Received Lower Term \"), rf.currentTerm, rf.me, args.CandidateID, args.CandidateID)\n\t\treturn\n\t}\n\n\t/* 2. If\n\t *\t\t1. votedFor is null or candidateId\n\t *\t\t2. candidate’s log is at least as up-to-date as receiver’s log\n\t *\tgrant vote (§5.2, §5.4)\n\t */\n\n\t// Check 1 vote: should be able to vote or voted for candidate\n\tvoteCheck := rf.votedFor == noVote || rf.votedFor == args.CandidateID\n\t// Check 2 up-to-date = (same indices OR candidate's lastLogIndex > current peer's lastLogIndex)\n\tlastLogIndex, lastLogTerm := rf.lastLogEntryIndex(), rf.lastLogEntryTerm()\n\tlogCheck := lastLogTerm < args.LastLogTerm || (lastLogTerm == args.LastLogTerm && lastLogIndex <= args.LastLogIndex)\n\n\t// Both checks should be true to grant vote\n\tif voteCheck && logCheck {\n\t\treply.VoteGranted = true\n\t\t_, _ = DPrintf(vote(\"[T%v] %v: Received RequestVote from %v | Vote Successful\"), rf.currentTerm, rf.me, args.CandidateID)\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = args.CandidateID\n\t} else if !voteCheck {\n\t\t_, _ = DPrintf(vote(\"[T%v] %v: Received RequestVote from %v | Vote Failure | Already voted for %v\"), rf.currentTerm, rf.me, args.CandidateID, rf.votedFor)\n\t} else {\n\t\t_, _ = DPrintf(vote(\"[T%v] %v: Received RequestVote from %v | Vote Failure | No Up-To-Date Log | Received {LastLogTerm: %v, LastLogIndex: %v} | Current {LastLogTerm: %v, LastLogIndex: %v}\"),\n\t\t\trf.currentTerm, rf.me, args.CandidateID, args.LastLogTerm, args.LastLogIndex, lastLogTerm, lastLogIndex)\n\t}\n\trf.resetTTL()\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\trf.mtx.Lock()\n\tdefer rf.mtx.Unlock()\n\n\tif ok {\n\t\tif rf.state != STATE_CANDIDATE {\n\t\t\treturn ok\n\t\t}\n\t\tif args.Term != rf.currentTerm { // consider the current term's reply\n\t\t\treturn ok\n\t\t}\n\t\tif reply.Term > rf.currentTerm {\n\t\t\trf.currentTerm = reply.Term\n\t\t\trf.state = STATE_FOLLOWER\n\t\t\trf.voteFor = -1\n\t\t\trf.persist()\n\t\t}\n\t\tif reply.VoteGranted {\n\t\t\trf.beenVotedCount++\n\t\t\tif rf.state == STATE_CANDIDATE && rf.beenVotedCount > len(rf.peers)/2 {\n\t\t\t\trf.state = STATE_FOLLOWER // ...\n\t\t\t\trf.chanBecomeLeader <- 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\r\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\r\n\treturn ok\r\n}", "func rpc_call(reqMethod string, reqParam interface{}, ip string, port int) Node {\n\n\ttempClient, _ := jsonrpc.Dial(serverInfo1.Protocol, ip+\":\"+strconv.Itoa(port))\n\tdefer tempClient.Close()\n\tvar resp Node\n\terr := tempClient.Call(\"DICT3.\"+reqMethod, reqParam, &resp)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn Node{}\n\t}\n\treturn resp\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tDPrintf(\"[%v to %v]: RequestVote REQ: args: %+v\", rf.me, server, args)\n\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\n\tDPrintf(\"[%v to %v]: RequestVote ACK. result: %v, reply: %+v\", rf.me, server, ok, reply)\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tif ok {\n\t\tterm := rf.currentTerm\n\t\tif rf.state != CANDIDATE {\n\t\t\treturn ok\n\t\t}\n\n\t\tif args.Term != term {\n\t\t\treturn ok\n\t\t}\n\n\t\tif reply.Term > term {\n\t\t\trf.currentTerm = reply.Term\n\t\t\trf.state = FOLLOWER\n\t\t\trf.votedFor = -1\n\t\t\trf.persist()\n\t\t}\n\n\t\tif reply.VoteGranted {\n\t\t\trf.voteCounter++\n\t\t\tif rf.voteCounter > len(rf.peers) / 2 && rf.state == CANDIDATE {\n\t\t\t\t//\n\t\t\t\trf.state = FOLLOWER\n\t\t\t\trf.leaderChan <- true\n\t\t\t}\n\t\t}\n\n\t\t//rf.mu.Unlock()\n\t}\n\n\n\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply, once *sync.Once) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\tif ok {\n\t\tif rf.identity != CANDIDATE {\n\t\t\treturn ok\n\t\t}\n\t\tif reply.Term > rf.CurrentTerm {\n\t\t\trf.CurrentTerm = reply.Term\n\t\t\trf.identity = FOLLOWER\n\t\t\treturn ok\n\t\t}\n\t\tif reply.VoteGranted == true {\n\t\t\trf.votes++\n\t\t\t//fmt.Println(\"peer\", server, \"vote peer\", rf.me, \"at term\", rf.CurrentTerm)\n\t\t\tif rf.votes > len(rf.peers)/2 {\n\t\t\t\tonce.Do(func() {\n\t\t\t\t\trf.hasBecomeLeader <- true\n\t\t\t\t})\n\t\t\t\treturn ok\n\t\t\t}\n\t\t}\n\t}\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\tif ok {\n\t\treply.Timeout = false\n\t} else {\n\t\treply.Timeout = true\n\t}\n\treturn ok\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\tDPrintf(\"Raft node (%d) handles with RequestVote, candidateId: %v\\n\", rf.me, args.CandidateId)\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\treply.Term = rf.currentTerm\n\treply.PeerId = rf.me\n\n\tif rf.currentTerm == args.Term && rf.votedFor != -1 && rf.votedFor != args.CandidateId {\n\t\tDPrintf(\"Raft node (%v) denied vote, votedFor: %v, candidateId: %v.\\n\", rf.me,\n\t\t\trf.votedFor, args.CandidateId)\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\n\tlastLogIndex := len(rf.logs) - 1\n\tlastLogEntry := rf.logs[lastLogIndex]\n\tif lastLogEntry.Term > args.LastLogTerm || lastLogIndex > args.LastLogIndex {\n\t\t// If this node is more up-to-date than candidate, then reject vote\n\t\t//DPrintf(\"Raft node (%v) LastLogIndex: %v, LastLogTerm: %v, args (%v, %v)\\n\", rf.me,\n\t\t//\tlastLogIndex, lastLogEntry.Term, args.LastLogIndex, args.LastLogTerm)\n\t\treply.VoteGranted = false\n\t\treturn\n\t}\n\n\trf.tryEnterFollowState(args.Term)\n\n\trf.currentTerm = args.Term\n\trf.votedFor = args.CandidateId\n\treply.VoteGranted = true\n}", "func (r *Raft) serviceRequestVote(request RequestVote, state int) {\n\t//fmt.Println(\"In service RV method of \", r.Myconfig.Id)\n\tresponse := RequestVoteResponse{}\n\tcandidateId := request.CandidateId\n\tresponse.Id = r.Myconfig.Id\n\tif r.isDeservingCandidate(request) {\n\t\tresponse.VoteGranted = true\n\t\tr.myCV.VotedFor = candidateId\n\t\tr.myCV.CurrentTerm = request.Term\n\t} else {\n\t\tif request.Term > r.myCV.CurrentTerm {\n\t\t\tr.myCV.CurrentTerm = request.Term\n\t\t\tr.myCV.VotedFor = -1\n\t\t}\n\t\tresponse.VoteGranted = false\n\t}\n\tif request.Term > r.myCV.CurrentTerm {\n\t\tr.WriteCVToDisk()\n\t}\n\tresponse.Term = r.myCV.CurrentTerm\n\tr.send(candidateId, response) //send to sender using send(sender,response)\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\trf.mu.Lock()\n\trf.persist()\n\trf.mu.Unlock()\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\tDPrintf(\"%s %d sent request vote args %v to %d, ok = %t, reply %v\\n\", rf.serverState, rf.me, args, server, ok, *reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\n\tif args.Term < rf.currentTerm {\n\t\t\treply.Term = rf.currentTerm\n\t\t\treply.VoteGranted = false\n\t\t\treturn\n\t\t}\n\tif args.Term > rf.currentTerm{\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = -1\n\t\trf.role = 0\n\t\trf.roleChan <- 0\n\t\t}\n\treply.Term = args.Term\n\tfmt.Printf(\"LastLogTerm:%v rf.log:%v sever:%v \\n\", args.LastLogTerm, rf.log[len(rf.log)-1].Term, rf.me)\n\tif rf.votedFor != -1 && rf.votedFor != args.CandidateId {\n\t reply.VoteGranted = false \n\t }else if rf.log[len(rf.log)-1].Term > args.LastLogTerm{\n\t \treply.VoteGranted = false\n\t }else if rf.log[len(rf.log)-1].Index > args.LastLogIndex && rf.log[len(rf.log)-1].Term == args.LastLogTerm{\n\t \treply.VoteGranted = false\n\t }else{\n\t fmt.Printf(\"Server %v vote for server %v \\n\", rf.me, args.CandidateId)\n\t reply.VoteGranted = true\n\t rf.votedFor = args.CandidateId\n\t rf.GrantVote <- true\n\t }\n\n\t}", "func (r *Raft) requestVote(rpc RPC, req *RequestVoteRequest) (transition bool) {\n\tr.peerLock.Lock()\n\tdefer r.peerLock.Unlock()\n\t// Setup a response\n\tpeers := make([][]byte, 0, len(r.peers))\n\tfor _, p := range r.peers {\n\t\tpeers = append(peers, []byte(p.String()))\n\t}\n\tresp := &RequestVoteResponse{\n\t\tTerm: r.getCurrentTerm(),\n\t\tGranted: false,\n\t\tPeers: peers,\n\t}\n\tvar err error\n\tdefer rpc.Respond(resp, err)\n\n\t// Ignore an older term\n\tif req.Term < r.getCurrentTerm() {\n\t\terr = errors.New(\"obsolete term\")\n\t\treturn\n\t}\n\n\t// Increase the term if we see a newer one\n\tif req.Term > r.getCurrentTerm() {\n\t\tif err := r.setCurrentTerm(req.Term); err != nil {\n\t\t\tr.logE.Printf(\"Failed to update current term: %w\", err)\n\t\t\treturn\n\t\t}\n\t\tresp.Term = req.Term\n\n\t\t// Ensure transition to follower\n\t\ttransition = true\n\t\tr.setState(Follower)\n\t}\n\n\t// Check if we have voted yet\n\tlastVoteTerm, err := r.stable.GetUint64(keyLastVoteTerm)\n\tif err != nil && err.Error() != \"not found\" {\n\t\tr.logE.Printf(\"raft: Failed to get last vote term: %w\", err)\n\t\treturn\n\t}\n\tlastVoteCandyBytes, err := r.stable.Get(keyLastVoteCand)\n\tif err != nil && err.Error() != \"not found\" {\n\t\tr.logE.Printf(\"raft: Failed to get last vote candidate: %w\", err)\n\t\treturn\n\t}\n\n\t// Check if we've voted in this election before\n\tif lastVoteTerm == req.Term && lastVoteCandyBytes != nil {\n\t\tr.logW.Printf(\"raft: Duplicate RequestVote for same term: %d\", req.Term)\n\t\tif bytes.Compare(lastVoteCandyBytes, req.Candidate) == 0 {\n\t\t\tr.logW.Printf(\"raft: Duplicate RequestVote from candidate: %s\", req.Candidate)\n\t\t\tresp.Granted = true\n\t\t}\n\t\treturn\n\t}\n\n\t// Reject if their term is older\n\tif r.getLastLogIndex() > 0 {\n\t\tvar lastLog Log\n\t\tif err := r.logs.GetLog(r.getLastLogIndex(), &lastLog); err != nil {\n\t\t\tr.logE.Printf(\"Failed to get last log: %d %v\",\n\t\t\t\tr.getLastLogIndex(), err)\n\t\t\treturn\n\t\t}\n\t\tif lastLog.Term > req.LastLogTerm {\n\t\t\tr.logW.Printf(\"Rejecting vote since our last term is greater\")\n\t\t\treturn\n\t\t}\n\n\t\tif lastLog.Index > req.LastLogIndex {\n\t\t\tr.logW.Printf(\"Rejecting vote since our last index is greater\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Persist a vote for safety\n\tif err := r.persistVote(req.Term, req.Candidate); err != nil {\n\t\tr.logE.Printf(\"raft: Failed to persist vote: %w\", err)\n\t\treturn\n\t}\n\n\tresp.Granted = true\n\treturn\n}", "func (b *Backend) RPC(choice uint64, body []byte, v interface{}) error {\n\tconn, err := b.Dial()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer conn.Close()\n\n\tchoiceBuf := make([]byte, binary.MaxVarintLen64)\n\tbinary.PutUvarint(choiceBuf, choice)\n\t_, err = conn.conn.Write(choiceBuf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbodyLenBuf := make([]byte, binary.MaxVarintLen64)\n\tbinary.PutUvarint(bodyLenBuf, uint64(len(body)))\n\n\t_, err = conn.conn.Write(bodyLenBuf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = conn.conn.Write(body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trespLenBuf := make([]byte, binary.MaxVarintLen64)\n\t_, err = conn.conn.Read(respLenBuf)\n\tif err != nil {\n\t\treturn err\n\t}\n\trespLen, _ := binary.Uvarint(respLenBuf)\n\trespBuf := make([]byte, respLen)\n\t_, err = conn.conn.Read(respBuf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(respBuf, v)\n\n\treturn err\n}", "func (sc *SnippetClient) RPC(ctx context.Context, timeout time.Duration, method string, args ...interface{}) (*JSONRPCResponse, error) {\n\t// Create and send the request.\n\treqID := sc.requestID\n\trequest := jsonRPCRequest{ID: reqID, Method: method, Params: make([]interface{}, 0)}\n\tif len(args) > 0 {\n\t\trequest.Params = args\n\t}\n\trequestBytes, err := json.Marshal(&request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to marshal request to json\")\n\t}\n\ttesting.ContextLog(ctx, \"\\tRPC request: \", string(requestBytes))\n\n\tif err := sc.clientSend(requestBytes); err != nil {\n\t\treturn nil, err\n\t}\n\tsc.requestID++\n\n\t// Receive and process the response.\n\tvar res JSONRPCResponse\n\tb, err := sc.clientReceive(timeout)\n\ttesting.ContextLog(ctx, \"\\tRPC response: \", string(b))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := json.Unmarshal(b, &res); err != nil {\n\t\treturn nil, err\n\t}\n\tif res.Error != \"\" {\n\t\treturn nil, errors.Errorf(\"response error %v\", res.Error)\n\t}\n\tif res.ID != reqID {\n\t\treturn nil, errors.Errorf(\"response ID mismatch; expected %v, got %v\", reqID, res.ID)\n\t}\n\treturn &res, nil\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// TODO: fail this rpc when killed\n\n\t// Your code here (2A, 2B).\n\tisGoodRequestVote := false\n\trf.mu.Lock()\n\n\tdefer func() {\n\t\tAssertF(reply.Term >= args.Term, \"reply.Term {%d} >= args.Term {%d}\", reply.Term, args.Term)\n\t\trf.mu.Unlock()\n\t\trf.resetElectionTimerIf(isGoodRequestVote)\n\t}()\n\n\tif args.Term < rf.currentTerm {\n\t\t*reply = RequestVoteReply{Term: rf.currentTerm, VoteGranted: false}\n\t\treturn\n\t}\n\n\tif args.Term > rf.currentTerm {\n\t\trf.transitionToFollower(args.Term, -1)\n\t}\n\n\tAssertF(args.Term == rf.currentTerm, \"\")\n\n\tif (rf.votedFor == -1 || rf.votedFor == args.CandidateId) && rf.isUptoDate(args.LastLogIndex, args.LastLogTerm) {\n\t\tisGoodRequestVote = true\n\t\trf.votedFor = args.CandidateId\n\t\t*reply = RequestVoteReply{Term: args.Term, VoteGranted: true}\n\t} else {\n\t\t*reply = RequestVoteReply{Term: args.Term, VoteGranted: false}\n\t}\n\n\trf.persist()\n}", "func (node *Node) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) error {\n\tnode.mu.Lock()\n\tdefer node.mu.Unlock()\n\tif node.state == dead {\n\t\treturn nil\n\t}\n\n\tlog.Printf(\"RequestVote args: %+v\\ncurrentTerm=%d\\nvotedFor=%d\", args, node.currentTerm, node.votedFor)\n\n\t// If the RPC term is less than the current term then we must reject the\n\t// vote request.\n\tif args.term < node.currentTerm {\n\t\treply.term = node.currentTerm\n\t\treply.voteGranted = false\n\t\tlog.Printf(\"RequestVote has been rejected by %d\", node.id)\n\t\treturn nil\n\t}\n\n\tif args.term > node.currentTerm {\n\t\t// Update the current node's state to follower.\n\t\tnode.updateStateToFollower(args.term)\n\t}\n\n\t// If the above condition was not true then we have to ensure that we have\n\t// not voted for some other node with the same term.\n\tif args.term == node.currentTerm && (node.votedFor == -1 || node.votedFor == args.candidateID) {\n\t\treply.voteGranted = true\n\t\tnode.votedFor = args.candidateID\n\t\tnode.timeSinceTillLastReset = time.Now()\n\t} else {\n\t\treply.voteGranted = false\n\t}\n\treply.term = node.currentTerm\n\tlog.Printf(\"RequestVote reply: %+v\", reply)\n\treturn nil\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\tDPrintf(\"before voted reply is %v, me id is %d, votedFor is %d, candidateId is %d, current term is %v, \" +\n\t\t\"args term is %v args log is %v log is %v\", reply, rf.me, rf.votedFor, args.CandidateId,\n\t\trf.currentTerm, args.LastLogTerm, args.LastLogIndex, rf.addLastIncludedIndex(len(rf.log)-1))\n\n\tif rf.currentTerm < args.Term {\n\t\trf.votedFor = -1\n\t\trf.currentTerm = args.Term\n\t\trf.raftState = Follower\n\t\trf.resetTimer()\n\t}\n\tif rf.votedFor == args.CandidateId || rf.votedFor == -1 {\n\t\tlastIndex := len(rf.log) - 1\n\t\tlastLogTerm := rf.log[lastIndex].Term\n\t\tif (args.LastLogTerm > lastLogTerm) ||\n\t\t\t(args.LastLogTerm == lastLogTerm && args.LastLogIndex >= rf.addLastIncludedIndex(lastIndex)) {\n\t\t\trf.votedFor = args.CandidateId\n\t\t\trf.raftState = Follower\n\t\t\treply.VoteGranted = true\n\t\t\trf.resetTimer()\n\t\t}\n\t}\n\trf.persist()\n}", "func (rf *Raft) sendRequestVote(server int, args *VoteRequest, reply *VoteResponse) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (r *RaftNode) Vote(rv RequestVoteStruct, response *RPCResponse) error {\n\tr.Lock()\n\tdefer r.Unlock()\n\tif r.verbose {\n\t\tlog.Println(\"Vote()\")\n\t}\n\n\tdefer r.persistState()\n\n\tresponse.Term = r.CurrentTerm\n\n\tmyLastLogTerm := r.getLastLogTerm()\n\tmyLastLogIdx := r.getLastLogIndex()\n\n\tif r.verbose {\n\t\tlog.Printf(\"RequestVoteStruct: %s. \\nMy node: term: %d, votedFor %d, lastLogTerm: %d, lastLogIdx: %d\",\n\t\t\trv.String(), r.CurrentTerm, r.VotedFor, myLastLogTerm, myLastLogIdx)\n\t}\n\n\tlooksEligible := r.CandidateLooksEligible(rv.LastLogIdx, rv.LastLogTerm)\n\n\tif rv.Term > r.CurrentTerm {\n\t\tr.shiftToFollower(rv.Term, HostID(-1)) // We do not yet know who is leader for this term\n\t}\n\n\tif rv.Term < r.CurrentTerm {\n\t\tif r.verbose {\n\t\t\tlog.Println(\"RV from prior term - do not grant vote\")\n\t\t}\n\t\tresponse.Success = false\n\t} else if (r.VotedFor == -1 || r.VotedFor == rv.CandidateID) && looksEligible {\n\t\tif r.verbose {\n\t\t\tlog.Println(\"Grant vote\")\n\t\t}\n\t\tr.resetTickers()\n\t\tresponse.Success = true\n\t\tr.VotedFor = rv.CandidateID\n\t} else {\n\t\tif r.verbose {\n\t\t\tlog.Println(\"Do not grant vote\")\n\t\t}\n\t\tresponse.Success = false\n\t}\n\n\treturn nil\n}", "func (s *Server) call(req *Request) *Response {\n\t// TODO: simplfy this function, or split into several functions\n\tdot := strings.LastIndex(req.Method, \".\") // split req.Method like \"type.Method\"\n\tif dot < 0 {\n\t\terr := errors.New(\"rpc: service/method request ill-formed: \" + req.Method)\n\t\treturn NewResponse(req.ID, nil, NewJsonrpcErr(ParseErr, err.Error(), err))\n\t}\n\n\tserviceName := req.Method[:dot]\n\tmethodName := req.Method[dot+1:]\n\n\t// method existed or not\n\tsvci, ok := s.m.Load(serviceName)\n\tif !ok {\n\t\terr := errors.New(\"rpc: can't find service \" + req.Method)\n\t\treturn NewResponse(req.ID, nil, NewJsonrpcErr(MethodNotFound, err.Error(), nil))\n\t}\n\tsvc := svci.(*service)\n\tmtype := svc.method[methodName]\n\tif mtype == nil {\n\t\terr := errors.New(\"rpc: can't find method \" + req.Method)\n\t\treturn NewResponse(req.ID, nil, NewJsonrpcErr(MethodNotFound, err.Error(), nil))\n\t}\n\n\t// to prepare argv and replyv in reflect.Value\n\t// ref to `net/http/rpc`\n\targIsValue := false // if true, need to indirect before calling.\n\tvar argv reflect.Value\n\tif mtype.ArgType.Kind() == reflect.Ptr {\n\t\targv = reflect.New(mtype.ArgType.Elem())\n\t} else {\n\t\targv = reflect.New(mtype.ArgType)\n\t\targIsValue = true\n\t}\n\n\t// argv guaranteed to be a pointer now.\n\tif argIsValue {\n\t\targv = argv.Elem()\n\t}\n\n\tconvert(req.Params, argv.Interface())\n\t// fmt.Println(argv.Interface())\n\n\treplyv := reflect.New(mtype.ReplyType.Elem())\n\tswitch mtype.ReplyType.Elem().Kind() {\n\tcase reflect.Map:\n\t\treplyv.Elem().Set(reflect.MakeMap(mtype.ReplyType.Elem()))\n\tcase reflect.Slice:\n\t\treplyv.Elem().Set(reflect.MakeSlice(mtype.ReplyType.Elem(), 0, 0))\n\t}\n\n\treturn svc.call(mtype, req, argv, replyv)\n}", "func (m *Member) RequestVote(ctx context.Context, leader string, term uint64, logSize uint64) (*raftapi.RequestVoteResponse, error) {\n\tlog.WithFields(log.Fields{\"member_name\": m.Name}).Debugln(\"Requesting vote from\")\n\tvar conn *grpc.ClientConn\n\tconn, err := grpc.Dial(m.Address(), grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\tapi := raftapi.NewRaftServiceClient(conn)\n\tresponse, err := api.RequestVote(ctx, &raftapi.RequestVoteMessage{\n\t\tTerm: term,\n\t\tCandidate: leader,\n\t\tLogSize: logSize,\n\t\tLastLogTerm: 0,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response, nil\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\t//fmt.Printf(\"[::RequestVote]\\n\")\n\t// Your code here.\n\trf.mtx.Lock()\n\tdefer rf.mtx.Unlock()\n\tdefer rf.persist()\n\n\treply.VoteGranted = false\n\n\t// case 1: check term\n\tif args.Term < rf.currentTerm {\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t}\n\n\tif args.Term > rf.currentTerm { // set term to max. and then maybe become leader.\n\t\trf.currentTerm = args.Term\n\t\trf.state = STATE_FOLLOWER\n\t\trf.voteFor = -1\n\t}\n\treply.Term = rf.currentTerm\n\n\t// case 2: check log\n\tisNewer := false\n\tif args.LastLogTerm == rf.log[len(rf.log)-1].Term {\n\t\tisNewer = args.LastLogIndex >= rf.log[len(rf.log)-1].LogIndex\n\t} else {\n\t\tisNewer = args.LastLogTerm > rf.log[len(rf.log)-1].Term\n\t}\n\n\tif (rf.voteFor == -1 || rf.voteFor == args.CandidateId) && isNewer {\n\t\trf.chanVoteOther <- 1\n\t\trf.state = STATE_FOLLOWER\n\t\treply.VoteGranted = true\n\t\trf.voteFor = args.CandidateId\n\t}\n\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVoteHandler\", args, reply)\n\treturn ok\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\n\treply.VoteGranted = false\n\n\tif args.Term < rf.currentTerm {\n\t\treply.Term = rf.currentTerm\n\t\tDPrintf(\"[reject] %v currentTerm:%v vote reject for:%v term:%v\",rf.me,rf.currentTerm,args.CandidateId,args.Term)\n\t\treturn\n\t}\n\n\tif args.Term > rf.currentTerm {\n\t\trf.state = FOLLOWER\n\t\trf.votedFor = -1\n\t\trf.currentTerm = args.Term\n\t}\n\n\treply.Term = rf.currentTerm\n\n\tlastLogTerm := rf.getLastLogTerm()\n\tlastLogIndex := rf.getLastLogIndex()\n\n\tlogFlag := false\n\tif (args.LastLogTerm > lastLogTerm) || (args.LastLogTerm == lastLogTerm && args.LastLogIndex >= lastLogIndex) {\n\t\tlogFlag = true\n\t}\n\n\tif (-1 == rf.votedFor || args.CandidateId == rf.votedFor) && logFlag {\n\t\treply.VoteGranted = true\n\t\trf.votedFor = args.CandidateId\n\t\trf.voteChan <- true\n\t\trf.state = FOLLOWER\n\t}\n\t//DPrintf(\"[RequestVote]: server %v send %v\", rf.me, args.CandidateId)\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tif rf.currentTerm < args.Term {\n\t\trf.debug(\"Updating term to new term %v\\n\", args.Term)\n\t\trf.currentTerm = args.Term\n\t\tatomic.StoreInt32(&rf.state, FOLLOWER)\n\t\trf.votedFor = LEADER_UNKNOWN\n\t}\n\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\n\t// late candidates\n\tif args.Term < rf.currentTerm {\n\t\trf.debug(\"Rejecting candidate %v. Reason: late term=%v\\n\", args.CandidateId, args.Term)\n\t\treturn\n\t}\n\n\t// avoid double vote\n\tif rf.votedFor != LEADER_UNKNOWN && rf.votedFor != args.CandidateId {\n\t\trf.debug(\"Rejecting candidate %v. Reason: already voted\\n\", args.CandidateId)\n\t\treturn\n\t}\n\n\tlastLogIndex := rf.lastEntryIndex()\n\n\t// reject old logs\n\tif rf.index(lastLogIndex).Term > args.LastLogTerm {\n\t\trf.debug(\"Rejecting candidate %v. Reason: old log\\n\", args.CandidateId)\n\t\treturn\n\t}\n\n\t// log is smaller\n\tif rf.index(lastLogIndex).Term == args.LastLogTerm && args.LastLogIndex < lastLogIndex {\n\t\trf.debug(\"Rejecting candidate %v. Reason: small log\\n\", args.CandidateId)\n\t\treturn\n\t}\n\n\trf.votedFor = args.CandidateId\n\trf.gotContacted = true\n\n\trf.debug(\"Granting vote to %v. me=(%v,%v), candidate=(%v,%v)\\n\", args.CandidateId, lastLogIndex, rf.index(lastLogIndex).Term, args.LastLogIndex, args.LastLogTerm)\n\treply.VoteGranted = true\n\n\t// save state\n\trf.persist(false)\n}", "func (raft *Raft) sendVoteRequest(server ServerConfig, ackChannel chan bool) {\n\t//Create args and reply\n\tlastLogTerm := raft.Log[raft.LastLsn()].Term\n\targs := RequestVoteArgs{raft.Term, uint64(raft.ServerID), raft.LastLsn(), lastLogTerm}\n\treply := RequestVoteResult{}\n\n\t//Request vote by RPC\n\t// err := raft.requestVote(server, args, &reply) //fake\n\terr := raft.voteRequestRPC(server, args, &reply) //\n\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tackChannel <- false\n\t\treturn\n\t}\n\n\t//Send ack\n\tackChannel <- reply.VoteGranted\n}", "func (client *RPCClient) Call(severName string, serverMethod string, args interface{}, reply interface{}) error {\n\taddrs, err := serverInstance.svrmgr.GetServerHosts(severName, FlagRPCHost)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// pick a random start index for round robin\n\ttotal := len(addrs)\n\tstart := client.random.Intn(total)\n\n\tfor idx := 0; idx < total; idx++ {\n\t\taddr := addrs[(start+idx)%total]\n\t\tmapkey := fmt.Sprintf(\"%s[%s]\", severName, addr)\n\t\tif client.clients[mapkey] == nil {\n\t\t\tclient.clients[mapkey], err = rpc.Dial(\"tcp\", addr)\n\t\t\tif err != nil {\n\t\t\t\tLog.Warnf(\"RPC dial error : %s\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\terr = rpcCallWithReconnect(client.clients[mapkey], addr, serverMethod, args, reply)\n\t\tif err != nil {\n\t\t\tLog.Warnf(\"RpcCallWithReconnect error : %s\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn errorf(err.Error())\n}", "func (rf *Raft) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here.\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tmay_grant_vote := true\n\tif len(rf.logs) > 0 {\n\t\t// rf.logs_term[len(rf.logs)-1] will always there, no matter snapshotedCount\n\t\tif rf.logs_term[len(rf.logs)-1] > args.LastLogTerm ||\n\t\t\t(rf.logs_term[len(rf.logs)-1] == args.LastLogTerm && len(rf.logs) > args.LogCount) {\n\t\t\tmay_grant_vote = false\n\t\t}\n\t}\n\trf.logger.Printf(\"Got vote request: %v, may grant vote: %v\\n\", args, may_grant_vote)\n\n\tif args.Term < rf.currentTerm {\n\t\trf.logger.Printf(\"Got vote request with term = %v, reject\\n\", args.Term)\n\t\treply.Term = rf.currentTerm\n\t\treply.Granted = false\n\t\treturn\n\t}\n\n\tif args.Term == rf.currentTerm {\n\t\trf.logger.Printf(\"Got vote request with current term, now voted for %v\\n\", rf.votedFor)\n\t\tif rf.votedFor == -1 && may_grant_vote {\n\t\t\trf.votedFor = args.CandidateID\n\t\t\trf.persist()\n\t\t}\n\t\treply.Granted = (rf.votedFor == args.CandidateID)\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t}\n\tif args.Term > rf.currentTerm {\n\t\trf.logger.Printf(\"Got vote request with term = %v, follow it\\n\", args.Term)\n\t\trf.state = FOLLOWER\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = -1\n\t\tif may_grant_vote {\n\t\t\trf.votedFor = args.CandidateID\n\t\t\trf.persist()\n\t\t}\n\t\trf.resetTimer()\n\n\t\treply.Granted = (rf.votedFor == args.CandidateID)\n\t\treply.Term = args.Term\n\t\treturn\n\t}\n}", "func call(rpcname string, args interface{}, reply interface{}) {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err != nil {\n\t\tlog.Fatal(\"rpc.Client.Call:\", err)\n\t}\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {\n\tok := rf.peers[server].Call(\"Raft.RequestVote\", args, reply)\n\treturn ok\n}", "func bitcoinRPC(arguments *bitcoinArguments, reply *bitcoinReply) error {\n\n\ts, err := json.Marshal(arguments)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tglobalData.log.Tracef(\"rpc send: %s\", s)\n\n\tpostData := bytes.NewBuffer(s)\n\n\trequest, err := http.NewRequest(\"POST\", globalData.url, postData)\n\tif nil != err {\n\t\treturn err\n\t}\n\trequest.SetBasicAuth(globalData.username, globalData.password)\n\n\tresponse, err := globalData.client.Do(request)\n\tif nil != err {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tglobalData.log.Tracef(\"rpc response body: %s\", body)\n\n\terr = json.Unmarshal(body, &reply)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tglobalData.log.Debugf(\"rpc receive: %s\", body)\n\n\treturn nil\n}", "func (r *Node) requestVotes(electionResults chan bool, fallbackChan chan bool, currTerm uint64) {\n\t// Votes received\n\tremaining := 0\n\tresultChan := make(chan RequestVoteResult)\n\tfor _, peer := range r.Peers {\n\t\tif r.Self.GetId() == peer.GetId() {\n\t\t\tcontinue\n\t\t}\n\t\tmsg := rpc.RequestVoteRequest{\n\t\t\tTerm: currTerm,\n\t\t\tCandidate: r.Self,\n\t\t\tLastLogIndex: r.LastLogIndex(),\n\t\t\tLastLogTerm: r.GetLog(r.LastLogIndex()).GetTermId(),\n\t\t}\n\t\tremaining++\n\t\tgo r.requestPeerVote(peer, &msg, resultChan)\n\t}\n\n\tvote := 1\n\treject := 0\n\tmajority := r.config.ClusterSize/2 + 1\n\tif vote >= majority {\n\t\telectionResults <- true\n\t\treturn\n\t}\n\tfor remaining > 0 {\n\t\trequestVoteResult := <-resultChan\n\t\tremaining--\n\t\tif requestVoteResult == RequestVoteFallback {\n\t\t\tfallbackChan <- true\n\t\t\treturn\n\t\t}\n\t\tif requestVoteResult == RequestVoteSuccess {\n\t\t\tvote++\n\t\t\tif vote >= majority {\n\t\t\t\telectionResults <- true\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\treject++\n\t\t\tif reject >= majority {\n\t\t\t\telectionResults <- false\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func CallRPC(rpcString string, args interface{}, reply interface{}, chordNodePtr *ChordNodePtr) error {\n\n\t// Just to test that my function signature syntax is correct:\n\tservice := chordNodePtr.IpAddress + \":\" + chordNodePtr.Port\n\tvar client *rpc.Client\n\tvar err error\n\tcallFailed := false\n\n\tclient = connections[service]\n\tif client != nil {\n\t\terr = client.Call(rpcString, args, reply)\n\t\tif err != nil {\n\t\t\tcallFailed = true\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif client == nil || callFailed {\n\n\t\tclient, err = jsonrpc.Dial(\"tcp\", service)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Only maintain a persistent connection if the node we're contacting is\n\t\t// in our finger table, or if it's our predecessor.\n\n\t\tif isFingerOrPredecessor(chordNodePtr) || aFingerOrPredecessorIsNil() {\n\t\t\tconnections[service] = client\n\t\t} else {\n\t\t\tdefer client.Close()\n\t\t}\n\t}\n\n\terr = client.Call(rpcString, args, reply)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func bitcoinRPC(arguments *bitcoinArguments, reply *bitcoinReply) error {\n\n\ts, err := json.Marshal(arguments)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tglobalBitcoinData.log.Debugf(\"rpc send: %s\", s)\n\n\tpostData := bytes.NewBuffer(s)\n\n\trequest, err := http.NewRequest(\"POST\", globalBitcoinData.url, postData)\n\tif nil != err {\n\t\treturn err\n\t}\n\trequest.SetBasicAuth(globalBitcoinData.username, globalBitcoinData.password)\n\n\tresponse, err := globalBitcoinData.client.Do(request)\n\tif nil != err {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(body, &reply)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tglobalBitcoinData.log.Debugf(\"rpc receive: %s\", body)\n\n\treturn nil\n}" ]
[ "0.7376517", "0.72222906", "0.71230114", "0.7042268", "0.70356125", "0.6997043", "0.6781738", "0.6726553", "0.67065567", "0.6693308", "0.6646905", "0.662608", "0.6614194", "0.65841985", "0.657042", "0.6511014", "0.6502666", "0.6452474", "0.64411473", "0.64388883", "0.64155316", "0.6402355", "0.6343826", "0.63125014", "0.6291179", "0.6285854", "0.6279952", "0.6269266", "0.62569135", "0.6228271", "0.6221665", "0.62130207", "0.6210267", "0.62061304", "0.6205815", "0.62034816", "0.61988175", "0.6194712", "0.61892766", "0.61874866", "0.6154519", "0.61266494", "0.61266494", "0.61259794", "0.6093278", "0.60772634", "0.60558563", "0.60532725", "0.6051529", "0.60479385", "0.6032505", "0.60285085", "0.6026685", "0.6023367", "0.6021312", "0.60168266", "0.6010766", "0.6007717", "0.60038376", "0.599664", "0.59711564", "0.59680617", "0.59518486", "0.59490794", "0.59490794", "0.59490794", "0.594094", "0.5921783", "0.59184384", "0.59143716", "0.59127605", "0.591098", "0.5883277", "0.5876779", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5875816", "0.5868961", "0.58645296", "0.5862505", "0.58534366" ]
0.6279757
27
the service using Raft (e.g. a k/v server) wants to start agreement on the next command to be appended to Raft's log. if this server isn't the leader, returns false. otherwise start the agreement and return immediately. there is no guarantee that this command will ever be committed to the Raft log, since the leader may fail or lose an election. the first return value is the index that the command will appear at if it's ever committed. the second return value is the current term. the third return value is true if this server believes it is the leader.
func (rf *Raft) Start(command interface{}) (int, int, bool) { rf.mu.Lock() state := rf.state rf.mu.Unlock() if state != LEADER { return -1, -1, false } DPrintf("[START COMMAND] %d ON NODE %d TERM %d", command, rf.me, rf.currentTerm) index := -1 term, isLeader := rf.GetState() // Your code here (2B). log := Log{rf.currentTerm, command} rf.mu.Lock() index = len(rf.logs) rf.logs = append(rf.logs, log) rf.matchIndex[rf.me] += 1 rf.nextIndex[rf.me] += 1 rf.mu.Unlock() return index, term, isLeader }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 (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 (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 rf.mu.Lock()\n defer rf.mu.Unlock()\n\n if rf.state != StateLeader {\n return nilIndex, nilIndex, false\n }\n\n // Your code here (2B).\n\n logLen := len(rf.log)\n index := logLen\n term := rf.currentTerm\n isLeader := true\n\n thisEntry := LogEntry{rf.currentTerm, command}\n rf.log = append(rf.log, thisEntry)\n rf.matchIndex[rf.me] = len(rf.log)\n\n rf.persist()\n\n // rf.print(\"Client start command %v\", command)\n\n return index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := int32(-1)\n\tisLeader := true\n\n\t_, isLeader = rf.GetState()\n\tif !isLeader {\n\t\treturn index, int(term), false\n\t}\n\n\t// TODO: take concurrent out-of-order commit to account\n\trf.stateLock.Lock()\n\tpreLogIndex := int32(0)\n\tpreLogTerm := int32(0)\n\tif len(rf.log) > 1 {\n\t\tpreLogIndex = int32(len(rf.log) - 1)\n\t\tpreLogTerm = rf.log[preLogIndex].Term\n\t}\n\tterm = rf.currentTerm\n\tnewEntry := LogEntry{\n\t\tCommand: command,\n\t\tTerm: term,\n\t}\n\trf.log = append(rf.log, newEntry)\n\t//rf.persist()\n\trf.matchIndex[rf.me] = int32(len(rf.log) - 1)\n\tDPrintf(\"[me : %v]start command: %v at index: %v\", rf.me, command, int32(len(rf.log) - 1))\n\tentries := []LogEntry{newEntry}\n\tappendReq := AppendEntriesRequest{\n\t\tTerm: rf.currentTerm,\n\t\tLeaderId: rf.me,\n\t\tPrevLogIndex: preLogIndex, // change\n\t\tPrevLogTerm: preLogTerm, // change\n\t\tEntries: entries,\n\t\tLeaderCommit: rf.commitIndex,\n\t}\n\trf.stateLock.Unlock()\n\n\tquorumAck := rf.quorumSendAppendEntries(appendReq)\n\tif !quorumAck {\n\t\treturn int(preLogIndex) + 1, int(term), true\n\t}\n\n\t// Your code here (2B).\n\treturn int(preLogIndex) + 1, int(term), isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n lastLogIndex := 0\n isLeader := true\n \n // TODO WED: check corner cases with -1\n rf.mu.Lock()\n term := rf.currentTerm\n myId := rf.me\n if len(rf.log) > 0 {\n lastLogIndex = len(rf.log)\n //term = rf.log[index].Term \n }\n \n if rf.state != Leader || rf.killed() {\n return lastLogIndex-1, term, false\n }\n \n var oneEntry LogEntry\n oneEntry.Command = command\n oneEntry.Term = term\n \n rf.log = append(rf.log, oneEntry)\n rf.mu.Unlock()\n\n \n go func() {\n \n // Add a while loop. when successReply count greater than threhsold, commit. loop breaks when successReply is equal to peers\n // the for loop inside only iterates over the left peers.\n \n var localMu sync.Mutex\n \n isLeader := true\n committed := false\n successReplyCount := 0\n var receivedResponse []int\n receivedResponse = append(receivedResponse, myId)\n\n for isLeader {\n if rf.killed() {\n fmt.Printf(\"*** Peer %d term %d: Terminated. Closing all outstanding Append Entries calls to followers.\",myId, term)\n return \n }\n\n var args = AppendEntriesArgs {\n LeaderId: myId,\n }\n rf.mu.Lock()\n numPeers := len(rf.peers)\n rf.mu.Unlock()\n\n for id := 0; id < numPeers && isLeader; id++ {\n if (!find(receivedResponse,id)) {\n if lastLogIndex < rf.nextIndex[id] {\n successReplyCount++\n receivedResponse = append(receivedResponse,id)\n continue\n }\n var logEntries []LogEntry\n logEntries = append(logEntries,rf.log[(rf.nextIndex[id]):]...)\n args.LogEntries = logEntries\n args.PrevLogTerm = rf.log[rf.nextIndex[id]-1].Term\n args.PrevLogIndex = rf.nextIndex[id]-1\n args.LeaderTerm = rf.currentTerm\n args.LeaderCommitIndex = rf.commitIndex\n \n go func(serverId int) {\n var reply AppendEntriesReply\n ok:=rf.sendAppendEntries(serverId, &args, &reply)\n if !rf.CheckTerm(reply.CurrentTerm) {\n localMu.Lock()\n isLeader=false\n localMu.Unlock()\n } else if reply.Success && ok {\n localMu.Lock()\n successReplyCount++\n receivedResponse = append(receivedResponse,serverId)\n localMu.Unlock()\n rf.mu.Lock()\n if lastLogIndex >= rf.nextIndex[id] {\n rf.matchIndex[id]= lastLogIndex\n rf.nextIndex[id] = lastLogIndex + 1\n }\n rf.mu.Unlock()\n } else {\n rf.mu.Lock()\n rf.nextIndex[id]-- \n rf.mu.Unlock()\n }\n } (id)\n }\n }\n \n fmt.Printf(\"\\nsleeping before counting success replies\\n\")\n time.Sleep(time.Duration(RANDOM_TIMER_MIN*time.Millisecond))\n\n if !committed && isLeader {\n votesForIndex := 0\n N := math.MaxInt32\n rf.mu.Lock()\n for i := 0; i < numPeers; i++ {\n if rf.matchIndex[i] > rf.commitIndex {\n if rf.matchIndex[i] < N {\n N = rf.matchIndex[i]\n }\n votesForIndex++\n }\n }\n rf.mu.Unlock()\n\n\n if (votesForIndex > (numPeers/2)){ \n go func(){\n committed = true\n rf.mu.Lock()\n rf.commitIndex = N // Discuss: 3. should we use lock?\n rf.log[N].Term = rf.currentTerm\n if rf.commitIndex >= lastLogIndex {\n var oneApplyMsg ApplyMsg\n oneApplyMsg.CommandValid = true\n oneApplyMsg.CommandIndex = lastLogIndex\n oneApplyMsg.Command = command\n go func() {rf.applyCh <- oneApplyMsg} ()\n }\n rf.mu.Unlock()\n }()\n }\n } else if successReplyCount == numPeers {\n return\n } \n }\n } ()\n \n // Your code here (2B code).\n return lastLogIndex, term, isLeader\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\t//rf.readPersist(rf.persister.ReadRaftState())\n\n\trf.mu.Lock()\n\tif isLeader = rf.raftState == Leader; isLeader {\n\t\tterm = rf.currentTerm\n\t\tindex = rf.addLastIncludedIndex(len(rf.log))\n\t\trf.log = append(rf.log, LogEntries{rf.currentTerm, command})\n\t\trf.matchIndex[rf.me] = rf.addLastIncludedIndex(len(rf.log) - 1)\n\t}\n\trf.persist()\n\trf.mu.Unlock()\n\t//leader commit vs commitIndex\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.stateCond.L.Lock()\n\tif rf.state == Leader {\n\t\tisLeader = true\n\t\tindex = rf.lastNewEntryIndex + 1\n\t\tterm = *rf.CurrentTerm\n\t\trf.appendEntry(index, Entry{command, term, index})\n\t\trf.lastNewEntryIndex = index\n\t\trf.nextIndex[rf.me] = index + 1\n\t\trf.matchIndex[rf.me] = index\n\t\trf.persist()\n\t\trf.notifyReplica()\n\t\tlogger.Debugf(\"Client send command {%v} to %s[%d]. Success.Update nextIndex[%d] and matchIndex[%d]\",\n\t\t\tcommand, rf.state, rf.me, rf.nextIndex[rf.me], rf.matchIndex[rf.me])\n\t} else {\n\t\tlogger.Debugf(\"Client send command {%v} to %s[%d]. Fail.\", command, rf.state, rf.me)\n\t\tisLeader = false\n\t}\n\trf.stateCond.L.Unlock()\n\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\tif rf.state == Leader {\n\t\tnewLogEntry := LogEntry{}\n\t\trf.mu.Lock()\n\t\tif rf.state == Leader {\n\t\t\tterm = rf.currentTerm\n\t\t\tnewLogEntry.Term = term\n\t\t\tnewLogEntry.Command = command\n\t\t\trf.log = append(rf.log, newLogEntry)\n\t\t\tindex = len(rf.log) - 1\n\t\t\t// update leader's matchIndex and nextIndex\n\t\t\trf.matchIndex[rf.me] = index\n\t\t\trf.nextIndex[rf.me] = index + 1\n\t\t\trf.persist()\n\t\t} else {\n\t\t\tDPrintf(\"Peer-%d, before lock, the state has changed to %d.\\n\", rf.me, rf.state)\n\t\t}\n\t\tif term != -1 {\n\t\t\tDPrintf(\"Peer-%d start to append %v to peers.\\n\", rf.me, command)\n\t\t\trequest := rf.createAppendEntriesRequest(index, index+1, term)\n\t\t\tappendProcess := func(server int) bool {\n\t\t\t\treply := new(AppendEntriesReply)\n\t\t\t\trf.sendAppendEntries(server, request, reply)\n\t\t\t\tok := rf.processAppendEntriesReply(index+1, reply)\n\t\t\t\tif ok {\n\t\t\t\t\tDPrintf(\"Peer-%d append log=%v to peer-%d successfully.\\n\", rf.me, request.Entries, server)\n\t\t\t\t} else {\n\t\t\t\t\tDPrintf(\"Peer-%d append log=%v to peer-%d failed.\\n\", rf.me, request.Entries, server)\n\t\t\t\t}\n\t\t\t\treturn ok\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tok := rf.agreeWithServers(appendProcess)\n\t\t\t\tif ok {\n\t\t\t\t\t// if append successfully, update commit index.\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\tif index >= rf.commitIndex {\n\t\t\t\t\t\tDPrintf(\"Peer-%d set commit=%d, origin=%d.\", rf.me, index, rf.commitIndex)\n\t\t\t\t\t\trf.commitIndex = index\n\t\t\t\t\t} else {\n\t\t\t\t\t\tDPrintf(\"Peer-%d get a currentIndex=%d < commitIndex=%d, it can not be happend.\", rf.me, index, rf.commitIndex)\n\t\t\t\t\t}\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t} else {\n\t\t\t\t\tDPrintf(\"Peer-%d start agreement with servers failed. currentIndex=%d.\\n\", rf.me, index)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\trf.mu.Unlock()\n\t} else {\n\t\tisLeader = false\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\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 (cfg *config) one(cmd interface{}, expectedServers int, retry bool) int {\n\tt0 := time.Now()\n\tstarts := 0\n\tfor time.Since(t0).Seconds() < 10 {\n\t\t// try all the servers, maybe one is the leader.\n\t\tindex := -1\n\t\tfor si := 0; si < cfg.n; si++ {\n\t\t\tstarts = (starts + 1) % cfg.n\n\t\t\tvar rf *Raft\n\t\t\tcfg.mu.Lock()\n\t\t\tif cfg.connected[starts] {\n\t\t\t\trf = cfg.rafts[starts]\n\t\t\t}\n\t\t\tcfg.mu.Unlock()\n\t\t\tif rf != nil {\n\t\t\t\tindex1, _, ok := rf.Start(cmd)\n\t\t\t\tif ok {\n\t\t\t\t\tindex = index1\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif index != -1 {\n\t\t\t// somebody claimed to be the leader and to have\n\t\t\t// submitted our command; wait a while for agreement.\n\t\t\tt1 := time.Now()\n\t\t\tfor time.Since(t1).Seconds() < 2 {\n\t\t\t\tnd, e := cfg.nCommitted(index)\n\t\t\t\tif nd > 0 && nd >= expectedServers {\n\t\t\t\t\t// committed\n\t\t\t\t\tif e == (logEntry{true, cmd}) {\n\t\t\t\t\t\t// and it was the command we submitted.\n\t\t\t\t\t\treturn index\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttime.Sleep(20 * time.Millisecond)\n\t\t\t}\n\t\t\tif retry == false {\n\t\t\t\tlog.Fatalf(\"one(%v) failed to reach agreement\", cmd)\n\t\t\t}\n\t\t} else {\n\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t}\n\t}\n\tlog.Fatalf(\"one(%v) failed to reach agreement\", cmd)\n\treturn -1\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\tfmt.Println(\"start cmd \", command)\n\t//mcommand := reflect.ValueOf(command)\n\tif rf.state != leader {\n\t\treturn index, term, !isLeader\n\t}\n\n\t/*here comes the leader*/\n\tfmt.Println(\"leader found!\")\n\tnewEntry := new(Entry)\n\tnewEntry.Term = rf.currentTerm\n\tnewEntry.Command = command\n\trf.mu.Lock()\n\tindex = len(rf.log)\n\trf.log = append(rf.log, *newEntry)\n\tterm = rf.currentTerm\n\trf.eAppended<-true\n\trf.mu.Unlock()\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n index := -1\n term := -1\n isLeader := true\n\n rf.mu.Lock()\n isLeader = rf.state == \"Leader\"\n if isLeader {\n newEntry := Entry{}\n newEntry.Command = command\n newEntry.Term = rf.currentTerm\n\n index = rf.convertToGlobalViewIndex(len(rf.log))\n term = rf.currentTerm\n rf.log = append(rf.log, newEntry)\n\n rf.persist()\n //go rf.startAppendEntries()\n\n DLCPrintf(\"Leader (%d) append entries and now log is from %v to %v(index=%d in Raft Log view)\", rf.me, rf.log[1], rf.log[len(rf.log)-1], len(rf.log)-1)\n }\n rf.mu.Unlock()\n\n return index, 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 (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 (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 (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\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 (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 (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\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\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tindex := -1\n\tterm := rf.currentTerm\n\tisLeader := rf.status == Leader\n\n\t// Your code here (2B).\n\n\tif !isLeader {\n\t\treturn index, term, isLeader\n\t}\n\tindex = rf.getLastIndex() + 1\n\trf.logs = append(rf.logs, LogEntry{Index: index, Term: term, Command: command})\n\trf.sendAllAppendEntriesOrInstallSnapshot() // broadcast new log to followers\n\trf.persist()\n\tAssertF(rf.getOffsetFromIndex(index) < len(rf.logs), \"index=%d, len(rf.logs)=%d, rf.snapshotIndex=%d\", index, len(rf.logs), rf.snapshotIndex)\n\tRaftInfo(\"New entry appended to leader's log: %v\", rf, rf.logs[rf.getOffsetFromIndex(index)])\n\n\treturn index, term, isLeader\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 (rf *Raft) Start(command interface{}) (int, int, bool) {\n\n\tindex := -1\n\tterm := -1\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\t//_, isLeader := rf.GetState()\n\tisLeader := rf.state == Leader\n\n\t// Your code here (2B).\n\n\tif isLeader {\n\t\t//rf.mu.Lock()\n\t\t_commandIndex := rf.getLastLogIndex() + 1\n\t\trf.logOfRaft = append(rf.logOfRaft, LogOfRaft{_commandIndex, rf.currentTerm, command})\n\t\tindex = _commandIndex\n\t\tterm = rf.currentTerm //函数返回值\n\t\trf.persist()\n\t\tDPrintf(\" %v need to send command %v, and its index is %v\", rf.me, command, index)\n\t\t//rf.mu.Unlock()\n\n\t}\n\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\t//Client 给复制状态机发送了一个command\n\trf.mu.Lock()\n\tindex := len(rf.log)\n\tterm := rf.currentTerm\n\tisLeader := true\n\n\t// Your code here (2B).\n\t//DPrintf(\"2B TEST: current server is %d, state is %s\", rf.me, rf.state)\n\tif rf.state != \"leader\" {\n\t\tisLeader = false\n\t}else{\n\t\t//if rf.log[0].Term == 0 && rf.log[0].Index == 0 && rf.log[0].Command == nil {\n\t\t//\trf.log[0].Term = rf.currentTerm\n\t\t//\trf.log[0].Command = command\n\t\t//}else{\n\t\t//\tindex = len(rf.log)\n\t\t//\tlogEntry := Entry{\n\t\t//\t\tTerm: rf.currentTerm,\n\t\t//\t\tIndex: index,\n\t\t//\t\tCommand: command,\n\t\t//\t}\n\t\t//\trf.log = append(rf.log, logEntry)\n\t\t//\trf.matchIndex[rf.me] = index\n\t\t//\tDPrintf(\"2B TEST: %d's log is %v; index is %d, term is %d, logEntry is %v\", rf.me, rf.log, index, term, logEntry)\n\t\t//}\n\t\tindex = len(rf.log)\n\t\tlogEntry := Entry{\n\t\t\tTerm: rf.currentTerm,\n\t\t\tIndex: index,\n\t\t\tCommand: command,\n\t\t}\n\t\trf.log = append(rf.log, logEntry)\n\t\trf.matchIndex[rf.me] = index\n\t\t//DPrintf(\"2B TEST: %d's log is %v; index is %d, term is %d, logEntry is %v\", rf.me, rf.log, index, term, logEntry)\n\t}\n\trf.resetHeartBeatTimers()\n\trf.mu.Unlock()\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\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\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 (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 //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 (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\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tindex = rf.commitIndex + 1\n\tterm = rf.currentTerm\n\tisLeader = rf.currentState == StateLeader\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := 0\n\tisLeader := false\n\tselect {\n\tcase <-rf.shutdown:\n\t\treturn index, term, isLeader\n\tdefault:\n\n\t}\n\t// Your code here (2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tif rf.isLeader {\n\t\tlog := LogEntry{rf.CurrentTerm, command}\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\n\t\trf.nextIndex[rf.me] = index + 1\n\t\trf.matchIndex[rf.me] = index\n\n\t\trf.wakeupConsistencyCheck()\n\n\t\trf.persist()\n\t}\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\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{}) (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 (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 (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 (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 (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\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 (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 (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\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 (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 (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 (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\tif rf.status == LEADER {\n\t\trf.mu.Lock()\n\t\tindex = len(rf.logEntries)\n\t\tlogEntry := LogEntry{Command: command, Term: rf.currentTerm}\n\t\trf.logEntries = append(rf.logEntries, logEntry)\n\t\trf.mu.Unlock()\n\t\tterm = rf.currentTerm\n\t\tisLeader = true\n\t\tgo func() {\n\t\t\trf.revCommand <- struct{}{}\n\t\t}()\n\t\tDPrintf(\"Node %d,执行命令%d\\n\", rf.me, command)\n\t}\n\treturn index, term, isLeader\n\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.Lock()\n\t//log.Println(\"start \", command)\n\t//defer log.Println(\"start return\", command)\n\tindex := -1\n\tterm := rf.currentTerm\n\tisLeader := rf.state == Leader\n\tif !isLeader {\n\t\trf.Unlock()\n\t\treturn index, term, isLeader\n\t}\n\tindex = rf.logLength()\n\tterm = rf.currentTerm\n\tnewEntry := &Entry{Term: term, Command: command}\n\t//rf.log = append(rf.log, newEntry)\n\trf.appendLog(newEntry)\n\trf.persist()\n\trf.heartBeatsTimer.Reset(0)\n\t// Your code here (2B).\n\trf.Unlock()\n\t//go rf.broadcastAppendEntries()\n\tatomic.AddInt32(&StartsCounts, 1)\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.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 (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 (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 (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 (kv *ShardKV) syncRaftStart(op Op) (Err, Op) {\n\tindex, _, ok := kv.rf.Start(op)\n\n\t// not leader\n\tif !ok {\n\t\treturn ErrWrongLeader, op\n\t}\n\n\t// wait for response on this channel\n\t// NB: it is possible that a major GC is triggered here and\n\t// this channel can never receive the response.\n\tkv.mu.Lock()\n\tch, ok := kv.completionCh[index]\n\tif !ok {\n\t\tch = make(chan Op)\n\t\tkv.completionCh[index] = ch\n\t}\n\tkv.mu.Unlock()\n\n\tvar err Err\n\tvar committedOp Op\n\tselect {\n\tcase committedOp = <-ch:\n\t\t// successful commit at this index\n\t\tif op.ClerkId == committedOp.ClerkId && op.SeqNum == committedOp.SeqNum {\n\t\t\terr = OK\n\t\t} else {\n\t\t\terr = ErrWrongLeader\n\t\t}\n\tcase <-time.After(1000 * time.Millisecond):\n\t\t// timeout, but not necessarily failed commit. simply retry.\n\t\terr = ErrWrongLeader\n\t}\n\n\tkv.mu.Lock()\n\tdelete(kv.completionCh, index)\n\tkv.mu.Unlock()\n\treturn err, committedOp\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\r\n\tindex := -1\r\n\tterm := -1\r\n\tisLeader := true\r\n\r\n\r\n\treturn index, term, isLeader\r\n}", "func (s *Server) campaignLeader() (bool, *clientv3.LeaseGrantResponse, error) {\n\tclient := s.node.RawClient()\n\t// Init a new lease\n\tlessor := client.NewLease()\n\tdefer lessor.Close()\n\tctx, cancelFunc := context.WithCancel(s.ctx)\n\tdefer cancelFunc()\n\tlr, err := lessor.Grant(ctx, s.cfg.LeaderLeaseTTL)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn false, nil, errors.Trace(err)\n\t}\n\n\tresp, err := client.Txn(ctx).\n\t\tIf(clientv3.Compare(clientv3.CreateRevision(s.fullLeaderPath()), \"=\", 0)).\n\t\tThen(append(s.leaderPutOps(lr.ID, s.term+1), s.myTermPutOps(true)...)...).\n\t\tCommit()\n\n\tif err != nil {\n\t\tlog.Info(\"error when campaign leader \", err)\n\t\treturn false, nil, errors.Trace(err)\n\t}\n\n\tif !resp.Succeeded {\n\t\treturn false, nil, nil\n\t}\n\treturn true, lr, 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\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\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 (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\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\treturn index, term, isLeader\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 (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tev := newRaftEV(&DispatchCommandArgs{\n\t\tCommand: command,\n\t})\n\n\tselect {\n\tcase <-rf.quitc:\n\t\treturn -1, -1, false\n\tcase rf.eventc <- ev:\n\t}\n\n\t<-ev.c\n\n\tif ev.result == nil {\n\t\treturn -1, -1, false\n\t}\n\n\treply := ev.result.(*DispatchCommandReply)\n\treturn reply.Index, reply.Term, reply.IsLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tif !rf.IsLeader() {\n\t\treturn rf.raftLog.Size(), rf.term, false\n\t}\n\trf.mu.Lock()\n\tindex := rf.raftLog.GetDataIndex() + 1\n\tDebugPrint(\"%d Store a message, at index: %d, term: %d\\n\",\n\t\trf.me, index, rf.term)\n\t//rf.propose(command, index)\n\trf.proposeNew(command, index,rf.me)\t\n\trf.mu.Unlock()\n\treturn index, rf.term, true\n}", "func (s *ReplicaServer) StartAppend(op LogEntry) bool {\n\ts.mu.Lock()\n\tif !s.isPrimary {\n\t\ts.mu.Unlock()\n\t\treturn false\n\t}\n\ts.opLog = append(s.opLog, op)\n\ts.matchIdx[0] = uint64(len(s.opLog)) // FIXME: trigger commitIdx update\n\n\tclerks := s.replicaClerks\n\targs := &AppendArgs{\n\t\tcn: s.cn,\n\t\tlog: s.opLog,\n\t\tcommitIdx: s.commitIdx,\n\t}\n\ts.mu.Unlock()\n\n\t// XXX: use multipar?\n\tfor i, ck := range clerks {\n\t\tck := ck // XXX: because goose doesn't support passing in parameters\n\t\ti := i\n\t\tgo func() {\n\t\t\tck.AppendRPC(args)\n\t\t\ts.postAppendRPC(uint64(i)+1, args)\n\t\t}()\n\t}\n\treturn true\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 (rf *Raft) agreeWithServers(process func(server int) bool) (agree bool) {\n\tdoneChan := make(chan int)\n\tfor i, _ := range rf.peers {\n\t\tif i == rf.me {\n\t\t\tcontinue\n\t\t}\n\t\tgo func(server int) {\n\t\t\tok := process(server)\n\t\t\tif ok {\n\t\t\t\tdoneChan <- server\n\t\t\t}\n\t\t}(i)\n\t}\n\tdeadline := time.After(rf.electionTimeout)\n\tdoneCount := 1\n\tpeerCount := len(rf.peers)\n\tfor {\n\t\tselect {\n\t\tcase <-deadline:\n\t\t\tDPrintf(\"Peer-%d, agreement timeout!\\n\", rf.me)\n\t\t\treturn false\n\t\tcase server := <-doneChan:\n\t\t\tif server >= 0 && server < peerCount {\n\t\t\t\tdoneCount += 1\n\t\t\t\tif doneCount >= peerCount/2+1 {\n\t\t\t\t\tDPrintf(\"Peer-%d's agreement is successful.\", rf.me)\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tDPrintf(\"Peer-%d find an illegal server number=%d when do agreement.\", rf.me, server)\n\t\t\t}\n\t\t}\n\t}\n}", "func (kv *KVServer) ApplyOp(op1 Op) (bool, Op) {\n\t// DPrintf(\"ApplyOp -- KVServer[%d]\", kv.me)\n\n\t// check if I'm leader\n\tindex, term, isLeader := kv.rf.Start(op1)\n\tif !isLeader {\n\t\treturn false, op1\n\t}\n\n\tkv.mu.Lock()\n\t// map index to a channel\n\tkv.msgCh[index] = make(chan raft.ApplyMsg, 1)\n\tch, _ := kv.msgCh[index]\n\tkv.mu.Unlock()\n\n\tselect {\n\tcase msg := <-ch:\n\t\t// DPrintf(\"ApplyOp -- KVServer[%d]: kv.msgCh[%d] receive op2 %+v; op1 %+v\", kv.me, index, msg, op1)\n\n\t\tkv.mu.Lock()\n\t\tdelete(kv.msgCh, index)\n\t\tkv.mu.Unlock()\n\n\t\top2 := msg.Command.(Op)\n\t\tcommandIndex := msg.CommandIndex\n\t\tcommandTerm := msg.CommandTerm\n\n\t\t// One way to do this is for the server to detect that it has lost leadership,\n\t\t// by noticing that a different request has appeared at the index returned by Start(),\n\t\t// or that Raft's term has changed.\n\t\tif commandIndex == index && commandTerm == term && op1.OpID == op2.OpID && op1.ClerkID == op2.ClerkID { // same op\n\t\t\t// DPrintf(\"ApplyOp -- KVServer[%d]: true\", kv.me)\n\t\t\treturn true, op2\n\t\t} else { // op2 is different from op1\n\t\t\treturn false, op1\n\t\t}\n\n\tcase <-time.After(waitTimeout * time.Millisecond):\n\t\t// DPrintf(\"ApplyOp -- KVServer[%d]: term[%d]\", kv.me, term)\n\n\t\tkv.mu.Lock()\n\t\tdelete(kv.msgCh, index)\n\t\tkv.mu.Unlock()\n\n\t\treturn false, op1\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n fmt.Printf(\"\\n -> I the Peer %d in got Vote Request from cadidate %d!\\n\",rf.me, args.CandidateId)\n \n rf.mu.Lock()\n defer rf.mu.Unlock() // TODO: ask professor/TA about this atomisitc and if mutex is needed.\n \n reply.FollowerTerm = rf.currentTerm\n \n rf.CheckTerm(args.CandidateTerm) \n \n // 2B code - fix if needed\n logUpToDate := false\n if len(rf.log) == 0 {\n logUpToDate = true\n } else if rf.log[len(rf.log)-1].Term < args.LastLogTerm {\n logUpToDate = true\n } else if rf.log[len(rf.log)-1].Term == args.LastLogTerm && \n len(rf.log) <= (args.LastLogIndex+1) {\n logUpToDate = true\n }\n // 2B code end\n \n reply.VoteGranted = (rf.currentTerm <= args.CandidateTerm && \n (rf.votedFor == -1 || rf.votedFor == args.CandidateId) &&\n logUpToDate) \n\n if reply.VoteGranted {\n rf.votedFor = args.CandidateId\n fmt.Printf(\"-> I the Peer %d say: Vote for cadidate %d Granted!\\n\",rf.me, args.CandidateId)\n } else {\n fmt.Printf(\"-> I the Peer %d say: Vote for cadidate %d Denied :/\\n\",rf.me, args.CandidateId)\n }\n}", "func (c *Curator) isLeader() bool {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\treturn c.iAmLeader\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 startAgreemnt(agreementID string) (string, error) {\n\tlog.Println(pathLOG + \"[startAgreemnt] Starting SLA agrement [\" + agreementID + \"] ...\")\n\t// ==> curl -k -X PUT -d @agreement.json http://rotterdam-slalite60.192.168.7.28.xip.io/agreements/a03/start\n\tdata := url.Values{}\n\tstatus, _, err := common.HTTPPUT(cfg.Config.Clusters[0].SLALiteEndPoint+\"/agreements/\"+agreementID+\"/start\", false, data)\n\n\tif err != nil {\n\t\tlog.Error(pathLOG+\"[startAgreemnt] ERROR\", err)\n\t\treturn \"Error starting the SLA Agreement\", err\n\t}\n\tlog.Println(pathLOG + \"[startAgreemnt] RESPONSE: OK\")\n\n\treturn strconv.Itoa(status), nil\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tcurrentTerm := rf.currentTerm\n\tif args == nil {\n\t\tDPrintf(\"Peer-%d received a null vote request.\", rf.me)\n\t\treturn\n\t}\n\tcandidateTerm := args.Term\n\tcandidateId := args.Candidate\n\tDPrintf(\"Peer-%d received a vote request %v from peer-%d.\", rf.me, *args, candidateId)\n\tif candidateTerm < currentTerm {\n\t\tDPrintf(\"Peer-%d's term=%d > candidate's term=%d.\\n\", rf.me, currentTerm, candidateTerm)\n\t\treply.Term = currentTerm\n\t\treply.VoteGrant = false\n\t\treturn\n\t} else if candidateTerm == currentTerm {\n\t\tif rf.voteFor != -1 && rf.voteFor != candidateId {\n\t\t\tDPrintf(\"Peer-%d has grant to peer-%d before this request from peer-%d.\", rf.me, rf.voteFor, candidateId)\n\t\t\treply.Term = currentTerm\n\t\t\treply.VoteGrant = false\n\t\t\treturn\n\t\t}\n\t\tDPrintf(\"Peer-%d's term=%d == candidate's term=%d, to check index.\\n\", rf.me, currentTerm, candidateTerm)\n\t} else {\n\t\tDPrintf(\"Peer-%d's term=%d < candidate's term=%d.\\n\", rf.me, currentTerm, candidateTerm)\n\t\t// begin to update status\n\t\trf.currentTerm = candidateTerm // find larger term, up to date\n\t\trf.transitionState(NewTerm) // transition to Follower.\n\t\tgo func() {\n\t\t\trf.eventChan <- NewTerm // tell the electionService to change state.\n\t\t}()\n\t}\n\t// check whose log is up-to-date\n\tcandiLastLogIndex := args.LastLogIndex\n\tcandiLastLogTerm := args.LastLogTerm\n\tlocalLastLogIndex := len(rf.log) - 1\n\tlocalLastLogTerm := -1\n\tif localLastLogIndex >= 0 {\n\t\tlocalLastLogTerm = rf.log[localLastLogIndex].Term\n\t}\n\t// check term first, if term is the same, then check the index.\n\tDPrintf(\"Peer-%d try to check last entry, loacl: index=%d;term=%d, candi: index=%d,term=%d.\", rf.me, localLastLogIndex, localLastLogTerm, candiLastLogIndex, candiLastLogTerm)\n\tif localLastLogTerm > candiLastLogTerm {\n\t\treply.Term = rf.currentTerm\n\t\treply.VoteGrant = false\n\t\treturn\n\t} else if localLastLogTerm == candiLastLogTerm {\n\t\tif localLastLogIndex > candiLastLogIndex {\n\t\t\treply.Term = rf.currentTerm\n\t\t\treply.VoteGrant = false\n\t\t\treturn\n\t\t}\n\t} else {\n\t}\n\t// heartbeat.\n\tgo func() {\n\t\trf.eventChan <- HeartBeat\n\t}()\n\t// local log are up-to-date, grant\n\t// before grant to candidate, we should reset ourselves state.\n\trf.transitionState(NewLeader)\n\trf.voteFor = candidateId\n\treply.Term = rf.currentTerm\n\treply.VoteGrant = true\n\tDPrintf(\"Peer-%d grant to peer-%d.\", rf.me, candidateId)\n\trf.persist()\n\treturn\n}", "func startLeaderListener(\n\tappendEntriesCom * [8]AppendEntriesCom,\n\tstate * ServerState,\n\ttimeSinceLastUpdate * time.Time,\n\tisElection * bool,\n\tserverStateLock * sync.Mutex,\n\t) {\n\tfor {\n\t\tselect {\n\t\tcase appendEntryRequest := <-appendEntriesCom[state.ServerId].message:\n\t\t\tif appendEntryRequest.Term >= state.CurrentTerm {\n\t\t\t\t*timeSinceLastUpdate = time.Now()\n\t\t\t\tif *isElection { //received message from leader during election,\n\t\t\t\t\t*isElection = false\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tprintMessageFromLeader(state.ServerId, appendEntryRequest)\n\t\t\t\tif state.Role != LeaderRole && len(appendEntryRequest.Entries) != 0 { //implements C3\n\t\t\t\t\tprocessAppendEntryRequest(appendEntryRequest, state, appendEntriesCom)\n\t\t\t\t\tfmt.Println(\"Server \", state.ServerId, \"'s current log: \", state.Log)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (rf *Raft) repositionNextIndex(server int, prevIndex int) (int, bool) {\n\tfor {\n\t\tvar args AppendEntriesArgs\n\t\tvar reply AppendEntriesReply\n\n\t\targs.Me = rf.me\n\t\targs.Term = rf.currentTerm\n\t\targs.PrevIndex = prevIndex\n\t\targs.PrevTerm = rf.log[args.PrevIndex].Term\n\t\tok := rf.sendAppendEntries(server, &args, &reply)\n\t\tif !ok {\n\t\t\t//log.Println(\"Rf \", rf.me, \" repositon \", server, \" log index failed\")\n\t\t} else if !reply.Ok && reply.Term > rf.currentTerm {\n\t\t\t// Follower has high term, do nothing and just wait new leader's heartbeat\n\t\t\tlog.Println(\"Follower \", server, \" has higher term \", reply.Term, \" than Rf \", rf.me, \" term \", rf.currentTerm)\n\t\t\treturn -1, false\n\n\t\t} else if !reply.Ok && reply.Term <= rf.currentTerm {\n\t\t\t// Normal follower, decrement index to find the match index\n\t\t\tprevIndex--\n\t\t\tlog.Println(\"Follower \", server, \" term \", reply.Term, \" has inconsist log with Rf \", rf.me, \" term \",\n\t\t\t\trf.currentTerm, \" at prevIndex \", prevIndex + 1, \" adjuct to \", prevIndex)\n\n\t\t} else {\n\t\t\t// Leader and follower agree on log index prevIndex, adjust nextIndex\n\t\t\tlog.Println(\"Follower \", server, \" agree on prevIndex \", prevIndex)\n\t\t\treturn prevIndex + 1, true\n\t\t}\n\t}\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 (s *SharedLog_) Commit_follower(Entry_pre LogEntry_, Entry_cur LogEntry_, conn net.Conn) bool {\n\tse := r.GetServer(r.id)\n\ti := len(r.log.Entries)\n\tif i == 1{\n\t\tif r.log.Entries[i-1].Term == Entry_cur.Term && r.log.Entries[i-1].SequenceNumber == Entry_cur.SequenceNumber{\n\t\t\t raft.Input_ch <- raft.String_Conn{string(r.log.Entries[i-1].Command), conn}\n\t\t\t\tr.log.Entries[i-1].IsCommitted = true\n\t\t\t\tse.LsnToCommit++\n\t\t\t\treturn true\n\t\t}// end of inner if\n\t} //end i == 1\n\t\n\tif i>1{\n\t\tif r.log.Entries[i-2].Term == Entry_pre.Term && r.log.Entries[i-2].SequenceNumber == Entry_pre.SequenceNumber{\n\t\t\tif r.log.Entries[i-1].Term == Entry_cur.Term && r.log.Entries[i-1].SequenceNumber == Entry_cur.SequenceNumber{\n\t\t\t\traft.Input_ch <- raft.String_Conn{string(r.log.Entries[i-1].Command), conn}\n\t\t\t\tr.log.Entries[i-1].IsCommitted = true\n\t\t\t\tse.LsnToCommit++\n\t\t\t\treturn true\n\t\t\t}//end of cur_entry\n\t\t}//end of prev_entry\n\t}//end of index check\n\treturn false\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 (r *Raft) leader() int {\n\t//fmt.Println(\"In leader(), I am: \", r.Myconfig.Id)\n\n\tr.sendAppendEntriesRPC() //send Heartbeats\n\t//waitTime := 4 //duration between two heartbeats\n\twaitTime := 1\n\twaitTime_secs := secs * time.Duration(waitTime)\n\t//fmt.Println(\"Heartbeat time out is\", waitTime)\n\n\twaitTimeAE := 5 //max time to wait for AE_Response\n\tHeartbeatTimer := r.StartTimer(HeartbeatTimeout, waitTime) //starts the timer and places timeout object on the channel\n\t//var AppendEntriesTimer *time.Timer\n\twaitStepDown := 7\n\tRetryTimer := r.StartTimer(RetryTimeOut, waitStepDown)\n\t//fmt.Println(\"I am\", r.Myconfig.Id, \"timer created\", AppendEntriesTimer)\n\tresponseCount := 0\n\tfor {\n\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_secs)\n\t\t\trequest := req.(ClientAppendReq)\n\t\t\tdata := request.data\n\t\t\t//fmt.Println(\"Received CA request,cmd is: \", string(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\t\t//AppendEntriesTimer = r.StartTimer(AppendEntriesTimeOut, waitTimeAE) //Can be written in HeartBeatTimer too\n\t\t\t//fmt.Println(\"I am\", r.Myconfig.Id, \"Timer assigned a value\", AppendEntriesTimer)\n\t\tcase AppendEntriesResponse:\n\t\t\tresponse := req.(AppendEntriesResponse)\n\t\t\t//fmt.Println(\"got AE_Response! from : \", response.followerId, response)\n\t\t\tresponseCount += 1\n\t\t\tif responseCount >= majority {\n\t\t\t\twaitTime_retry := secs * time.Duration(waitStepDown)\n\t\t\t\tRetryTimer.Reset(waitTime_retry)\n\t\t\t}\n\t\t\t//when isHeartBeat is true then success is also true according to the code in serviceAEReq so case wont be there when isHB is true and success is false\n\t\t\t// isHB true means it is a succeeded heartbeat hence no work to do if it is AE req then only proceed else do nothing and continue\n\t\t\t//So when follower's log is stale or he is more latest, it would set isHB false\n\t\t\tif !response.isHeartBeat {\n\t\t\t\tretVal := r.serviceAppendEntriesResp(response, HeartbeatTimer, waitTimeAE, waitTime)\n\t\t\t\tif retVal == follower {\n\t\t\t\t\treturn follower\n\t\t\t\t}\n\n\t\t\t}\n\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.currentTerm {\n\t\t\t\t//fmt.Println(\"In leader,AE_Req case, I am \", r.Myconfig.Id, \"becoming follower now, because request.term, r.currentTerm\", request.term, r.currentTerm)\n\t\t\t\tr.currentTerm = request.term //update self term and step down\n\t\t\t\tr.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.currentTerm, false, r.Myconfig.Id, false, r.myMetaData.lastLogIndex}\n\t\t\t\tsend(request.leaderId, reply)\n\t\t\t}\n\n\t\tcase int: //Time out-time to send Heartbeats!\n\t\t\ttimeout := req.(int)\n\t\t\tif timeout == RetryTimeOut {\n\t\t\t\tRetryTimer.Stop()\n\t\t\t\treturn follower\n\t\t\t}\n\t\t\t//fmt.Println(\"Timeout of\", r.Myconfig.Id, \"is of type:\", timeout)\n\n\t\t\t//waitTime_secs := secs * time.Duration(waitTime)\n\t\t\tif timeout == HeartbeatTimeout {\n\t\t\t\t//fmt.Println(\"Leader:Reseting HB timer\")\n\t\t\t\tHeartbeatTimer.Reset(waitTime_secs)\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,\n\t\t\t\t//since it was AE other than HB(last entry), it would have already modified the nextIndex map\n\t\t\t\tr.sendAppendEntriesRPC() //This either sends Heartbeats or retries the failed AE due to which the timeout happened,\n\t\t\t\t//HeartbeatTimer.Reset(secs * time.Duration(8)) //for checking leader change, setting timer of f4 to 8s--DOESN'T work..-_CHECK\n\t\t\t}\n\n\t\t}\n\t}\n}", "func (a *RPC) AppendRPC(args *AppendRPCArgs, reply *AppendRPCReply) error {\n\t//raft.ElectionTimer_ch <- args.LeaderId //TODO\n\tr.ResetTimer() // Reset timer for election \n\tmutex.Lock() \t \n\tr.ResetTimer()\n var logIndex int \n if len(r.Log) > 0 { // If Log is not emtpy.. Initialised Log intex to last heighest log index\n \tlogIndex =len(r.Log)-1\n }else{ \n \tlogIndex =0 // Else Log index is 0\n }\n //fmt.Println(\"LogInedx \",logIndex,\" PrevLogIndex \",args.PrevLogIndex)\n\tif len(args.Entry.Command)!=0{ // If This request has actual logentry to append, else it is heartbeat. \n\t\t\n\t\tr.IsLeader=2 \t\t\t\t // Fall back to Follower state \n\t\tr.LeaderId=args.LeaderId\t // Update to current Leader id \n\t\tr.VotedFor=-1 \t\t\t // Election is over, No need to remember whome u voted for. \n\t\t\t\t\t\t\t\t\t// Thank god... Leader will keep remembering you periodaically :)\n \n\t\t \t if(args.Term < r.CurrentTerm) { // If this logentry has came from Previous Term.. Just Reject it. \n\t\t \treply.Reply=false\n\t\t } else if (logIndex <args.PrevLogIndex) { // log lagging behind, \n\t\t \treply.Reply=false // Set appened to false and \n\t\t reply.NextIndex=logIndex+1 // Set next expected log entry to Heighet log Index +1\n\t\t reply.MatchIndex=-1 \n\t\t r.CurrentTerm=args.Term\t\n\t\t } else if (logIndex > args.PrevLogIndex){ // log is ahead \n\t\t \t if (r.Log[args.PrevLogIndex].Term != args.PrevLogTerm) { // If previous log term does matches with leaders Previous log term \n\t\t \t \t\t\treply.Reply=false \n\t\t reply.NextIndex=args.PrevLogIndex // Set expected next log index to previous to do check matching\n\t\t \treply.MatchIndex = -1\n\t\t \tr.CurrentTerm=args.Term\t\n\t\t } else{ \t\t\t\t\t\t\t\t\t\t// Else Terms is matching, overwrite with log with new entry\n\t\t \t\tr.Log[args.PrevLogIndex+1]=args.Entry \n\t\t\t\t\t\t\treply.Reply=true\n\t\t \treply.MatchIndex=args.PrevLogIndex+1 // Match Index is set to added entry \n\t\t \treply.NextIndex=args.PrevLogIndex+2 // Expected Entry is next log entry after added entry\n\t\t \tr.CurrentTerm=args.Term\t\n\t\t \t//fmt.Println(\"Calling commit in logIndex>PrevLogIndex\")\n\t\t \tCommitCh <- CommitI_LogI{args.LeaderCommit,args.PrevLogIndex+1} // Send Commit index to commitCh to commit log entries, Commit only till newly added aentry\n\t\t }\n\t\t }else if(logIndex == args.PrevLogIndex) { // log is at same space\n\t\t \tif logIndex!=0 && (r.Log[logIndex].Term != args.PrevLogTerm) { // if log is not emtpy, and previous log tersm is matching\n\t\t reply.Reply=false \t\t\t\t\t\t\t\t\t// Reject the log entry \n\t\t reply.NextIndex=args.PrevLogIndex \n\t\t reply.MatchIndex = -1\n\t\t r.CurrentTerm=args.Term\t\n\t\t } else if len(r.Log)==0 && args.Entry.SequenceNumber==0{ // If log is empty and Recieved log entry index is 0, Add Entry\n\t\t \t\t\tr.Log=append(r.Log,args.Entry) \t\n\t\t \t\treply.Reply=true\n\t\t \t\treply.NextIndex=len(r.Log) \t\t\t\t\n\t\t \t\treply.MatchIndex=len(r.Log)-1\n\t\t \t\tr.CurrentTerm=args.Term\t\n\t\t \t\t//fmt.Println(\"Calling commit in logIndex=PrevLogIndex\")\n\t\t \t\tCommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }else if len(r.Log)!=args.Entry.SequenceNumber{ // If log is empty and Recieved log entry index is not 0, Missmatch, Reject\n\t\t \t\t \t//r.Log=append(r.Log,args.Entry)\n\t\t \t\treply.Reply=false\n\t\t \t\treply.NextIndex=len(r.Log)\n\t\t \t\treply.MatchIndex=-1\n\t\t \t\tr.CurrentTerm=args.Term\t\n\t\t \t\t//fmt.Println(\"Calling commit in logIndex=PrevLogIndex\")\n\t\t \t\t//CommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }else {\t\t\t\t\t\t\t\t\t\t\t// Previous log is matched , and this is new entry, add it to last of log\n\t\t \t\t\tr.Log=append(r.Log,args.Entry)\n\t\t \t\treply.Reply=true\n\t\t \t\treply.NextIndex=len(r.Log)\n\t\t \t\treply.MatchIndex=len(r.Log)-1\n\t\t \t\tr.CurrentTerm=args.Term\t\n\t\t \t\t//fmt.Println(\"Calling commit in logIndex=PrevLogIndex\")\n\t\t \t\tCommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }\n\t\t }\n\t\t /* if len (args.Entry.Command)!=0{\n\t\t\t\tfmt.Println(\"Received append rpc for\",r.Id ,\" From \",args.LeaderId, \" Log size is \",logIndex, \" == \",args.PrevLogIndex,\" < \", args.Entry.SequenceNumber ,\" Commitindex \",r.CommitIndex,\" < \",args.LeaderCommit, \"added \",reply.Reply)\n\t\t\t}*/\n\tr.ResetTimer() // This is For precautionaru measure, as system was slow and it was taking more time, leading to expiry of timer\n\t\t\t\t\t// Before replying \t\n\t}else\n\t{\n\t\t/*\n\t\tThis part is same as above but only without actually aadding entries to log. Next index and match index is updated.\n\t\tand CommitCh is feed with commit Index entries\n\t\t*/\n\t\t//fmt.Println(\"Heart Beat recieved \",r.Id,\" \",\"LogInedx \" , len(r.Log)-1,\" PrevLogIndex \",args.PrevLogIndex)\n\t\t//fmt.Println(\"LogInedx \",logIndex,\" PrevLogIndex \",args.PrevLogIndex)\n\t\t if(r.CurrentTerm <= args.Term) { \n\t\t\t\tr.IsLeader=2\n\t\t\t\tr.LeaderId=args.LeaderId\t\n\t\t\t\tr.VotedFor=-1\n\t\t\t\tr.CurrentTerm=args.Term\t\n\t\t\t\tif(logIndex == args.PrevLogIndex && len(r.Log)==0){\n\t\t\t\t\treply.NextIndex=0\n\t\t\t\t\treply.MatchIndex=-1\n\t\t\t\t\t//fmt.Println(\"HeartBeat Recieved logIndex == args.PrevLogIndex && len(r.Log)==0\") \n\t\t\t\t}else if (logIndex <args.PrevLogIndex){\n\t\t\t\t\treply.NextIndex=logIndex+1\n\t\t\t\t\treply.MatchIndex=-1\n\t\t\t\t\t//fmt.Println(\"HeartBeat Recieved logIndex <args.PrevLogIndex\") \n\t\t\t\t}else if (logIndex >args.PrevLogIndex){\n\t\t\t\t\tif (r.Log[args.PrevLogIndex].Term != args.PrevLogTerm) {\n\t\t\t\t\t\treply.Reply=false \n\t\t reply.NextIndex=-1\n\t\t reply.MatchIndex = -1\n\t\t\t\t\t}else{\n\t\t\t\t\t\treply.Reply=true\n\t\t reply.MatchIndex=args.PrevLogIndex\n\t\t reply.NextIndex=args.PrevLogIndex+1\n\t\t CommitCh <- CommitI_LogI{args.LeaderCommit,args.PrevLogIndex+1}\n\t\t\t\t\t}\n\t\t\t\t}else if(logIndex == args.PrevLogIndex) {\n\t\t\t\t\t\tif logIndex!=0 && (r.Log[logIndex].Term != args.PrevLogTerm) {\n\t\t\t\t\t\t\t reply.Reply=false\n\t\t reply.NextIndex=-1\n\t\t reply.MatchIndex = -1\n\n\t\t }else{\n\t\t \treply.Reply=true\n\t\t reply.NextIndex=args.PrevLogIndex+1\n\t\t reply.MatchIndex=args.PrevLogIndex\n\t\t CommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }\n\t\t\t\t\t}\n\t\t\t}\n\tr.ResetTimer()\n\t}\n mutex.Unlock()\n\treturn nil\n}", "func (rf *Raft) tryToBeLeader() {\n\t//Step 1\n\tvar maxVoteNum, currentSuccessNum int\n\trf.mu.Lock()\n\trf.currentTerm++\n\trf.votedFor = rf.me\n\trf.role = Candidate\n\tmaxVoteNum = len(rf.peers)\n\trf.mu.Unlock()\n\trf.persist()\n\n\tcurrentSuccessNum = 1\n\tvar mutex sync.Mutex\n\tfor i := 0; i < maxVoteNum; i++ {\n\t\tif i != rf.me {\n\t\t\tgo func(idx int) {\n\t\t\t\tvar templateArgs RequestVoteArgs\n\t\t\t\trf.mu.Lock()\n\t\t\t\taLeaderComeUp := rf.role == Follower || rf.role == Leader\n\n\t\t\t\tif aLeaderComeUp {\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttemplateArgs.Term = rf.currentTerm\n\t\t\t\ttemplateArgs.CandidateID = rf.me\n\t\t\t\ttemplateArgs.LastLogTerm = rf.logs[len(rf.logs)-1].Term\n\t\t\t\ttemplateArgs.LastLogIndex = len(rf.logs) - 1\n\t\t\t\trf.mu.Unlock()\n\n\t\t\t\targs := templateArgs\n\t\t\t\tvar reply RequestVoteReply\n\t\t\t\tok := rf.sendRequestVote(idx, &args, &reply)\n\n\t\t\t\trf.mu.Lock()\n\t\t\t\taLeaderComeUp = rf.role == Follower || rf.role == Leader || rf.role == None\n\t\t\t\trf.mu.Unlock()\n\t\t\t\tif aLeaderComeUp {\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tmutex.Lock()\n\t\t\t\t\t\tcurrentSuccessNum++\n\t\t\t\t\t\tmutex.Unlock()\n\t\t\t\t\t\tif currentSuccessNum >= maxVoteNum/2+1 {\n\t\t\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\t\t\trf.role = Leader\n\t\t\t\t\t\t\tfor i := 0; i < len(rf.peers); i++ {\n\t\t\t\t\t\t\t\trf.nextIndex[i] = len(rf.logs)\n\t\t\t\t\t\t\t\trf.matchIndex[i] = 0\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\tgo rf.logDuplicate()\n\t\t\t\t\t\t\trf.msgChan <- BecomeLeader\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}(i)\n\t\t}\n\t}\n\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\trf.mu.Lock()\n\tdefer DPrintf(\"%d received RequestVote from %d, args.Term : %d, args.LastLogIndex: %d, args.LastLogTerm: %d, rf.log: %v, rf.voteFor: %d, \" +\n\t\t\"reply: %v\", rf.me, args.CandidatedId, args.Term, args.LastLogIndex, args.LastLogTerm, rf.log, rf.voteFor, reply)\n\t// Your code here (2A, 2B).\n\trf.resetElectionTimer()\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\tlastLogIndex := rf.log[len(rf.log)-1].Index\n\tlastLogTerm := rf.log[lastLogIndex].Term\n\n\tif lastLogTerm > args.LastLogTerm || (args.LastLogTerm == lastLogTerm && args.LastLogIndex < lastLogIndex) {\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\t// 5.1 Reply false if term < currentTerm\n\tif args.Term < rf.currentTerm {\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\tif (args.Term == rf.currentTerm && rf.state == \"leader\") || (args.Term == rf.currentTerm && rf.voteFor != -1){\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\tif args.Term == rf.currentTerm && rf.voteFor == args.CandidatedId {\n\t\treply.VoteGranted = true\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\t// Rules for Servers\n\t// All Servers\n\t// If RPC request or response contains term T > currentTerm: set currentTerm = T, convert to follower\n\tif args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\trf.voteFor = -1\n\t\trf.mu.Unlock()\n\t\trf.changeState(\"follower\")\n\t\trf.mu.Lock()\n\t}\n\n\trf.voteFor = args.CandidatedId\n\treply.VoteGranted = true\n\t//rf.persist()\n\trf.mu.Unlock()\n\treturn\n}", "func (s *Server) resumeLeader() (bool, *clientv3.LeaseGrantResponse, error) {\n\tclient := s.node.RawClient()\n\t// Init a new lease\n\tlessor := client.NewLease()\n\tdefer lessor.Close()\n\tctx, cancelFunc := context.WithCancel(s.ctx)\n\tdefer cancelFunc()\n\tlr, err := lessor.Grant(ctx, s.cfg.LeaderLeaseTTL)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn false, nil, errors.Trace(err)\n\t}\n\n\tresp, err := client.Txn(ctx).\n\t\tIf(s.leaderCmp()).\n\t\tThen(s.leaderPutOps(lr.ID, s.term)...).\n\t\tCommit()\n\n\tif err != nil {\n\t\tlog.Error(\"error when resume leader \", err)\n\t\treturn false, nil, errors.Trace(err)\n\t}\n\n\tif !resp.Succeeded {\n\t\treturn false, nil, nil\n\t}\n\ts.updateLeaseExpireTS()\n\treturn true, lr, nil\n}", "func (rf *Raft) StartAppendLog() {\n\tvar count int32 = 1\n\tfor i, _ := range rf.peers {\n\t\tif i == rf.me {\n\t\t\tcontinue\n\t\t}\n\t\tgo func(i int) {\n\t\t\tfor{\n\t\t\t\trf.mu.Lock()\n\t\t\t\t//fmt.Printf(\"follower %d lastlogindex: %v, nextIndex: %v\\n\",i, rf.GetPrevLogIndex(i), rf.nextIndex[i])\n\t\t\t\t//fmt.Print(\"sending log entries from leader %d to peer %d for term %d\\n\", rf.me, i, rf.currentTerm)\n\t\t\t\t//fmt.Print(\"nextIndex:%d\\n\", rf.nextIndex[i])\n\t\t\t\tif rf.state != Leader {\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\targs := AppendEntriesArgs{\n\t\t\t\t\tTerm: rf.currentTerm,\n\t\t\t\t\tLeaderId: rf.me,\n\t\t\t\t\tPrevLogIndex: rf.GetPrevLogIndex(i),\n\t\t\t\t\tPrevLogTerm: rf.GetPrevLogTerm(i),\n\t\t\t\t\tEntries: append(make([]LogEntry, 0), rf.logEntries[rf.nextIndex[i]:]...),\n\t\t\t\t\tLeaderCommit: rf.commitIndex,\n\t\t\t\t}\n\t\t\t\treply := AppendEntriesReply{}\n\t\t\t\trf.mu.Unlock()\n\t\t\t\tok := rf.sendAppendEntries(i, &args, &reply)\n\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\trf.mu.Lock()\n\t\t\t\tif rf.state != Leader {\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif reply.Term > rf.currentTerm {\n\t\t\t\t\trf.BeFollower(reply.Term)\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tsend(rf.appendEntry)\n\t\t\t\t\t}()\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif reply.Success {\n\t\t\t\t\trf.matchIndex[i] = args.PrevLogIndex + len(args.Entries)\n\t\t\t\t\trf.nextIndex[i] = rf.matchIndex[i] + 1\n\t\t\t\t\t//fmt.Print(\"leader: %v, for peer %v, match index: %d, next index: %d, peers: %d\\n\", rf.me, i, rf.matchIndex[i], rf.nextIndex[i], len(rf.peers))\n\t\t\t\t\tatomic.AddInt32(&count, 1)\n\t\t\t\t\tif atomic.LoadInt32(&count) > int32(len(rf.peers)/2) {\n\t\t\t\t\t\t//fmt.Print(\"leader %d reach agreement\\n, args.prevlogindex:%d, len:%d\\n\", rf.me, args.PrevLogIndex, len(args.Entries))\n\t\t\t\t\t\trf.UpdateCommitIndex()\n\t\t\t\t\t}\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\t//fmt.Printf(\"peer %d reset the next index from %d to %d\\n\", i, rf.nextIndex[i], rf.nextIndex[i]-1)\n\t\t\t\t\tif rf.nextIndex[i] > 0 {\n\t\t\t\t\t\trf.nextIndex[i]--\n\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t} else {\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}\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t}\n\t\t}(i)\n\t}\n\n}", "func (kv *RaftKV) await(index int, op Op) (success bool) {\n\tkv.Lock()\n\tawaitChan := make(chan raft.ApplyMsg, 1)\n\tkv.requestHandlers[index] = awaitChan\n\tkv.Unlock()\n\n\tfor {\n\t\tselect {\n\t\tcase message := <-awaitChan:\n\t\t\tkv.Lock()\n\t\t\tdelete(kv.requestHandlers, index)\n\t\t\tkv.Unlock()\n\n\t\t\tif index == message.Index && op == message.Command {\n\t\t\t\treturn true\n\t\t\t} else { // Message at index was not what we're expecting, must not be leader in majority partition\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase <-time.After(AwaitLeaderCheckInterval):\n\t\t\tkv.Lock()\n\t\t\tif _, stillLeader := kv.rf.GetState(); !stillLeader { // We're no longer leader. Abort\n\t\t\t\tdelete(kv.requestHandlers, index)\n\t\t\t\tkv.Unlock()\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tkv.Unlock()\n\t\t}\n\t}\n}", "func startServer(\n\tstate *ServerState,\n\tvoteChannels *[ClusterSize]chan Vote,\n\tappendEntriesCom *[ClusterSize]AppendEntriesCom,\n\tclientCommunicationChannel chan KeyValue,\n\tpersister Persister,\n\tchannel ApplyChannel,\n\t) Raft {\n\n\tisElection := true\n\telectionThreadSleepTime := time.Millisecond * 1000\n\ttimeSinceLastUpdate := time.Now() //update includes election or message from leader\n\tserverStateLock := new(sync.Mutex)\n\tonWinChannel := make(chan bool)\n\n\tgo runElectionTimeoutThread(&timeSinceLastUpdate, &isElection, state, voteChannels, &onWinChannel, electionThreadSleepTime)\n\tgo startLeaderListener(appendEntriesCom, state, &timeSinceLastUpdate, &isElection, serverStateLock) //implements F1.\n\tgo onWinChannelListener(state, &onWinChannel, serverStateLock, appendEntriesCom, &clientCommunicationChannel, persister, channel) //in leader.go\n\n\t//creates raft object with closure\n\traft := Raft{}\n\traft.Start = func (logEntry LogEntry) (int, int, bool){ //implements\n\t\tgo func () { //non blocking sent through client (leader may not be choosen yet).\n\t\t\tclientCommunicationChannel <- logEntry.Content\n\t\t}()\n\t\treturn len(state.Log), state.CurrentTerm, state.Role == LeaderRole\n\t}\n\n\traft.GetState = func ()(int, bool) {\n\t\treturn state.CurrentTerm, state.Role == LeaderRole\n\t}\n\treturn raft\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\n\t// Your code here (2A, 2B).\n\n\tDPrintf(\" before %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\t//log.Printf(\" before %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\tlog.Printf(\" before %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\n\tDPrintf(\" %v's requesetvote args is %v, and the reciever %v currentTerm is %v\", args.CandidateId, *args, rf.me, rf.currentTerm)\n\t//log.Printf(\" %v's requesetvote args is %v, and the reciever %v currentTerm is %v\", args.CandidateId, *args, rf.me, rf.currentTerm)\n\n\t// all servers\n\tif rf.currentTerm < args.Term {\n\t\trf.convertToFollower(args.Term)\n\t}\n\n\t_voteGranted := false\n\tif rf.currentTerm == args.Term && (rf.voteFor == VOTENULL || rf.voteFor == args.CandidateId) && (rf.getLastLogTerm() < args.LastLogTerm || (rf.getLastLogTerm() == args.LastLogTerm && rf.getLastLogIndex() <= args.LastLogIndex)) {\n\t\trf.state = Follower\n\t\tdropAndSet(rf.grantVoteCh)\n\t\t_voteGranted = true\n\t\trf.voteFor = args.CandidateId\n\t}\n\n\treply.VoteGranted = _voteGranted\n\treply.Term = rf.currentTerm\n\n\tDPrintf(\" after %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n\tlog.Printf(\" after %v 's request,%v 's votefor is %v\", args.CandidateId, rf.me, rf.voteFor)\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n DPrintf(\"%d: %d recieve RequestVote from %d:%d\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate)\n // Your code here (2A, 2B).\n rf.mu.Lock()\n defer rf.mu.Unlock()\n if args.Term < rf.currentTerm {\n \n reply.VoteGranted = false\n reply.Term = rf.currentTerm\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n return\n }\n\n if args.Term > rf.currentTerm {\n rf.votedFor = -1\n rf.currentTerm = args.Term\n }\n\n if rf.votedFor == -1 || rf.votedFor == args.Candidate {\n // election restriction\n if args.LastLogTerm < rf.log[len(rf.log) - 1].Term ||\n (args.LastLogTerm == rf.log[len(rf.log) - 1].Term &&\n args.LastLogIndex < len(rf.log) - 1) {\n rf.votedFor = -1\n reply.VoteGranted = false\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n return\n }\n\n \n if rf.state == FOLLOWER {\n rf.heartbeat <- true\n }\n rf.state = FOLLOWER\n rf.resetTimeout()\n rf.votedFor = args.Candidate\n\n \n reply.VoteGranted = true\n reply.Term = args.Term\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n return\n }\n reply.VoteGranted = false\n reply.Term = args.Term\n DPrintf(\"%d: %d recieve voteRequest from %d:%d %v\\n\", rf.currentTerm, rf.me, args.Term, args.Candidate, reply.VoteGranted)\n}", "func (a *RPC) VoteForLeader(args *RequestVoteRPCArgs,reply *bool) error{\n\t//r.ResetTimer()\n \t//fmt.Println(\"received Vote request parameter \",(*args).CandidateId,\" \",(*args).Term,\" \",(*args).LastLogTerm,\" \",(*args).LastLogIndex)\n \t//if len(r.Log)>1{\n \t//\tfmt.Println(\"Vote Request folloer parameter \",r.Id,\" \", r.CurrentTerm,\" \",r.Log[len(r.Log)-1].Term ,\" \",len(r.Log)-1)\n \t//}\n\tif r.IsLeader==2 { // if this server is follower\n\t\t//r.ResetTimer() //TODO\n\t\tif r.CurrentTerm > args.Term || r.VotedFor >-1 { // if follower has updated Term or already voted for other candidate in same term , reply nagative\n\t\t\t*reply = false\n\t\t} else if r.VotedFor== -1{ // if follower has not voted for anyone in current Term \n\t\t\tlastIndex:= len(r.Log) \n\t\t\tif lastIndex > 0 && args.LastLogIndex >0{ // if Candiate log and this server log is not empty. \n\t\t\t\tif r.Log[lastIndex-1].Term > args.LastLogTerm { // and Term of last log in follower is updated than Candidate, reject vote\n *reply=false\n }else if r.Log[lastIndex-1].Term == args.LastLogTerm{ // else if Terms of Follower and candidate is same\n \tif (lastIndex-1) >args.LastLogIndex { // but follower log is more updated, reject vote\n \t\t*reply = false\n \t} else {\n \t\t\t*reply = true // If last log terms is match and followe log is sync with candiate, vote for candidate\n \t\t}\n }else{ // if last log term is not updated and Term does not match, \n \t \t\t*reply=true//means follower is lagging behind candiate in log entries, vote for candidate\n \t\t}\n \t\n\t\t\t} else if lastIndex >args.LastLogIndex { // either of them is Zero\n\t\t\t\t*reply = false // if Follower has entries in Log, its more updated, reject vote\n\t\t\t}else{\n\t\t\t\t\t*reply = true // else Vote for candiate\n\t\t\t\t}\n\t\t}else{\n\t\t\t*reply=false\n\t\t}\n\t}else{\n\t\t*reply = false // This server is already a leader or candiate, reject vote\n\t}\n\n\tif(*reply) {\n r.VotedFor=args.CandidateId // Set Voted for to candiate Id if this server has voted positive\n }\n\t/*if(*reply) {\n\t\tfmt.Println(\"Follower \",r.Id,\" Voted for \",r.VotedFor)\n\t}else{\n\t\tfmt.Println(\"Follower \",r.Id,\" rejected vote for \",args.CandidateId)\n\t}*/\n\treturn nil\n}", "func (s *server) processAppendEntriesRequest(req *AppendEntriesRequest) (*AppendEntriesResponse, bool) {\n\ts.traceln(\"server.ae.process\")\n\n\tif req.Term < s.currentTerm {\n\t\ts.debugln(\"server.ae.error: stale term\")\n\t\treturn newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), false\n\t}\n\n\tif req.Term == s.currentTerm {\n\t\t// change state to follower\n\t\ts.state = Follower\n\t\t// discover new leader when candidate\n\t\t// save leader name when follower\n\t\ts.leader = req.LeaderName\n\t} else {\n\t\t// Update term and leader.\n\t\ts.updateCurrentTerm(req.Term, req.LeaderName)\n\t}\n\n\t// Reject if log doesn't contain a matching previous entry.\n\tif err := s.log.truncate(req.PrevLogIndex, req.PrevLogTerm); err != nil {\n\t\ts.debugln(\"server.ae.truncate.error: \", err)\n\t\treturn newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true\n\t}\n\n\t// Append entries to the log.\n\tif err := s.log.appendEntries(req.Entries); err != nil {\n\t\ts.debugln(\"server.ae.append.error: \", err)\n\t\treturn newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true\n\t}\n\n\t// Commit up to the commit index.\n\tif err := s.log.setCommitIndex(req.CommitIndex); err != nil {\n\t\ts.debugln(\"server.ae.commit.error: \", err)\n\t\treturn newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true\n\t}\n\n\t// once the server appended and committed all the log entries from the leader\n\n\treturn newAppendEntriesResponse(s.currentTerm, true, s.log.currentIndex(), s.log.CommitIndex()), true\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tcurrentTerm := rf.currentTerm\n\n\t//If RPC request or response contains term T > currentTerm:\n\t//set currentTerm = T, convert to follower\n\tif (args.Term > currentTerm) {\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = NILVOTE\n\n\t\tif rf.role == LEADER {\n\t\t\tDPrintf(\"LeaderCondition sorry server %d term %d not a leader, logs %v, commitIndex %d\\n\",rf.me, rf.currentTerm, rf.log, rf.commitIndex) \n\t\t} \n\t\trf.role = FOLLOWER\n\t\trf.persist()\n\t}\n\n\tif args.Term < currentTerm {\n\t\t// Reply false if term < currentTerm \n\t\treply.VoteGranted = false\n\t\treply.Term = currentTerm \n\t}else {\n\t\t//If votedFor is null or candidateId,\n\t\t//and candidate’s log is at least as up-to-date as receiver’s log,\n\t\t//&& rf.atLeastUptodate(args.LastLogIndex, args.LastLogTerm)\n\t\tif (rf.votedFor == NILVOTE || rf.votedFor == args.CandidateId) && rf.atLeastUptodate(args.LastLogIndex, args.LastLogTerm) {\n\t\t\ti , t := rf.lastLogIdxAndTerm()\n\t\t\tPrefixDPrintf(rf, \"voted to candidate %d, args %v, lastlogIndex %d, lastlogTerm %d\\n\", args.CandidateId, args, i, t)\n\t\t\trf.votedFor = args.CandidateId\n\t\t\trf.persist()\t\n\t\t\treply.VoteGranted = true\n\t\t\treply.Term = rf.currentTerm\n\t\t\t//you grant a vote to another peer.\n\t\t\trf.resetTimeoutEvent = makeTimestamp()\n\t\t}else {\n\t\t\treply.VoteGranted = false\n\t\t\treply.Term = rf.currentTerm\n\t\t}\t\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.executeLock.Lock()\n\tdefer rf.executeLock.Unlock()\n\n\t//DPrintf(\"[ReceiveRequestVote] [me %v] from [peer %v] start\", rf.me, args.CandidateId)\n\trf.stateLock.Lock()\n\n\tdebugVoteArgs := &RequestVoteArgs{\n\t\tTerm: rf.currentTerm,\n\t\tCandidateId: rf.votedFor,\n\t\tLastLogIndex: int32(len(rf.log) - 1),\n\t\tLastLogTerm: rf.log[len(rf.log)-1].Term,\n\t}\n\tDPrintf(\"[ReceiveRequestVote] [me %#v] self info: %#v from [peer %#v] start\", rf.me, debugVoteArgs, args)\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\treply.LastLog = int32(len(rf.log) - 1)\n\treply.LastLogTerm = rf.log[reply.LastLog].Term\n\tif args.Term < rf.currentTerm {\n\t\tDPrintf(\"[ReceiveRequestVote] [me %v] from %v Term :%v <= currentTerm: %v, return\", rf.me, args.CandidateId, args.Term, rf.currentTerm)\n\t\trf.stateLock.Unlock()\n\t\treturn\n\t}\n\n\tconvrt2Follower := false\n\tif args.Term > rf.currentTerm {\n\t\trf.currentTerm = args.Term\n\t\trf.votedFor = -1\n\t\tconvrt2Follower = true\n\t\trf.persist()\n\t}\n\n\tif rf.votedFor == -1 || rf.votedFor == args.CandidateId {\n\t\tlastLogIndex := int32(len(rf.log) - 1)\n\t\tlastLogTerm := rf.log[lastLogIndex].Term\n\n\t\tif args.LastLogTerm < lastLogTerm || (args.LastLogTerm == lastLogTerm && args.LastLogIndex < lastLogIndex) {\n\t\t\trf.votedFor = -1\n\t\t\trf.lastHeartbeat = time.Now()\n\t\t\tDPrintf(\"[ReceiveRequestVote] [me %v] index from [%v] is oldest, return\", rf.me, args.CandidateId)\n\n\t\t\tif convrt2Follower && rf.role != _Follower {\n\t\t\t\tDPrintf(\"[ReceiveRequestVote] [me %v] from %v Term :%v (non-follower) > currentTerm: %v, return\", rf.me, args.CandidateId, args.Term, rf.currentTerm)\n\t\t\t\trf.role = _Unknown\n\t\t\t\trf.stateLock.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase <-rf.closeCh:\n\t\t\t\tcase rf.roleCh <- _Follower:\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\trf.stateLock.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\trf.votedFor = args.CandidateId\n\t\t// [WARNING] 一旦授权,应该重置超时\n\t\trf.lastHeartbeat = time.Now()\n\t\treply.VoteGranted = true\n\t\tDPrintf(\"[ReceiveRequestVote] [me %v] granted vote for %v\", rf.me, args.CandidateId)\n\t\tif rf.role != _Follower {\n\t\t\tDPrintf(\"[ReceiveRequestVote] [me %v] become follower\", rf.me)\n\t\t\trf.role = _Unknown\n\t\t\trf.stateLock.Unlock()\n\t\t\tselect {\n\t\t\tcase <-rf.closeCh:\n\t\t\t\treturn\n\t\t\tcase rf.roleCh <- _Follower:\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\trf.stateLock.Unlock()\n\t\treturn\n\t}\n\tDPrintf(\"[ReceiveRequestVote] [me %v] have voted: %v, return\", rf.me, rf.votedFor)\n\trf.stateLock.Unlock()\n}", "func (r *Raft) CallElection(){\n\t\n\tr.CurrentTerm+=1 // increase the current term by 1 to avoid conflict\n\tVoteAckcount:=1 // Number of vote received, initialised to 1 as own vote fo candiate is positive\n\tr.IsLeader = 0 // Set the state of server as candiate\n\tvar VoteCount =make (chan int,(len(r.ClusterConfigV.Servers)-1))\n\t//fmt.Println(\"Sending vote requests for:\",r.Id)\n\t\n\tfor _,server := range r.ClusterConfigV.Servers {\t\t\t\n\t\t\t\tif server.Id != r.Id{\n\t\t\t\t\tgo r.sendVoteRequestRpc(server,VoteCount) \t\t\t\t\t\n\t\t\t\t}}\n\n\tfor i:=0;i< len(r.ClusterConfigV.Servers)-1;i++ {\n\t\t\t\t\tVoteAckcount = VoteAckcount+ <- VoteCount \n\t\t\t\t\t// if Candiate gets majoirty, declare candiate as Leader and send immediae heartbeat to followers declaring\n\t\t\t\t\t// election of new leader\n\t\t\t\tif VoteAckcount > (len(r.ClusterConfigV.Servers)/2) && r.IsLeader == 0 { \n\t\t\t\t\tlog.Println(\"New leader is:\",r.Id)\n\t\t\t\t\tr.IsLeader=1\n\t\t\t\t\tr.LeaderId=r.Id\n\t\t\t\t\traft.SendImmediateHeartBit <- 1\n\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\t\t\n\t\tif r.IsLeader==1{\n\t\t\t// initlised next index to lastlog index, and match index to 0 fro all servers\n\t\tfor _,server := range r.ClusterConfigV.Servers {\n\t\t\t\tr.NextIndex[server.Id]=len(r.Log)\n\t\t\t\tr.MatchIndex[server.Id]=0\n\t\t\t\tr.ResetTimer()\n\t\t\t}\n\t\t}else{ \n\t\t\t// Is candidate fails to get elected, fall back to follower state and reset timer for reelection \n\t\t\tr.IsLeader=2\n\t\t\tr.ResetTimer()\n\t\t}\n}", "func (kv *KVServer) waitApplying(index int, term int) bool {\n\tresCh := make(chan bool, 1)\n\tkv.mu.Lock()\n\tkv.requestHandler[index] = resCh\n\tkv.mu.Unlock()\n\n\t// Block until the request processed, or timeout\n\tselect {\n\tcase <-time.After(ApplyTimeout):\n\t\tkv.mu.Lock()\n\t\tdelete(kv.requestHandler, index)\n\t\tkv.mu.Unlock()\n\t\treturn false\n\tcase <-resCh:\n\t}\n\n\tcurTerm, isLeader := kv.rf.GetState()\n\n\t// Not a leader or wrong term\n\tif !isLeader || term != curTerm {\n\t\treturn false\n\t}\n\treturn true\n}", "func IsLeader() bool {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\treturn leading\n}", "func TestLeaderAcknowledgeCommit(t *testing.T) {\n\ttests := []struct {\n\t\tsize int\n\t\tacceptors map[uint64]bool\n\t\twack bool\n\t}{\n\t\t{1, nil, true},\n\t\t{3, nil, false},\n\t\t{3, map[uint64]bool{2: true}, true},\n\t\t{3, map[uint64]bool{2: true, 3: true}, true},\n\t\t{5, nil, false},\n\t\t{5, map[uint64]bool{2: true}, false},\n\t\t{5, map[uint64]bool{2: true, 3: true}, true},\n\t\t{5, map[uint64]bool{2: true, 3: true, 4: true}, true},\n\t\t{5, map[uint64]bool{2: true, 3: true, 4: true, 5: true}, true},\n\t}\n\tfor i, tt := range tests {\n\t\ts := NewMemoryStorage()\n\t\tr := newTestRaft(1, idsBySize(tt.size), 10, 1, s)\n\t\tdefer closeAndFreeRaft(r)\n\t\tr.becomeCandidate()\n\t\tr.becomeLeader()\n\t\tcommitNoopEntry(r, s)\n\t\tli := r.raftLog.lastIndex()\n\t\tr.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte(\"some data\")}}})\n\n\t\tfor _, m := range r.readMessages() {\n\t\t\tif tt.acceptors[m.To] {\n\t\t\t\tr.Step(acceptAndReply(m))\n\t\t\t}\n\t\t}\n\n\t\tif g := r.raftLog.committed > li; g != tt.wack {\n\t\t\tt.Errorf(\"#%d: ack commit = %v, want %v\", i, g, tt.wack)\n\t\t}\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.currentTerm > args.Term {\n\t\treply.VoteGranted = false\n\t\treply.Term = rf.currentTerm\n\t\treturn\n\t}\n\n\tif rf.currentTerm < args.Term {\n\t\trf.currentTerm = args.Term\n\t\trf.updateStateTo(FOLLOWER)\n\t\t//妈的咋突然少了段代码~~ 这里要变为follower状态\n\t\t//var wg sync.WaitGroup\n\t\t//wg.Add(1)\n\t\tgo func() {\n\t\t\t//\tdefer wg.Done()\n\t\t\trf.stateChangeCh <- struct{}{}\n\t\t}()\n\n\t\t//wg.Wait()\n\n\t\t//直接return,等待下一轮投票会导致活锁,比如node 1 ,2,3 。 node 1 加term为2,发请求给node2,3,term1。 node2,3更新term拒绝投票\n\t\t//return\n\t}\n\n\t//此处if 在 currentTerm < args.Term下必然成立,在currentTerm等于args.Term下不一定成立\n\n\tif rf.votedFor == -1 || rf.votedFor == args.CandidatedId {\n\t\t//if candidate的log 至少 as up-to-date as reveiver's log\n\t\tlastLogIndex := len(rf.logEntries) - 1\n\t\t//fmt.Println(lastLogIndex,rf.me,rf.logEntries )\n\t\tlastLogTerm := rf.logEntries[len(rf.logEntries)-1].Term\n\t\t//fmt.Println(lastLogIndex,lastLogTerm , args.LastLogIndex,args.LastLogTerm)\n\t\tif lastLogTerm < args.LastLogTerm || (lastLogTerm == args.LastLogTerm && lastLogIndex <= args.LastLogIndex) {\n\t\t\trf.votedFor = args.CandidatedId\n\t\t\treply.Term = rf.currentTerm\n\t\t\treply.VoteGranted = true\n\t\t\t//fmt.Printf(\"[Term %d],Node %d Reply 值为%v. Term= %d , lastIndex = %d <= args.lastLogIndex %d\\n\", rf.currentTerm, rf.me, reply, args.LastLogTerm, lastLogIndex, args.LastLogIndex)\n\t\t\tif rf.status == FOLLOWER {\n\t\t\t\tgo func() { rf.giveVoteCh <- struct{}{} }()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tfmt.Println(lastLogIndex, lastLogTerm, args.LastLogIndex, args.LastLogTerm)\n\t}\n\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\t//fmt.Printf(\"[Term %d] Node %d Reply 值为%v,rf.votefor=%d,\\n\", rf.currentTerm, rf.me, reply, rf.votedFor)\n\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\n\t//All Server rule\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif args.Term > rf.currentTerm {\n\t\trf.beFollower(args.Term)\n\t\t// TODO check\n\t\t// send(rf.voteCh)\n\t}\n\treply.Term = rf.currentTerm\n\treply.VoteGranted = false\n\tif (args.Term < rf.currentTerm) || (rf.votedFor != NULL && rf.votedFor != args.CandidateId) {\n\t\t// Reply false if term < currentTerm (§5.1) If votedFor is not null and not candidateId,\n\t} else if args.LastLogTerm < rf.getLastLogTerm() || (args.LastLogTerm == rf.getLastLogTerm() &&\n\t\targs.LastLogIndex < rf.getLastLogIndex()) {\n\t\t//If the logs have last entries with different terms, then the log with the later term is more up-to-date.\n\t\t// If the logs end with the same term, then whichever log is longer is more up-to-date.\n\t\t// Reply false if candidate’s log is at least as up-to-date as receiver’s log\n\t} else {\n\t\t//grant vote\n\t\trf.votedFor = args.CandidateId\n\t\treply.VoteGranted = true\n\t\trf.state = Follower\n\t\trf.persist()\n\t\tsend(rf.voteCh) //because If election timeout elapses without receiving granting vote to candidate, so wake up\n\t}\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\n\t//defer rf.updateAppliedLock()\n\t//Your code here (2A, 2B).\n\tisALeader := rf.role == Leader\n\n\tif rf.updateTermLock(args.Term) && isALeader {\n\t\t//DPrintf(\"[DEBUG] Server %d from %d to Follower {requestVote : Term higher}\", rf.me, Leader)\n\t}\n\treply.VoteCranted = false\n\tvar votedFor interface{}\n\t//var isLeader bool\n\tvar candidateID, currentTerm, candidateTerm, currentLastLogIndex, candidateLastLogIndex, currentLastLogTerm, candidateLastLogTerm int\n\n\tcandidateID = args.CandidateID\n\tcandidateTerm = args.Term\n\tcandidateLastLogIndex = args.LastLogIndex\n\tcandidateLastLogTerm = args.LastLogTerm\n\n\trf.mu.Lock()\n\n\treply.Term = rf.currentTerm\n\tcurrentTerm = rf.currentTerm\n\tcurrentLastLogIndex = len(rf.logs) - 1 //TODO: fix the length corner case\n\tcurrentLastLogTerm = rf.logs[len(rf.logs)-1].Term\n\tvotedFor = rf.votedFor\n\tisFollower := rf.role == Follower\n\trf.mu.Unlock()\n\t//case 0 => I'm leader, so you must stop election\n\tif !isFollower {\n\t\tDPrintf(\"[DEBUG] Case0 I [%d] is Candidate than %d\", rf.me, args.CandidateID)\n\t\treturn\n\t}\n\n\t//case 1 => the candidate is not suit to be voted\n\tif currentTerm > candidateTerm {\n\t\tDPrintf(\"[DEBUG] Case1 Follower %d > Candidate %d \", rf.me, args.CandidateID)\n\t\treturn\n\t}\n\n\t//case 2 => the candidate's log is not lastest than the follwer\n\tif currentLastLogTerm > candidateLastLogTerm || (currentLastLogTerm == candidateLastLogTerm && currentLastLogIndex > candidateLastLogIndex) {\n\t\tDPrintf(\"[DEBUG] Case2 don't my[%d] newer than can[%d]\", rf.me, args.CandidateID)\n\t\treturn\n\t}\n\trf.mu.Lock()\n\t//case3 => I have voted and is not you\n\tif votedFor != nil && votedFor != candidateID {\n\t\trf.mu.Unlock()\n\t\treturn\n\t}\n\n\t//now I will vote you\n\n\tvar notFollower bool\n\trf.votedFor = candidateID\n\tif rf.role != Follower {\n\t\tnotFollower = true\n\t}\n\tDPrintf(\"[Vote] Server[%d] vote to Can[%d]\", rf.me, args.CandidateID)\n\trf.role = Follower\n\treply.VoteCranted = true\n\trf.mu.Unlock()\n\trf.persist()\n\tif notFollower {\n\t\trf.msgChan <- RecivedVoteRequest\n\t} else {\n\t\trf.msgChan <- RecivedVoteRequest\n\t}\n\n\treturn\n}", "func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {\n\t// Your code here (2A, 2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tlastLogIndex, lastLogTerm := len(rf.log) + rf.compactIndex , 0\n\tif lastLogIndex > rf.compactIndex {\n\t\tlastLogTerm = rf.log[lastLogIndex - rf.compactIndex -1].Term\n\t} else if lastLogIndex == rf.compactIndex {\n\t\tlastLogTerm = rf.compactTerm\n\t}\n\n\tif args.Term < rf.currentTerm || (args.Term == rf.currentTerm && args.CandidateID != rf.votedFor) || args.LastLogTerm < lastLogTerm || (args.LastLogTerm == lastLogTerm && lastLogIndex > args.LastLogIndex) {\n\t\t// 1. The Term of RequestVote is out of date.\n\t\t// 2. The instance vote for other peer in this term.\n\t\t// 3. The log of Candidate is not the most update.\n\t\treply.VoteGranted = false\n\t\treply.Term = rf.currentTerm\n\t} else {\n\t\t// DPrintf(\"instance %d vote for %d, Term is %d, lastLogTerm is %d, args.LastLogTerm is %d, lastLogIndex is %d, args.LastLogIndex is %d, original votedFor is %d\", rf.me, args.CandidateID, args.Term, lastLogTerm, args.LastLogTerm, lastLogIndex, args.LastLogIndex, rf.votedFor)\n\t\trf.votedFor = args.CandidateID\n\t\trf.currentTerm = args.Term\n\n\t\treply.VoteGranted = true\n\t\treply.Term = rf.currentTerm\n\n\t\tif rf.role == Follower {\n\t\t\trf.validRpcTimestamp = time.Now()\n\t\t} else {\n\t\t\t// Notify the change of the role of instance.\n\t\t\tclose(rf.rollback)\n\t\t\trf.role = Follower\n\t\t}\n\t}\n\n\treturn\n}", "func (s *raftState) checkLeaderCommit() bool {\n\tmatches := make([]int, 0, len(s.MatchIndex))\n\tfor _, x := range s.MatchIndex {\n\t\tmatches = append(matches, x)\n\t}\n\tsort.Sort(sort.Reverse(sort.IntSlice(matches)))\n\tnewC := matches[s.majority()-1]\n\tif newC > s.CommitIndex {\n\t\ts.commitUntil(newC)\n\t\tglog.V(utils.VDebug).Infof(\"%s Leader update commitIndex: %d\", s.String(), newC)\n\t\treturn true\n\t}\n\treturn false\n}", "func (this *Protocol) proposeAgreement(peerId PeerId, localBytes int, remoteBytes int) bool {\n\targs := &ProposeAgreementArgs{\n\t\tMe: this.GetMe(),\n\t\tMyBytes: localBytes,\n\t\tYourBytes: remoteBytes,\n\t}\n\tvar reply ProposeAgreementReply\n\tsuccess := this.call(peerId, \"ProposeAgreement\", args, &reply)\n\tLog.Debug.Printf(\"ProposeAgreement %s (local: %d; remote: %d): %t\", peerId.String(), localBytes, remoteBytes, success && reply.Accept)\n\treturn success && reply.Accept\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 (node *Node) Submit(command interface{}) bool {\n\tnode.mu.Lock()\n\tdefer node.mu.Unlock()\n\n\tif node.state == leader {\n\t\tlogEntry := LogEntry{\n\t\t\tterm: node.currentTerm,\n\t\t\tCommand: command,\n\t\t}\n\t\tnode.log = append(node.log, logEntry)\n\t\tlog.Printf(\"Leader %d has receieved a command %+v\", node.id, logEntry)\n\t\treturn true\n\t}\n\treturn false\n}" ]
[ "0.71829545", "0.7178914", "0.69504184", "0.6793831", "0.6647047", "0.6420316", "0.64161277", "0.63980305", "0.63170063", "0.62880915", "0.62421924", "0.6215371", "0.62086695", "0.6181203", "0.61622494", "0.61511195", "0.6136433", "0.6072022", "0.6071861", "0.60547066", "0.6052555", "0.60302734", "0.6028343", "0.6015936", "0.60109556", "0.599308", "0.59878623", "0.59802073", "0.5978394", "0.59691995", "0.59471136", "0.5919136", "0.59050936", "0.58835715", "0.5872179", "0.58603483", "0.584545", "0.5843692", "0.58373", "0.58326566", "0.5828165", "0.5824866", "0.5802473", "0.57957125", "0.57931226", "0.57356447", "0.57200396", "0.5704582", "0.56929594", "0.56562513", "0.56290686", "0.56139535", "0.5606933", "0.5552089", "0.5547549", "0.5545839", "0.5545839", "0.5448545", "0.5393713", "0.53450114", "0.5284179", "0.5254094", "0.5246164", "0.52419305", "0.52115065", "0.51360315", "0.5125413", "0.5113958", "0.5107699", "0.50837255", "0.5083401", "0.5033418", "0.50240684", "0.49877658", "0.49781024", "0.49765566", "0.49728364", "0.49705884", "0.49678355", "0.49444386", "0.4939767", "0.4937226", "0.49365988", "0.49357763", "0.49331462", "0.49023786", "0.48908827", "0.48866096", "0.487952", "0.487947", "0.48699912", "0.4860479", "0.48531097", "0.48481798", "0.4844188", "0.48127037", "0.48098776", "0.48065218", "0.47764418", "0.47717157" ]
0.5784449
45
the tester calls Kill() when a Raft instance won't be needed again. you are not required to do anything in Kill(), but it might be convenient to (for example) turn off debug output from this instance.
func (rf *Raft) Kill() { // Your code here, if desired. }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (rf *Raft) Kill() {// {{{\n // could disable debug message.\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\t//DEBUG HERE\n}", "func (rf *Raft) Kill() {\n // Your code here, if desired.\n rf.print(\"is killed\")\n // TODO: exit go routines if killed\n rf.isKilled = true\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\t//PrintStatistics()\n}", "func (rf *Raft) Kill() {\r\n\t// Your code here, if desired.\r\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\trf.alive = false\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n\tDPrintln(\"test is killing Raft server\")\n\trf.chSender(rf.killChan)\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\tfor idx := range rf.clients {\n\t\tif idx != rf.me {\n\t\t\trf.clients[idx].Stop()\n\t\t}\n\t}\n\tDebugPrint(\"Kill Raft %d, fail rpc: %d\\n\", rf.me, rf.failCount)\n\t//for ts := 1; atomic.LoadInt32(&rf.stop) != 2 && ts < 20; ts ++ {\n\t//\ttime.Sleep(1000 * time.Millisecond)\n\t//}\n\trf.mu.Lock()\n\trf.stop = true\n\trf.mu.Unlock()\n\trf.stopChan <- true\n\tDebugPrint(\"Kill Raft %d\\n\", rf.me)\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n\t// TODO dump info\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\tclose(rf.close)\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n\trf.killed()\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n\tclose(rf.stopCh)\n\tDPrintf(\"Server %v Kill\\n\", rf.me)\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\trf.Lock()\n\tdefer rf.Unlock()\n\n\trf.isDecommissioned = true\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n\t//Once.Do(func() {\n\t//\tlog.Println(\n\t//\t\tatomic.LoadInt32(&AppendEntriesCounts),\n\t//\t\tatomic.LoadInt32(&AppendEntriesFailed),\n\t//\t\tatomic.LoadInt32(&StartsCounts),\n\t//\t\tatomic.LoadInt32(&BroadcastAppendCounts),\n\t//\n\t//\t)\n\t//})\n}", "func (rf *Raft) Kill() {\n\trf.lock()\n\tad.DebugObj(rf, ad.RPC, \"Dying\")\n\trf.isAlive = false\n\trf.unlock()\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\trf.mu.Lock()\n\trf.transitionState(Stop)\n\trf.mu.Unlock()\n\tsleep(2000)\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\n\tgo func() {\n\t\trf.stop <- struct{}{}\n\t}()\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\tDPrintf(\" Kill Server(%v)\", rf.me)\n\tdropAndSet(rf.exitCh)\n}", "func (rf *Raft) Kill() {\n atomic.StoreInt32(&rf.dead, 1)\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n\trf.quitOnce.Do(func() {\n\t\tclose(rf.quitc)\n\t\trf.routineGroup.Wait()\n\t\tDPrintf(\"%v killed\", rf.raftInfo())\n\t})\n}", "func (rf *Raft) Kill() {\n\tif !atomic.CompareAndSwapInt32(&rf.killed, 0, 1) {\n\t\treturn\n\t}\n\n\t// this is a dirty (but smart) hack...\n\t// which prevent future functions running...\n\t// while also wait for all currently running functions to complete\n\trf.mu.Lock()\n\n\t// free up memory\n\trf.logs = nil\n\trf.logs_term = nil\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\trf.mu.Lock()\n\tRaftDebug(\"Killed!\", rf)\n\trf.mu.Unlock()\n\n\tclose(rf.killCh)\n\t//close(rf.applyCh)\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n}", "func (rf *Raft) Kill() {\n\trf.mu.Lock()\n\trf.killAllGoRoutines = true\n\trf.mu.Unlock()\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\trf.lock(\"kill\")\n\t// defer rf.unlock(\"kill\")\n\tif rf.state == LEADER {\n\t\t// rf.heartbeatTimer.Stop()\n\t\trf.stop(rf.heartbeatTimer)\n\t}\n\tclose(rf.stopCh)\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// rf.electionTimer.Stop()\n\trf.stop(rf.electionTimer)\n\trf.unlock(\"kill\")\n}", "func (kv *RaftKV) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *RaftKV) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *RaftKV) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *RaftKV) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\tclose(rf.closeCh)\n\t<-rf.deadCh\n\n\trf.stateLock.Lock()\n\trf.persist()\n\trf.stateLock.Unlock()\n\trf.exitWg.Wait()\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\tgo func() {\n\t\tlogger.Debugf(\"Server[%d] is dead\", rf.me)\n\t\trf.stateCond.L.Lock()\n\t\trf.toState(Dead)\n\t\trf.stateCond.L.Unlock()\n\t}()\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\tsend(rf.killCh)\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\tsend(rf.killCh)\n}", "func (rf *Raft) Kill() {\n\t// Your code here, if desired.\n\n\trf.mu.Lock()\n\tclose(rf.applyCh)\n\trf.applyCh = nil\n\tclose(rf.stateCh)\n\trf.stateCh = nil\n\trf.mu.Unlock()\n}", "func (kv *RaftKV) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\tkv.done = true\n}", "func (kv *KVServer) Kill() {\n kv.rf.Kill()\n // Your code here, if desired.\n kv.kill = true\n}", "func (rf *Raft) Kill() {\n atomic.StoreInt32(&rf.dead, 1)\n // Your code here, if desired.\n}", "func (kv *RaftKV) Kill() {\n\tkv.Lock()\n\tdefer kv.Unlock()\n\n\tkv.rf.Kill()\n\tkv.isDecommissioned = true\n}", "func (kv *KVServer) Kill(){\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (m *TimeServiceManager) Kill() {\n\tif len(m.Instances) > 0 {\n\t\tfmt.Printf(\"There are %d instances. \", len(m.Instances))\n\t\tn := rand.Intn(len(m.Instances))\n\t\tfmt.Printf(\"Killing Instance %d\\n\", n)\n\t\tclose(m.Instances[n].Dead)\n\t\tm.Instances = append(m.Instances[:n], m.Instances[n+1:]...)\n\t} else {\n\t\tfmt.Println(\"No instance to kill\")\n\t}\n}", "func (sc *ShardCtrler) Kill() {\n\tsc.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *RaftKV) Kill() {\n\n\tkv.rf.Kill()\n\tclose(kv.kvraftShutdownChannel)\n}", "func (kv *KVRaft) kill() {\n\tDPrintf(\"Kill(%d): die\\n\", kv.me)\n\tkv.dead = true\n\tclose(kv.srvStopc)\n\t//remove socket file\n}", "func (px *Paxos) Kill() {\n atomic.StoreInt32(&px.dead, 1)\n if px.l != nil {\n px.l.Close()\n }\n}", "func (kv *KVServer) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (sc *ShardCtrler) Kill() {\n\tatomic.StoreInt32(&sc.dead, 1)\n\tsc.rf.Kill()\n\t// Your code here, if desired.\n}", "func (sc *ShardCtrler) Kill() {\n\tatomic.StoreInt32(&sc.dead, 1)\n\tsc.rf.Kill()\n\t// Your code here, if desired.\n}", "func (px *Paxos) Kill() {\n px.dead = true\n if px.l != nil {\n px.l.Close()\n }\n}", "func (px *Paxos) Kill() {\n px.dead = true\n if px.l != nil {\n px.l.Close()\n }\n}", "func (sc *ShardCtrler) Kill() {\n\tsc.rf.Kill()\n\t// Your code here, if desired.\n\tsc.killCh <- struct{}{}\n}", "func (kv *KVServer) Kill() {\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n\tclose(kv.shutdown)\n}", "func (kv *KVServer) Kill() {\n\tatomic.StoreInt32(&kv.dead, 1)\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n\tkv.killed()\n}", "func (kv *KVServer) Kill() {\n\tatomic.StoreInt32(&kv.dead, 1)\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tatomic.StoreInt32(&kv.dead, 1)\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tatomic.StoreInt32(&kv.dead, 1)\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tatomic.StoreInt32(&kv.dead, 1)\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}", "func (kv *KVServer) Kill() {\n\tatomic.StoreInt32(&kv.dead, 1)\n\tkv.rf.Kill()\n\t// Your code here, if desired.\n}" ]
[ "0.8227772", "0.8019247", "0.7852746", "0.7802516", "0.76599604", "0.76491994", "0.76054895", "0.7588172", "0.74876153", "0.7480657", "0.7443233", "0.7435706", "0.7402889", "0.73981386", "0.7357357", "0.73271185", "0.732235", "0.7312849", "0.7312849", "0.7312849", "0.7312849", "0.7312849", "0.7312849", "0.7312849", "0.7312849", "0.7312849", "0.7312849", "0.7312849", "0.7312849", "0.7312849", "0.7312849", "0.72944313", "0.7281173", "0.7276784", "0.72428894", "0.72352225", "0.7197167", "0.7197167", "0.7197167", "0.7197167", "0.7084097", "0.7054675", "0.7017594", "0.7017594", "0.7017594", "0.7017594", "0.69288963", "0.69216883", "0.69096005", "0.69096005", "0.6895683", "0.68267626", "0.68202156", "0.67739344", "0.6758504", "0.6739807", "0.6694033", "0.66464263", "0.661473", "0.6556139", "0.6502445", "0.6495768", "0.6495768", "0.6495768", "0.6495768", "0.6495768", "0.6495768", "0.6495768", "0.6495768", "0.6495768", "0.6495768", "0.6477726", "0.6477726", "0.6412334", "0.6412334", "0.6370658", "0.6342836", "0.63397974", "0.6324921", "0.6324921", "0.6324921", "0.6324921", "0.6324921" ]
0.76822865
21
is leader, check logs
func (rf *Raft) CheckLogs() { rf.mu.Lock() state := rf.state rf.mu.Unlock() for state == LEADER { //DPrintf("CHECKLOGS ON NODE %d: logs %s", rf.me, rf.logs) //appendChan := make(chan AppendResult, len(rf.peers)) for peerId := range rf.peers { if peerId == rf.me { continue } rf.mu.Lock() logLen := len(rf.logs) nextIndex := rf.nextIndex[peerId] rf.mu.Unlock() if logLen > nextIndex { go func(peerId int) { rf.mu.Lock() prevLogIndex := rf.matchIndex[peerId] prevLogTerm := rf.logs[prevLogIndex].Term args := AppendEntriesArgs{rf.currentTerm, rf.me, prevLogIndex, prevLogTerm, rf.logs[prevLogIndex+1:], rf.commitIndex} //DPrintf("[BEFOREAPPEND] ENTRIES %s PREV %d LOGS %s", args.Entries, args.PrevLogIndex, rf.logs) repl := AppendResult{} rf.mu.Unlock() for rf.state == LEADER { rf.sendAppendEntries(peerId, &args, &repl) //DPrintf("[CHECKAPPENDENTRIES REPLY]me: %d Term %d send to %d args: %s repl %s", rf.me, rf.currentTerm, peerId, args, repl) if repl.Success && rf.state == LEADER{ rf.mu.Lock() rf.nextIndex[peerId] = args.PrevLogIndex + len(args.Entries) + 1 rf.matchIndex[peerId] = args.PrevLogIndex + len(args.Entries) rf.mu.Unlock() break } rf.mu.Lock() if repl.Term > rf.currentTerm { rf.currentTerm = repl.Term rf.state = FOLLOWER break } if args.PrevLogIndex > 0 { args.PrevLogIndex -= 1 args.PrevLogTerm = rf.logs[args.PrevLogIndex].Term args.Entries = rf.logs[args.PrevLogIndex+1:] } rf.mu.Unlock() } }(peerId) } } time.Sleep(time.Duration(50) * time.Millisecond) // sleep for a while } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Raft) leaderProcessLog(s *leaderState, l *Log) bool {\n\t// Only handle LogAddPeer and LogRemove Peer\n\tif l.Type != LogAddPeer && l.Type != LogRemovePeer {\n\t\treturn false\n\t}\n\n\t// Process the log immediately to update the peer list\n\tr.processLog(l)\n\n\t// Decode the peer\n\tpeer := r.trans.DecodePeer(l.Data)\n\tisSelf := peer.String() == r.localAddr.String()\n\n\t// Get the replication state\n\trepl, ok := s.replicationState[peer.String()]\n\n\t// Start replication for new nodes\n\tif l.Type == LogAddPeer && !ok && !isSelf {\n\t\tr.startReplication(s, peer)\n\t}\n\n\t// Stop replication for old nodes\n\tif l.Type == LogRemovePeer && ok {\n\t\tclose(repl.stopCh)\n\t\tdelete(s.replicationState, peer.String())\n\t}\n\n\t// Step down if we are being removed\n\tif l.Type == LogRemovePeer && isSelf {\n\t\tr.logD.Printf(\"Removed ourself, stepping down as leader\")\n\t\treturn true\n\t}\n\treturn false\n}", "func (c *Curator) isLeader() bool {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\treturn c.iAmLeader\n}", "func (s *store) isLeader() bool {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tif s.raftState == nil {\n\t\treturn false\n\t}\n\treturn s.raftState.raft.State() == raft.Leader\n}", "func startLeaderListener(\n\tappendEntriesCom * [8]AppendEntriesCom,\n\tstate * ServerState,\n\ttimeSinceLastUpdate * time.Time,\n\tisElection * bool,\n\tserverStateLock * sync.Mutex,\n\t) {\n\tfor {\n\t\tselect {\n\t\tcase appendEntryRequest := <-appendEntriesCom[state.ServerId].message:\n\t\t\tif appendEntryRequest.Term >= state.CurrentTerm {\n\t\t\t\t*timeSinceLastUpdate = time.Now()\n\t\t\t\tif *isElection { //received message from leader during election,\n\t\t\t\t\t*isElection = false\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tprintMessageFromLeader(state.ServerId, appendEntryRequest)\n\t\t\t\tif state.Role != LeaderRole && len(appendEntryRequest.Entries) != 0 { //implements C3\n\t\t\t\t\tprocessAppendEntryRequest(appendEntryRequest, state, appendEntriesCom)\n\t\t\t\t\tfmt.Println(\"Server \", state.ServerId, \"'s current log: \", state.Log)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func IsLeader() bool {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\treturn leading\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 (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 (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 (r *Raft) leader() int {\n\t//fmt.Println(\"In leader(), I am: \", r.Myconfig.Id)\n\n\tr.sendAppendEntriesRPC() //send Heartbeats\n\t//waitTime := 4 //duration between two heartbeats\n\twaitTime := 1\n\twaitTime_secs := secs * time.Duration(waitTime)\n\t//fmt.Println(\"Heartbeat time out is\", waitTime)\n\n\twaitTimeAE := 5 //max time to wait for AE_Response\n\tHeartbeatTimer := r.StartTimer(HeartbeatTimeout, waitTime) //starts the timer and places timeout object on the channel\n\t//var AppendEntriesTimer *time.Timer\n\twaitStepDown := 7\n\tRetryTimer := r.StartTimer(RetryTimeOut, waitStepDown)\n\t//fmt.Println(\"I am\", r.Myconfig.Id, \"timer created\", AppendEntriesTimer)\n\tresponseCount := 0\n\tfor {\n\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_secs)\n\t\t\trequest := req.(ClientAppendReq)\n\t\t\tdata := request.data\n\t\t\t//fmt.Println(\"Received CA request,cmd is: \", string(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\t\t//AppendEntriesTimer = r.StartTimer(AppendEntriesTimeOut, waitTimeAE) //Can be written in HeartBeatTimer too\n\t\t\t//fmt.Println(\"I am\", r.Myconfig.Id, \"Timer assigned a value\", AppendEntriesTimer)\n\t\tcase AppendEntriesResponse:\n\t\t\tresponse := req.(AppendEntriesResponse)\n\t\t\t//fmt.Println(\"got AE_Response! from : \", response.followerId, response)\n\t\t\tresponseCount += 1\n\t\t\tif responseCount >= majority {\n\t\t\t\twaitTime_retry := secs * time.Duration(waitStepDown)\n\t\t\t\tRetryTimer.Reset(waitTime_retry)\n\t\t\t}\n\t\t\t//when isHeartBeat is true then success is also true according to the code in serviceAEReq so case wont be there when isHB is true and success is false\n\t\t\t// isHB true means it is a succeeded heartbeat hence no work to do if it is AE req then only proceed else do nothing and continue\n\t\t\t//So when follower's log is stale or he is more latest, it would set isHB false\n\t\t\tif !response.isHeartBeat {\n\t\t\t\tretVal := r.serviceAppendEntriesResp(response, HeartbeatTimer, waitTimeAE, waitTime)\n\t\t\t\tif retVal == follower {\n\t\t\t\t\treturn follower\n\t\t\t\t}\n\n\t\t\t}\n\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.currentTerm {\n\t\t\t\t//fmt.Println(\"In leader,AE_Req case, I am \", r.Myconfig.Id, \"becoming follower now, because request.term, r.currentTerm\", request.term, r.currentTerm)\n\t\t\t\tr.currentTerm = request.term //update self term and step down\n\t\t\t\tr.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.currentTerm, false, r.Myconfig.Id, false, r.myMetaData.lastLogIndex}\n\t\t\t\tsend(request.leaderId, reply)\n\t\t\t}\n\n\t\tcase int: //Time out-time to send Heartbeats!\n\t\t\ttimeout := req.(int)\n\t\t\tif timeout == RetryTimeOut {\n\t\t\t\tRetryTimer.Stop()\n\t\t\t\treturn follower\n\t\t\t}\n\t\t\t//fmt.Println(\"Timeout of\", r.Myconfig.Id, \"is of type:\", timeout)\n\n\t\t\t//waitTime_secs := secs * time.Duration(waitTime)\n\t\t\tif timeout == HeartbeatTimeout {\n\t\t\t\t//fmt.Println(\"Leader:Reseting HB timer\")\n\t\t\t\tHeartbeatTimer.Reset(waitTime_secs)\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,\n\t\t\t\t//since it was AE other than HB(last entry), it would have already modified the nextIndex map\n\t\t\t\tr.sendAppendEntriesRPC() //This either sends Heartbeats or retries the failed AE due to which the timeout happened,\n\t\t\t\t//HeartbeatTimer.Reset(secs * time.Duration(8)) //for checking leader change, setting timer of f4 to 8s--DOESN'T work..-_CHECK\n\t\t\t}\n\n\t\t}\n\t}\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 (s *raftState) checkLeaderCommit() bool {\n\tmatches := make([]int, 0, len(s.MatchIndex))\n\tfor _, x := range s.MatchIndex {\n\t\tmatches = append(matches, x)\n\t}\n\tsort.Sort(sort.Reverse(sort.IntSlice(matches)))\n\tnewC := matches[s.majority()-1]\n\tif newC > s.CommitIndex {\n\t\ts.commitUntil(newC)\n\t\tglog.V(utils.VDebug).Infof(\"%s Leader update commitIndex: %d\", s.String(), newC)\n\t\treturn true\n\t}\n\treturn false\n}", "func (m *MsgPing) Leader(state interfaces.IState) bool {\n\tswitch state.GetNetworkNumber() {\n\tcase 0: // Main Network\n\t\tpanic(\"Not implemented yet\")\n\tcase 1: // Test Network\n\t\tpanic(\"Not implemented yet\")\n\tcase 2: // Local Network\n\t\tpanic(\"Not implemented yet\")\n\tdefault:\n\t\tpanic(\"Not implemented yet\")\n\t}\n}", "func (db *Ops) IsLeader() bool {\n\treturn db.metaDB.IsLeader()\n}", "func (n *Ncd) IsLeader() bool {\n\treturn n.rtconf.Leader\n}", "func (r *Raft) AppendToLog_Leader(cmd []byte) {\n\tterm := r.currentTerm\n\tlogVal := LogVal{term, cmd, 0} //make object for log's value field with acks set to 0\n\t//fmt.Println(\"Before putting in log,\", logVal)\n\tr.myLog = append(r.myLog, logVal)\n\t//fmt.Println(\"I am:\", r.Myconfig.Id, \"Added cmd to my log\")\n\n\t//modify metadata after appending\n\t//fmt.Println(\"Metadata before appending,lastLogIndex,prevLogIndex,prevLogTerm\", r.myMetaData.lastLogIndex, r.myMetaData.prevLogIndex, r.myMetaData.prevLogTerm)\n\tlastLogIndex := r.myMetaData.lastLogIndex + 1\n\tr.myMetaData.prevLogIndex = r.myMetaData.lastLogIndex\n\tr.myMetaData.lastLogIndex = lastLogIndex\n\t//fmt.Println(r.myId(), \"Length of my log is\", len(r.myLog))\n\tif len(r.myLog) == 1 {\n\t\tr.myMetaData.prevLogTerm = r.myMetaData.prevLogTerm + 1 //as for empty log prevLogTerm is -2\n\n\t} else if len(r.myLog) > 1 { //explicit check, else would have sufficed too, just to eliminate len=0 possibility\n\t\tr.myMetaData.prevLogTerm = r.myLog[r.myMetaData.prevLogIndex].Term\n\t}\n\t//r.currentTerm = term\n\t//fmt.Println(\"I am leader, Appended to log, last index, its term is\", r.myMetaData.lastLogIndex, r.myLog[lastLogIndex].term)\n\t//fmt.Println(\"Metadata after appending,lastLogIndex,prevLogIndex,prevLogTerm\", r.myMetaData.lastLogIndex, r.myMetaData.prevLogIndex, r.myMetaData.prevLogTerm)\n\tr.setNextIndex_All() //Added-28 march for LogRepair\n\t//Write to disk\n\t//fmt.Println(r.myId(), \"In append_leader, appended to log\", string(cmd))\n\tr.WriteLogToDisk()\n\n}", "func (rf *Raft) tryToBeLeader() {\n\t//Step 1\n\tvar maxVoteNum, currentSuccessNum int\n\trf.mu.Lock()\n\trf.currentTerm++\n\trf.votedFor = rf.me\n\trf.role = Candidate\n\tmaxVoteNum = len(rf.peers)\n\trf.mu.Unlock()\n\trf.persist()\n\n\tcurrentSuccessNum = 1\n\tvar mutex sync.Mutex\n\tfor i := 0; i < maxVoteNum; i++ {\n\t\tif i != rf.me {\n\t\t\tgo func(idx int) {\n\t\t\t\tvar templateArgs RequestVoteArgs\n\t\t\t\trf.mu.Lock()\n\t\t\t\taLeaderComeUp := rf.role == Follower || rf.role == Leader\n\n\t\t\t\tif aLeaderComeUp {\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttemplateArgs.Term = rf.currentTerm\n\t\t\t\ttemplateArgs.CandidateID = rf.me\n\t\t\t\ttemplateArgs.LastLogTerm = rf.logs[len(rf.logs)-1].Term\n\t\t\t\ttemplateArgs.LastLogIndex = len(rf.logs) - 1\n\t\t\t\trf.mu.Unlock()\n\n\t\t\t\targs := templateArgs\n\t\t\t\tvar reply RequestVoteReply\n\t\t\t\tok := rf.sendRequestVote(idx, &args, &reply)\n\n\t\t\t\trf.mu.Lock()\n\t\t\t\taLeaderComeUp = rf.role == Follower || rf.role == Leader || rf.role == None\n\t\t\t\trf.mu.Unlock()\n\t\t\t\tif aLeaderComeUp {\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tmutex.Lock()\n\t\t\t\t\t\tcurrentSuccessNum++\n\t\t\t\t\t\tmutex.Unlock()\n\t\t\t\t\t\tif currentSuccessNum >= maxVoteNum/2+1 {\n\t\t\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\t\t\trf.role = Leader\n\t\t\t\t\t\t\tfor i := 0; i < len(rf.peers); i++ {\n\t\t\t\t\t\t\t\trf.nextIndex[i] = len(rf.logs)\n\t\t\t\t\t\t\t\trf.matchIndex[i] = 0\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\tgo rf.logDuplicate()\n\t\t\t\t\t\t\trf.msgChan <- BecomeLeader\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}(i)\n\t\t}\n\t}\n\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 (s *Server) getLeader() (bool, *metadata.Server) {\n\t// Check if we are the leader\n\tif s.IsLeader() {\n\t\treturn true, nil\n\t}\n\n\t// Get the leader\n\tleader := s.raft.Leader()\n\tif leader == \"\" {\n\t\treturn false, nil\n\t}\n\n\t// Lookup the server\n\tserver := s.serverLookup.Server(leader)\n\n\t// Server could be nil\n\treturn false, server\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\tif rf.state == Leader {\n\t\tnewLogEntry := LogEntry{}\n\t\trf.mu.Lock()\n\t\tif rf.state == Leader {\n\t\t\tterm = rf.currentTerm\n\t\t\tnewLogEntry.Term = term\n\t\t\tnewLogEntry.Command = command\n\t\t\trf.log = append(rf.log, newLogEntry)\n\t\t\tindex = len(rf.log) - 1\n\t\t\t// update leader's matchIndex and nextIndex\n\t\t\trf.matchIndex[rf.me] = index\n\t\t\trf.nextIndex[rf.me] = index + 1\n\t\t\trf.persist()\n\t\t} else {\n\t\t\tDPrintf(\"Peer-%d, before lock, the state has changed to %d.\\n\", rf.me, rf.state)\n\t\t}\n\t\tif term != -1 {\n\t\t\tDPrintf(\"Peer-%d start to append %v to peers.\\n\", rf.me, command)\n\t\t\trequest := rf.createAppendEntriesRequest(index, index+1, term)\n\t\t\tappendProcess := func(server int) bool {\n\t\t\t\treply := new(AppendEntriesReply)\n\t\t\t\trf.sendAppendEntries(server, request, reply)\n\t\t\t\tok := rf.processAppendEntriesReply(index+1, reply)\n\t\t\t\tif ok {\n\t\t\t\t\tDPrintf(\"Peer-%d append log=%v to peer-%d successfully.\\n\", rf.me, request.Entries, server)\n\t\t\t\t} else {\n\t\t\t\t\tDPrintf(\"Peer-%d append log=%v to peer-%d failed.\\n\", rf.me, request.Entries, server)\n\t\t\t\t}\n\t\t\t\treturn ok\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tok := rf.agreeWithServers(appendProcess)\n\t\t\t\tif ok {\n\t\t\t\t\t// if append successfully, update commit index.\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\tif index >= rf.commitIndex {\n\t\t\t\t\t\tDPrintf(\"Peer-%d set commit=%d, origin=%d.\", rf.me, index, rf.commitIndex)\n\t\t\t\t\t\trf.commitIndex = index\n\t\t\t\t\t} else {\n\t\t\t\t\t\tDPrintf(\"Peer-%d get a currentIndex=%d < commitIndex=%d, it can not be happend.\", rf.me, index, rf.commitIndex)\n\t\t\t\t\t}\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t} else {\n\t\t\t\t\tDPrintf(\"Peer-%d start agreement with servers failed. currentIndex=%d.\\n\", rf.me, index)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\trf.mu.Unlock()\n\t} else {\n\t\tisLeader = false\n\t}\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n lastLogIndex := 0\n isLeader := true\n \n // TODO WED: check corner cases with -1\n rf.mu.Lock()\n term := rf.currentTerm\n myId := rf.me\n if len(rf.log) > 0 {\n lastLogIndex = len(rf.log)\n //term = rf.log[index].Term \n }\n \n if rf.state != Leader || rf.killed() {\n return lastLogIndex-1, term, false\n }\n \n var oneEntry LogEntry\n oneEntry.Command = command\n oneEntry.Term = term\n \n rf.log = append(rf.log, oneEntry)\n rf.mu.Unlock()\n\n \n go func() {\n \n // Add a while loop. when successReply count greater than threhsold, commit. loop breaks when successReply is equal to peers\n // the for loop inside only iterates over the left peers.\n \n var localMu sync.Mutex\n \n isLeader := true\n committed := false\n successReplyCount := 0\n var receivedResponse []int\n receivedResponse = append(receivedResponse, myId)\n\n for isLeader {\n if rf.killed() {\n fmt.Printf(\"*** Peer %d term %d: Terminated. Closing all outstanding Append Entries calls to followers.\",myId, term)\n return \n }\n\n var args = AppendEntriesArgs {\n LeaderId: myId,\n }\n rf.mu.Lock()\n numPeers := len(rf.peers)\n rf.mu.Unlock()\n\n for id := 0; id < numPeers && isLeader; id++ {\n if (!find(receivedResponse,id)) {\n if lastLogIndex < rf.nextIndex[id] {\n successReplyCount++\n receivedResponse = append(receivedResponse,id)\n continue\n }\n var logEntries []LogEntry\n logEntries = append(logEntries,rf.log[(rf.nextIndex[id]):]...)\n args.LogEntries = logEntries\n args.PrevLogTerm = rf.log[rf.nextIndex[id]-1].Term\n args.PrevLogIndex = rf.nextIndex[id]-1\n args.LeaderTerm = rf.currentTerm\n args.LeaderCommitIndex = rf.commitIndex\n \n go func(serverId int) {\n var reply AppendEntriesReply\n ok:=rf.sendAppendEntries(serverId, &args, &reply)\n if !rf.CheckTerm(reply.CurrentTerm) {\n localMu.Lock()\n isLeader=false\n localMu.Unlock()\n } else if reply.Success && ok {\n localMu.Lock()\n successReplyCount++\n receivedResponse = append(receivedResponse,serverId)\n localMu.Unlock()\n rf.mu.Lock()\n if lastLogIndex >= rf.nextIndex[id] {\n rf.matchIndex[id]= lastLogIndex\n rf.nextIndex[id] = lastLogIndex + 1\n }\n rf.mu.Unlock()\n } else {\n rf.mu.Lock()\n rf.nextIndex[id]-- \n rf.mu.Unlock()\n }\n } (id)\n }\n }\n \n fmt.Printf(\"\\nsleeping before counting success replies\\n\")\n time.Sleep(time.Duration(RANDOM_TIMER_MIN*time.Millisecond))\n\n if !committed && isLeader {\n votesForIndex := 0\n N := math.MaxInt32\n rf.mu.Lock()\n for i := 0; i < numPeers; i++ {\n if rf.matchIndex[i] > rf.commitIndex {\n if rf.matchIndex[i] < N {\n N = rf.matchIndex[i]\n }\n votesForIndex++\n }\n }\n rf.mu.Unlock()\n\n\n if (votesForIndex > (numPeers/2)){ \n go func(){\n committed = true\n rf.mu.Lock()\n rf.commitIndex = N // Discuss: 3. should we use lock?\n rf.log[N].Term = rf.currentTerm\n if rf.commitIndex >= lastLogIndex {\n var oneApplyMsg ApplyMsg\n oneApplyMsg.CommandValid = true\n oneApplyMsg.CommandIndex = lastLogIndex\n oneApplyMsg.Command = command\n go func() {rf.applyCh <- oneApplyMsg} ()\n }\n rf.mu.Unlock()\n }()\n }\n } else if successReplyCount == numPeers {\n return\n } \n }\n } ()\n \n // Your code here (2B code).\n return lastLogIndex, term, isLeader\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 (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 (rf *Raft) Start(command interface{}) (int, int, bool) {\n index := -1\n term := -1\n isLeader := true\n\n rf.mu.Lock()\n isLeader = rf.state == \"Leader\"\n if isLeader {\n newEntry := Entry{}\n newEntry.Command = command\n newEntry.Term = rf.currentTerm\n\n index = rf.convertToGlobalViewIndex(len(rf.log))\n term = rf.currentTerm\n rf.log = append(rf.log, newEntry)\n\n rf.persist()\n //go rf.startAppendEntries()\n\n DLCPrintf(\"Leader (%d) append entries and now log is from %v to %v(index=%d in Raft Log view)\", rf.me, rf.log[1], rf.log[len(rf.log)-1], len(rf.log)-1)\n }\n rf.mu.Unlock()\n\n return index, term, isLeader\n}", "func (vs *VolMgrServer) showLeaders() {\n\tticker := time.NewTicker(time.Second * 10)\n\tgo func() {\n\t\tfor range ticker.C {\n\t\t\tl, t := vs.RaftServer.LeaderTerm(1)\n\t\t\tlogger.Debug(\"ShowLeaders RaftGroup LeaderID %v Term %v\", l, t)\n\t\t}\n\t}()\n}", "func (c *Coordinator) IsLeader() bool {\n\n\treturn c.raft.State() == raft.Leader\n}", "func TestLogReplication1(t *testing.T) {\n\n\tack := make(chan bool)\n\n\t//Get leader\n\tleaderId := raft.GetLeaderId()\n\n\t//Append a log entry to leader as client\n\traft.InsertFakeLogEntry(leaderId)\n\n\tleaderLog := raft.GetLogAsString(leaderId)\n\t// log.Println(leaderLog)\n\n\ttime.AfterFunc(1*time.Second, func() { ack <- true })\n\t<-ack //Wait for 1 second for log replication to happen\n\n\t//Get logs of all others and compare with each\n\tfor i := 0; i < 5; i++ {\n\t\tcheckIfExpected(t, raft.GetLogAsString(i), leaderLog)\n\t}\n\n}", "func (r *Raft) becomeLeader() {\n\t// leader 先发送一个空数据\n\tr.State = StateLeader\n\tr.Lead = r.id\n\tlastIndex := r.RaftLog.LastIndex()\n\tr.heartbeatElapsed = 0\n\tfor peer := range r.Prs {\n\t\tif peer == r.id {\n\t\t\tr.Prs[peer].Next = lastIndex + 2\n\t\t\tr.Prs[peer].Match = lastIndex + 1\n\t\t} else {\n\t\t\tr.Prs[peer].Next = lastIndex + 1\n\t\t}\n\t}\n\tr.RaftLog.entries = append(r.RaftLog.entries, pb.Entry{Term: r.Term, Index: r.RaftLog.LastIndex() + 1})\n\tr.bcastAppend()\n\tif len(r.Prs) == 1 {\n\t\tr.RaftLog.committed = r.Prs[r.id].Match\n\t}\n}", "func (r *Raft) leaderNoop() {\n\tlogFuture := &DeferLog{\n\t\tlog: Log{\n\t\t\tType: LogNoop,\n\t\t},\n\t}\n\tselect {\n\tcase r.applyCh <- logFuture:\n\tcase <-r.shutdownCh:\n\t}\n}", "func (rf *Raft) StartAppendLog() {\n\tvar count int32 = 1\n\tfor i, _ := range rf.peers {\n\t\tif i == rf.me {\n\t\t\tcontinue\n\t\t}\n\t\tgo func(i int) {\n\t\t\tfor{\n\t\t\t\trf.mu.Lock()\n\t\t\t\t//fmt.Printf(\"follower %d lastlogindex: %v, nextIndex: %v\\n\",i, rf.GetPrevLogIndex(i), rf.nextIndex[i])\n\t\t\t\t//fmt.Print(\"sending log entries from leader %d to peer %d for term %d\\n\", rf.me, i, rf.currentTerm)\n\t\t\t\t//fmt.Print(\"nextIndex:%d\\n\", rf.nextIndex[i])\n\t\t\t\tif rf.state != Leader {\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\targs := AppendEntriesArgs{\n\t\t\t\t\tTerm: rf.currentTerm,\n\t\t\t\t\tLeaderId: rf.me,\n\t\t\t\t\tPrevLogIndex: rf.GetPrevLogIndex(i),\n\t\t\t\t\tPrevLogTerm: rf.GetPrevLogTerm(i),\n\t\t\t\t\tEntries: append(make([]LogEntry, 0), rf.logEntries[rf.nextIndex[i]:]...),\n\t\t\t\t\tLeaderCommit: rf.commitIndex,\n\t\t\t\t}\n\t\t\t\treply := AppendEntriesReply{}\n\t\t\t\trf.mu.Unlock()\n\t\t\t\tok := rf.sendAppendEntries(i, &args, &reply)\n\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\trf.mu.Lock()\n\t\t\t\tif rf.state != Leader {\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif reply.Term > rf.currentTerm {\n\t\t\t\t\trf.BeFollower(reply.Term)\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tsend(rf.appendEntry)\n\t\t\t\t\t}()\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif reply.Success {\n\t\t\t\t\trf.matchIndex[i] = args.PrevLogIndex + len(args.Entries)\n\t\t\t\t\trf.nextIndex[i] = rf.matchIndex[i] + 1\n\t\t\t\t\t//fmt.Print(\"leader: %v, for peer %v, match index: %d, next index: %d, peers: %d\\n\", rf.me, i, rf.matchIndex[i], rf.nextIndex[i], len(rf.peers))\n\t\t\t\t\tatomic.AddInt32(&count, 1)\n\t\t\t\t\tif atomic.LoadInt32(&count) > int32(len(rf.peers)/2) {\n\t\t\t\t\t\t//fmt.Print(\"leader %d reach agreement\\n, args.prevlogindex:%d, len:%d\\n\", rf.me, args.PrevLogIndex, len(args.Entries))\n\t\t\t\t\t\trf.UpdateCommitIndex()\n\t\t\t\t\t}\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\t//fmt.Printf(\"peer %d reset the next index from %d to %d\\n\", i, rf.nextIndex[i], rf.nextIndex[i]-1)\n\t\t\t\t\tif rf.nextIndex[i] > 0 {\n\t\t\t\t\t\trf.nextIndex[i]--\n\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t} else {\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}\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t}\n\t\t}(i)\n\t}\n\n}", "func (z *ZkRegistry) watchLeader() error {\n\tif z.node.IsLeader {\n\t\treturn errors.New(\"No node watcher for Leader!!!\")\n\t}\n\n\tleaderPath := z.node.RealRootPath + \"/\" + z.node.RealPrevSrvPath\n\tchildren, childrenState, eventChan, err := z.Conn.ChildrenW(leaderPath)\n\tif err != nil {\n\t\treturn errors.New(\"Watch Leader node error: \\n\" + err.Error())\n\t}\n\n\tfmt.Println(\"Watch Leader Node, \", children, childrenState)\nWATCH_LEADER_LOOP:\n\tfor {\n\t\tselect {\n\t\tcase zkEvent := <-eventChan:\n\t\t\tif zkEvent.Type == zk.EventNodeDeleted {\n\t\t\t\tbreak WATCH_LEADER_LOOP\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *Server) IsLeader() bool {\n\treturn atomic.LoadInt64(&s.isLeaderValue) == 1\n}", "func (r *Range) IsLeader() bool {\n\treturn true\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\t//Client 给复制状态机发送了一个command\n\trf.mu.Lock()\n\tindex := len(rf.log)\n\tterm := rf.currentTerm\n\tisLeader := true\n\n\t// Your code here (2B).\n\t//DPrintf(\"2B TEST: current server is %d, state is %s\", rf.me, rf.state)\n\tif rf.state != \"leader\" {\n\t\tisLeader = false\n\t}else{\n\t\t//if rf.log[0].Term == 0 && rf.log[0].Index == 0 && rf.log[0].Command == nil {\n\t\t//\trf.log[0].Term = rf.currentTerm\n\t\t//\trf.log[0].Command = command\n\t\t//}else{\n\t\t//\tindex = len(rf.log)\n\t\t//\tlogEntry := Entry{\n\t\t//\t\tTerm: rf.currentTerm,\n\t\t//\t\tIndex: index,\n\t\t//\t\tCommand: command,\n\t\t//\t}\n\t\t//\trf.log = append(rf.log, logEntry)\n\t\t//\trf.matchIndex[rf.me] = index\n\t\t//\tDPrintf(\"2B TEST: %d's log is %v; index is %d, term is %d, logEntry is %v\", rf.me, rf.log, index, term, logEntry)\n\t\t//}\n\t\tindex = len(rf.log)\n\t\tlogEntry := Entry{\n\t\t\tTerm: rf.currentTerm,\n\t\t\tIndex: index,\n\t\t\tCommand: command,\n\t\t}\n\t\trf.log = append(rf.log, logEntry)\n\t\trf.matchIndex[rf.me] = index\n\t\t//DPrintf(\"2B TEST: %d's log is %v; index is %d, term is %d, logEntry is %v\", rf.me, rf.log, index, term, logEntry)\n\t}\n\trf.resetHeartBeatTimers()\n\trf.mu.Unlock()\n\treturn index, term, isLeader\n}", "func (l *listener) NewLeader(id string) {\n\tlog.Printf(\"[INFO] %s: new leader: %s\", hostname(), id)\n}", "func (t *Txn) IsLeader() bool {\n\treturn t.isLeader\n}", "func (c *Client) IsLeader() bool {\n\t// self node key\n\tself := c.dir.ElectionNode(c.address)\n\tif c.leader != nil && c.leader.Key == self {\n\t\treturn true\n\t}\n\treturn false\n}", "func (r *Raft) AppendToLog_Leader(cmd []byte) {\n\tTerm := r.myCV.CurrentTerm\n\tlogVal := LogVal{Term, cmd, 0} //make object for log's value field with acks set to 0\n\tr.MyLog = append(r.MyLog, logVal)\n\t//modify metaData after appending\n\tLastLogIndex := r.MyMetaData.LastLogIndex + 1\n\tr.MyMetaData.PrevLogIndex = r.MyMetaData.LastLogIndex\n\tr.MyMetaData.LastLogIndex = LastLogIndex\n\tif len(r.MyLog) == 1 {\n\t\tr.MyMetaData.PrevLogTerm = r.MyMetaData.PrevLogTerm + 1 //as for empty log PrevLogTerm is -2\n\n\t} else if len(r.MyLog) > 1 { //explicit check, else would have sufficed too, just to eliminate len=0 possibility\n\t\tr.MyMetaData.PrevLogTerm = r.MyLog[r.MyMetaData.PrevLogIndex].Term\n\t}\n\tr.setNextIndex_All() //Added-28 march for LogRepair\n\tr.WriteLogToDisk()\n\n}", "func (a *Adapter) isLoggable(level string) bool {\n\treturn granularity[level] >= granularity[a.cfg.Level]\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 (dn *DNode) IsLeader() bool {\n\treturn dn.metaNode.IsLeader()\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 (t *Txn) Leader() {\n\tif t.isLeader {\n\t\tpanic(\"transaction is already marked as leader\")\n\t}\n\tt.isLeader = true\n\tt.DryRun()\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n rf.mu.Lock()\n defer rf.mu.Unlock()\n\n if rf.state != StateLeader {\n return nilIndex, nilIndex, false\n }\n\n // Your code here (2B).\n\n logLen := len(rf.log)\n index := logLen\n term := rf.currentTerm\n isLeader := true\n\n thisEntry := LogEntry{rf.currentTerm, command}\n rf.log = append(rf.log, thisEntry)\n rf.matchIndex[rf.me] = len(rf.log)\n\n rf.persist()\n\n // rf.print(\"Client start command %v\", command)\n\n return index, term, isLeader\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 (s *Server) startEnterpriseLeader() {}", "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 (rf *Raft) convertToLeader() {\n\trf.state = Leader\n\tDPrintf(\"peer-%d becomes the new leader!!!\", rf.me)\n\t// when a leader first comes to power, it initializes all nextIndex values to the index just after the last one in its log. (Section 5.3)\n\trf.nextIndex = make([]int, len(rf.peers))\n\trf.matchIndex = make([]int, len(rf.peers))\n\tnext_index_initval := len(rf.log) + 1\n\tfor i := 0; i < len(rf.peers); i++ {\n\t\trf.nextIndex[i] = next_index_initval\n\t\trf.matchIndex[i] = 0 // increases monotonically.\n\t}\n\trf.repCount = make(map[int]int)\n\tDPrintf(\"peer-%d Leader's log array's length = %d.\", rf.me, len(rf.log))\n\trf.leaderCh <- true\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 (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 (s *Server) campaignLeader() (bool, *clientv3.LeaseGrantResponse, error) {\n\tclient := s.node.RawClient()\n\t// Init a new lease\n\tlessor := client.NewLease()\n\tdefer lessor.Close()\n\tctx, cancelFunc := context.WithCancel(s.ctx)\n\tdefer cancelFunc()\n\tlr, err := lessor.Grant(ctx, s.cfg.LeaderLeaseTTL)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn false, nil, errors.Trace(err)\n\t}\n\n\tresp, err := client.Txn(ctx).\n\t\tIf(clientv3.Compare(clientv3.CreateRevision(s.fullLeaderPath()), \"=\", 0)).\n\t\tThen(append(s.leaderPutOps(lr.ID, s.term+1), s.myTermPutOps(true)...)...).\n\t\tCommit()\n\n\tif err != nil {\n\t\tlog.Info(\"error when campaign leader \", err)\n\t\treturn false, nil, errors.Trace(err)\n\t}\n\n\tif !resp.Succeeded {\n\t\treturn false, nil, nil\n\t}\n\treturn true, lr, nil\n}", "func (sia *statefulsetInitAwaiter) checkAndLogStatus() bool {\n\tif sia.replicasReady && sia.revisionReady {\n\t\tsia.config.logStatus(diag.Info,\n\t\t\tfmt.Sprintf(\"%sStatefulSet initialization complete\", cmdutil.EmojiOr(\"✅ \", \"\")))\n\t\treturn true\n\t}\n\n\tisInitialDeployment := sia.currentGeneration <= 1\n\n\t// For initial generation, the revision doesn't need to be updated, so skip that step in the log.\n\tif isInitialDeployment {\n\t\tsia.config.logStatus(diag.Info, fmt.Sprintf(\"[1/2] Waiting for StatefulSet to create Pods (%d/%d Pods ready)\",\n\t\t\tsia.currentReplicas, sia.targetReplicas))\n\t} else {\n\t\tswitch {\n\t\tcase !sia.replicasReady:\n\t\t\tsia.config.logStatus(diag.Info, fmt.Sprintf(\"[1/3] Waiting for StatefulSet update to roll out (%d/%d Pods ready)\",\n\t\t\t\tsia.currentReplicas, sia.targetReplicas))\n\t\tcase !sia.revisionReady:\n\t\t\tsia.config.logStatus(diag.Info,\n\t\t\t\t\"[2/3] Waiting for StatefulSet to update .status.currentRevision\")\n\t\t}\n\t}\n\n\treturn false\n}", "func (s *store) leader() string {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tif s.raftState == nil || s.raftState.raft == nil {\n\t\treturn \"\"\n\t}\n\n\ts.logger.Info(\"query leader. \" + string(s.raftState.raft.Leader()))\n\treturn string(s.raftState.raft.Leader())\n}", "func (l *DistributedLog) WaitForLeader(timeout time.Duration) error {\n\ttimeoutc := time.After(timeout)\n\tticker := time.NewTicker(time.Second)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-timeoutc:\n\t\t\treturn fmt.Errorf(\"timed out\")\n\t\tcase <-ticker.C:\n\t\t\tif l := l.raft.Leader(); l != \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n}", "func (actor *Actor) IsLeader() bool {\n\tif actor.Raft != nil {\n\t\treturn actor.Raft.State() == raft.Leader\n\t}\n\treturn false\n}", "func TestLogReplication2(t *testing.T) {\n\tack := make(chan bool)\n\n\t//Kill one server\n\traft.KillServer(1)\n\n\t//Append log to server\n\ttime.AfterFunc(1*time.Second, func() {\n\t\t//Get leader\n\t\tleaderId := raft.GetLeaderId()\n\n\t\t//Append a log entry to leader as client\n\t\traft.InsertFakeLogEntry(leaderId)\n\t})\n\n\t//Resurrect old server after enough time for other to move on\n\ttime.AfterFunc(2*time.Second, func() {\n\t\t//Resurrect old server\n\t\traft.ResurrectServer(1)\n\t})\n\n\t//Check log after some time to see if it matches with current leader\n\ttime.AfterFunc(3*time.Second, func() {\n\t\tleaderId := raft.GetLeaderId()\n\t\tleaderLog := raft.GetLogAsString(leaderId)\n\t\tserverLog := raft.GetLogAsString(1)\n\n\t\tcheckIfExpected(t, serverLog, leaderLog)\n\n\t\tack <- true\n\t})\n\n\t<-ack\n\n}", "func (rf *Raft) IsLeader() bool {\n\treturn rf.identity == LEADER\n}", "func findLeader(nodes []*Node) (*Node, error) {\n\tleaders := make([]*Node, 0)\n\tfor _, node := range nodes {\n\t\tif node.raft.State == raft.LeaderState {\n\t\t\tleaders = append(leaders, node)\n\t\t}\n\t}\n\n\tif len(leaders) == 0 {\n\t\treturn nil, fmt.Errorf(\"No leader found in slice of nodes\")\n\t} else if len(leaders) == 1 {\n\t\treturn leaders[0], nil\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Found too many leaders in slice of nodes: %v\", len(leaders))\n\t}\n}", "func (handler *RuleHandler) FollowerOnAppendEntries(msg iface.MsgAppendEntries, log iface.RaftLog, status iface.Status) []interface{} {\n\tactions := make([]interface{}, 0) // list of actions created\n\t// since we are hearing from the leader, reset timeout\n\tactions = append(actions, iface.ActionResetTimer{\n\t\tHalfTime: false,\n\t})\n\tactions = append(actions, iface.ActionSetLeaderLastHeard{\n\t\tInstant: time.Now(),\n\t})\n\n\t// maybe we are outdated\n\tif msg.Term > status.CurrentTerm() {\n\t\tactions = append(actions, iface.ActionSetCurrentTerm{\n\t\t\tNewCurrentTerm: msg.Term,\n\t\t})\n\t}\n\n\tprevEntry, _ := log.Get(msg.PrevLogIndex)\n\n\t// leader is outdated ?\n\tif msg.Term < status.CurrentTerm() {\n\t\tactions = append(actions, iface.ReplyAppendEntries{\n\t\t\tAddress: status.NodeAddress(),\n\t\t\tSuccess: false,\n\t\t\tTerm: status.CurrentTerm(),\n\t\t})\n\t\treturn actions\n\t}\n\n\t// I dont have previous log entry (but should)\n\tif prevEntry == nil && msg.PrevLogIndex != -1 {\n\t\tactions = append(actions, iface.ReplyAppendEntries{\n\t\t\tAddress: status.NodeAddress(),\n\t\t\tSuccess: false,\n\t\t\tTerm: status.CurrentTerm(),\n\t\t})\n\t\treturn actions\n\t}\n\n\t// I have previous log entry, but it does not match\n\tif prevEntry != nil && prevEntry.Term != msg.PrevLogTerm {\n\t\tactions = append(actions, iface.ReplyAppendEntries{\n\t\t\tAddress: status.NodeAddress(),\n\t\t\tSuccess: false,\n\t\t\tTerm: status.CurrentTerm(),\n\t\t})\n\t\treturn actions\n\t}\n\n\t// all is ok. accept new entries\n\tactions = append(actions, iface.ReplyAppendEntries{\n\t\tAddress: status.NodeAddress(),\n\t\tSuccess: true,\n\t\tTerm: status.CurrentTerm(),\n\t})\n\n\t// if there is anything to append, do it\n\tif len(msg.Entries) > 0 {\n\t\t// delete all entries in log after PrevLogIndex\n\t\tactions = append(actions, iface.ActionDeleteLog{\n\t\t\tCount: log.LastIndex() - msg.PrevLogIndex,\n\t\t})\n\n\t\t// take care ! Maybe we are removing an entry\n\t\t// containing our current cluster configuration.\n\t\t// In this case, revert to previous cluster\n\t\t// configuration\n\t\tcontainsClusterChange := false\n\t\tstabilized := false\n\t\tclusterChangeIndex := status.ClusterChangeIndex()\n\t\tclusterChangeTerm := status.ClusterChangeTerm()\n\t\tcluster := append(status.PeerAddresses(), status.NodeAddress())\n\t\tfor !stabilized {\n\t\t\tstabilized = true\n\t\t\tif clusterChangeIndex > msg.PrevLogIndex {\n\t\t\t\tstabilized = false\n\t\t\t\tcontainsClusterChange = true\n\t\t\t\tentry, _ := log.Get(clusterChangeIndex)\n\t\t\t\trecord := &iface.ClusterChangeCommand{}\n\t\t\t\tjson.Unmarshal(entry.Command, &record)\n\t\t\t\tclusterChangeIndex = record.OldClusterChangeIndex\n\t\t\t\tclusterChangeTerm = record.OldClusterChangeTerm\n\t\t\t\tcluster = record.OldCluster\n\t\t\t}\n\t\t}\n\n\t\t// if deletion detected, rewind to previous configuration\n\t\tif containsClusterChange {\n\t\t\tactions = append(actions, iface.ActionSetClusterChange{\n\t\t\t\tNewClusterChangeIndex: clusterChangeIndex,\n\t\t\t\tNewClusterChangeTerm: clusterChangeTerm,\n\t\t\t})\n\t\t\tpeers := []iface.PeerAddress{}\n\t\t\tfor _, addr := range cluster {\n\t\t\t\tif addr != status.NodeAddress() {\n\t\t\t\t\tpeers = append(peers, addr)\n\t\t\t\t}\n\t\t\t}\n\t\t\tactions = append(actions, iface.ActionSetPeers{\n\t\t\t\tPeerAddresses: peers,\n\t\t\t})\n\t\t}\n\n\t\t// append all entries sent by leader\n\t\tactions = append(actions, iface.ActionAppendLog{\n\t\t\tEntries: msg.Entries,\n\t\t})\n\n\t\t// once again, take care ! Maybe we are adding some entry\n\t\t// describing a cluster change. In such a case, we must apply\n\t\t// the new cluster configuration to ourselves (specifically,\n\t\t// the last cluster configuration among the new entries)\n\t\tfor index := len(msg.Entries) - 1; index >= 0; index-- {\n\t\t\tif msg.Entries[index].Kind != iface.EntryAddServer &&\n\t\t\t\tmsg.Entries[index].Kind != iface.EntryRemoveServer {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trecord := &iface.ClusterChangeCommand{}\n\t\t\tjson.Unmarshal(msg.Entries[index].Command, &record)\n\t\t\tactions = append(actions, iface.ActionSetClusterChange{\n\t\t\t\tNewClusterChangeIndex: msg.PrevLogIndex + int64(index+1),\n\t\t\t\tNewClusterChangeTerm: msg.Entries[index].Term,\n\t\t\t})\n\t\t\tpeers := []iface.PeerAddress{}\n\t\t\tfor _, addr := range record.NewCluster {\n\t\t\t\tif addr != status.NodeAddress() {\n\t\t\t\t\tpeers = append(peers, addr)\n\t\t\t\t}\n\t\t\t}\n\t\t\tactions = append(actions, iface.ActionSetPeers{\n\t\t\t\tPeerAddresses: peers,\n\t\t\t})\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\t// if leader has committed more than we know, update our index\n\t// and demand state-machine application\n\tif msg.LeaderCommitIndex > status.CommitIndex() {\n\t\tactions = append(actions, iface.ActionSetCommitIndex{\n\t\t\tNewCommitIndex: int64(math.Min(\n\t\t\t\tfloat64(msg.LeaderCommitIndex),\n\t\t\t\tfloat64(msg.PrevLogIndex+int64(len(msg.Entries))),\n\t\t\t)),\n\t\t})\n\t\t// order the state machine to apply the new committed entries\n\t\t// (only if they are state machine commands)\n\t\t// TODO: Treat configuration change\n\t\tfor index := status.CommitIndex() + 1; index < msg.LeaderCommitIndex; index++ {\n\t\t\tvar entry *iface.LogEntry\n\n\t\t\t// get from my log\n\t\t\tif index <= msg.PrevLogIndex {\n\t\t\t\tentry, _ = log.Get(index)\n\n\t\t\t\t// get from leader\n\t\t\t} else {\n\t\t\t\tentry = &msg.Entries[index-msg.PrevLogIndex-1]\n\t\t\t}\n\n\t\t\tswitch entry.Kind {\n\t\t\tcase iface.EntryStateMachineCommand:\n\t\t\t\tactions = append(actions, iface.ActionStateMachineApply{\n\t\t\t\t\tEntryIndex: index,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn actions\n}", "func (s *store) waitForLeader(timeout time.Duration) error {\n\t// Begin timeout timer.\n\ttimer := time.NewTimer(timeout)\n\tdefer timer.Stop()\n\n\t// Continually check for leader until timeout.\n\tticker := time.NewTicker(100 * time.Millisecond)\n\tdefer ticker.Stop()\n\ts.logger.Info(\"waitForLeader start\")\n\tfor {\n\t\tselect {\n\t\tcase <-s.closing:\n\t\t\treturn errors.New(\"closing\")\n\t\tcase <-timer.C:\n\t\t\tif timeout != 0 {\n\t\t\t\treturn errors.New(\"timeout\")\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif s.leader() != \"\" {\n\t\t\t\ts.logger.Info(\"waitForLeader done\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n}", "func TestLeaderFailure(t *testing.T){\r\n\tif !TESTLEADERFAILURE{\r\n\t\treturn\r\n\t}\r\n rafts,_ := makeRafts(5, \"input_spec.json\", \"log\", 200, 300)\t\r\n\ttime.Sleep(2*time.Second)\t\t\t\r\n\trunning := make(map[int]bool)\r\n\tfor i:=1;i<=5;i++{\r\n\t\trunning[i] = true\r\n\t}\r\n\trafts[0].smLock.RLock()\r\n\tlid := rafts[0].LeaderId()\r\n\trafts[0].smLock.RUnlock()\r\n\tdebugRaftTest(fmt.Sprintf(\"leader Id:%v\\n\", lid))\r\n\tif lid != -1{\r\n\t\trafts[lid-1].Shutdown()\r\n\t\tdebugRaftTest(fmt.Sprintf(\"Leader(id:%v) is down, now\\n\", lid))\r\n\t\ttime.Sleep(4*time.Second)\t\t\t\r\n\t\trunning[lid] = false\r\n\t\tfor i := 1; i<= 5;i++{\r\n\t\t\tif running[i] {\r\n\t\t\t\trafts[i-1].Append([]byte(\"first\"))\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\ttime.Sleep(5*time.Second)\t\t\t\r\n\r\n\tfor idx, node := range rafts {\r\n\t\tnode.smLock.RLock()\r\n\t\tdebugRaftTest(fmt.Sprintf(\"%v\", node.sm.String()))\r\n\t\tnode.smLock.RUnlock()\r\n\t\tif running[idx-1]{\r\n\t\t\tnode.Shutdown()\r\n\t\t}\r\n\t}\r\n}", "func (rf *Raft) BeLeader() {\n\tif rf.state != Candidate {\n\t\treturn\n\t}\n\trf.state = Leader\n\trf.nextIndex = make([]int, len(rf.peers))\n\trf.matchIndex = make([]int, len(rf.peers))\n\n\tfor i := range rf.nextIndex {\n\t\trf.nextIndex[i] = rf.GetLastLogIndex() + 1\n\t}\n}", "func LeaderWatcher() {\n\t//initial check\n\tresp, err := kapi.Get(context.Background(), \"/leader\", nil)\n\tif err != nil {\n\t\tclierr := err.(client.Error)\n\t\tlog.Println(clierr.Code)\n\t\tSetLeader()\n\t} else {\n\t\tLeader = resp.Node.Value\n\t}\n\n\t//keep watching for changes\n\twatcher := kapi.Watcher(\"/leader\", nil)\n\tfor {\n\t\tresp, err := watcher.Next(context.Background())\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t}\n\n\t\tif resp.Action == \"expire\" {\n\t\t\tSetLeader()\n\t\t} else {\n\t\t\tLeader = resp.Node.Value\n\t\t\tlog.Printf(\"Current Leader: %s\\n\", Leader)\n\t\t}\n\t}\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 (this *RaftNode) whenLeaderChanged(funcs ...func(isLeader bool) error) {\n\tfor isLeader := range this.raft.LeaderCh() {\n\t\twg := new(sync.WaitGroup)\n\t\twg.Add(len(funcs))\n\t\tfor _, f := range funcs {\n\t\t\tgo func(f func(isLeader bool) error) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tif err := f(isLeader); err != nil {\n\t\t\t\t\tthis.log.Infof(\"[WARN] server: error while executing function when leader changed: %v\", err)\n\t\t\t\t}\n\t\t\t}(f)\n\t\t}\n\t\twg.Wait()\n\t}\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.status == Leader\n\n\t// Your code here (2B).\n\n\tif !isLeader {\n\t\treturn index, term, isLeader\n\t}\n\tindex = rf.getLastIndex() + 1\n\trf.logs = append(rf.logs, LogEntry{Index: index, Term: term, Command: command})\n\trf.sendAllAppendEntriesOrInstallSnapshot() // broadcast new log to followers\n\trf.persist()\n\tAssertF(rf.getOffsetFromIndex(index) < len(rf.logs), \"index=%d, len(rf.logs)=%d, rf.snapshotIndex=%d\", index, len(rf.logs), rf.snapshotIndex)\n\tRaftInfo(\"New entry appended to leader's log: %v\", rf, rf.logs[rf.getOffsetFromIndex(index)])\n\n\treturn index, term, isLeader\n}", "func (a *RPC) AppendRPC(args *AppendRPCArgs, reply *AppendRPCReply) error {\n\t//raft.ElectionTimer_ch <- args.LeaderId //TODO\n\tr.ResetTimer() // Reset timer for election \n\tmutex.Lock() \t \n\tr.ResetTimer()\n var logIndex int \n if len(r.Log) > 0 { // If Log is not emtpy.. Initialised Log intex to last heighest log index\n \tlogIndex =len(r.Log)-1\n }else{ \n \tlogIndex =0 // Else Log index is 0\n }\n //fmt.Println(\"LogInedx \",logIndex,\" PrevLogIndex \",args.PrevLogIndex)\n\tif len(args.Entry.Command)!=0{ // If This request has actual logentry to append, else it is heartbeat. \n\t\t\n\t\tr.IsLeader=2 \t\t\t\t // Fall back to Follower state \n\t\tr.LeaderId=args.LeaderId\t // Update to current Leader id \n\t\tr.VotedFor=-1 \t\t\t // Election is over, No need to remember whome u voted for. \n\t\t\t\t\t\t\t\t\t// Thank god... Leader will keep remembering you periodaically :)\n \n\t\t \t if(args.Term < r.CurrentTerm) { // If this logentry has came from Previous Term.. Just Reject it. \n\t\t \treply.Reply=false\n\t\t } else if (logIndex <args.PrevLogIndex) { // log lagging behind, \n\t\t \treply.Reply=false // Set appened to false and \n\t\t reply.NextIndex=logIndex+1 // Set next expected log entry to Heighet log Index +1\n\t\t reply.MatchIndex=-1 \n\t\t r.CurrentTerm=args.Term\t\n\t\t } else if (logIndex > args.PrevLogIndex){ // log is ahead \n\t\t \t if (r.Log[args.PrevLogIndex].Term != args.PrevLogTerm) { // If previous log term does matches with leaders Previous log term \n\t\t \t \t\t\treply.Reply=false \n\t\t reply.NextIndex=args.PrevLogIndex // Set expected next log index to previous to do check matching\n\t\t \treply.MatchIndex = -1\n\t\t \tr.CurrentTerm=args.Term\t\n\t\t } else{ \t\t\t\t\t\t\t\t\t\t// Else Terms is matching, overwrite with log with new entry\n\t\t \t\tr.Log[args.PrevLogIndex+1]=args.Entry \n\t\t\t\t\t\t\treply.Reply=true\n\t\t \treply.MatchIndex=args.PrevLogIndex+1 // Match Index is set to added entry \n\t\t \treply.NextIndex=args.PrevLogIndex+2 // Expected Entry is next log entry after added entry\n\t\t \tr.CurrentTerm=args.Term\t\n\t\t \t//fmt.Println(\"Calling commit in logIndex>PrevLogIndex\")\n\t\t \tCommitCh <- CommitI_LogI{args.LeaderCommit,args.PrevLogIndex+1} // Send Commit index to commitCh to commit log entries, Commit only till newly added aentry\n\t\t }\n\t\t }else if(logIndex == args.PrevLogIndex) { // log is at same space\n\t\t \tif logIndex!=0 && (r.Log[logIndex].Term != args.PrevLogTerm) { // if log is not emtpy, and previous log tersm is matching\n\t\t reply.Reply=false \t\t\t\t\t\t\t\t\t// Reject the log entry \n\t\t reply.NextIndex=args.PrevLogIndex \n\t\t reply.MatchIndex = -1\n\t\t r.CurrentTerm=args.Term\t\n\t\t } else if len(r.Log)==0 && args.Entry.SequenceNumber==0{ // If log is empty and Recieved log entry index is 0, Add Entry\n\t\t \t\t\tr.Log=append(r.Log,args.Entry) \t\n\t\t \t\treply.Reply=true\n\t\t \t\treply.NextIndex=len(r.Log) \t\t\t\t\n\t\t \t\treply.MatchIndex=len(r.Log)-1\n\t\t \t\tr.CurrentTerm=args.Term\t\n\t\t \t\t//fmt.Println(\"Calling commit in logIndex=PrevLogIndex\")\n\t\t \t\tCommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }else if len(r.Log)!=args.Entry.SequenceNumber{ // If log is empty and Recieved log entry index is not 0, Missmatch, Reject\n\t\t \t\t \t//r.Log=append(r.Log,args.Entry)\n\t\t \t\treply.Reply=false\n\t\t \t\treply.NextIndex=len(r.Log)\n\t\t \t\treply.MatchIndex=-1\n\t\t \t\tr.CurrentTerm=args.Term\t\n\t\t \t\t//fmt.Println(\"Calling commit in logIndex=PrevLogIndex\")\n\t\t \t\t//CommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }else {\t\t\t\t\t\t\t\t\t\t\t// Previous log is matched , and this is new entry, add it to last of log\n\t\t \t\t\tr.Log=append(r.Log,args.Entry)\n\t\t \t\treply.Reply=true\n\t\t \t\treply.NextIndex=len(r.Log)\n\t\t \t\treply.MatchIndex=len(r.Log)-1\n\t\t \t\tr.CurrentTerm=args.Term\t\n\t\t \t\t//fmt.Println(\"Calling commit in logIndex=PrevLogIndex\")\n\t\t \t\tCommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }\n\t\t }\n\t\t /* if len (args.Entry.Command)!=0{\n\t\t\t\tfmt.Println(\"Received append rpc for\",r.Id ,\" From \",args.LeaderId, \" Log size is \",logIndex, \" == \",args.PrevLogIndex,\" < \", args.Entry.SequenceNumber ,\" Commitindex \",r.CommitIndex,\" < \",args.LeaderCommit, \"added \",reply.Reply)\n\t\t\t}*/\n\tr.ResetTimer() // This is For precautionaru measure, as system was slow and it was taking more time, leading to expiry of timer\n\t\t\t\t\t// Before replying \t\n\t}else\n\t{\n\t\t/*\n\t\tThis part is same as above but only without actually aadding entries to log. Next index and match index is updated.\n\t\tand CommitCh is feed with commit Index entries\n\t\t*/\n\t\t//fmt.Println(\"Heart Beat recieved \",r.Id,\" \",\"LogInedx \" , len(r.Log)-1,\" PrevLogIndex \",args.PrevLogIndex)\n\t\t//fmt.Println(\"LogInedx \",logIndex,\" PrevLogIndex \",args.PrevLogIndex)\n\t\t if(r.CurrentTerm <= args.Term) { \n\t\t\t\tr.IsLeader=2\n\t\t\t\tr.LeaderId=args.LeaderId\t\n\t\t\t\tr.VotedFor=-1\n\t\t\t\tr.CurrentTerm=args.Term\t\n\t\t\t\tif(logIndex == args.PrevLogIndex && len(r.Log)==0){\n\t\t\t\t\treply.NextIndex=0\n\t\t\t\t\treply.MatchIndex=-1\n\t\t\t\t\t//fmt.Println(\"HeartBeat Recieved logIndex == args.PrevLogIndex && len(r.Log)==0\") \n\t\t\t\t}else if (logIndex <args.PrevLogIndex){\n\t\t\t\t\treply.NextIndex=logIndex+1\n\t\t\t\t\treply.MatchIndex=-1\n\t\t\t\t\t//fmt.Println(\"HeartBeat Recieved logIndex <args.PrevLogIndex\") \n\t\t\t\t}else if (logIndex >args.PrevLogIndex){\n\t\t\t\t\tif (r.Log[args.PrevLogIndex].Term != args.PrevLogTerm) {\n\t\t\t\t\t\treply.Reply=false \n\t\t reply.NextIndex=-1\n\t\t reply.MatchIndex = -1\n\t\t\t\t\t}else{\n\t\t\t\t\t\treply.Reply=true\n\t\t reply.MatchIndex=args.PrevLogIndex\n\t\t reply.NextIndex=args.PrevLogIndex+1\n\t\t CommitCh <- CommitI_LogI{args.LeaderCommit,args.PrevLogIndex+1}\n\t\t\t\t\t}\n\t\t\t\t}else if(logIndex == args.PrevLogIndex) {\n\t\t\t\t\t\tif logIndex!=0 && (r.Log[logIndex].Term != args.PrevLogTerm) {\n\t\t\t\t\t\t\t reply.Reply=false\n\t\t reply.NextIndex=-1\n\t\t reply.MatchIndex = -1\n\n\t\t }else{\n\t\t \treply.Reply=true\n\t\t reply.NextIndex=args.PrevLogIndex+1\n\t\t reply.MatchIndex=args.PrevLogIndex\n\t\t CommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }\n\t\t\t\t\t}\n\t\t\t}\n\tr.ResetTimer()\n\t}\n mutex.Unlock()\n\treturn nil\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 *Raft) ClientListener(listener net.Conn) {\n\t\n\tcommand, rem := \"\", \"\"\n\tdefer listener.Close()\n\tfor {\n\t\t\tinput := make([]byte, 1000)\n\t\t\tlistener.SetDeadline(time.Now().Add(3 * time.Second)) // 3 second timeout\n\t\t\tlistener.Read(input)\n\t\t\tinput_ := string(Trim(input))\n\t\t\t\n\t\t\tif len(input_) == 0 { continue }\t\t// If this is not the leader\n\t\t\t\n\t\t\tif r.id != r.clusterConfig.LeaderId {\n\t\t\t\tleader := r.GetServer(r.clusterConfig.LeaderId)\n\t\t\t\traft.Output_ch <- raft.String_Conn{\"ERR_REDIRECT \" + leader.Hostname + \" \" + strconv.Itoa(leader.ClientPort), listener}\n\t\t\t\tinput = input[:0]\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcommand, rem = GetCommand(rem + input_)\n\t\t\t// For multiple commands in the byte stream\n\n\t\t\tfor {\n\t\t\t\t\tif command != \"\" {\n\t\t\t\t\t\tif command[0:3] == \"get\" {\n\t\t\t\t\t\t\traft.Input_ch <- raft.String_Conn{command, listener}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcommandbytes := []byte(command)\n\t\t\t\t\t\t\tl, _ := r.log.Append(commandbytes) \t\t\t// Append in its own log\n\t\t\t\t\t\t\tlogentry := raft.LogEntry(l)\n\t\t\t\t\t\t\traft.Append_ch <- logentry //call appendcalller() \n\t\t\t\t\t\t\tvar append_no int \n\t\t\t\t\t\t\tappend_no = <-raft.No_Append\t\t\t\t\t//recives no of server on which log relicated\n\t\t\t\t\t\t//\tlog.Println(r.id,\" No_Append: \",append_no)\n\t\t\t\t\t\t\tif append_no > (N+1)/2{ \n\t\t\t\t\t\t\t\tr.log.Commit(r.GetServer(r.id).LsnToCommit, listener) //commit in its own log\n \t\t\t\t\t\t\t\traft.Commit_ch <- logentry.Lsn()\n\t\t\t\t\t\t }\n\t\t\t\t\t\t}//ends inner if\n\t\t\t\t\t} else { break \t} //end of outer if\n\n\t\t\t\t\tcommand, rem = GetCommand(rem)\n\t\t\t\t}//end of for\n\t}//end of infinite for\n}", "func (c *Client) isLearner(memberID uint64) (bool, error) {\n\tresp, err := c.listMembers()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, member := range resp.Members {\n\t\tif member.ID == memberID && member.IsLearner {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}", "func (r *Raft) becomeLeader() {\n\t// NOTE: Leader should propose a noop entry on its term\n\tr.State = StateLeader\n\tr.Vote = 0\n\tfor p, _ := range r.Prs {\n\t\tif p == r.id {\n\t\t\tcontinue\n\t\t}\n\t\tr.Prs[p].Match = 0\n\t\tr.Prs[p].Next = r.RaftLog.LastIndex() + 1\n\t}\n\t//r.initializeProgress()\n\n\t// send heartbeat\n\t//m := pb.Message{MsgType: pb.MessageType_MsgBeat, From: r.id, To: r.id}\n\t//r.sendMsgLocally(m)\n\t// send noop message\n\tr.sendInitialAppend()\n\tr.electionElapsed = 0\n}", "func (r *warmupRunnable) NeedLeaderElection() bool {\n\treturn true\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 (rf *Raft) correctPrevLogEntry(PrevLogIndex int, PrevLogTerm int) bool {\n\t// if no log, have to check lastIncludedIndex and lastIncludedTerm\n\tif len(rf.log) == 0 {\n\t\treturn PrevLogIndex == rf.lastIncludedIndex && PrevLogTerm == rf.lastIncludedTerm\n\t}\n\tprevRaftLogIndex := rf.getTrimmedLogIndex(PrevLogIndex)\n\t// the leader nextIndex is ahead of us\n\tif prevRaftLogIndex >= len(rf.log) {\n\t\treturn false\n\t}\n\n\t// NOTE:\n\t// if prevRaftLogIndex == -1 ... this should never happen?\n\t// We know length of rf.log > 0 (see where this function is called), so this\n\t// would only occur if leader nextIndex for this server preceded our snapshot;\n\t// but on leader election, nextIndex is set to the end of the leader log,\n\t// including all committed entries.\n\t// However, our snapshot includes AT MOST all committed entries,\n\t// so nextIndex should never precede it.\n\tif prevRaftLogIndex == -1 && len(rf.log) > 0 {\n\t\trf.Log(LogInfo, \"AppendEntries call has PrevLogIndex preceding our log!\")\n\t\treturn true\n\t}\n\n\t// we must have an entry at the given index (see above note for why\n\t// PrevLogIndex will never precede our snapshot), so just return a bool for whether\n\t// or not the term of this entry is correct\n\treturn rf.log[prevRaftLogIndex].Term == PrevLogTerm\n\n}", "func (m *MonLeaderDetector) Leader() int {\n\t// TODO(student): Implement\n\tif len(m.alive) == 0 {\n\t\tm.Allsuspected = true\n\t\treturn UnknownID\n\t}\n\n\tleader := -1\n\tfor key := range m.alive { //elect the node with highest id as a leader\n\t\tif key > leader {\n\t\t\tleader = key\n\t\t}\n\t}\n\n\tif leader < 0 { // if all suspected\n\t\treturn UnknownID\n\t}\n\n\tif m.CurrentLeader != leader { // if the leader changed\n\t\tm.LeaderChange = true\n\t} else {\n\t\tm.LeaderChange = false\n\t}\n\n\tm.CurrentLeader = leader //save the current elected leader\n\treturn leader\n\n}", "func (le *LeaderElector) PollLeader() {\n\t//Ping leader repeatdly every 15sec, if hasnt responded for 2 consequent pings, init LeaderChange\n\t//The frequency can be changed in paxos.config.json file.\n\tif le.LeaderSID != NO_LEADER && le.LeaderSID != le.ThisServer.SID {\n\t\talive := false\n\t\tstillLeader := false\n\t\tfor i := 0; i < 2; i++ {\n\t\t\tok := call(le.CurrentLeader, \"LeaderElector.Alive\", new(interface{}), &stillLeader)\n\t\t\tif ok && stillLeader {\n\t\t\t\talive = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !alive {\n\t\t\tdebug(\"[*] Info : LeaderElector : Leader with SID : %d && address : %s Suspected To have Failed. Starting Leader Election.\",\n\t\t\t\tle.LeaderSID, le.CurrentLeader)\n\t\t\tle.initElection()\n\t\t}\n\t} else if le.LeaderSID == NO_LEADER && !le.adjustingLead {\n\t\tle.initElection()\n\t}\n\t//Wait for 15 or specified secs\n\t<-time.After(le.PollLeaderFreq * time.Second)\n\tle.PollLeader()\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 *raftServer) lead() {\n\ts.hbTimeout.Reset(time.Duration(s.config.HbTimeoutInMillis) * time.Millisecond)\n\t// launch a goroutine to handle followersFormatInt(\n\tfollower := s.followers()\n\tnextIndex, matchIndex, aeToken := s.initLeader(follower)\n\ts.leaderId.Set(s.server.Pid())\n\n\tgo s.handleFollowers(follower, nextIndex, matchIndex, aeToken)\n\tgo s.updateLeaderCommitIndex(follower, matchIndex)\n\tfor s.State() == LEADER {\n\t\tselect {\n\t\tcase <-s.hbTimeout.C:\n\t\t\t//s.writeToLog(\"Sending hearbeats\")\n\t\t\ts.sendHeartBeat()\n\t\t\ts.hbTimeout.Reset(time.Duration(s.config.HbTimeoutInMillis) * time.Millisecond)\n\t\tcase msg := <-s.outbox:\n\t\t\t// received message from state machine\n\t\t\ts.writeToLog(\"Received message from state machine layer\")\n\t\t\ts.localLog.Append(&raft.LogEntry{Term: s.Term(), Data: msg})\n\t\tcase e := <-s.server.Inbox():\n\t\t\traftMsg := e.Msg\n\t\t\tif ae, ok := raftMsg.(AppendEntry); ok { // AppendEntry\n\t\t\t\ts.handleAppendEntry(e.Pid, &ae)\n\t\t\t} else if rv, ok := raftMsg.(RequestVote); ok { // RequestVote\n\t\t\t\ts.handleRequestVote(e.Pid, &rv)\n\t\t\t} else if entryReply, ok := raftMsg.(EntryReply); ok {\n\t\t\t\tn, found := nextIndex.Get(e.Pid)\n\t\t\t\tvar m int64\n\t\t\t\tif !found {\n\t\t\t\t\tpanic(\"Next index not found for follower \" + strconv.Itoa(e.Pid))\n\t\t\t\t} else {\n\t\t\t\t\tm, found = matchIndex.Get(e.Pid)\n\t\t\t\t\tif !found {\n\t\t\t\t\t\tpanic(\"Match index not found for follower \" + strconv.Itoa(e.Pid))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif entryReply.Success {\n\t\t\t\t\t// update nextIndex for follower\n\t\t\t\t\tif entryReply.LogIndex != HEARTBEAT {\n\t\t\t\t\t\taeToken.Set(e.Pid, 1)\n\t\t\t\t\t\tnextIndex.Set(e.Pid, max(n+1, entryReply.LogIndex+1))\n\t\t\t\t\t\tmatchIndex.Set(e.Pid, max(m, entryReply.LogIndex))\n\t\t\t\t\t\t//s.writeToLog(\"Received confirmation from \" + strconv.Itoa(e.Pid))\n\t\t\t\t\t}\n\t\t\t\t} else if s.Term() >= entryReply.Term {\n\t\t\t\t\tnextIndex.Set(e.Pid, n-1)\n\t\t\t\t} else {\n\t\t\t\t\ts.setState(FOLLOWER)\n\t\t\t\t\t// There are no other goroutines active\n\t\t\t\t\t// at this point which modify term\n\t\t\t\t\tif s.Term() >= entryReply.Term {\n\t\t\t\t\t\tpanic(\"Follower replied false even when Leader's term is not smaller\")\n\t\t\t\t\t}\n\t\t\t\t\ts.setTerm(entryReply.Term)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ts.hbTimeout.Stop()\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 (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 (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 HasLeaders(topics []TopicInfo) bool {\n\tfor _, topic := range topics {\n\t\tfor _, partition := range topic.Partitions {\n\t\t\tif partition.Leader > 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}", "func (a *RPC) VoteForLeader(args *RequestVoteRPCArgs,reply *bool) error{\n\t//r.ResetTimer()\n \t//fmt.Println(\"received Vote request parameter \",(*args).CandidateId,\" \",(*args).Term,\" \",(*args).LastLogTerm,\" \",(*args).LastLogIndex)\n \t//if len(r.Log)>1{\n \t//\tfmt.Println(\"Vote Request folloer parameter \",r.Id,\" \", r.CurrentTerm,\" \",r.Log[len(r.Log)-1].Term ,\" \",len(r.Log)-1)\n \t//}\n\tif r.IsLeader==2 { // if this server is follower\n\t\t//r.ResetTimer() //TODO\n\t\tif r.CurrentTerm > args.Term || r.VotedFor >-1 { // if follower has updated Term or already voted for other candidate in same term , reply nagative\n\t\t\t*reply = false\n\t\t} else if r.VotedFor== -1{ // if follower has not voted for anyone in current Term \n\t\t\tlastIndex:= len(r.Log) \n\t\t\tif lastIndex > 0 && args.LastLogIndex >0{ // if Candiate log and this server log is not empty. \n\t\t\t\tif r.Log[lastIndex-1].Term > args.LastLogTerm { // and Term of last log in follower is updated than Candidate, reject vote\n *reply=false\n }else if r.Log[lastIndex-1].Term == args.LastLogTerm{ // else if Terms of Follower and candidate is same\n \tif (lastIndex-1) >args.LastLogIndex { // but follower log is more updated, reject vote\n \t\t*reply = false\n \t} else {\n \t\t\t*reply = true // If last log terms is match and followe log is sync with candiate, vote for candidate\n \t\t}\n }else{ // if last log term is not updated and Term does not match, \n \t \t\t*reply=true//means follower is lagging behind candiate in log entries, vote for candidate\n \t\t}\n \t\n\t\t\t} else if lastIndex >args.LastLogIndex { // either of them is Zero\n\t\t\t\t*reply = false // if Follower has entries in Log, its more updated, reject vote\n\t\t\t}else{\n\t\t\t\t\t*reply = true // else Vote for candiate\n\t\t\t\t}\n\t\t}else{\n\t\t\t*reply=false\n\t\t}\n\t}else{\n\t\t*reply = false // This server is already a leader or candiate, reject vote\n\t}\n\n\tif(*reply) {\n r.VotedFor=args.CandidateId // Set Voted for to candiate Id if this server has voted positive\n }\n\t/*if(*reply) {\n\t\tfmt.Println(\"Follower \",r.Id,\" Voted for \",r.VotedFor)\n\t}else{\n\t\tfmt.Println(\"Follower \",r.Id,\" rejected vote for \",args.CandidateId)\n\t}*/\n\treturn nil\n}", "func (p *plugin) cmdLog(w irc.ResponseWriter, r *irc.Request, params cmd.ParamList) {\n\tif params.Len() > 0 {\n\t\tp.profile.SetLogging(params.Bool(0))\n\t}\n\n\tif p.profile.Logging() {\n\t\tproto.PrivMsg(w, r.SenderName, TextLogEnabled)\n\t} else {\n\t\tproto.PrivMsg(w, r.SenderName, TextLogDisabled)\n\t}\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\tfmt.Println(\"start cmd \", command)\n\t//mcommand := reflect.ValueOf(command)\n\tif rf.state != leader {\n\t\treturn index, term, !isLeader\n\t}\n\n\t/*here comes the leader*/\n\tfmt.Println(\"leader found!\")\n\tnewEntry := new(Entry)\n\tnewEntry.Term = rf.currentTerm\n\tnewEntry.Command = command\n\trf.mu.Lock()\n\tindex = len(rf.log)\n\trf.log = append(rf.log, *newEntry)\n\tterm = rf.currentTerm\n\trf.eAppended<-true\n\trf.mu.Unlock()\n\treturn index, term, isLeader\n}", "func (r *Raft) becomeLeader() {\n\n\tr.State = StateLeader\n\tr.heartbeatElapsed = 0\n\tr.Vote = None\n\n\t// init prs\n\tprs := make(map[uint64]*Progress)\n\tfor _, nodeId := range r.nodes {\n\t\tprs[nodeId] = &Progress{\n\t\t\tMatch: r.RaftLog.LastIndex(),\n\t\t\tNext: r.RaftLog.LastIndex() + 1,\n\t\t}\n\t}\n\tr.Prs = prs\n\n\t// NOTE: Leader should propose a noop entry on its term\n\tr.addNoopEntryToLog()\n\tif len(r.nodes) > 1 {\n\t\tr.sendMsgToAll(r.sendAppendWrap)\n\t} else {\n\t\tr.updateCommitted()\n\t}\n}", "func (r Replicator) Get_Isleader() bool {\n\treturn r.leader\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\t//rf.readPersist(rf.persister.ReadRaftState())\n\n\trf.mu.Lock()\n\tif isLeader = rf.raftState == Leader; isLeader {\n\t\tterm = rf.currentTerm\n\t\tindex = rf.addLastIncludedIndex(len(rf.log))\n\t\trf.log = append(rf.log, LogEntries{rf.currentTerm, command})\n\t\trf.matchIndex[rf.me] = rf.addLastIncludedIndex(len(rf.log) - 1)\n\t}\n\trf.persist()\n\trf.mu.Unlock()\n\t//leader commit vs commitIndex\n\treturn index, term, isLeader\n}", "func (m *MsgReject) Leader(state interfaces.IState) bool {\n\tswitch state.GetNetworkNumber() {\n\tcase 0: // Main Network\n\t\tpanic(\"Not implemented yet\")\n\tcase 1: // Test Network\n\t\tpanic(\"Not implemented yet\")\n\tcase 2: // Local Network\n\t\tpanic(\"Not implemented yet\")\n\tdefault:\n\t\tpanic(\"Not implemented yet\")\n\t}\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 (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 (r *raft) leaderHandler(evt interface{}) {\n\tswitch e := evt.(type) {\n\tcase *RPCEvt:\n\t\tswitch o := e.o.(type) {\n\t\tcase *AppendEntriesResults:\n\t\t\tif o.Term > r.currentTerm {\n\t\t\t\tr.state = FollowerState\n\t\t\t\tr.votedFor = e.srcId\n\t\t\t\tr.currentTerm = o.Term\n\t\t\t\tr.cleanVoteGranteds()\n\t\t\t\tr.cleanIndexAryOnLeader()\n\t\t\t\tr.resetElectionTimeout()\n\t\t\t\tr.resetHeatbeatTimeout()\n\t\t\t\tr.saveStates()\n\t\t\t} else if !o.Success { //o.Term==r.currentTerm\n\t\t\t\tif e.srcId > -1 && e.srcId < r.nodes {\n\t\t\t\t\tif o.Term == r.currentTerm {\n\t\t\t\t\t\tr.nextIndex[e.srcId] -= 1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// retry\n\t\t\t\tr.sndAppendEntries()\n\t\t\t} else {\n\t\t\t\tif e.srcId > -1 && e.srcId < r.nodes {\n\t\t\t\t\t// for we just append on entry per time\n\t\t\t\t\tlastIndex, _ := r.log.LastIndex()\n\t\t\t\t\t//\n\t\t\t\t\tif lastIndex >= r.nextIndex[e.srcId] {\n\t\t\t\t\t\tr.matchIndex[e.srcId] = r.nextIndex[e.srcId]\n\t\t\t\t\t\tr.nextIndex[e.srcId] += 1\n\t\t\t\t\t\tr.updateCommitIndex()\n\t\t\t\t\t\tr.apply()\n\t\t\t\t\t\t// retry\n\t\t\t\t\t\tr.sndAppendEntries()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase *AppendEntries:\n\t\t\tif o.Term > r.currentTerm {\n\t\t\t\t// TODO\n\t\t\t\tr.state = FollowerState\n\t\t\t\tr.cleanVoteGranteds()\n\t\t\t\tr.cleanIndexAryOnLeader()\n\t\t\t\tr.resetElectionTimeout()\n\t\t\t\tr.resetHeatbeatTimeout()\n\t\t\t\tr.saveStates()\n\t\t\t\tr.appendEntries(o)\n\t\t\t}\n\t\tcase *RequestVote:\n\t\t\tif o.Term > r.currentTerm {\n\t\t\t\tr.state = FollowerState\n\t\t\t\tr.cleanVoteGranteds()\n\t\t\t\tr.cleanIndexAryOnLeader()\n\t\t\t\tr.resetElectionTimeout()\n\t\t\t\tr.resetHeatbeatTimeout()\n\t\t\t\tr.saveStates()\n\t\t\t\tr.votefor(o)\n\t\t\t}\n\t\tdefault:\n\t\t}\n\tcase BaseTimeoutEvt:\n\t\tr.heartbeatTimeoutCnt += 1\n\t\tif r.isHeatbeatTimeout() {\n\t\t\tr.resetHeatbeatTimeout()\n\t\t\tr.sndAppendEntries()\n\t\t}\n\n\tdefault:\n\t}\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 (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 (le *LeaderElector) initElection() {\n\thighestRank := false\n\t//Poll servers with higher rank\n\tfor SID, serv := range le.ThisServer.GroupInfoPtr.GroupMembers {\n\t\tif SID < le.ThisServer.SID {\n\t\t\t//Has Higher rank, SID 0 > SID 1 > SID 2 ....\n\t\t\tok := call(serv, \"LeaderElector.ChangeLeader\", new(interface{}), &highestRank)\n\t\t\tif ok && highestRank == true {\n\t\t\t\t//Theres a server with higher rank, let go\n\t\t\t\tdebug(\"[*] Info : LeaderElector : There is Another Server - %s- With Higher Rank.Backing off. \", serv)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\t//No server with higher rank, become leader\n\tle.becomeLeader()\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 Check(level int32) bool {\n\tvar lvl zapcore.Level\n\tif level < 5 {\n\t\tlvl = zapcore.InfoLevel\n\t} else {\n\t\tlvl = zapcore.DebugLevel\n\t}\n\tcheckEntry := getLogger().Check(lvl, \"\")\n\treturn checkEntry != nil\n}", "func (m *MsgPing) LeaderExecute(state interfaces.IState) error {\n\treturn nil\n}", "func (vs *VolMgrServer) startHealthCheck() {\n\ttd := time.NewTicker(time.Second * 1)\n\tgo func() {\n\t\tfor range td.C {\n\t\t\tif vs.RaftServer.IsLeader(1) {\n\t\t\t\tvs.DetectDataNodes()\n\t\t\t}\n\t\t}\n\t}()\n\n\ttm := time.NewTicker(time.Second * 1)\n\tgo func() {\n\t\tfor range tm.C {\n\t\t\tif vs.RaftServer.IsLeader(1) {\n\t\t\t\tvs.DetectMetaNodes()\n\t\t\t}\n\t\t}\n\t}()\n}", "func ExampleLeader() {\n\t// Init server\n\tsrv := redeo.NewServer(nil)\n\n\t// Start raft\n\trft, tsp, err := startRaft(srv)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer rft.Shutdown()\n\tdefer tsp.Close()\n\n\t// Report leader\n\tsrv.Handle(\"raftleader\", redeoraft.Leader(rft))\n\n\t// $ redis-cli -p 9736 raftleader\n\t// \"10.0.0.1:9736\"\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := int32(-1)\n\tisLeader := true\n\n\t_, isLeader = rf.GetState()\n\tif !isLeader {\n\t\treturn index, int(term), false\n\t}\n\n\t// TODO: take concurrent out-of-order commit to account\n\trf.stateLock.Lock()\n\tpreLogIndex := int32(0)\n\tpreLogTerm := int32(0)\n\tif len(rf.log) > 1 {\n\t\tpreLogIndex = int32(len(rf.log) - 1)\n\t\tpreLogTerm = rf.log[preLogIndex].Term\n\t}\n\tterm = rf.currentTerm\n\tnewEntry := LogEntry{\n\t\tCommand: command,\n\t\tTerm: term,\n\t}\n\trf.log = append(rf.log, newEntry)\n\t//rf.persist()\n\trf.matchIndex[rf.me] = int32(len(rf.log) - 1)\n\tDPrintf(\"[me : %v]start command: %v at index: %v\", rf.me, command, int32(len(rf.log) - 1))\n\tentries := []LogEntry{newEntry}\n\tappendReq := AppendEntriesRequest{\n\t\tTerm: rf.currentTerm,\n\t\tLeaderId: rf.me,\n\t\tPrevLogIndex: preLogIndex, // change\n\t\tPrevLogTerm: preLogTerm, // change\n\t\tEntries: entries,\n\t\tLeaderCommit: rf.commitIndex,\n\t}\n\trf.stateLock.Unlock()\n\n\tquorumAck := rf.quorumSendAppendEntries(appendReq)\n\tif !quorumAck {\n\t\treturn int(preLogIndex) + 1, int(term), true\n\t}\n\n\t// Your code here (2B).\n\treturn int(preLogIndex) + 1, int(term), isLeader\n}" ]
[ "0.65966475", "0.65467894", "0.63243586", "0.60938084", "0.6083241", "0.6064377", "0.5992619", "0.5986434", "0.5889797", "0.5841409", "0.5832994", "0.58241165", "0.5678572", "0.56745255", "0.56603634", "0.5652244", "0.56418204", "0.5630083", "0.5621441", "0.560337", "0.5602786", "0.5561111", "0.5552577", "0.55500764", "0.5538116", "0.551718", "0.5507243", "0.5497193", "0.54868805", "0.5471935", "0.544678", "0.54291", "0.5396297", "0.5394754", "0.53910166", "0.53833646", "0.53813255", "0.5378711", "0.5366468", "0.53661877", "0.5344312", "0.53342", "0.5323931", "0.53165907", "0.53163874", "0.52964616", "0.52867466", "0.5274063", "0.5270256", "0.52683973", "0.5264937", "0.5256802", "0.525084", "0.5242069", "0.52241856", "0.5199379", "0.51970196", "0.51915836", "0.5191574", "0.5184964", "0.517986", "0.5151909", "0.5140493", "0.5128117", "0.51221645", "0.51056176", "0.51020604", "0.50740916", "0.5064959", "0.50525135", "0.50474936", "0.5040895", "0.5027448", "0.50239456", "0.5000746", "0.5000051", "0.49947768", "0.49933168", "0.4990564", "0.4981425", "0.49800882", "0.49731913", "0.4969718", "0.49626192", "0.49612123", "0.4957851", "0.49399945", "0.49355236", "0.492099", "0.49204692", "0.4917273", "0.4914404", "0.49084345", "0.49065545", "0.49012417", "0.4898753", "0.48934686", "0.48891416", "0.48849127", "0.48848367" ]
0.61715776
3