query
stringlengths 8
6.75k
| document
stringlengths 9
1.89M
| negatives
listlengths 19
19
| metadata
dict |
|---|---|---|---|
GetVersion get current config version.
|
func (s serverConfigV14) GetVersion() string {
serverConfigMu.RLock()
defer serverConfigMu.RUnlock()
return s.Version
}
|
[
"func (cfg *Config) GetVersion() int {\n\treturn cfg.Version\n}",
"func (d config) Version() string {\n\tst := structs.New(d.data)\n\n\tf, ok := st.FieldOk(\"Version\")\n\tif !ok {\n\t\treturn \"\"\n\t}\n\n\tval := f.Value()\n\tver, ok := val.(string)\n\tif ok {\n\t\treturn ver\n\t}\n\treturn \"\"\n}",
"func Get() string {\n\treturn version\n}",
"func GetVersion() string {\n\treturn version\n}",
"func GetVersion() string {\n\treturn version.VERSIONSTR\n}",
"func GetVersion() string {\n\treturn getEnv(\"ENM_API_VERSION\", \"v1\")\n}",
"func GetVersion() string {\n\tif len(Version) == 0 {\n\t\treturn \"dev\"\n\t}\n\treturn Version\n}",
"func Get() string {\n\tvar version string\n\tversion = \"v1.3.4\"\n\treturn version\n}",
"func (this *NetServer) GetVersion() uint32 {\n\treturn this.base.GetVersion()\n}",
"func GetVersion() string {\n\treturn \"v\" + appVersion\n}",
"func (c *InjectionConfig) Version() string {\n\tif c.version == \"\" {\n\t\treturn defaultVersion\n\t}\n\n\treturn c.version\n}",
"func (c Client) GetVersion() (reply VersionInfo, err error) {\n\terr = c.Caller.Call(\"aria2.getVersion\", &reply)\n\treturn\n}",
"func GetVersion() string {\n\treturn binaryVersion\n}",
"func (o *AddonStatus) GetVersion() (value string, ok bool) {\n\tok = o != nil && o.bitmap_&64 != 0\n\tif ok {\n\t\tvalue = o.version\n\t}\n\treturn\n}",
"func Version() (v string) {\n\treturn version\n}",
"func (c *Client) GetVersion() (string, error) {\n\tvar version string\n\tvar statusResponse internal.StatusResponse\n\n\treq, err := http.NewRequest(http.MethodGet, c.baseURL+statusEndpoint, nil)\n\tif err != nil {\n\t\treturn version, fmt.Errorf(\"failed to build request for status endpoint - %s\", err.Error())\n\t}\n\treq.Header.Set(\"Accept\", \"application/xml\")\n\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn version, fmt.Errorf(\"failed to fetch backend version - %s\", err.Error())\n\t}\n\tdefer resp.Body.Close()\n\n\terr = json.NewDecoder(resp.Body).Decode(&statusResponse)\n\tif err != nil {\n\t\treturn version, fmt.Errorf(\"failed to fetch backend version - %s\", err.Error())\n\t}\n\n\treturn statusResponse.Version.Backend, nil\n}",
"func (p *DefaultPolicy) GetVersion() string {\n\treturn p.Version\n}",
"func (o CSIVXFlexOSSpecDriverOutput) ConfigVersion() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CSIVXFlexOSSpecDriver) string { return v.ConfigVersion }).(pulumi.StringOutput)\n}",
"func (k Keeper) GetCurrentVersion(ctx sdk.Context) uint64 {\n\treturn k.protocolKeeper.GetCurrentVersion(ctx)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetBrowser set if browser is enabled.
|
func (s *serverConfigV14) SetBrowser(v string) {
serverConfigMu.Lock()
defer serverConfigMu.Unlock()
// Set browser param
s.Browser = v
}
|
[
"func (m *UserSimulationEventInfo) SetBrowser(value *string)() {\n m.browser = value\n}",
"func (m *IosiPadOSWebClip) SetUseManagedBrowser(value *bool)() {\n err := m.GetBackingStore().Set(\"useManagedBrowser\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (ec *EventCreate) SetBrowser(b *Browser) *EventCreate {\n\treturn ec.SetBrowserID(b.ID)\n}",
"func (m *ManagedAppProtection) SetManagedBrowser(value *ManagedBrowserType)() {\n m.managedBrowser = value\n}",
"func (m *AndroidGeneralDeviceConfiguration) SetWebBrowserBlockJavaScript(value *bool)() {\n err := m.GetBackingStore().Set(\"webBrowserBlockJavaScript\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *AndroidGeneralDeviceConfiguration) SetWebBrowserBlockAutofill(value *bool)() {\n err := m.GetBackingStore().Set(\"webBrowserBlockAutofill\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (tick *ChainServer) AddBrowser(cate string, browser chainlib.CommonFunc) {\n\ttick.browser[cate] = browser\n}",
"func (m *AndroidGeneralDeviceConfiguration) SetWebBrowserBlockPopups(value *bool)() {\n err := m.GetBackingStore().Set(\"webBrowserBlockPopups\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *AndroidGeneralDeviceConfiguration) SetWebBrowserCookieSettings(value *WebBrowserCookieSettings)() {\n err := m.GetBackingStore().Set(\"webBrowserCookieSettings\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (s *Portal) SetBrowserType(v string) *Portal {\n\ts.BrowserType = &v\n\treturn s\n}",
"func (s *PortalSummary) SetBrowserType(v string) *PortalSummary {\n\ts.BrowserType = &v\n\treturn s\n}",
"func (m *ManagedAppProtection) SetManagedBrowserToOpenLinksRequired(value *bool)() {\n m.managedBrowserToOpenLinksRequired = value\n}",
"func (cli *MockCli) OpenBrowser(url string) error {\n\treturn nil\n}",
"func CanOpenBrowser() bool {\n\tif runtime.GOOS == \"windows\" || runtime.GOOS == \"darwin\" {\n\t\treturn true\n\t}\n\n\toutput, err := execCommand(\"xdg-settings\", \"get\", \"default-web-browser\").Output()\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif string(output) == \"\" {\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func (ec *EventCreate) SetBrowserID(id int) *EventCreate {\n\tec.mutation.SetBrowserID(id)\n\treturn ec\n}",
"func (bow *Browser) SetUserAgent(userAgent string) {\n\tbow.userAgent = userAgent\n}",
"func startBrowser(url string) bool {\n\t// try to start the browser\n\tvar args []string\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\targs = []string{\"open\"}\n\tcase \"windows\":\n\t\targs = []string{\"cmd\", \"/c\", \"start\"}\n\tdefault:\n\t\targs = []string{\"xdg-open\"}\n\t}\n\tcmd := exec.Command(args[0], append(args[1:], url)...)\n\treturn cmd.Start() == nil\n}",
"func OpenBrowser(url string) {\n\tif !strings.HasPrefix(url, \"http\") {\n\t\turl = \"http://\" + url\n\t}\n\n\tDefaultRunner.Run(cmdOpenBrowser[0], url)\n}",
"func IsBrowserName(name string) bool {\n\tname = strings.TrimSuffix(name, \"-\"+ExperimentalLabel)\n\treturn IsStableBrowserName(name)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
String returns a JSONformatted string representing the exported variables of all underlying machines. TODO(marius): aggregate values too?
|
func (v machineVars) String() string {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
g, ctx := errgroup.WithContext(ctx)
var (
mu sync.Mutex
vars = make(map[string]Expvars)
)
for _, m := range v.B.Machines() {
// Only propagate stats for machines we own, otherwise we can
// create stats loops.
if !m.Owned() {
continue
}
m := m
g.Go(func() error {
var mvars Expvars
if err := m.Call(ctx, "Supervisor.Expvars", struct{}{}, &mvars); err != nil {
log.Error.Printf("failed to retrieve variables for %s: %v", m.Addr, err)
return nil
}
mu.Lock()
vars[m.Addr] = mvars
mu.Unlock()
return nil
})
}
if err := g.Wait(); err != nil {
b, err2 := json.Marshal(err.Error())
if err2 != nil {
log.Error.Printf("machineVars marshal: %v", err2)
return `"error"`
}
return string(b)
}
b, err := json.Marshal(vars)
if err != nil {
log.Error.Printf("machineVars marshal: %v", err)
return `"error"`
}
return string(b)
}
|
[
"func (v varExporter) String() string {\n\tout := map[string]probeInfo{}\n\n\tv.p.mu.Lock()\n\tprobes := make([]*Probe, 0, len(v.p.probes))\n\tfor _, probe := range v.p.probes {\n\t\tprobes = append(probes, probe)\n\t}\n\tv.p.mu.Unlock()\n\n\tfor _, probe := range probes {\n\t\tprobe.mu.Lock()\n\t\tinf := probeInfo{\n\t\t\tLabels: probe.labels,\n\t\t\tStart: probe.start,\n\t\t\tEnd: probe.end,\n\t\t\tResult: probe.result,\n\t\t}\n\t\tif probe.end.After(probe.start) {\n\t\t\tinf.Latency = probe.end.Sub(probe.start).String()\n\t\t}\n\t\tout[probe.name] = inf\n\t\tprobe.mu.Unlock()\n\t}\n\n\tbs, err := json.Marshal(out)\n\tif err != nil {\n\t\treturn fmt.Sprintf(`{\"error\": %q}`, err)\n\t}\n\treturn string(bs)\n}",
"func (tm *TuringMachine) ToJSONString() string {\n\tvar jsonBuf, err = json.MarshalIndent(tm, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: Turing Machine JSON Marshal err: %v\\n\", err)\n\t}\n\treturn string(jsonBuf)\n}",
"func (r *Registry) String() string {\n\tout := make([]string, 0, len(r.nameToObject))\n\tfor name, object := range r.nameToObject {\n\t\tout = append(out, fmt.Sprintf(\"* %s:\\n%s\", name, object.serialization))\n\t}\n\treturn strings.Join(out, \"\\n\\n\")\n}",
"func (self *monitoringData) String() string {\n\tstr, _ := self.JSON()\n\treturn str\n}",
"func (h *Host) String() string {\n\t// Errors only occur for non-UTF8 characters in strings or unmarshalable types (which we don't have).\n\tb, _ := json.MarshalIndent(h, \"\", \" \")\n\treturn string(b)\n}",
"func (n *Network) to_json( ) ( jstr string ) {\n\tvar\tsep string = \"\"\n\n\tjstr = `{ \"netele\": [ `\n\n\tfor k := range n.switches {\n\t\tjstr += fmt.Sprintf( \"%s%s\", sep, n.switches[k].To_json( ) )\n\t\tsep = \",\"\n\t}\n\n\tjstr += \"] }\"\n\n\treturn\n}",
"func (i *Info) JSONString(indent bool) string {\n\treturn marshal.SafeJSON(i.ctx, gpuPrinter{i}, indent)\n}",
"func (h *Host) JSON() []byte {\n\tb, _ := json.MarshalIndent(h, \"\", \" \")\n\treturn b\n}",
"func (s *Switch) To_json( ) ( jstr string ) {\n\tvar sep = \"\"\n\n\tif s == nil {\n\t\tjstr = `{ id: \"null_switch\" }`\n\t\treturn\n\t}\n\n\tif s.lidx > 0 {\n\t\tjstr = fmt.Sprintf( `{ \"id\": %q, \"links\": [ `, *s.id )\n\n\t\tfor i := 0; i < s.lidx; i++ {\n\t\t\tjstr += fmt.Sprintf( \"%s%s\", sep, s.links[i].To_json() )\n\t\t\tsep = \",\"\n\t\t}\n\t\tjstr += \" ]\"\n\t} else {\n\t\tjstr = fmt.Sprintf( `{ \"id\": %q }`, *s.id )\n\t}\n\n\n\tif len( s.hosts ) > 0 {\n\t\tjstr += fmt.Sprintf( `, \"conn_hosts\": [ ` )\n\t\tsep = \"\"\n\t\tfor k := range s.hosts {\n\t\t\tif s.hosts[k] == true {\n\t\t\t\tvmid := \"unknown\"\n\t\t\t\tif s.hvmid[k] != nil {\n\t\t\t\t\tvmid = *s.hvmid[k]\n\t\t\t\t}\n\t\t\t\tjstr += fmt.Sprintf( `%s { \"host\": %q, \"port\": %d, \"vmid\": %q }`, sep, k, s.hport[k], vmid )\n\t\t\t\tsep = \",\"\n\t\t\t}\n\t\t}\n\t\tjstr += \" ]\"\n\t}\n\n\tjstr += \" }\"\n\treturn\n}",
"func (e envVariable) String() string { return string(e) }",
"func (pm partitionMap) String() string {\n\tres := bytes.Buffer{}\n\tfor ns, partitions := range pm {\n\t\tres.WriteString(\"-----------------------------------------------------------------------\\n\")\n\t\tres.WriteString(\"Namespace: \" + ns + \"\\n\")\n\t\tres.WriteString(fmt.Sprintf(\"Regimes: %v\\n\", partitions.regimes))\n\t\tres.WriteString(fmt.Sprintf(\"SCMode: %v\\n\", partitions.SCMode))\n\t\treplicaArray := partitions.Replicas\n\t\tfor i, nodeArray := range replicaArray {\n\t\t\tif i == 0 {\n\t\t\t\tres.WriteString(\"\\nMASTER:\")\n\t\t\t} else {\n\t\t\t\tres.WriteString(fmt.Sprintf(\"\\nReplica %d: \", i))\n\t\t\t}\n\t\t\tfor partitionID, node := range nodeArray {\n\t\t\t\tres.WriteString(strconv.Itoa(partitionID) + \"/\")\n\t\t\t\tif node != nil {\n\t\t\t\t\tres.WriteString(node.host.String())\n\t\t\t\t\tres.WriteString(\", \")\n\t\t\t\t} else {\n\t\t\t\t\tres.WriteString(\"nil, \")\n\t\t\t\t}\n\t\t\t}\n\t\t\tres.WriteString(\"\\n\")\n\t\t}\n\t}\n\tres.WriteString(\"\\n\")\n\treturn res.String()\n}",
"func (r Register) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}",
"func (r SendAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}",
"func getAsJson(pIFC interface{}) string {\n\tvar labJSON []byte\n\tvar lsText string\n\t// var lErr error\n\n\tlabJSON, _ = json.MarshalIndent(pIFC, \"\", \" \")\n\n\tlsText = bytes.NewBuffer(labJSON).String()\n\tlog.Println(lsText)\n\treturn lsText\n}",
"func (s *Siegfried) JSON() string {\n\tversion := config.Version()\n\tstr := fmt.Sprintf(\n\t\t\"{\\\"siegfried\\\":\\\"%d.%d.%d\\\",\\\"scandate\\\":\\\"%v\\\",\\\"signature\\\":\\\"%s\\\",\\\"created\\\":\\\"%v\\\",\\\"identifiers\\\":[\",\n\t\tversion[0], version[1], version[2],\n\t\ttime.Now().Format(time.RFC3339),\n\t\tconfig.SignatureBase(),\n\t\ts.C.Format(time.RFC3339))\n\tfor i, id := range s.ids {\n\t\tif i > 0 {\n\t\t\tstr += \",\"\n\t\t}\n\t\td := id.Describe()\n\t\tstr += fmt.Sprintf(\"{\\\"name\\\":\\\"%s\\\",\\\"details\\\":\\\"%s\\\"}\", d[0], d[1])\n\t}\n\tstr += \"],\"\n\treturn str\n}",
"func (mVar Machine) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif mVar.MachinePropertiesModel != nil {\n\t\tobjectMap[\"properties\"] = mVar.MachinePropertiesModel\n\t}\n\tif mVar.Identity != nil {\n\t\tobjectMap[\"identity\"] = mVar.Identity\n\t}\n\tif mVar.Tags != nil {\n\t\tobjectMap[\"tags\"] = mVar.Tags\n\t}\n\tif mVar.Location != nil {\n\t\tobjectMap[\"location\"] = mVar.Location\n\t}\n\treturn json.Marshal(objectMap)\n}",
"func (r ReceiveAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\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 (this *Variable) String() string {\n\ttyp := this.GetType()\n\tif types.IsList(typ) {\n\t\ttypes.ListToSingle(typ)\n\t}\n\tswitch typ {\n\tcase types.SINGLE_DOUBLE:\n\t\treturn \"$double\"\n\tcase types.SINGLE_INT:\n\t\treturn \"$int\"\n\tcase types.SINGLE_UINT:\n\t\treturn \"$uint\"\n\tcase types.SINGLE_BOOL:\n\t\treturn \"$bool\"\n\tcase types.SINGLE_STRING:\n\t\treturn \"$string\"\n\tcase types.SINGLE_BYTES:\n\t\treturn \"$[]byte\"\n\t}\n\tpanic(fmt.Errorf(\"unknown type %s\", this.GetType()))\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewAdminSvc exposed the ORM to the admin functions in the module
|
func NewAdminSvc(db *orm.ORM, rdb *redis.Client) AdminService {
return &ORM{db, rdb}
}
|
[
"func newAdminService(w *wildflyv1alpha1.WildFlyServer, labels map[string]string) *corev1.Service {\n\theadlessService := &corev1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: AdminServiceName(w),\n\t\t\tNamespace: w.Namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tType: corev1.ServiceTypeClusterIP,\n\t\t\tSelector: labels,\n\t\t\tClusterIP: corev1.ClusterIPNone,\n\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t{\n\t\t\t\t\tName: \"admin\",\n\t\t\t\t\tPort: resources.HTTPManagementPort,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn headlessService\n}",
"func New(db *gorm.DB, prefix, cookiesecret string) *Admin {\n\tadminpath := filepath.Join(prefix, \"/admin\")\n\ta := Admin{\n\t\tdb: db,\n\t\tprefix: prefix,\n\t\tadminpath: adminpath,\n\t\tauth: auth{\n\t\t\tdb: db,\n\t\t\tpaths: pathConfig{\n\t\t\t\tadmin: adminpath,\n\t\t\t\tlogin: filepath.Join(prefix, \"/login\"),\n\t\t\t\tlogout: filepath.Join(prefix, \"/logout\"),\n\t\t\t},\n\t\t\tsession: sessionConfig{\n\t\t\t\tkey: \"userid\",\n\t\t\t\tname: \"admsession\",\n\t\t\t\tstore: cookie.NewStore([]byte(cookiesecret)),\n\t\t\t},\n\t\t},\n\t}\n\ta.adm = admin.New(&admin.AdminConfig{\n\t\tSiteName: \"My Admin Interface\",\n\t\tDB: db,\n\t\tAuth: a.auth,\n\t\tAssetFS: bindatafs.AssetFS.NameSpace(\"admin\"),\n\t})\n\taddUser(a.adm)\n\tresources.AddProduct(a.adm)\n\treturn &a\n}",
"func (_Bindings *BindingsFilterer) FilterNewAdmin(opts *bind.FilterOpts) (*BindingsNewAdminIterator, error) {\n\n\tlogs, sub, err := _Bindings.contract.FilterLogs(opts, \"NewAdmin\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BindingsNewAdminIterator{contract: _Bindings.contract, event: \"NewAdmin\", logs: logs, sub: sub}, nil\n}",
"func NewAdmin(client proto.PowergateAdminServiceClient) *Admin {\n\treturn &Admin{\n\t\tStorageJobs: &StorageJobs{client: client},\n\t\tProfiles: &Profiles{client: client},\n\t\tWallet: &Wallet{client: client},\n\t}\n}",
"func (ach *AdminAdminHandler) AdminAdminsNew(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\r\n\r\n\tif r.Method == http.MethodPost {\r\n\r\n\t\tctg := entity.Admin{}\r\n\t\tctg.Username = r.FormValue(\"username\")\r\n\t\tctg.FirstName = r.FormValue(\"firstname\")\r\n\t\tctg.LastName = r.FormValue(\"lastname\")\r\n\t\tctg.Email = r.FormValue(\"email\")\r\n\t\tctg.Password = r.FormValue(\"password\")\r\n\r\n\t\tmf, fh, err := r.FormFile(\"catimg\")\r\n\t\tif mf != nil {\r\n\t\t\tctg.ImagePath = fh.Filename\r\n\t\t\tif err != nil {\r\n\t\t\t\tpanic(err)\r\n\t\t\t}\r\n\t\t\tdefer mf.Close()\r\n\t\t\twriteFile(&mf, ctg.ImagePath)\r\n\t\t} else {\r\n\t\t\tctg.ImagePath = \"defaultCompany.jpg\"\r\n\t\t}\r\n\r\n\t\terr = ach.AdminSrv.StoreAdmin(ctg)\r\n\r\n\t\tif err != nil {\r\n\t\t\tach.tmpl.ExecuteTemplate(w, \"admin.admins.new.layout\", \"username inuse\")\r\n\t\t}\r\n\r\n\t\thttp.Redirect(w, r, \"/admin/admins\", http.StatusSeeOther)\r\n\r\n\t} else {\r\n\r\n\t\tach.tmpl.ExecuteTemplate(w, \"admin.admins.new.layout\", nil)\r\n\r\n\t}\r\n}",
"func NewAdminContractService(runner *Runner) *AdminContractService {\n\tmethods := map[string]bool{\n\t\t\"migration.getInfo\": true,\n\t\t\"migration.deactivateDaemon\": true,\n\t\t\"migration.activateDaemon\": true,\n\t\t\"migration.checkDaemon\": true,\n\t\t\"migration.addAddresses\": true,\n\t\t\"deposit.migration\": true,\n\t\t\"member.getBalance\": true,\n\t\t\"contract.registerNode\": true,\n\t\t\"contract.getNodeRef\": true,\n\t\t\"CreateHelloWorld\": true,\n\t\t\"Greet\": true,\n\t\t\"Count\": true,\n\t\t\"CreateChild\": true,\n\t\t\"ReturnObj\": true,\n\t\t\"PulseNumber\": true,\n\t}\n\treturn &AdminContractService{runner: runner, allowedMethods: methods}\n}",
"func AdminCreate(w http.ResponseWriter, data interface{}) {\n\trender(tpAdminCreate, w, data)\n}",
"func NewDummyAdmin(keepData ...bool) *admin.Admin {\n\tvar (\n\t\tdb = utils.TestDB()\n\t\tmodels = []interface{}{&User{}, &CreditCard{}, &Address{}, &Language{}, &Profile{}, &Phone{}, &Company{}}\n\t\tAdmin = admin.New(&admin.AdminConfig{Auth: DummyAuth{}, DB: db})\n\t)\n\n\tmedia.RegisterCallbacks(db)\n\n\tInitRoles()\n\n\tfor _, value := range models {\n\t\tif len(keepData) == 0 {\n\t\t\tdb.DropTableIfExists(value)\n\t\t}\n\t\tdb.AutoMigrate(value)\n\t}\n\n\tc := Admin.AddResource(&Company{})\n\tc.Action(&admin.Action{\n\t\tName: \"Publish\",\n\t\tHandler: func(argument *admin.ActionArgument) (err error) {\n\t\t\tfmt.Println(\"Publish company\")\n\t\t\treturn\n\t\t},\n\t\tMethod: \"GET\",\n\t\tResource: c,\n\t\tModes: []string{\"edit\"},\n\t})\n\tc.Action(&admin.Action{\n\t\tName: \"Preview\",\n\t\tPermission: roles.Deny(roles.CRUD, Role_system_administrator),\n\t\tHandler: func(argument *admin.ActionArgument) (err error) {\n\t\t\tfmt.Println(\"Preview company\")\n\t\t\treturn\n\t\t},\n\t\tMethod: \"GET\",\n\t\tResource: c,\n\t\tModes: []string{\"edit\"},\n\t})\n\tc.Action(&admin.Action{\n\t\tName: \"Approve\",\n\t\tPermission: roles.Allow(roles.Read, Role_system_administrator),\n\t\tHandler: func(argument *admin.ActionArgument) (err error) {\n\t\t\tfmt.Println(\"Approve company\")\n\t\t\treturn\n\t\t},\n\t\tMethod: \"GET\",\n\t\tModes: []string{\"edit\"},\n\t})\n\tAdmin.AddResource(&CreditCard{})\n\n\tAdmin.AddResource(&Language{}, &admin.Config{Name: \"语种 & 语言\", Priority: -1})\n\tuser := Admin.AddResource(&User{}, &admin.Config{Permission: roles.Allow(roles.CRUD, Role_system_administrator)})\n\tuser.Meta(&admin.Meta{\n\t\tName: \"CreditCard\",\n\t\tType: \"single_edit\",\n\t})\n\tuser.Meta(&admin.Meta{\n\t\tName: \"Languages\",\n\t\tType: \"select_many\",\n\t\tCollection: func(resource interface{}, context *qor.Context) (results [][]string) {\n\t\t\tif languages := []Language{}; !context.GetDB().Find(&languages).RecordNotFound() {\n\t\t\t\tfor _, language := range languages {\n\t\t\t\t\tresults = append(results, []string{fmt.Sprint(language.ID), language.Name})\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t},\n\t})\n\n\treturn Admin\n}",
"func NewService(version version.Version, nodeID ids.ShortID, networkID uint32, log logging.Logger, chainManager chains.Manager, peers network.Network, httpServer *api.Server) *common.HTTPHandler {\n\tnewServer := rpc.NewServer()\n\tcodec := cjson.NewCodec()\n\tnewServer.RegisterCodec(codec, \"application/json\")\n\tnewServer.RegisterCodec(codec, \"application/json;charset=UTF-8\")\n\tnewServer.RegisterService(&Admin{\n\t\tversion: version,\n\t\tnodeID: nodeID,\n\t\tnetworkID: networkID,\n\t\tlog: log,\n\t\tchainManager: chainManager,\n\t\tnetworking: peers,\n\t\thttpServer: httpServer,\n\t}, \"admin\")\n\treturn &common.HTTPHandler{Handler: newServer}\n}",
"func NewService(config Config) (*common.HTTPHandler, error) {\n\tnewServer := rpc.NewServer()\n\tcodec := json.NewCodec()\n\tnewServer.RegisterCodec(codec, \"application/json\")\n\tnewServer.RegisterCodec(codec, \"application/json;charset=UTF-8\")\n\tif err := newServer.RegisterService(&Admin{\n\t\tConfig: config,\n\t\tprofiler: profiler.New(config.ProfileDir),\n\t}, \"admin\"); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &common.HTTPHandler{Handler: newServer}, nil\n}",
"func CreatePgAdminHandler(w http.ResponseWriter, r *http.Request) {\n\t// swagger:operation POST /pgadmin pgadminservice pgadmin-post\n\t/*```\n\t Create a pgAdmin instance\n\t*/\n\t// ---\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: \"Create PgAdmin Request\"\n\t// in: \"body\"\n\t// schema:\n\t// \"$ref\": \"#/definitions/CreatePgAdminRequest\"\n\t// responses:\n\t// '200':\n\t// description: Output\n\t// schema:\n\t// \"$ref\": \"#/definitions/CreatePgAdminResponse\"\n\tvar ns string\n\tlog.Debug(\"pgadminservice.CreatePgAdminHandler called\")\n\tusername, err := apiserver.Authn(apiserver.CREATE_PGADMIN_PERM, w, r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tw.Header().Set(\"WWW-Authenticate\", `Basic realm=\"Restricted\"`)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\n\tvar request msgs.CreatePgAdminRequest\n\t_ = json.NewDecoder(r.Body).Decode(&request)\n\n\tresp := msgs.CreatePgAdminResponse{}\n\n\tif request.ClientVersion != msgs.PGO_VERSION {\n\t\tresp.SetError(apiserver.VERSION_MISMATCH_ERROR)\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tns, err = apiserver.GetNamespace(apiserver.Clientset, username, request.Namespace)\n\tif err != nil {\n\t\tresp.SetError(err.Error())\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tresp = CreatePgAdmin(&request, ns, username)\n\tjson.NewEncoder(w).Encode(resp)\n\n}",
"func (c *Client) AdminCreate(u types.AdminsRequest) (ur types.AdminsResponse, err error) {\n\tv := url.Values{}\n\tv.Set(\"fields\", \"*\")\n\tv.Set(\"related\", strings.Join([]string{\"user_lookup_by_user_id\"}, \",\"))\n\terr = c.send(\"POST\", \"/api/v2/system/admin?\"+v.Encode(), 201, u, &ur)\n\treturn\n}",
"func NewAdminService(\n\tetcdClient *etcd.Client, reg *DataNodeRegistry) *AdminService {\n\treturn &AdminService{\n\t\tetcdClient: etcdClient,\n\t\treg: reg,\n\t}\n}",
"func (_CrToken *CrTokenFilterer) FilterNewAdmin(opts *bind.FilterOpts) (*CrTokenNewAdminIterator, error) {\n\n\tlogs, sub, err := _CrToken.contract.FilterLogs(opts, \"NewAdmin\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CrTokenNewAdminIterator{contract: _CrToken.contract, event: \"NewAdmin\", logs: logs, sub: sub}, nil\n}",
"func GetAdminList(q *QueryAdminForm, db *gorm.DB) (ret []*Admin, err error) {\n\t// order\n\tif len(q.Order) > 0 {\n\t\tfor _, v := range q.Order {\n\t\t\tdb = db.Order(v)\n\t\t}\n\t}\n\t// pageSize\n\tif q.PageSize != 0 {\n\t\tdb = db.Limit(q.PageSize)\n\t}\n\t// pageNum\n\tif q.PageNum != 0 {\n\t\tq.PageNum = (q.PageNum - 1) * q.PageSize\n\t\tdb = db.Offset(q.PageNum)\n\t}\n\n\t// CreatedAt\n\tif q.CreatedAt != nil {\n\t\tdb = db.Where(\"created_at\"+q.CreatedAt.Symbol+\"?\", q.CreatedAt.Value)\n\t}\n\t// UpdatedAt\n\tif q.UpdatedAt != nil {\n\t\tdb = db.Where(\"updated_at\"+q.UpdatedAt.Symbol+\"?\", q.UpdatedAt.Value)\n\t}\n\t// Age\n\tif q.Age != nil {\n\t\tdb = db.Where(\"age\"+q.Age.Symbol+\"?\", q.Age.Value)\n\t}\n\t// Email\n\tif q.Email != nil {\n\t\tdb = db.Where(\"email\"+q.Email.Symbol+\"?\", q.Email.Value)\n\t}\n\tif err = db.Find(&ret).Error; err != nil {\n\t\treturn\n\t}\n\treturn\n}",
"func getAdmin(e echo.Context) error {\n\tdb := e.Get(\"database\").(*mgo.Database)\n\tif db == nil {\n\t\treturn fmt.Errorf(\"Bad database session\")\n\t}\n\n\tvar id bson.ObjectId\n\tif idParam := e.QueryParam(\"id\"); idParam != \"\" && bson.IsObjectIdHex(idParam) {\n\t\tid = bson.ObjectIdHex(idParam)\n\t}\n\tuuid, err := uuid.FromString(e.QueryParam(\"uuid\"))\n\tif !id.Valid() && err != nil {\n\t\treturn fmt.Errorf(\"Bad parameters\")\n\t}\n\n\ta := models.Admin{}\n\tif id.Valid() {\n\t\terr = db.C(\"Admins\").FindId(id).One(&a)\n\t} else {\n\t\terr = db.C(\"Admins\").Find(bson.M{\"adminUuid\": uuid}).One(&a)\n\t}\n\tif err != nil {\n\t\treturn e.NoContent(http.StatusNotFound)\n\t}\n\treturn e.JSON(http.StatusOK, a)\n}",
"func NewAdminService(ipList repository.IPStorable, login, password, ip repository.BucketStorable) service.AdminService {\n\treturn &adminService{\n\t\tipList: ipList,\n\t\tloginBuckets: login,\n\t\tpasswordBuckets: password,\n\t\tipBuckets: ip,\n\t}\n}",
"func GetAdminNewVersion(c *gin.Context) {\n\tvar Version database.Version\n\tVersion.ID = uuid.NewV4()\n\tvar Products []database.Product\n\tdatabase.Db.Order(\"name ASC\").Find(&Products)\n\tc.HTML(http.StatusOK, \"admin_version.html\", gin.H{\n\t\t\"admin\": true,\n\t\t\"prods\": database.Products,\n\t\t\"title\": \"Admin — New Version\",\n\t\t\"item\": Version,\n\t\t\"products\": Products,\n\t\t\"form\": \"/admin/versions/new\",\n\t})\n}",
"func GetAdminIndex(c *gin.Context) {\n\tvar countReports int\n\tvar countCrashes int\n\tvar countSymfiles int\n\tvar countProducts int\n\tvar countVersions int\n\tvar countUsers int\n\tvar countComments int\n\tdatabase.Db.Model(database.Report{}).Count(&countReports)\n\tdatabase.Db.Model(database.Crash{}).Count(&countCrashes)\n\tdatabase.Db.Model(database.Symfile{}).Count(&countSymfiles)\n\tdatabase.Db.Model(database.Product{}).Count(&countProducts)\n\tdatabase.Db.Model(database.Version{}).Count(&countVersions)\n\tdatabase.Db.Model(database.User{}).Count(&countUsers)\n\tdatabase.Db.Model(database.Comment{}).Count(&countComments)\n\tc.HTML(http.StatusOK, \"admin_index.html\", gin.H{\n\t\t\"admin\": true,\n\t\t\"prods\": database.Products,\n\t\t\"title\": \"Admin Index\",\n\t\t\"countReports\": countReports,\n\t\t\"countCrashes\": countCrashes,\n\t\t\"countSymfiles\": countSymfiles,\n\t\t\"countProducts\": countProducts,\n\t\t\"countVersions\": countVersions,\n\t\t\"countUsers\": countUsers,\n\t\t\"countComments\": countComments,\n\t})\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
LoginAdmin checks if the email is having valid credentials and returns them a unique, secured token to help them get resources from app
|
func (orm *ORM) LoginAdmin(ctx context.Context, email string, password string) (*LoginResult, error) {
var _Admin models.Admin
//check if email is in db
_Result := orm.DB.DB.Joins("CreatedBy").First(&_Admin, "admins.email = ?", email)
if errors.Is(_Result.Error, gorm.ErrRecordNotFound) {
return nil, errors.New("AdminNotFound")
}
//since email in db, lets validate hash and then send back
isSame := validatehash.ValidateCipher(password, _Admin.Password)
if isSame == false {
return nil, errors.New("PasswordIncorrect")
}
//sign token
token, signTokenErrr := signjwt.SignJWT(jwt.MapClaims{
"id": _Admin.ID,
"role": _Admin.Role,
}, utils.MustGet("SECRET"))
if signTokenErrr != nil {
return nil, signTokenErrr
}
return &LoginResult{
Token: token,
Admin: _Admin,
}, nil
}
|
[
"func adminToken(c *C) string {\n\treturn loginAs(c, adminUsername, adminPassword)\n}",
"func (s *rpcServer) LoginAdmin(ctx context.Context, req *api.LoginAdminRequest) (*api.LoginAdminResponse, error) {\n\tadmin, err := admin.Login(req.Email, req.Password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcl := auth.New(admin.ID, admin.ACL)\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, cl)\n\ttokenStr, err := token.SignedString(s.privKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &api.LoginAdminResponse{\n\t\tToken: tokenStr,\n\t\tAdmin: &api.Admin{\n\t\t\tId: admin.ID,\n\t\t\tName: admin.Name,\n\t\t\tEmail: admin.Email,\n\t\t\tACL: admin.ACL,\n\t\t},\n\t}, nil\n}",
"func AdminAuth(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {\n\t\tif status, err := validateAdminToken(req); err != nil {\n\t\t\tresponse.JSON(res, status, response.Body{\"message\": err.Error()})\n\n\t\t\treturn\n\t\t}\n\n\t\tnext.ServeHTTP(res, req)\n\t})\n}",
"func Login(userPoolID string, clientID string, email string, password string, svc cognitoidentityprovider.CognitoIdentityProvider) *cognitoidentityprovider.AdminInitiateAuthOutput {\n\treq, resp := svc.AdminInitiateAuthRequest(&cognitoidentityprovider.AdminInitiateAuthInput{\n\t\tAuthFlow: aws.String(\"ADMIN_NO_SRP_AUTH\"),\n\t\tUserPoolId: aws.String(userPoolID),\n\t\tClientId: aws.String(clientID),\n\t\tAuthParameters: map[string]*string{\n\t\t\t\"USERNAME\": aws.String(email),\n\t\t\t\"PASSWORD\": aws.String(password),\n\t\t},\n\t})\n\n\terr := req.Send()\n\tif err != nil {\n\t\tlog.Fatal(\"failed to sign in: \", err)\n\t}\n\n\treturn resp\n}",
"func (c *mockUserUsecase) EmailLogin(_ context.Context, email string, password string) (*entities.User, string, error) {\n\tu := entities.User{}\n\tu.Email = email\n\treturn &u, \"token\", nil\n}",
"func AdminLogin(w http.ResponseWriter, data *AdminLoginData) {\n\trender(tpAdminLogin, w, data)\n\tdata.Flash.Del(\"errors\")\n}",
"func AdminLogin(w http.ResponseWriter, data interface{}) {\n\trender(tpAdminLogin, w, data)\n}",
"func (server *Server) LoginAdmin(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tuid, err := strconv.ParseUint(vars[\"id\"], 10, 32)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tadmin := models.Admin{}\n\tadminGet, err := admin.FindAdminByID(server.DB, uint32(uid))\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, adminGet)\n}",
"func (e *Email) generateEmailAuthToken(email string) string {\n\n\t// 创建验证信息存储,每10分钟执行一次GC\n\tstore := validate.NewMemoryStore(time.Second * 60 * 60)\n\t// 创建验证信息管理器,验证信息的过期时间为1小时\n\ttokenv := validate.NewTokenValidate(store, validate.Config{Expire: time.Second * 60 * 60})\n\t// 使用邮箱生成验证令牌\n\ttoken, err := tokenv.Generate(email)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\te.tokenv = tokenv\n\tglog.Infof(\"check user email token[%s]\\n\", token)\n\n\treturn token\n}",
"func CheckAdminByToken(token *string) error {\n\n\tvar databaseAdmin models.Admin\n\n\tdb, err := Connect()\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer db.Close()\n\n\trows, err := db.Query(`\n\t\tselect * from admins\n\t\tlimit 10;\n\t`)\n\tdefer rows.Close()\n\n\n\tfor rows.Next() {\n\t\trows.Scan(&databaseAdmin.ID, &databaseAdmin.Email, &databaseAdmin.Password) // hashed\n\t\terr = framework.CompareHashandPassword(databaseAdmin.Password, os.Getenv(\"ADMIN_PASS\"))\n\t\tif err == nil {\n\t\t\tdatabaseAdmin.Password = os.Getenv(\"ADMIN_PASS\")\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\n\t\tdatabaseAdminJSON, err := json.Marshal(databaseAdmin)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = framework.CompareHashandPassword(*token, string(databaseAdminJSON))\n\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn errors.New(\"Not Found\")\n\n}",
"func (a *auth) Login() (string, error) {\n\tpath := fmt.Sprintf(\"/v1/auth/%s/login\", a.path)\n\treq := a.vClient.NewRequest(\"POST\", path)\n\n\tpayload := make(map[string]interface{})\n\tpayload[\"role\"] = a.role\n\tpayload[\"jwt\"] = a.signedJWT\n\n\tif len(a.subscriptionID) > 0 {\n\t\tpayload[\"subscription_id\"] = a.subscriptionID\n\t}\n\tif len(a.resourceGroupName) > 0 {\n\t\tpayload[\"resource_group_name\"] = a.resourceGroupName\n\t}\n\tif len(a.vmName) > 0 {\n\t\tpayload[\"vm_name\"] = a.vmName\n\t}\n\tif len(a.vmssName) > 0 {\n\t\tpayload[\"vmss_name\"] = a.vmssName\n\t}\n\n\tif err := req.SetJSONBody(payload); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp, err := a.vClient.RawRequest(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar loginResp authtype.AuthLoginResponse\n\tdefer resp.Body.Close()\n\terr = json.NewDecoder(resp.Body).Decode(&loginResp)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn loginResp.Auth.ClientToken, nil\n}",
"func validateAdminToken(req *http.Request) (int, error) {\n\tadminToken := os.Getenv(\"APP_ADMIN_TOKEN\")\n\n\t// Require token if only backend is configured and the uri matches admin prefix.\n\tif adminToken == \"\" || strings.Index(req.URL.Path, AdminURIPrefix) != 0 {\n\t\treturn 0, nil\n\t}\n\n\ttoken := req.Header.Get(\"Authorization\")\n\tif token == \"\" {\n\t\treturn http.StatusUnauthorized, common.ErrTokenRequired\n\t}\n\n\tif strings.Index(token, \"Bearer \") != 0 {\n\t\treturn http.StatusUnauthorized, common.ErrTokenInvalid\n\t}\n\n\tif token[7:] != adminToken {\n\t\treturn http.StatusForbidden, common.ErrTokenInvalid\n\t}\n\n\treturn 0, nil\n}",
"func AuthLogin(db *models.Repository, sm *scs.Manager) http.HandlerFunc {\n\n\ttype Request struct {\n\t\tEmail string `json:\"email\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tvar req Request\n\n\t\tif err := jsonDecode(r, &req); err != nil {\n\t\t\thandleError(w, r, ErrInvalidJSON)\n\t\t\treturn\n\t\t}\n\n\t\tu, err := db.UsersLogin(req.Email, req.Password)\n\n\t\tif err != nil {\n\t\t\thandleError(w, r, ErrInvalidCreds)\n\t\t\treturn\n\t\t}\n\n\t\tif !u.IsActivated {\n\t\t\thandleError(w, r, ErrAccountIsNotActivated)\n\t\t\treturn\n\t\t}\n\n\t\tsession := sm.Load(r)\n\n\t\tif err := session.RenewToken(w); err != nil {\n\t\t\thandleError(w, r, ErrInternal.SetError(err))\n\t\t\treturn\n\t\t}\n\n\t\tif err := session.PutInt64(w, \"userId\", u.ID); err != nil {\n\t\t\thandleError(w, r, ErrInternal.SetError(err))\n\t\t\treturn\n\t\t}\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"controller\": \"auth\",\n\t\t\t\"action\": \"login\",\n\t\t\t\"user\": u.Name,\n\t\t\t\"email\": u.Email,\n\t\t}).Info(\"User logged in\")\n\n\t\tresponseOK(w)\n\t}\n}",
"func tokenEmail(s string) (string, bool) {\n\tjwt, err := token.ParseInsecure(s)\n\tif err != nil {\n\t\treturn \"\", false\n\t}\n\treturn jwt.Payload.Email, jwt.Payload.Email != \"\"\n}",
"func (this *UserManagerImpl) Login(ss *user.Secret) (signedToken string, err error) {\n\tuser, err := user.Login(ss)\n\tif err != nil {\n\t\tappLogger.Debugf(\"User Login failed [%v]\\n\", err)\n\t\treturn \"\", err\n\t}\n\n\tvar isAdmin bool = false\n\tif user.Type == 0 {\n\t\tisAdmin = true\n\t}\n\tsignedToken = auth.CreateToken(user.Id, user.Name, isAdmin)\n\treturn signedToken, nil\n}",
"func (s *server) GenerateAdminToken(ctx context.Context,\n\treq *api.GenerateAdminTokenRequest) (*api.GenerateAdminTokenResponse, error) {\n\tif !s.HasConfiguredDeployment() {\n\t\treturn nil, ErrorNotConfigured\n\t}\n\n\tauthnAddr := s.AddressForService(\"authn-service\")\n\tauthzAddr := s.AddressForService(\"authz-service\")\n\treturn generateAdminToken(ctx, req, s.connFactory, authnAddr, authzAddr)\n}",
"func (client AzureClient) Login(httpClient httpclient.HttpClient, browser browser.Browser) (string, error) {\n\tauthCode(browser)\n\tif authCodeValue == \"\" {\n\t\treturn \"\", errors.New(\"No auth code received\")\n\t}\n\ttoken, err := accessToken(httpClient)\n\treturn token, err\n}",
"func (c *Client) GetAdminEmail(username string, password string) (string, error) {\n\tdebug(\"[TRACE] Getting admin email\")\n\tpath := fmt.Sprintf(\"https://%s/v1/backend1\", c.ControllerIP)\n\tadmin := new(LoginProcRequest)\n\tadmin.Action = \"login_proc\"\n\tadmin.Username = username\n\tadmin.Password = password\n\tresp, err := c.Post(path, admin)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar data LoginProcResponse\n\tif err = json.NewDecoder(resp.Body).Decode(&data); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn data.AdminEmail, nil\n}",
"func (s *userService) ValidateLoginAndReturnJwtToken(req *request.Login) (string, error) {\n\tu, err := s.ur.FindByEmail(req.Email)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif utils.CheckPasswordHash(req.Password, u.Password) == false {\n\t\treturn \"\", app.UnauthorizedError(\"JWT Login\")\n\t}\n\n\tmySigningKey := []byte(s.config.JwtSecret)\n\n\ttype jwtClaims struct {\n\t\tUserId int `json:\"user_id\"`\n\t\tAccountId int `json:\"account_id\"`\n\t\tjwt.StandardClaims\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwtClaims{\n\t\tu.ID,\n\t\tu.AccountID,\n\t\tjwt.StandardClaims{\n\t\t\tExpiresAt: time.Now().AddDate(1, 0, 0).Unix(),\n\t\t\tIssuer: \"api\",\n\t\t},\n\t})\n\n\treturn token.SignedString(mySigningKey)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
UpdateAdminRole updates role of an admin
|
func (orm *ORM) UpdateAdminRole(ctx context.Context, adminID string, role string) (bool, error) {
var _Admin models.Admin
err := orm.DB.DB.First(&_Admin, "id = ?", adminID).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return false, errors.New("AdminNotFound")
}
_Admin.Role = role
orm.DB.DB.Save(&_Admin)
return true, nil
}
|
[
"func (bs *DefaultSecurity) UpdateAdminRoles(login string, delete bool) error {\n\tfor i, name := range bs.Admins.Roles {\n\t\tif name == login {\n\t\t\tif delete {\n\t\t\t\tbs.Admins.Roles = append(bs.Admins.Roles[:i], bs.Admins.Roles[i+1:]...)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn errors.New(\"Role already exists\")\n\t\t}\n\t}\n\tbs.Admins.Roles = append(bs.Admins.Roles, login)\n\treturn nil\n}",
"func UpdateRole(w http.ResponseWriter, r *http.Request) {\n\troleID := reqID(r)\n\treqBytes, err := ioutil.ReadAll(r.Body)\n\tcode := e.SUCCESS\n\tres := &JSONResponse{Writer: w}\n\tif err != nil || roleID == \"\" {\n\t\tcode = e.INVALID_PARAMS\n\t} else {\n\t\trole := models.Role{}\n\t\tif err = json.Unmarshal(reqBytes, &role); err != nil {\n\t\t\tlogger.Info(\"Faile to unmarshal role parameters:\", err)\n\t\t\tcode = e.INVALID_PARAMS\n\t\t} else {\n\t\t\tfuncNames := []string{}\n\t\t\tfor _, funcm := range role.Func {\n\t\t\t\tfuncNames = append(funcNames, funcm.Name)\n\t\t\t}\n\t\t\tif err = application.EditRole(roleID, role.Name, funcNames); err != nil {\n\t\t\t\tcode = e.UPDATE_FAILED\n\t\t\t\tres.Data = false\n\t\t\t} else {\n\t\t\t\tres.Data = true\n\t\t\t}\n\t\t}\n\t}\n\tres.Code = code\n\tres.Response()\n}",
"func (sc *ServiceController) UpdateRole(name string, body map[string]interface{}) (bool, string) {\n\turl := urlRole(sc.ID, name)\n\n\treturn sc.c.boolResponse(\"PUT\", url, body)\n}",
"func UpdateRole(c *gin.Context) {\n\tupdatedRole := model.Role{}\n\tc.BindJSON(&updatedRole)\n\n\terr := service.UpdateRole(updatedRole)\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\terror := service.GetGormErrorCode(err.Error())\n\n\t\tc.JSON(500, error)\n\t} else {\n\t\tc.String(200, \"ok\")\n\t}\n}",
"func UpdateAdmin(w http.ResponseWriter, r *http.Request) {\n\tvar body UpdateAdminRequest\n\tif err := read.JSON(r.Body, &body); err != nil {\n\t\trender.Error(w, admin.WrapError(admin.ErrorBadRequestType, err, \"error reading request body\"))\n\t\treturn\n\t}\n\n\tif err := body.Validate(); err != nil {\n\t\trender.Error(w, err)\n\t\treturn\n\t}\n\n\tid := chi.URLParam(r, \"id\")\n\tauth := mustAuthority(r.Context())\n\tadm, err := auth.UpdateAdmin(r.Context(), id, &linkedca.Admin{Type: body.Type})\n\tif err != nil {\n\t\trender.Error(w, admin.WrapErrorISE(err, \"error updating admin %s\", id))\n\t\treturn\n\t}\n\n\trender.ProtoJSON(w, adm)\n}",
"func (aaa *RolesService) SetRoleAsAdmin(input *roles.SetRoleAsAdminParams) error {\n\ttoken, err := aaa.TokenRepository.GetToken()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, badRequest, unauthorized, forbidden, notFound, err := aaa.Client.Roles.SetRoleAsAdmin(input, client.BearerToken(*token.AccessToken))\n\tif badRequest != nil {\n\t\treturn badRequest\n\t}\n\tif unauthorized != nil {\n\t\treturn unauthorized\n\t}\n\tif forbidden != nil {\n\t\treturn forbidden\n\t}\n\tif notFound != nil {\n\t\treturn notFound\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (aaa *RolesService) AdminUpdateAdminRoleStatusV3(input *roles.AdminUpdateAdminRoleStatusV3Params) error {\n\ttoken, err := aaa.TokenRepository.GetToken()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, badRequest, unauthorized, forbidden, notFound, internalServerError, err := aaa.Client.Roles.AdminUpdateAdminRoleStatusV3(input, client.BearerToken(*token.AccessToken))\n\tif badRequest != nil {\n\t\treturn badRequest\n\t}\n\tif unauthorized != nil {\n\t\treturn unauthorized\n\t}\n\tif forbidden != nil {\n\t\treturn forbidden\n\t}\n\tif notFound != nil {\n\t\treturn notFound\n\t}\n\tif internalServerError != nil {\n\t\treturn internalServerError\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (_PermInterface *PermInterfaceTransactor) ApproveAdminRole(opts *bind.TransactOpts, _orgId string, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"approveAdminRole\", _orgId, _account)\n}",
"func (store *Store) UpdateRole(name string, prms *graylog.RoleUpdateParams) (*graylog.Role, error) {\n\tstore.imutex.Lock()\n\tdefer store.imutex.Unlock()\n\trole, ok := store.roles[name]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(`no role with name \"%s\"`, name)\n\t}\n\tif prms.Description != nil {\n\t\trole.Description = *prms.Description\n\t}\n\trole.Permissions = prms.Permissions\n\trole.Name = prms.Name\n\tdelete(store.roles, name)\n\tstore.roles[role.Name] = role\n\treturn &role, nil\n}",
"func GuildRoleUpdated(s *discordgo.Session, m *discordgo.GuildRoleUpdate) {\n\n\t// ignore roles that dont contain \"acm\"\n\tif !strings.Contains(m.GuildRole.Role.Name, \"acm\") {\n\t\treturn\n\t}\n\n\trole := architecting.Role{\n\t\tDiscordID: m.GuildRole.Role.ID,\n\t\tName: m.GuildRole.Role.Name,\n\t}\n\n\terr := as.UpdateRole(&role)\n\tif err != nil {\n\t\tlog.Println(err.GetMessage())\n\t\treturn\n\t}\n\n\tlog.Println(\"role successfully updated\")\n}",
"func (s Service) UpdateRole(ctx context.Context, docID, roleID []byte, dids []identity.DID) (*coredocumentpb.Role, error) {\n\treturn s.pendingDocSrv.UpdateRole(ctx, docID, roleID, dids)\n}",
"func (srv *Service) UpdateUserRole(id string, role string) (*string, error) {\n\t//check if the user exists\n\tresponse, err := srv.mongoRepository.GetUserByID(id)\n\tif response == nil { //user doesn't exist\n\t\treturn nil, &pkg.Error{Err: err, Code: http.StatusNotFound, Message: \"User not found\"}\n\t}\n\n\t//call driven adapter responsible for updating a user's role inside the database\n\t_, err = srv.mongoRepository.UpdateUserRole(id, role)\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 := \"User's role updated sucessfully\"\n\n\treturn &message, nil\n}",
"func (_PermInterface *PermInterfaceTransactorSession) ApproveAdminRole(_orgId string, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.ApproveAdminRole(&_PermInterface.TransactOpts, _orgId, _account)\n}",
"func (role *Role) Update() error {\n\toptions := metav1.GetOptions{}\n\n\tupdate, err := role.client.Kubernetes.\n\t\tRbacV1().\n\t\tRoles(role.Namespace).\n\t\tGet(role.client.Ctx, role.Name, options)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to update role %s in namespace %s: %w\", role.Name, role.Namespace, err)\n\t}\n\n\trole.Role = *update\n\n\treturn nil\n}",
"func (_AcctManager *AcctManagerTransactor) AssignAdminRole(opts *bind.TransactOpts, _account common.Address, _orgId string, _roleId string, _status *big.Int) (*types.Transaction, error) {\n\treturn _AcctManager.contract.Transact(opts, \"assignAdminRole\", _account, _orgId, _roleId, _status)\n}",
"func (aaa *RolesService) AdminUpdateRolePermissionsV3(input *roles.AdminUpdateRolePermissionsV3Params) error {\n\ttoken, err := aaa.TokenRepository.GetToken()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, badRequest, unauthorized, forbidden, notFound, internalServerError, err := aaa.Client.Roles.AdminUpdateRolePermissionsV3(input, client.BearerToken(*token.AccessToken))\n\tif badRequest != nil {\n\t\treturn badRequest\n\t}\n\tif unauthorized != nil {\n\t\treturn unauthorized\n\t}\n\tif forbidden != nil {\n\t\treturn forbidden\n\t}\n\tif notFound != nil {\n\t\treturn notFound\n\t}\n\tif internalServerError != nil {\n\t\treturn internalServerError\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func NewAdminRole() *Role {\n\treturn &Role{\n\t\tname: \"admin\",\n\t\tpermissionList: PermissionList{},\n\t}\n}",
"func (arh *AdminRoleHandler) PutRole(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n}",
"func (aaa *RolesService) AdminUpdateRolePermissionsV4(input *roles.AdminUpdateRolePermissionsV4Params) (*iamclientmodels.ModelRoleV4Response, 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.AdminUpdateRolePermissionsV4(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}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ResendCode helps to resend a new code
|
func (orm *ORM) ResendCode(ctx context.Context, adminID string) (*models.Admin, error) {
var _Admin models.Admin
// check if admin exists
err := orm.DB.DB.First(&_Admin, "id = ?", adminID).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.New("AdminNotFound")
}
//generate code
code := generatecode.GenerateCode(6)
//save in redis and expire in an hours time
redisErr := orm.rdb.Set(ctx, fmt.Sprintf("%s", _Admin.ID), code, 1*time.Hour).Err()
if redisErr != nil {
return nil, redisErr
}
// send code to email
mailErr := mail.SendMail(_Admin.Email, fmt.Sprintf("Your code is %s", code))
if mailErr != nil {
return nil, mailErr
}
return &_Admin, nil
}
|
[
"func (dc *DexClient) ResendActivationCode(email string) error {\n\treturn dc.ResendActivationCodeContext(context.Background(), email)\n}",
"func RenewCode(c *gin.Context) {\n\n\tphoneKeyPost := strings.TrimSpace(c.PostForm(\"phone_key\"))\n\n\tif phoneKeyPost == \"\" {\n\t\tc.JSON(http.StatusBadRequest, &response.Data{Data: &response.ValidationError{Error: \"کلید شماره تماس الزامی است\"}})\n\t\treturn\n\t}\n\n\tphoneId := driver.NewDocumentID(constants.Phones, phoneKeyPost)\n\n\t//Search code by PHONE ID in users GRAPH with phone_to_code TYPE\n\tif codeDoc, found := database.FindItemInGraph(constants.UsersGraph, phoneId, constants.PhoneToCode); !found {\n\t\tc.JSON(http.StatusNotFound, &response.Data{Data: &response.DatabaseError{Message: \"اطلاعاتی برای این شماره تماس یافت نشد\"}})\n\t\treturn\n\t} else {\n\n\t\tactiveCode := utility.GenerateRandomCode()\n\n\t\t//Update CODE with new active code\n\t\tif err := model.Update(codeDoc[\"_key\"].(string), &model.Code{Code: activeCode, CreatedAt: time.Now().Unix()}); err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, &response.Data{Data: &response.ServerError{Message: err.Error()}})\n\t\t\treturn\n\t\t}\n\n\t\t//TODO Send active code with SMS\n\t\tc.JSON(http.StatusOK, &response.Data{\n\t\t\tData: &response.SendActiveCode{\n\t\t\t\tPhoneKey: phoneKeyPost,\n\t\t\t},\n\t\t\tState: true,\n\t\t})\n\t}\n}",
"func (dc *DexClient) ResendActivationCodeContext(ctx context.Context, email string) error {\n\t// Create request body\n\treq := map[string]string{\n\t\t\"email\": email,\n\t}\n\trBytes, err := json.Marshal(&req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn dc.responseOp(ctx, http.MethodPost, ResendActivationCodePath, bytes.NewBuffer(rBytes), nil)\n}",
"func (c *mockUserUsecase) ResendVerficationCode(ctx context.Context) error {\n\t_ = ctx.Value(entities.UserIDKey).(uint)\n\treturn nil\n}",
"func (c *Client) ResendEmailAddressVerificationCode(ctx context.Context) (*EmailAddressAuthenticationCodeInfo, error) {\n\tvar result EmailAddressAuthenticationCodeInfo\n\n\trequest := &ResendEmailAddressVerificationCodeRequest{}\n\tif err := c.rpc.Invoke(ctx, request, &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}",
"func (client BaseClient) RestartDeployedCodePackageResponder(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),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}",
"func (client BaseClient) RestartDeployedCodePackageSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}",
"func (res *Response) SetCode(num int) error {\n\tif res.done {\n\t\treturn errors.New(\"Unable to set code on finished response\")\n\t}\n\n\tres.StatusCode = num\n\treturn nil\n}",
"func ResendConfirmationCodeHandler(ctx *gin.Context) {\n\tbody, _ := schemavalidation.GetRequestBodyAsByteArray(ctx)\n\tvar resendConfirmationCodeSchema schema.ResendConfirmationCodeSchema\n\t// Validate input data\n\terrorMessages, ok := schemavalidation.ValidateJSONData(body, &resendConfirmationCodeSchema)\n\tif !ok {\n\t\tctx.JSON(http.StatusUnprocessableEntity, gin.H{\n\t\t\t\"data\": map[string]string {},\n\t\t\t\"errors\": errorMessages,\n\t\t\t\"message\": \"Invalid JSON input data.\",\n\t\t\t\"statusCode\": http.StatusUnprocessableEntity,\n\t\t})\n\t\treturn\n\t} \n\t// Resend a confirmation code\n\tresponse, awsError := cognitoAuth.ResendConfirmationCode(resendConfirmationCodeSchema.Email)\n\tif awsError == nil {\n\t\tctx.JSON(http.StatusOK, gin.H{\n\t\t\t\"data\": map[string]string {},\n\t\t\t\"errors\": map[string]string {},\n\t\t\t\"message\": response,\n\t\t\t\"statusCode\": http.StatusOK,\n\t\t})\n\t} else {\n\t\terrorCode, errorMessage := auth.CognitoErrorDetails(awsError)\n\t\tctx.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"data\": map[string]string {},\n\t\t\t\"errors\": map[string]string {errorCode: errorMessage},\n\t\t\t\"message\": errorMessage,\n\t\t\t\"statusCode\": http.StatusBadRequest,\n\t\t})\n\t}\n}",
"func (ctr *RegistRequestController) ResendEmailRegister(c echo.Context) error {\n\tresendEmailParams := new(param.ResendEmailParams)\n\n\tif err := c.Bind(resendEmailParams); err != nil {\n\t\tmsgErrBind := err.Error()\n\t\tfieldErr := utils.GetFieldBindForm(msgErrBind)\n\n\t\tif fieldErr != \"\" {\n\t\t\treturn c.JSON(http.StatusOK, cf.JsonResponse{\n\t\t\t\tStatus: cf.FailResponseCode,\n\t\t\t\tMessage: \"Invalid field \" + fieldErr,\n\t\t\t})\n\t\t}\n\t}\n\n\trequestObj, err := ctr.RegistRequestRepo.GetRegRequestsByID(resendEmailParams.RequestID)\n\tif err != nil {\n\t\tif err.Error() == pg.ErrNoRows.Error() {\n\t\t\treturn c.JSON(http.StatusOK, cf.JsonResponse{\n\t\t\t\tStatus: cf.FailResponseCode,\n\t\t\t\tMessage: \"Request is not exists\",\n\t\t\t})\n\t\t}\n\n\t\treturn c.JSON(http.StatusInternalServerError, cf.JsonResponse{\n\t\t\tStatus: cf.FailResponseCode,\n\t\t\tMessage: \"System error\",\n\t\t})\n\t}\n\n\tnewestRegistCode, err := ctr.RegCodeRepo.GetNewRegistCodeByRequestID(resendEmailParams.RequestID)\n\tif err != nil {\n\t\tif err.Error() != pg.ErrNoRows.Error() {\n\t\t\treturn c.JSON(http.StatusInternalServerError, cf.JsonResponse{\n\t\t\t\tStatus: cf.FailResponseCode,\n\t\t\t\tMessage: \"System error\",\n\t\t\t})\n\t\t}\n\t}\n\n\tif !newestRegistCode.ExpiredAt.IsZero() && newestRegistCode.ExpiredAt.After(utils.TimeNowUTC()) {\n\t\treturn c.JSON(http.StatusInternalServerError, cf.JsonResponse{\n\t\t\tStatus: cf.FailResponseCode,\n\t\t\tMessage: \"The register code is not expired yet, please check your email and spam mail\",\n\t\t})\n\t}\n\n\tresendEmailParams.Email = requestObj.Email\n\tregCodeObj, err := ctr.RegistRequestRepo.GetResendRegistCode(ctr.RegCodeRepo, resendEmailParams)\n\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, cf.JsonResponse{\n\t\t\tStatus: cf.FailResponseCode,\n\t\t\tMessage: \"System error\",\n\t\t})\n\t}\n\n\tuserProfile := c.Get(\"user_profile\").(m.User)\n\torg, err := ctr.OrgRepo.SelectEmailAndPassword(userProfile.OrganizationID)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, cf.JsonResponse{\n\t\t\tStatus: cf.FailResponseCode,\n\t\t\tMessage: \"System error\",\n\t\t})\n\t}\n\tif org.Email == \"\" || org.EmailPassword == \"\" {\n\t\treturn c.JSON(http.StatusUnprocessableEntity, cf.JsonResponse{\n\t\t\tStatus: cf.FailResponseCode,\n\t\t\tMessage: \"Your organization must have an email\",\n\t\t})\n\t}\n\n\tctr.InitSmtp(org.Email, org.EmailPassword)\n\n\tsampleData := new(param.SampleData)\n\tsampleData.SendTo = []string{regCodeObj.Email}\n\tsampleData.URL = os.Getenv(\"BASE_SPA_URL\") + \"/organization/create-organization/\" + regCodeObj.Code\n\tif err := ctr.SendMail(\"Micro Erp Registration Email\", sampleData, cf.CreateOrganizationTemplate); err != nil {\n\t\tctr.Logger.Error(err)\n\t\treturn c.JSON(http.StatusInternalServerError, cf.JsonResponse{\n\t\t\tStatus: cf.FailResponseCode,\n\t\t\tMessage: \"System error\",\n\t\t})\n\t}\n\n\treturn c.JSON(http.StatusOK, cf.JsonResponse{\n\t\tStatus: cf.SuccessResponseCode,\n\t\tMessage: \"Success\",\n\t})\n}",
"func (client BaseClient) RestartDeployedCodePackage(ctx context.Context, nodeName string, applicationID string, restartDeployedCodePackageDescription RestartDeployedCodePackageDescription, timeout *int64) (result autorest.Response, err error) {\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: restartDeployedCodePackageDescription,\n\t\t\tConstraints: []validation.Constraint{{Target: \"restartDeployedCodePackageDescription.ServiceManifestName\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t{Target: \"restartDeployedCodePackageDescription.CodePackageName\", Name: validation.Null, Rule: true, Chain: nil},\n\t\t\t\t{Target: \"restartDeployedCodePackageDescription.CodePackageInstanceID\", Name: validation.Null, Rule: true, Chain: nil}}},\n\t\t{TargetValue: timeout,\n\t\t\tConstraints: []validation.Constraint{{Target: \"timeout\", Name: validation.Null, Rule: false,\n\t\t\t\tChain: []validation.Constraint{{Target: \"timeout\", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil},\n\t\t\t\t\t{Target: \"timeout\", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil},\n\t\t\t\t}}}}}); err != nil {\n\t\treturn result, validation.NewError(\"servicefabric.BaseClient\", \"RestartDeployedCodePackage\", err.Error())\n\t}\n\n\treq, err := client.RestartDeployedCodePackagePreparer(ctx, nodeName, applicationID, restartDeployedCodePackageDescription, timeout)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"servicefabric.BaseClient\", \"RestartDeployedCodePackage\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.RestartDeployedCodePackageSender(req)\n\tif err != nil {\n\t\tresult.Response = resp\n\t\terr = autorest.NewErrorWithError(err, \"servicefabric.BaseClient\", \"RestartDeployedCodePackage\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.RestartDeployedCodePackageResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"servicefabric.BaseClient\", \"RestartDeployedCodePackage\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}",
"func (s *BaseSndAsmListener) ExitCode(ctx *CodeContext) {}",
"func (dns *Msg) SetRcode(request *Msg, rcode int) *Msg {\n\tdns.SetReply(request)\n\tdns.Rcode = rcode\n\treturn dns\n}",
"func (v *Verifier) SatisfyCode(code string, kittyID string) error {\n\tif !v.Enabled {\n\t\treturn nil\n\t}\n\n\tsatisfyRequest, err := json.Marshal(SatisfyRequest{\n\t\tcode,\n\t\tkittyID,\n\t})\n\tif err != nil {\n\t\tv.log.WithError(err).Error(\"unable to marshal satisfy request\")\n\t\treturn err\n\t}\n\n\t// make a satisfy request to verification service\n\tresp, err := v.client.Post(\"/api/satisfy_code\",\n\t\t\"application/json\", bytes.NewBuffer(satisfyRequest))\n\tif err != nil {\n\t\tv.log.WithError(err).Error(\"failed to verify reservation code\")\n\t\treturn err\n\t}\n\n\tswitch resp.StatusCode {\n\tcase http.StatusNoContent:\n\t\tbreak\n\tcase http.StatusRequestTimeout:\n\t\treturn ErrSatisfyRequestTimeOut\n\tdefault:\n\t\treturn ErrSatisfyFailed\n\t}\n\n\treturn nil\n}",
"func (service AccountsService) Reopen(code string) (*Response, error) {\n\taction := fmt.Sprintf(\"accounts/%s/reopen\", code)\n\treq, err := service.client.newRequest(\"PUT\", action, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn service.client.do(req, nil)\n}",
"func (p *Persister) UseRecoveryCode(ctx context.Context, fID uuid.UUID, codeVal string) (*code.RecoveryCode, error) {\n\tctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, \"persistence.sql.UseRecoveryCode\")\n\tdefer span.End()\n\n\tvar recoveryCode *code.RecoveryCode\n\n\tnid := p.NetworkID(ctx)\n\n\tflowTableName := new(recovery.Flow).TableName(ctx)\n\n\tif err := sqlcon.HandleError(p.Transaction(ctx, func(ctx context.Context, tx *pop.Connection) (err error) {\n\n\t\t//#nosec G201 -- TableName is static\n\t\tif err := sqlcon.HandleError(tx.RawQuery(fmt.Sprintf(\"UPDATE %s SET submit_count = submit_count + 1 WHERE id = ? AND nid = ?\", flowTableName), fID, nid).Exec()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar submitCount int\n\t\t// Because MySQL does not support \"RETURNING\" clauses, but we need the updated `submit_count` later on.\n\t\t//#nosec G201 -- TableName is static\n\t\tif err := sqlcon.HandleError(tx.RawQuery(fmt.Sprintf(\"SELECT submit_count FROM %s WHERE id = ? AND nid = ?\", flowTableName), fID, nid).First(&submitCount)); err != nil {\n\t\t\tif errors.Is(err, sqlcon.ErrNoRows) {\n\t\t\t\t// Return no error, as that would roll back the transaction\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn err\n\t\t}\n\n\t\t// This check prevents parallel brute force attacks to generate the recovery code\n\t\t// by checking the submit count inside this database transaction.\n\t\t// If the flow has been submitted more than 5 times, the transaction is aborted (regardless of whether the code was correct or not)\n\t\t// and we thus give no indication whether the supplied code was correct or not. See also https://github.com/ory/kratos/pull/2645#discussion_r984732899\n\t\tif submitCount > 5 {\n\t\t\treturn errors.WithStack(code.ErrCodeSubmittedTooOften)\n\t\t}\n\n\t\tvar recoveryCodes []code.RecoveryCode\n\t\tif err = sqlcon.HandleError(tx.Where(\"nid = ? AND selfservice_recovery_flow_id = ?\", nid, fID).All(&recoveryCodes)); err != nil {\n\t\t\tif errors.Is(err, sqlcon.ErrNoRows) {\n\t\t\t\t// Return no error, as that would roll back the transaction\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn err\n\t\t}\n\n\tsecrets:\n\t\tfor _, secret := range p.r.Config().SecretsSession(ctx) {\n\t\t\tsuppliedCode := []byte(p.hmacValueWithSecret(ctx, codeVal, secret))\n\t\t\tfor i := range recoveryCodes {\n\t\t\t\tcode := recoveryCodes[i]\n\t\t\t\tif subtle.ConstantTimeCompare([]byte(code.CodeHMAC), suppliedCode) == 0 {\n\t\t\t\t\t// Not the supplied code\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trecoveryCode = &code\n\t\t\t\tbreak secrets\n\t\t\t}\n\t\t}\n\n\t\tif recoveryCode == nil || !recoveryCode.IsValid() {\n\t\t\t// Return no error, as that would roll back the transaction\n\t\t\treturn nil\n\t\t}\n\n\t\tvar ra identity.RecoveryAddress\n\t\tif err := tx.Where(\"id = ? AND nid = ?\", recoveryCode.RecoveryAddressID, nid).First(&ra); err != nil {\n\t\t\tif err = sqlcon.HandleError(err); !errors.Is(err, sqlcon.ErrNoRows) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\trecoveryCode.RecoveryAddress = &ra\n\n\t\t//#nosec G201 -- TableName is static\n\t\treturn sqlcon.HandleError(tx.RawQuery(fmt.Sprintf(\"UPDATE %s SET used_at = ? WHERE id = ? AND nid = ?\", recoveryCode.TableName(ctx)), time.Now().UTC(), recoveryCode.ID, nid).Exec())\n\t})); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif recoveryCode == nil {\n\t\treturn nil, code.ErrCodeNotFound\n\t}\n\n\tif recoveryCode.IsExpired() {\n\t\treturn nil, flow.NewFlowExpiredError(recoveryCode.ExpiresAt)\n\t}\n\n\tif recoveryCode.WasUsed() {\n\t\treturn nil, code.ErrCodeAlreadyUsed\n\t}\n\n\treturn recoveryCode, nil\n}",
"func (controller *playgroundController) RunCode(ctx context.Context, info *pb.RunCodeRequest) (*pb.RunCodeResponse, error) {\n\t// check for correct sdk\n\tif info.Sdk != controller.env.BeamSdkEnvs.ApacheBeamSdk {\n\t\tlogger.Errorf(\"RunCode(): request contains incorrect sdk: %s\\n\", info.Sdk)\n\t\treturn nil, errors.InvalidArgumentError(\"Run code()\", \"incorrect sdk: \"+info.Sdk.String())\n\t}\n\tswitch info.Sdk {\n\tcase pb.Sdk_SDK_UNSPECIFIED, pb.Sdk_SDK_PYTHON, pb.Sdk_SDK_SCIO:\n\t\tlogger.Errorf(\"RunCode(): unimplemented sdk: %s\\n\", info.Sdk)\n\t\treturn nil, errors.InvalidArgumentError(\"Run code()\", \"unimplemented sdk: \"+info.Sdk.String())\n\t}\n\n\tcacheExpirationTime := controller.env.ApplicationEnvs.CacheEnvs().KeyExpirationTime()\n\tpipelineId := uuid.New()\n\n\tlc, err := life_cycle.Setup(info.Sdk, info.Code, pipelineId, controller.env.ApplicationEnvs.WorkingDir())\n\tif err != nil {\n\t\tlogger.Errorf(\"RunCode(): error during setup file system: %s\\n\", err.Error())\n\t\treturn nil, errors.InternalError(\"Run code\", \"Error during setup file system: \"+err.Error())\n\t}\n\n\tcompileBuilder, err := compile_builder.Setup(lc.GetAbsoluteExecutableFilePath(), lc.GetAbsoluteExecutableFilesFolderPath(), info.Sdk, controller.env.BeamSdkEnvs.ExecutorConfig)\n\tif err != nil {\n\t\tlogger.Errorf(\"RunCode(): error during setup run builder: %s\\n\", err.Error())\n\t\treturn nil, errors.InvalidArgumentError(\"Run code\", \"Error during setup compile builder: \"+err.Error())\n\t}\n\n\tif err = utils.SetToCache(ctx, controller.cacheService, pipelineId, cache.Status, pb.Status_STATUS_VALIDATING); err != nil {\n\t\treturn nil, errors.InternalError(\"Run code()\", \"Error during set value to cache: \"+err.Error())\n\t}\n\tif err = controller.cacheService.SetExpTime(ctx, pipelineId, cacheExpirationTime); err != nil {\n\t\tlogger.Errorf(\"%s: RunCode(): cache.SetExpTime(): %s\\n\", pipelineId, err.Error())\n\t\treturn nil, errors.InternalError(\"Run code()\", \"Error during set expiration to cache: \"+err.Error())\n\t}\n\n\t// TODO change using of context.TODO() to context.Background()\n\tgo code_processing.Process(context.TODO(), controller.cacheService, lc, compileBuilder, pipelineId, &controller.env.ApplicationEnvs, &controller.env.BeamSdkEnvs)\n\n\tpipelineInfo := pb.RunCodeResponse{PipelineUuid: pipelineId.String()}\n\treturn &pipelineInfo, nil\n}",
"func (controller *playgroundController) RunCode(ctx context.Context, info *pb.RunCodeRequest) (*pb.RunCodeResponse, error) {\n\t// check if we can take a new RunCode request\n\tif !utils.CheckNumOfTheParallelJobs(controller.env.ApplicationEnvs.WorkingDir(), controller.env.BeamSdkEnvs.NumOfParallelJobs()) {\n\t\tlogger.Warnf(\"RunCode(): number of parallel jobs is exceeded\\n\")\n\t\treturn nil, cerrors.ResourceExhaustedError(\"Error during preparing\", \"Number of parallel jobs is exceeded\")\n\t}\n\t// check for correct sdk\n\tif info.Sdk != controller.env.BeamSdkEnvs.ApacheBeamSdk {\n\t\tlogger.Errorf(\"RunCode(): request contains incorrect sdk: %s\\n\", info.Sdk)\n\t\treturn nil, cerrors.InvalidArgumentError(\"Error during preparing\", \"Incorrect sdk. Want to receive %s, but the request contains %s\", controller.env.BeamSdkEnvs.ApacheBeamSdk.String(), info.Sdk.String())\n\t}\n\tswitch info.Sdk {\n\tcase pb.Sdk_SDK_UNSPECIFIED:\n\t\tlogger.Errorf(\"RunCode(): unimplemented sdk: %s\\n\", info.Sdk)\n\t\treturn nil, cerrors.InvalidArgumentError(\"Error during preparing\", \"Sdk is not implemented yet: %s\", info.Sdk.String())\n\t}\n\n\tcacheExpirationTime := controller.env.ApplicationEnvs.CacheEnvs().KeyExpirationTime()\n\tpipelineId := uuid.New()\n\n\tsources := make([]entity.FileEntity, 0)\n\tif len(info.Files) > 0 {\n\t\tfor _, file := range info.Files {\n\t\t\tsources = append(sources, entity.FileEntity{\n\t\t\t\tName: file.Name,\n\t\t\t\tContent: file.Content,\n\t\t\t\tIsMain: file.IsMain,\n\t\t\t\tCntxLine: 1,\n\t\t\t})\n\t\t}\n\t} else {\n\t\tfileName, err := utils.GetFileName(\"\", info.Code, info.Sdk)\n\t\tif err != nil {\n\t\t\treturn nil, cerrors.InternalError(errorTitleRunCode, \"Failed to get default filename\")\n\t\t}\n\t\tsources = append(sources, entity.FileEntity{\n\t\t\tName: fileName,\n\t\t\tContent: info.Code,\n\t\t\tIsMain: true,\n\t\t\tCntxLine: 1,\n\t\t})\n\t}\n\n\temulatorConfiguration := emulators.EmulatorConfiguration{\n\t\tDatasets: info.Datasets,\n\t\tDatasetsPath: controller.env.ApplicationEnvs.DatasetsPath(),\n\t\tKafkaEmulatorExecutablePath: controller.env.ApplicationEnvs.KafkaExecutablePath(),\n\t}\n\n\tlc, err := life_cycle.Setup(info.Sdk, sources, pipelineId, controller.env.ApplicationEnvs.WorkingDir(), controller.env.ApplicationEnvs.PipelinesFolder(), controller.env.BeamSdkEnvs.PreparedModDir(), emulatorConfiguration)\n\tif err != nil {\n\t\tlogger.Errorf(\"RunCode(): error during setup file system: %s\\n\", err.Error())\n\t\treturn nil, cerrors.InternalError(\"Error during preparing\", \"Error during setup file system for the code processing: %s\", err.Error())\n\t}\n\n\tif err = utils.SetToCache(controller.cacheService, pipelineId, cache.Status, pb.Status_STATUS_VALIDATING); err != nil {\n\t\tcode_processing.DeleteResources(pipelineId, lc)\n\t\treturn nil, cerrors.InternalError(\"Error during preparing\", \"Error during saving status of the code processing\")\n\t}\n\tif err = utils.SetToCache(controller.cacheService, pipelineId, cache.RunOutputIndex, 0); err != nil {\n\t\tcode_processing.DeleteResources(pipelineId, lc)\n\t\treturn nil, cerrors.InternalError(\"Error during preparing\", \"Error during saving initial run output\")\n\t}\n\tif err = utils.SetToCache(controller.cacheService, pipelineId, cache.LogsIndex, 0); err != nil {\n\t\tcode_processing.DeleteResources(pipelineId, lc)\n\t\treturn nil, cerrors.InternalError(\"Error during preparing\", \"Error during saving value for the logs output\")\n\t}\n\tif err = utils.SetToCache(controller.cacheService, pipelineId, cache.Canceled, false); err != nil {\n\t\tcode_processing.DeleteResources(pipelineId, lc)\n\t\treturn nil, cerrors.InternalError(\"Error during preparing\", \"Error during saving initial cancel flag\")\n\t}\n\tif err = controller.cacheService.SetExpTime(ctx, pipelineId, cacheExpirationTime); err != nil {\n\t\tlogger.Errorf(\"%s: RunCode(): cache.SetExpTime(): %s\\n\", pipelineId, err.Error())\n\t\tcode_processing.DeleteResources(pipelineId, lc)\n\t\treturn nil, cerrors.InternalError(\"Error during preparing\", \"Internal error\")\n\t}\n\n\tgo code_processing.Process(context.Background(), controller.cacheService, lc, pipelineId, &controller.env.ApplicationEnvs, &controller.env.BeamSdkEnvs, info.PipelineOptions)\n\n\tpipelineInfo := pb.RunCodeResponse{PipelineUuid: pipelineId.String()}\n\treturn &pipelineInfo, nil\n}",
"func (t *TestArtifactManager) DeployCode(domain core.RecordRef, request core.RecordRef, code []byte, mt core.MachineType) (*core.RecordRef, error) {\n\tref := testutils.RandomRef()\n\n\tt.Codes[ref] = &TestCodeDescriptor{\n\t\tARef: ref,\n\t\tACode: code,\n\t\tAMachineType: core.MachineTypeGoPlugin,\n\t}\n\treturn &ref, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
CompareAdminCodes compares the admin code sent by user
|
func (orm *ORM) CompareAdminCodes(ctx context.Context, adminID string, code string) (bool, error) {
//check in redis to see if its the same and not expired
value, err := orm.rdb.Get(ctx, fmt.Sprintf("%s", adminID)).Result()
if err == redis.Nil {
return false, errors.New("CodeHasExpired")
} else if err != nil {
return false, err
}
if value != code {
return false, errors.New("CodeIncorrect")
}
return true, nil
}
|
[
"func (o *CTROracle) CheckAdmin(ciphertext []byte) bool {\n\tctr := stream.NewCTR(o.Key, o.Nonce)\n\tdecrypted := string(ctr.Decrypt(ciphertext))\n\n\treturn strings.Index(decrypted, \";admin=true;\") >= 0\n}",
"func admin(b []byte) bool {\n\tvar dec bytes.Buffer\n\tif err := common.NewCTR(key, nonce).Process(bytes.NewReader(b), &dec); err != nil {\n\t\tpanic(err)\n\t}\n\treturn bytes.Contains(dec.Bytes(), []byte(\";admin=true;\"))\n}",
"func (c AESCBC) DecryptCheckAdmin(cipherText []byte) bool {\n\ttext := c.Decrypt(cipherText)\n\tfor _, val := range bytes.Split(text, []byte(\";\")) {\n\t\ttuple := bytes.Split(val, []byte(\"=\"))\n\t\t// If the tuple is of length 2, check if we have admin = true.\n\t\tif len(tuple) == 2 && bytes.Equal(tuple[0], []byte(\"admin\")) && bytes.Equal(tuple[1], []byte(\"true\")) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (o *PostTestcryptAdministratorsMoidDefault) Code() int {\n\treturn o._statusCode\n}",
"func Isadminorme(db *bolt.DB, settings rscore.Settings, c *rscore.Apicall,\n tu rscore.User, w http.ResponseWriter) bool {\n\n var ok bool\n\n if tu.Name == c.User {\n ok, _ = Userv(db, w, settings.Umax, c, rscore.ALEV_CONTRIB)\n } else {\n ok, _ = Userv(db, w, settings.Umax, c, rscore.ALEV_ADMIN)\n }\n\n return ok\n}",
"func CheckCode(c *gin.Context) {\n\n\tphoneKeyParam := strings.TrimSpace(c.Param(\"phone\"))\n\tactiveCodePost := strings.TrimSpace(c.PostForm(\"code\"))\n\n\t//Validation Queries\n\tif phoneKeyParam == \"\" {\n\t\tc.JSON(http.StatusBadRequest, &response.Data{Data: &response.ValidationError{Error: \"کلید شماره تماس الزامی است\"}})\n\t\treturn\n\t} else if activeCodePost == \"\" {\n\t\tc.JSON(http.StatusBadRequest, &response.Data{Data: &response.ValidationError{Error: \"کد فعالسازی الزامی است\"}})\n\t\treturn\n\t}\n\n\tcode, _ := strconv.Atoi(activeCodePost)\n\n\tphoneId := driver.NewDocumentID(constants.Phones, phoneKeyParam)\n\n\t//Search PHONE ID in users GRAPH by phone_to_code TYPE\n\tif codeDoc, found := database.FindItemInGraph(constants.UsersGraph, phoneId, constants.PhoneToCode); !found {\n\t\tc.JSON(http.StatusBadRequest, &response.Data{Data: &response.ServerError{Message: \"کدی برای این شماره تماس یافت نشد\"}})\n\t\treturn\n\t} else {\n\n\t\t//Check active code\n\t\tif int(codeDoc[\"code\"].(float64)) != code {\n\t\t\tc.JSON(http.StatusBadRequest, &response.Data{Data: &response.ValidationError{Error: \"کد فعالسازی صحیح نمیباشد\"}})\n\t\t} else {\n\n\t\t\t//Check active code TimeOut\n\t\t\tif !utility.CheckActiveTime(int64(codeDoc[\"created_at\"].(float64)), time.Now().Unix()) {\n\t\t\t\tc.JSON(http.StatusBadRequest, &response.Data{Data: &response.ValidationError{Error: \"مدت زمان اعتبار کد فعالسازی تمام شده است\"}})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t//Search PHONE ID in users GRAPH by phone_to_user TYPE\n\t\t\tif userDoc, found := database.FindItemInGraph(constants.UsersGraph, phoneId, constants.PhoneToUser); found {\n\n\t\t\t\ttoken := utility.Token(userDoc[\"_key\"].(string), constants.UserRole)\n\n\t\t\t\t//This user already registered\n\t\t\t\tc.JSON(http.StatusOK, &response.Data{\n\t\t\t\t\tData: &response.NewToken{\n\t\t\t\t\t\tToken: token,\n\t\t\t\t\t\tIsNewUser: false,\n\t\t\t\t\t},\n\t\t\t\t\tState: true,\n\t\t\t\t})\n\t\t\t} else {\n\n\t\t\t\ttoken := utility.RegisterToken(phoneId.Key())\n\n\t\t\t\t//This is new user\n\t\t\t\tc.JSON(http.StatusOK, &response.Data{\n\t\t\t\t\tData: &response.NewToken{\n\t\t\t\t\t\tToken: token,\n\t\t\t\t\t\tIsNewUser: true,\n\t\t\t\t\t},\n\t\t\t\t\tState: true,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n}",
"func adminFilter(cliAdmins []*cliAdmin, f func(*cliAdmin) bool) []*cliAdmin {\n\tvar result []*cliAdmin\n\tfor _, a := range cliAdmins {\n\t\tif f(a) {\n\t\t\tresult = append(result, a)\n\t\t}\n\t}\n\treturn result\n}",
"func (o ClientCertificateCommonNameOutput) IsAdmin() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v ClientCertificateCommonName) bool { return v.IsAdmin }).(pulumi.BoolOutput)\n}",
"func (s *AdminServer) checkAdmin(ctx context.Context, methodName string) error {\n\tcaller := auth.CurrentIdentity(ctx)\n\tlogging.Warningf(ctx, \"Admin call %q by %q\", methodName, caller)\n\tswitch yes, err := auth.IsMember(ctx, s.AdminGroup); {\n\tcase err != nil:\n\t\treturn status.Errorf(codes.Internal, \"failed to check ACL\")\n\tcase !yes:\n\t\treturn status.Errorf(codes.PermissionDenied, \"not an administrator\")\n\tdefault:\n\t\treturn nil\n\t}\n}",
"func IsAdminChecker(w http.ResponseWriter, r *http.Request, adminlevel string) error {\n\tswitch adminlevel {\n\tcase \"game\":\n\t\tqueries, err := getQueries(r, \"g\")\n\t\tif err != nil {\n\t\t\twriteResponse(w, http.StatusInternalServerError, fmt.Sprintf(\"{\\\"error\\\":\\\"%s\\\"}\", err))\n\t\t\treturn err\n\t\t}\n\n\t\tstatusCode, err := isAdmin(r, queries[\"g\"])\n\t\tif err != nil {\n\t\t\tweblog(fmt.Sprintf(\"IsAdminCheck failed in the handler\"))\n\t\t\twriteResponse(w, statusCode, fmt.Sprintf(\"{\\\"error\\\":\\\"%s\\\"}\", err))\n\t\t\treturn err\n\t\t}\n\t\tweblog(fmt.Sprintf(\"IsAdminCheck passed in the handler\"))\n\tcase \"global\":\n\t\tstatusCode, err := isGlobalAdmin(r)\n\t\tif err != nil {\n\t\t\tweblog(fmt.Sprintf(\"IsGlobalCheck failed in the handler\"))\n\t\t\twriteResponse(w, statusCode, fmt.Sprintf(\"{\\\"error\\\":\\\"%s\\\"}\", err))\n\t\t\treturn err\n\t\t}\n\t\tweblog(fmt.Sprintf(\"IsGlobalCheck passed in the handler\"))\n\tdefault:\n\t\treturn nil\n\t}\n\treturn nil\n}",
"func (o *UpdateUserGroupsForbidden) IsCode(code int) bool {\n\treturn code == 403\n}",
"func (o *UnixUserSettingsModifyOK) IsCode(code int) bool {\n\treturn code == 200\n}",
"func CheckAdminByToken(token *string) error {\n\n\tvar databaseAdmin models.Admin\n\n\tdb, err := Connect()\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer db.Close()\n\n\trows, err := db.Query(`\n\t\tselect * from admins\n\t\tlimit 10;\n\t`)\n\tdefer rows.Close()\n\n\n\tfor rows.Next() {\n\t\trows.Scan(&databaseAdmin.ID, &databaseAdmin.Email, &databaseAdmin.Password) // hashed\n\t\terr = framework.CompareHashandPassword(databaseAdmin.Password, os.Getenv(\"ADMIN_PASS\"))\n\t\tif err == nil {\n\t\t\tdatabaseAdmin.Password = os.Getenv(\"ADMIN_PASS\")\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\n\t\tdatabaseAdminJSON, err := json.Marshal(databaseAdmin)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = framework.CompareHashandPassword(*token, string(databaseAdminJSON))\n\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn errors.New(\"Not Found\")\n\n}",
"func compareAuth(au1, au2 string) (bool, bool) {\n\tshort, long := au1, au2\n\tif len(au1) > len(au2) {\n\t\tshort, long = au2, au1\n\t}\n\trsShort := []rune(short)\n\trs := []rune(long)[0:len(rsShort)]\n\tshort2 := string(rs)\n\n\treturn clt.CompareString(short, short2) == 0, au1 < au2\n}",
"func (o ClientCertificateCommonNameResponseOutput) IsAdmin() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v ClientCertificateCommonNameResponse) bool { return v.IsAdmin }).(pulumi.BoolOutput)\n}",
"func (_Contract *ContractFilterer) FilterAdminChanged(opts *bind.FilterOpts) (*ContractAdminChangedIterator, error) {\n\n\tlogs, sub, err := _Contract.contract.FilterLogs(opts, \"AdminChanged\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContractAdminChangedIterator{contract: _Contract.contract, event: \"AdminChanged\", logs: logs, sub: sub}, nil\n}",
"func CheckAuthorised(code string, adminReq bool, db *sql.DB) (bool, error) {\n\tif len(code) != 20 {\n\t\treturn false, errors.New(\"invalid code\")\n\t}\n\trows, err := db.Query(getAuthRowQuery, code)\n\tif err != nil {\n\t\tfmt.Printf(\"%v: error on CheckAuthorised query - %v\\n\", time.Now(), err)\n\t}\n\tdefer rows.Close()\n\n\tvar (\n\t\tid int\n\t\tadmin bool\n\t)\n\tfor rows.Next() {\n\t\trows.Scan(&id, &admin)\n\t}\n\tif id < 1 || (!admin && admin != adminReq) {\n\t\treturn false, errors.New(\"forbidden\")\n\t}\n\treturn true, nil\n}",
"func (o *UpdateRepository1Forbidden) IsCode(code int) bool {\n\treturn code == 403\n}",
"func (o *UpdatePrivilegeForbidden) IsCode(code int) bool {\n\treturn code == 403\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Value returns a value constructed from the type of the event and filled via the bound contract's UnpackLog function. The optional typ parameter allows to disambiguate the type to select. This is useful in cases where the ID of an EventInfo refers to multiples EventType where each of the bound contract would be able to unpack the log with no error.
|
func (ev *EventInfo) Value(log types.Log, typ ...reflect.Type) (res reflect.Value, err error) {
var ty reflect.Type
if len(typ) > 0 {
ty = typ[0]
}
for _, u := range ev.Types {
if ty != nil && ty != u.Type {
continue
}
event := reflect.New(u.Type.Elem())
err = u.BoundContract.UnpackLog(event.Interface(), ev.Name, log)
if err != nil {
continue
}
f := event.Elem().FieldByName("Raw")
if f.IsValid() && f.CanSet() {
f.Set(reflect.ValueOf(log))
}
return event, nil
}
return
}
|
[
"func (e _event) Type() string { return e.Type_ }",
"func (e *event) Type() string {\n\treturn e.typ\n}",
"func (e Event) Value(v interface{}) error {\n\tvar tmp struct {\n\t\tData interface{} `json:\"data\"`\n\t}\n\ttmp.Data = &v\n\treturn json.Unmarshal(e.rawData, &tmp)\n}",
"func EventType(val string) zap.Field {\n\treturn zap.String(FieldEventType, val)\n}",
"func (e *event) Value() interface{} {\n\treturn e.value\n}",
"func (bse *BaseEvent) Type(eventType string) {\n\tbse.EventType = eventType\n}",
"func (e *Event) Type() string {\n\treturn e.eventType\n}",
"func getEventLogInfo(parsedEventLogEntry types.TpmEvent) types.EventLog {\n\n\tlog.Trace(\"vmware_host_connector:getEventLogInfo() Entering\")\n\tdefer log.Trace(\"vmware_host_connector:getEventLogInfo() Leaving\")\n\teventLog := types.EventLog{Measurement: intArrayToHexString(parsedEventLogEntry.EventDetails.DataHash)}\n\n\tif parsedEventLogEntry.EventDetails.VibName != nil {\n\t\teventLog.TypeID = VIB_NAME_TYPE_ID\n\t\teventLog.TypeName = *parsedEventLogEntry.EventDetails.ComponentName\n\t\teventLog.Tags = append(eventLog.Tags, COMPONENT_PREFIX+*parsedEventLogEntry.EventDetails.ComponentName)\n\t\tif *parsedEventLogEntry.EventDetails.VibName != \"\" {\n\t\t\teventLog.Tags = append(eventLog.Tags, VIM_API_PREFIX+TPM_SOFTWARE_COMPONENT_EVENT_TYPE+DETAILS_SUFFIX+\"_\"+*parsedEventLogEntry.EventDetails.VibName+\"_\"+*parsedEventLogEntry.EventDetails.VibVendor)\n\t\t} else {\n\t\t\teventLog.Tags = append(eventLog.Tags, VIM_API_PREFIX+TPM_SOFTWARE_COMPONENT_EVENT_TYPE+DETAILS_SUFFIX)\n\t\t}\n\t} else if parsedEventLogEntry.EventDetails.CommandLine != nil {\n\t\teventLog.TypeID = COMMANDLINE_TYPE_ID\n\t\tuuid := getBootUUIDFromCL(*parsedEventLogEntry.EventDetails.CommandLine)\n\t\tif uuid != \"\" {\n\t\t\teventLog.Tags = append(eventLog.Tags, COMMANDLINE_PREFIX)\n\t\t} else {\n\t\t\teventLog.Tags = append(eventLog.Tags, COMMANDLINE_PREFIX+*parsedEventLogEntry.EventDetails.CommandLine)\n\t\t}\n\t\teventLog.TypeName = *parsedEventLogEntry.EventDetails.CommandLine\n\t\teventLog.Tags = append(eventLog.Tags, VIM_API_PREFIX+TPM_COMMAND_EVENT_TYPE+DETAILS_SUFFIX)\n\n\t} else if parsedEventLogEntry.EventDetails.OptionsFileName != nil {\n\t\teventLog.TypeID = OPTIONS_FILE_NAME_TYPE_ID\n\t\teventLog.TypeName = *parsedEventLogEntry.EventDetails.OptionsFileName\n\t\teventLog.Tags = append(eventLog.Tags, BOOT_OPTIONS_PREFIX+*parsedEventLogEntry.EventDetails.OptionsFileName)\n\t\teventLog.Tags = append(eventLog.Tags, VIM_API_PREFIX+TPM_OPTION_EVENT_TYPE+DETAILS_SUFFIX)\n\n\t} else if parsedEventLogEntry.EventDetails.BootSecurityOption != nil {\n\t\teventLog.TypeID = BOOT_SECURITY_OPTION_TYPE_ID\n\t\teventLog.TypeName = *parsedEventLogEntry.EventDetails.BootSecurityOption\n\t\teventLog.Tags = append(eventLog.Tags, BOOT_SECURITY_OPTIONS_PREFIX+*parsedEventLogEntry.EventDetails.BootSecurityOption)\n\t\teventLog.Tags = append(eventLog.Tags, VIM_API_PREFIX+TPM_BOOT_SECURITY_OPTION_EVENT_TYPE+DETAILS_SUFFIX)\n\t} else {\n\t\tlog.Warn(\"Unrecognized event in module event log\")\n\t}\n\n\treturn eventLog\n}",
"func (e Event) GetType() int {\n\treturn int(C.caca_get_event_type(e.Ev))\n}",
"func EventKind(val string) zap.Field {\n\treturn zap.String(FieldEventKind, val)\n}",
"func (me TEventTypeType) String() string { return xsdt.String(me).String() }",
"func (e *basicEvent) TypeString() string {\n\treturn e.etype\n}",
"func (uem UnknownEventMetadata) Type() string {\n\treturn \"unknown\"\n}",
"func gethUnpackLog(codec *contractCodec, out interface{}, event string, log types.Log) error {\n\tif len(log.Data) > 0 {\n\t\tif err := codec.abi.UnpackIntoInterface(out, event, log.Data); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tvar indexed abi.Arguments\n\tfor _, arg := range codec.abi.Events[event].Inputs {\n\t\tif arg.Indexed {\n\t\t\tindexed = append(indexed, arg)\n\t\t}\n\t}\n\treturn parseTopics(out, indexed, log.Topics[1:])\n}",
"func (e *Event) GetType() EventType {\n\treturn EventType(C.CALL_MACRO_GST_EVENT_TYPE(e.g()))\n}",
"func (ce *CustomEvent) GetType() string {\n\treturn ce.eventType.String()\n}",
"func (me TEventType) String() string { return xsdt.String(me).String() }",
"func (t *TimeDynamic) LogValue() interface{} {\n\tvar now time.Time\n\tif t.TimeKeeper == nil {\n\t\tnow = time.Now()\n\t} else {\n\t\tnow = t.TimeKeeper.Now()\n\t}\n\tif t.UTC {\n\t\tnow = now.UTC()\n\t}\n\tif !t.AsString {\n\t\treturn now\n\t}\n\tif t.Layout == \"\" {\n\t\treturn now.Format(time.RFC3339)\n\t}\n\treturn now.Format(t.Layout)\n}",
"func EntryVal(e *dwarf.Entry, a dwarf.Attr,) interface{}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewListGroupsOK creates a ListGroupsOK with default headers values
|
func NewListGroupsOK() *ListGroupsOK {
return &ListGroupsOK{}
}
|
[
"func NewListGroupsDefault(code int) *ListGroupsDefault {\n\treturn &ListGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewListFoodGroupsOK() *ListFoodGroupsOK {\n\treturn &ListFoodGroupsOK{}\n}",
"func NewListRuleGroupsDefault(code int) *ListRuleGroupsDefault {\n\treturn &ListRuleGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewListRuleGroupsOK() *ListRuleGroupsOK {\n\treturn &ListRuleGroupsOK{}\n}",
"func CreateListServerGroupsRequest() (request *ListServerGroupsRequest) {\n\trequest = &ListServerGroupsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Alb\", \"2020-06-16\", \"ListServerGroups\", \"alb\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}",
"func (b MockBroker) ListGroups(request *sarama.ListGroupsRequest) (*sarama.ListGroupsResponse, error) {\n\targs := b.Called(request)\n\treturn args.Get(0).(*sarama.ListGroupsResponse), args.Error(1)\n}",
"func ListGroup(cli bce.Client, lgr *ListGroupReq) (*ListGroupResult, error) {\n\turl := PREFIX\n\tparams := map[string]string{}\n\tif lgr.Name != \"\" {\n\t\tparams[\"name\"] = lgr.Name\n\t}\n\tif lgr.PageNo != 0 {\n\t\tparams[\"pageNo\"] = strconv.Itoa(lgr.PageNo)\n\t}\n\tif lgr.PageSize != 0 {\n\t\tparams[\"pageSize\"] = strconv.Itoa(lgr.PageSize)\n\t}\n\tresult := &ListGroupResult{}\n\treq := &GetHttpReq{Url: url, Result: result, Params: params}\n\terr := Get(cli, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}",
"func NewDefaultGroups(ctx *pulumi.Context,\n\tname string, args *DefaultGroupsArgs, opts ...pulumi.ResourceOption) (*DefaultGroups, error) {\n\tif args == nil || args.GroupIds == nil {\n\t\treturn nil, errors.New(\"missing required argument 'GroupIds'\")\n\t}\n\tif args == nil || args.RealmId == nil {\n\t\treturn nil, errors.New(\"missing required argument 'RealmId'\")\n\t}\n\tif args == nil {\n\t\targs = &DefaultGroupsArgs{}\n\t}\n\tvar resource DefaultGroups\n\terr := ctx.RegisterResource(\"keycloak:index/defaultGroups:DefaultGroups\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func NewListServerGroupOK() *ListServerGroupOK {\n\treturn &ListServerGroupOK{}\n}",
"func List(c messagebird.Client, options *messagebird.PaginationRequest) (*Groups, error) {\n\tgroupList := &Groups{}\n\tif err := c.Request(groupList, http.MethodGet, path+\"?\"+options.QueryParams(), nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn groupList, nil\n}",
"func NewListGroupsBadRequest() *ListGroupsBadRequest {\n\treturn &ListGroupsBadRequest{}\n}",
"func NewGroups(filename string, bad BadLineHandler) (*HTGroup, error) {\n\thtGroup := HTGroup{\n\t\tfilePath: filename,\n\t}\n\treturn &htGroup, htGroup.ReloadGroups(bad)\n}",
"func NewListNSGroupsParams() *ListNSGroupsParams {\n\tvar (\n\t\tpageSizeDefault = int64(1000)\n\t\tpopulateReferencesDefault = bool(false)\n\t)\n\treturn &ListNSGroupsParams{\n\t\tPageSize: &pageSizeDefault,\n\t\tPopulateReferences: &populateReferencesDefault,\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}",
"func getGroups(w http.ResponseWriter, r *http.Request) {\n InitResponse(&w)\n if r.Method == \"OPTIONS\" {return}\n\n allow, _ := HasPermission(&w, r, CoreGroupModuleID, CoreAccessRead)\n if !allow {\n w.WriteHeader(http.StatusUnauthorized)\n json.NewEncoder(w).Encode(&CoreMessage{\n Message: \"Not authorized!\",\n })\n return\n }\n\n groups := []CoreGroup{}\n\n err := Db.Model(&groups).Select()\n if err != nil {\n w.WriteHeader(http.StatusBadRequest)\n return\n }\n\n w.WriteHeader(http.StatusOK)\n json.NewEncoder(w).Encode(groups)\n}",
"func NewUserGroupListOK() *UserGroupListOK {\n\treturn &UserGroupListOK{}\n}",
"func NewListNSGroupsParamsWithHTTPClient(client *http.Client) *ListNSGroupsParams {\n\tvar (\n\t\tpageSizeDefault = int64(1000)\n\t\tpopulateReferencesDefault = bool(false)\n\t)\n\treturn &ListNSGroupsParams{\n\t\tPageSize: &pageSizeDefault,\n\t\tPopulateReferences: &populateReferencesDefault,\n\t\tHTTPClient: client,\n\t}\n}",
"func (s *GroupsService) List(opt ...CallOption) ([]*Group, *Response, error) {\n\tgroups, resp, err := listGroup(s.client, \"groups\", opt...)\n\n\treturn groups, resp, err\n}",
"func NewListGroupsNotFound() *ListGroupsNotFound {\n\treturn &ListGroupsNotFound{}\n}",
"func (c *Conn) NewGroups(since time.Time) ([]*Group, error) {\n\tif _, _, err := c.cmd(231, \"NEWGROUPS %s GMT\", since.Format(timeFormatNew)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.readGroups()\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewListGroupsBadRequest creates a ListGroupsBadRequest with default headers values
|
func NewListGroupsBadRequest() *ListGroupsBadRequest {
return &ListGroupsBadRequest{}
}
|
[
"func NewListEventLoopGroupBadRequest() *ListEventLoopGroupBadRequest {\n\treturn &ListEventLoopGroupBadRequest{}\n}",
"func NewListFoodGroupsBadRequest() *ListFoodGroupsBadRequest {\n\treturn &ListFoodGroupsBadRequest{}\n}",
"func NewListServerGroupBadRequest() *ListServerGroupBadRequest {\n\treturn &ListServerGroupBadRequest{}\n}",
"func NewGetConsistencyGroupsBadRequest() *GetConsistencyGroupsBadRequest {\n\treturn &GetConsistencyGroupsBadRequest{}\n}",
"func NewGetRuleGroupsBadRequest() *GetRuleGroupsBadRequest {\n\treturn &GetRuleGroupsBadRequest{}\n}",
"func NewGetHostGroupsBadRequest() *GetHostGroupsBadRequest {\n\treturn &GetHostGroupsBadRequest{}\n}",
"func NewUserGroupListBadRequest() *UserGroupListBadRequest {\n\treturn &UserGroupListBadRequest{}\n}",
"func NewGetGroupBadRequest() *GetGroupBadRequest {\n\treturn &GetGroupBadRequest{}\n}",
"func NewGetUniverseGroupsBadRequest() *GetUniverseGroupsBadRequest {\n\treturn &GetUniverseGroupsBadRequest{}\n}",
"func NewGetFacilityGroupsBadRequest() *GetFacilityGroupsBadRequest {\n\n\treturn &GetFacilityGroupsBadRequest{}\n}",
"func NewListGroupsNotFound() *ListGroupsNotFound {\n\treturn &ListGroupsNotFound{}\n}",
"func NewListGroupsDefault(code int) *ListGroupsDefault {\n\treturn &ListGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewUpdateHostGroupsBadRequest() *UpdateHostGroupsBadRequest {\n\treturn &UpdateHostGroupsBadRequest{}\n}",
"func NewGetUsergroupsGroupIDBadRequest() *GetUsergroupsGroupIDBadRequest {\n\treturn &GetUsergroupsGroupIDBadRequest{}\n}",
"func NewGetAviServiceEngineGroupsBadRequest() *GetAviServiceEngineGroupsBadRequest {\n\n\treturn &GetAviServiceEngineGroupsBadRequest{}\n}",
"func validate_Groups_ValidatedList_0(ctx context.Context, r json.RawMessage) (err error) {\n\tif len(r) != 0 {\n\t\treturn fmt.Errorf(\"body is not allowed\")\n\t}\n\treturn nil\n}",
"func NewGetAviServiceEngineGroupsBadRequest() *GetAviServiceEngineGroupsBadRequest {\n\treturn &GetAviServiceEngineGroupsBadRequest{}\n}",
"func NewGetApi24HostsProtectionGroupsBadRequest() *GetApi24HostsProtectionGroupsBadRequest {\n\treturn &GetApi24HostsProtectionGroupsBadRequest{}\n}",
"func NewAggregateRuleGroupsBadRequest() *AggregateRuleGroupsBadRequest {\n\treturn &AggregateRuleGroupsBadRequest{}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewListGroupsForbidden creates a ListGroupsForbidden with default headers values
|
func NewListGroupsForbidden() *ListGroupsForbidden {
return &ListGroupsForbidden{}
}
|
[
"func NewListRuleGroupsForbidden() *ListRuleGroupsForbidden {\n\treturn &ListRuleGroupsForbidden{}\n}",
"func NewGetGroupForbidden() *GetGroupForbidden {\n\treturn &GetGroupForbidden{}\n}",
"func NewListGroupsBadRequest() *ListGroupsBadRequest {\n\treturn &ListGroupsBadRequest{}\n}",
"func NewGetHostGroupsForbidden() *GetHostGroupsForbidden {\n\treturn &GetHostGroupsForbidden{}\n}",
"func NewGetRuleGroupsForbidden() *GetRuleGroupsForbidden {\n\treturn &GetRuleGroupsForbidden{}\n}",
"func NewListGroupsUnauthorized() *ListGroupsUnauthorized {\n\treturn &ListGroupsUnauthorized{}\n}",
"func getGroups(w http.ResponseWriter, r *http.Request) {\n InitResponse(&w)\n if r.Method == \"OPTIONS\" {return}\n\n allow, _ := HasPermission(&w, r, CoreGroupModuleID, CoreAccessRead)\n if !allow {\n w.WriteHeader(http.StatusUnauthorized)\n json.NewEncoder(w).Encode(&CoreMessage{\n Message: \"Not authorized!\",\n })\n return\n }\n\n groups := []CoreGroup{}\n\n err := Db.Model(&groups).Select()\n if err != nil {\n w.WriteHeader(http.StatusBadRequest)\n return\n }\n\n w.WriteHeader(http.StatusOK)\n json.NewEncoder(w).Encode(groups)\n}",
"func NewListGroupsNotFound() *ListGroupsNotFound {\n\treturn &ListGroupsNotFound{}\n}",
"func NewListGroupsDefault(code int) *ListGroupsDefault {\n\treturn &ListGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func CreateListServerGroupsRequest() (request *ListServerGroupsRequest) {\n\trequest = &ListServerGroupsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Alb\", \"2020-06-16\", \"ListServerGroups\", \"alb\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}",
"func NewUpdateHostGroupsForbidden() *UpdateHostGroupsForbidden {\n\treturn &UpdateHostGroupsForbidden{}\n}",
"func NewListRegistryForbidden() *ListRegistryForbidden {\n\treturn &ListRegistryForbidden{}\n}",
"func validate_Groups_ValidatedList_0(ctx context.Context, r json.RawMessage) (err error) {\n\tif len(r) != 0 {\n\t\treturn fmt.Errorf(\"body is not allowed\")\n\t}\n\treturn nil\n}",
"func NewListServerGroupBadRequest() *ListServerGroupBadRequest {\n\treturn &ListServerGroupBadRequest{}\n}",
"func NewListEventLoopGroupBadRequest() *ListEventLoopGroupBadRequest {\n\treturn &ListEventLoopGroupBadRequest{}\n}",
"func (client IdentityClient) ListDynamicGroups(ctx context.Context, request ListDynamicGroupsRequest) (response ListDynamicGroupsResponse, 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.listDynamicGroups, 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 = ListDynamicGroupsResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListDynamicGroupsResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListDynamicGroupsResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListDynamicGroupsResponse\")\n\t}\n\treturn\n}",
"func NewListRuleGroupsUnauthorized() *ListRuleGroupsUnauthorized {\n\treturn &ListRuleGroupsUnauthorized{}\n}",
"func NewGetUsergroupsGroupIDForbidden() *GetUsergroupsGroupIDForbidden {\n\treturn &GetUsergroupsGroupIDForbidden{}\n}",
"func (m *ManagedTenantsManagementActionsItemMicrosoftGraphManagedTenantsApplyApplyPostRequestBody) SetExcludeGroups(value []string)() {\n err := m.GetBackingStore().Set(\"excludeGroups\", value)\n if err != nil {\n panic(err)\n }\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewListGroupsNotFound creates a ListGroupsNotFound with default headers values
|
func NewListGroupsNotFound() *ListGroupsNotFound {
return &ListGroupsNotFound{}
}
|
[
"func NewListGroupsDefault(code int) *ListGroupsDefault {\n\treturn &ListGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewListGroupsBadRequest() *ListGroupsBadRequest {\n\treturn &ListGroupsBadRequest{}\n}",
"func NewGetHostGroupsNotFound() *GetHostGroupsNotFound {\n\treturn &GetHostGroupsNotFound{}\n}",
"func NewGetAllGroupsNotFound() *GetAllGroupsNotFound {\n\n\treturn &GetAllGroupsNotFound{}\n}",
"func NewGetGroupNotFound() *GetGroupNotFound {\n\treturn &GetGroupNotFound{}\n}",
"func NewGetGroupsByDisplayNameUsingGETNotFound() *GetGroupsByDisplayNameUsingGETNotFound {\n\treturn &GetGroupsByDisplayNameUsingGETNotFound{}\n}",
"func NewGetHostGroupsDefault(code int) *GetHostGroupsDefault {\n\treturn &GetHostGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewGetGroupDefault(code int) *GetGroupDefault {\n\treturn &GetGroupDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewUpdateHostGroupsNotFound() *UpdateHostGroupsNotFound {\n\treturn &UpdateHostGroupsNotFound{}\n}",
"func NewListRuleGroupsDefault(code int) *ListRuleGroupsDefault {\n\treturn &ListRuleGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewGetReportGroupListDefault(code int) *GetReportGroupListDefault {\n\treturn &GetReportGroupListDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewListFoodGroupsBadRequest() *ListFoodGroupsBadRequest {\n\treturn &ListFoodGroupsBadRequest{}\n}",
"func NewDefaultGroups(ctx *pulumi.Context,\n\tname string, args *DefaultGroupsArgs, opts ...pulumi.ResourceOption) (*DefaultGroups, error) {\n\tif args == nil || args.GroupIds == nil {\n\t\treturn nil, errors.New(\"missing required argument 'GroupIds'\")\n\t}\n\tif args == nil || args.RealmId == nil {\n\t\treturn nil, errors.New(\"missing required argument 'RealmId'\")\n\t}\n\tif args == nil {\n\t\targs = &DefaultGroupsArgs{}\n\t}\n\tvar resource DefaultGroups\n\terr := ctx.RegisterResource(\"keycloak:index/defaultGroups:DefaultGroups\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func getGroups(w http.ResponseWriter, r *http.Request) {\n InitResponse(&w)\n if r.Method == \"OPTIONS\" {return}\n\n allow, _ := HasPermission(&w, r, CoreGroupModuleID, CoreAccessRead)\n if !allow {\n w.WriteHeader(http.StatusUnauthorized)\n json.NewEncoder(w).Encode(&CoreMessage{\n Message: \"Not authorized!\",\n })\n return\n }\n\n groups := []CoreGroup{}\n\n err := Db.Model(&groups).Select()\n if err != nil {\n w.WriteHeader(http.StatusBadRequest)\n return\n }\n\n w.WriteHeader(http.StatusOK)\n json.NewEncoder(w).Encode(groups)\n}",
"func (ggSession *GreengrassSession) ListGroup(name string) error {\n\tvar id string\n\n\tif name != \"\" {\n\t\tlistOutput, err := ggSession.greengrass.ListGroups(&greengrass.ListGroupsInput{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, v := range listOutput.Groups {\n\t\t\tif name == *v.Name {\n\t\t\t\tid = *v.Id\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif id == \"\" {\n\t\t\treturn fmt.Errorf(\"group %s not found\", name)\n\t\t}\n\t} else {\n\t\tid = ggSession.config.Group.ID\n\t}\n\n\tgroup, err := ggSession.greengrass.GetGroup(&greengrass.GetGroupInput{\n\t\tGroupId: &id,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"group: %v\\n\", group)\n\n\tif group.LatestVersion == nil {\n\t\treturn nil\n\t}\n\n\tgroupVersion, err := ggSession.greengrass.GetGroupVersion(&greengrass.GetGroupVersionInput{\n\t\tGroupId: group.Id,\n\t\tGroupVersionId: group.LatestVersion,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"group version: %v\\n\", groupVersion)\n\n\treturn nil\n}",
"func NewListEventLoopGroupBadRequest() *ListEventLoopGroupBadRequest {\n\treturn &ListEventLoopGroupBadRequest{}\n}",
"func NewListGroupsUnauthorized() *ListGroupsUnauthorized {\n\treturn &ListGroupsUnauthorized{}\n}",
"func validate_Groups_Create_0(ctx context.Context, r json.RawMessage) (err error) {\n\treturn validate_Object_Group(ctx, r, \"\")\n}",
"func NewGetUniverseGroupsGroupIDNotFound() *GetUniverseGroupsGroupIDNotFound {\n\treturn &GetUniverseGroupsGroupIDNotFound{}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewListGroupsDefault creates a ListGroupsDefault with default headers values
|
func NewListGroupsDefault(code int) *ListGroupsDefault {
return &ListGroupsDefault{
_statusCode: code,
}
}
|
[
"func NewListRuleGroupsDefault(code int) *ListRuleGroupsDefault {\n\treturn &ListRuleGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewDefaultGroups(ctx *pulumi.Context,\n\tname string, args *DefaultGroupsArgs, opts ...pulumi.ResourceOption) (*DefaultGroups, error) {\n\tif args == nil || args.GroupIds == nil {\n\t\treturn nil, errors.New(\"missing required argument 'GroupIds'\")\n\t}\n\tif args == nil || args.RealmId == nil {\n\t\treturn nil, errors.New(\"missing required argument 'RealmId'\")\n\t}\n\tif args == nil {\n\t\targs = &DefaultGroupsArgs{}\n\t}\n\tvar resource DefaultGroups\n\terr := ctx.RegisterResource(\"keycloak:index/defaultGroups:DefaultGroups\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func NewGetHostGroupsDefault(code int) *GetHostGroupsDefault {\n\treturn &GetHostGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewGetReportGroupListDefault(code int) *GetReportGroupListDefault {\n\treturn &GetReportGroupListDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewPostVolumeGroupsListDefault(code int) *PostVolumeGroupsListDefault {\n\treturn &PostVolumeGroupsListDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func DefaultGroups(clusterName, addonName string) []string {\n\treturn []string{\n\t\tfmt.Sprintf(\"system:open-cluster-management:cluster:%s:addon:%s\", clusterName, addonName),\n\t\tfmt.Sprintf(\"system:open-cluster-management:addon:%s\", addonName),\n\t\t\"system:authenticated\",\n\t}\n}",
"func NewGetGroupDefault(code int) *GetGroupDefault {\n\treturn &GetGroupDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewUpdateHostGroupsDefault(code int) *UpdateHostGroupsDefault {\n\treturn &UpdateHostGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewGetRuleGroupsDefault(code int) *GetRuleGroupsDefault {\n\treturn &GetRuleGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func GetDefaultGroups(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *DefaultGroupsState, opts ...pulumi.ResourceOption) (*DefaultGroups, error) {\n\tvar resource DefaultGroups\n\terr := ctx.ReadResource(\"keycloak:index/defaultGroups:DefaultGroups\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func NewDeleteCIDGroupsDefault(code int) *DeleteCIDGroupsDefault {\n\treturn &DeleteCIDGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewQueryUserGroupsDefault(code int) *QueryUserGroupsDefault {\n\treturn &QueryUserGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewDeleteUserGroupsDefault(code int) *DeleteUserGroupsDefault {\n\treturn &DeleteUserGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewGetDeviceDatasourceInstanceGroupListDefault(code int) *GetDeviceDatasourceInstanceGroupListDefault {\n\treturn &GetDeviceDatasourceInstanceGroupListDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewDeleteAuthGroupsDefault(code int) *DeleteAuthGroupsDefault {\n\treturn &DeleteAuthGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewResonateUserListUsersUserGroupsDefault(code int) *ResonateUserListUsersUserGroupsDefault {\n\treturn &ResonateUserListUsersUserGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func DefaultDescribeGroupParser() *DelegatingParser {\n\treturn &DelegatingParser{\n\t\t[]DescribeGroupParser{\n\t\t\tkafka0_9_0_1DescribeGroupParser,\n\t\t\tkafka0_10_0_1DescribeGroupParser,\n\t\t\tkafka0_10_1DescribeGroupParser,\n\t\t\tkafka0_10_2_1DescribeGroupParser,\n\t\t},\n\t}\n}",
"func NewListIdpGroupMappingsDefault(code int) *ListIdpGroupMappingsDefault {\n\treturn &ListIdpGroupMappingsDefault{\n\t\t_statusCode: code,\n\t}\n}",
"func NewListGroupsNotFound() *ListGroupsNotFound {\n\treturn &ListGroupsNotFound{}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Code gets the status code for the list groups default response
|
func (o *ListGroupsDefault) Code() int {
return o._statusCode
}
|
[
"func (o *ListRuleGroupsDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *PostVolumeGroupsListDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *GetHostGroupsDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *QueryCIDGroupsDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *ListServerGroupOK) Code() int {\n\treturn 200\n}",
"func (o *QueryUserGroupsDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *ListEventLoopGroupOK) Code() int {\n\treturn 200\n}",
"func (o *GetReportGroupListDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *GetRuleGroupsDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *ResonateUserListUsersUserGroupsDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *GetGroupDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *QueryCIDGroupsOK) Code() int {\n\treturn 200\n}",
"func (o *DeleteCIDGroupsDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *GetDashboardGroupByIDDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *DeleteAuthGroupsDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *GetDeviceDatasourceInstanceGroupListDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *GetUserGroupsByIDV2OK) Code() int {\n\treturn 200\n}",
"func (o *UpdateHostGroupsDefault) Code() int {\n\treturn o._statusCode\n}",
"func (o *DeleteUserGroupsDefault) Code() int {\n\treturn o._statusCode\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
initialize a scanner.Store given libscan.Opts
|
func initStore(ctx context.Context, opts *Opts) (*sqlx.DB, scanner.Store, error) {
var store scanner.Store
switch opts.DataStore {
case Postgres:
// we are going to use pgx for more control over connection pool and
// and a cleaner api around bulk inserts
cfg, err := pgxpool.ParseConfig(opts.ConnString)
if err != nil {
return nil, nil, fmt.Errorf("failed to parse ConnString: %v", err)
}
cfg.MaxConns = 30
pool, err := pgxpool.ConnectConfig(ctx, cfg)
if err != nil {
return nil, nil, fmt.Errorf("failed to create ConnPool: %v", err)
}
// setup sqlx
db, err := sqlx.Open("pgx", opts.ConnString)
if err != nil {
return nil, nil, fmt.Errorf("failed to open db: %v", err)
}
store = postgres.NewStore(db, pool)
return db, store, nil
default:
return nil, nil, fmt.Errorf("provided unknown DataStore")
}
}
|
[
"func InitStore(s Store) {\n\tstore = s\n}",
"func New(opts ...Option) (*Store, error) {\n\tvar s Store\n\n\tfor _, opt := range opts {\n\t\tif err := opt.Apply(&s); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &s, nil\n}",
"func (s *Store) Init(option Option) error {\n\treturn option.ApplyTo(s)\n}",
"func (scanner *Scanner) Init(flags zgrab2.ScanFlags) error {\n\tf, _ := flags.(*Flags)\n\tscanner.config = f\n\treturn nil\n}",
"func NewStore(dir string, hints map[string]string) *Store {\n\tif hints == nil {\n\t\thints = map[string]string{}\n\t}\n\treturn &Store{\n\t\tData: &sync.Map{},\n\t\tDir: dir,\n\t\tHints: hints,\n\t\tListFiles: listFiles,\n\t\tParseFile: parseFile,\n\t\tFileExists: fileExists,\n\t}\n}",
"func New(client Client, opt ...Option) *Scanner {\n\ts := Scanner{\n\t\tclient: client,\n\t\toptions: defaultOptions,\n\t}\n\tfor _, o := range opt {\n\t\to(&s.options)\n\t}\n\treturn &s\n}",
"func InitStore() {\n\tcurrentStore = NewStore(nil)\n\n}",
"func (l *Result) StoreWithOpts(opts ...inmem.Opt) (storage.Store, error) {\n\treturn inmem.NewFromObjectWithOpts(l.Documents, opts...), nil\n}",
"func StoreInit(params ...string) *Store {\n\tpath := common.CocktailCollectionFilePath\n\tif len(params) > 0 {\n\t\tpath = params[0]\n\t}\n\tstorePointer = &Store{dataPath: path}\n\tstorePointer.LoadCocktails()\n\treturn storePointer\n}",
"func (s *Store) Start(ctx context.Context, stopper *stop.Stopper) error {\n\ts.stopper = stopper\n\n\t// Populate the store ident. If not bootstrapped, ReadStoreIntent will\n\t// return an error.\n\tident, err := ReadStoreIdent(ctx, s.engine)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Ident = &ident\n\n\t// Set the store ID for logging.\n\ts.cfg.AmbientCtx.AddLogTag(\"s\", s.StoreID())\n\tctx = s.AnnotateCtx(ctx)\n\tlog.Event(ctx, \"read store identity\")\n\n\t// Add the store ID to the scanner's AmbientContext before starting it, since\n\t// the AmbientContext provided during construction did not include it.\n\t// Note that this is just a hacky way of getting around that without\n\t// refactoring the scanner/queue construction/start logic more broadly, and\n\t// depends on the scanner not having added its own log tag.\n\tif s.scanner != nil {\n\t\ts.scanner.AmbientContext.AddLogTag(\"s\", s.StoreID())\n\t}\n\n\t// If the nodeID is 0, it has not be assigned yet.\n\tif s.nodeDesc.NodeID != 0 && s.Ident.NodeID != s.nodeDesc.NodeID {\n\t\treturn errors.Errorf(\"node id:%d does not equal the one in node descriptor:%d\", s.Ident.NodeID, s.nodeDesc.NodeID)\n\t}\n\t// Always set gossip NodeID before gossiping any info.\n\tif s.cfg.Gossip != nil {\n\t\ts.cfg.Gossip.NodeID.Set(ctx, s.Ident.NodeID)\n\t}\n\n\t// Create ID allocators.\n\tidAlloc, err := idalloc.NewAllocator(idalloc.Options{\n\t\tAmbientCtx: s.cfg.AmbientCtx,\n\t\tKey: keys.RangeIDGenerator,\n\t\tIncrementer: idalloc.DBIncrementer(s.db),\n\t\tBlockSize: rangeIDAllocCount,\n\t\tStopper: s.stopper,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create the intent resolver.\n\tvar intentResolverRangeCache intentresolver.RangeCache\n\trngCache := s.cfg.RangeDescriptorCache\n\tif s.cfg.RangeDescriptorCache != nil {\n\t\tintentResolverRangeCache = rngCache\n\t}\n\n\ts.intentResolver = intentresolver.New(intentresolver.Config{\n\t\tClock: s.cfg.Clock,\n\t\tDB: s.db,\n\t\tStopper: stopper,\n\t\tTaskLimit: s.cfg.IntentResolverTaskLimit,\n\t\tAmbientCtx: s.cfg.AmbientCtx,\n\t\tTestingKnobs: s.cfg.TestingKnobs.IntentResolverKnobs,\n\t\tRangeDescriptorCache: intentResolverRangeCache,\n\t})\n\ts.metrics.registry.AddMetricStruct(s.intentResolver.Metrics)\n\n\t// Create the recovery manager.\n\ts.recoveryMgr = txnrecovery.NewManager(\n\t\ts.cfg.AmbientCtx, s.cfg.Clock, s.db, stopper,\n\t)\n\ts.metrics.registry.AddMetricStruct(s.recoveryMgr.Metrics())\n\n\ts.rangeIDAlloc = idAlloc\n\n\tnow := s.cfg.Clock.Now()\n\ts.startedAt = now.WallTime\n\n\t// Iterate over all range descriptors, ignoring uncommitted versions\n\t// (consistent=false). Uncommitted intents which have been abandoned\n\t// due to a split crashing halfway will simply be resolved on the\n\t// next split attempt. They can otherwise be ignored.\n\n\t// TODO(peter): While we have to iterate to find the replica descriptors\n\t// serially, we can perform the migrations and replica creation\n\t// concurrently. Note that while we can perform this initialization\n\t// concurrently, all of the initialization must be performed before we start\n\t// listening for Raft messages and starting the process Raft loop.\n\terr = IterateRangeDescriptors(ctx, s.engine,\n\t\tfunc(desc roachpb.RangeDescriptor) error {\n\t\t\tif !desc.IsInitialized() {\n\t\t\t\treturn errors.Errorf(\"found uninitialized RangeDescriptor: %+v\", desc)\n\t\t\t}\n\t\t\treplicaDesc, found := desc.GetReplicaDescriptor(s.StoreID())\n\t\t\tif !found {\n\t\t\t\t// This is a pre-emptive snapshot. It's also possible that this is a\n\t\t\t\t// range which has processed a raft command to remove itself (which is\n\t\t\t\t// possible prior to 19.2 or if the DisableEagerReplicaRemoval is\n\t\t\t\t// enabled) and has not yet been removed by the replica gc queue.\n\t\t\t\t// We treat both cases the same way. These should no longer exist in\n\t\t\t\t// 20.2 or after as there was a migration in 20.1 to remove them and\n\t\t\t\t// no pre-emptive snapshot should have been sent since 19.2 was\n\t\t\t\t// finalized.\n\t\t\t\treturn errors.AssertionFailedf(\n\t\t\t\t\t\"found RangeDescriptor for range %d at generation %d which does not\"+\n\t\t\t\t\t\t\" contain this store %d\",\n\t\t\t\t\tlog.Safe(desc.RangeID),\n\t\t\t\t\tlog.Safe(desc.Generation),\n\t\t\t\t\tlog.Safe(s.StoreID()))\n\t\t\t}\n\n\t\t\trep, err := newReplica(ctx, &desc, s, replicaDesc.ReplicaID)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// We can't lock s.mu across NewReplica due to the lock ordering\n\t\t\t// constraint (*Replica).raftMu < (*Store).mu. See the comment on\n\t\t\t// (Store).mu.\n\t\t\ts.mu.Lock()\n\t\t\terr = s.addReplicaInternalLocked(rep)\n\t\t\ts.mu.Unlock()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Add this range and its stats to our counter.\n\t\t\ts.metrics.ReplicaCount.Inc(1)\n\t\t\tif tenantID, ok := rep.TenantID(); ok {\n\t\t\t\ts.metrics.addMVCCStats(ctx, tenantID, rep.GetMVCCStats())\n\t\t\t} else {\n\t\t\t\treturn errors.AssertionFailedf(\"found newly constructed replica\"+\n\t\t\t\t\t\" for range %d at generation %d with an invalid tenant ID in store %d\",\n\t\t\t\t\tlog.Safe(desc.RangeID),\n\t\t\t\t\tlog.Safe(desc.Generation),\n\t\t\t\t\tlog.Safe(s.StoreID()))\n\t\t\t}\n\n\t\t\tif _, ok := desc.GetReplicaDescriptor(s.StoreID()); !ok {\n\t\t\t\t// We are no longer a member of the range, but we didn't GC the replica\n\t\t\t\t// before shutting down. Add the replica to the GC queue.\n\t\t\t\ts.replicaGCQueue.AddAsync(ctx, rep, replicaGCPriorityRemoved)\n\t\t\t}\n\n\t\t\t// Note that we do not create raft groups at this time; they will be created\n\t\t\t// on-demand the first time they are needed. This helps reduce the amount of\n\t\t\t// election-related traffic in a cold start.\n\t\t\t// Raft initialization occurs when we propose a command on this range or\n\t\t\t// receive a raft message addressed to it.\n\t\t\t// TODO(bdarnell): Also initialize raft groups when read leases are needed.\n\t\t\t// TODO(bdarnell): Scan all ranges at startup for unapplied log entries\n\t\t\t// and initialize those groups.\n\t\t\treturn nil\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Start Raft processing goroutines.\n\ts.cfg.Transport.Listen(s.StoreID(), s)\n\ts.processRaft(ctx)\n\n\t// Register a callback to unquiesce any ranges with replicas on a\n\t// node transitioning from non-live to live.\n\tif s.cfg.NodeLiveness != nil {\n\t\ts.cfg.NodeLiveness.RegisterCallback(s.nodeIsLiveCallback)\n\t}\n\n\t// Gossip is only ever nil while bootstrapping a cluster and\n\t// in unittests.\n\tif s.cfg.Gossip != nil {\n\t\t// Register update channel for any changes to the system config.\n\t\t// This may trigger splits along structured boundaries,\n\t\t// and update max range bytes.\n\t\tgossipUpdateC := s.cfg.Gossip.RegisterSystemConfigChannel()\n\t\t_ = s.stopper.RunAsyncTask(ctx, \"syscfg-listener\", func(context.Context) {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-gossipUpdateC:\n\t\t\t\t\tcfg := s.cfg.Gossip.GetSystemConfig()\n\t\t\t\t\ts.systemGossipUpdate(cfg)\n\t\t\t\tcase <-s.stopper.ShouldQuiesce():\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\t// Start a single goroutine in charge of periodically gossiping the\n\t\t// sentinel and first range metadata if we have a first range.\n\t\t// This may wake up ranges and requires everything to be set up and\n\t\t// running.\n\t\ts.startGossip()\n\n\t\t// Start the scanner. The construction here makes sure that the scanner\n\t\t// only starts after Gossip has connected, and that it does not block Start\n\t\t// from returning (as doing so might prevent Gossip from ever connecting).\n\t\t_ = s.stopper.RunAsyncTask(ctx, \"scanner\", func(context.Context) {\n\t\t\tselect {\n\t\t\tcase <-s.cfg.Gossip.Connected:\n\t\t\t\ts.scanner.Start(s.stopper)\n\t\t\tcase <-s.stopper.ShouldQuiesce():\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\t}\n\n\tif !s.cfg.TestingKnobs.DisableAutomaticLeaseRenewal {\n\t\ts.startLeaseRenewer(ctx)\n\t}\n\n\t// Connect rangefeeds to closed timestamp updates.\n\ts.startClosedTimestampRangefeedSubscriber(ctx)\n\ts.startRangefeedUpdater(ctx)\n\n\tif s.replicateQueue != nil {\n\t\ts.storeRebalancer = NewStoreRebalancer(\n\t\t\ts.cfg.AmbientCtx, s.cfg.Settings, s.replicateQueue, s.replRankings)\n\t\ts.storeRebalancer.Start(ctx, s.stopper)\n\t}\n\n\ts.consistencyLimiter = quotapool.NewRateLimiter(\n\t\t\"ConsistencyQueue\",\n\t\tquotapool.Limit(consistencyCheckRate.Get(&s.ClusterSettings().SV)),\n\t\tconsistencyCheckRate.Get(&s.ClusterSettings().SV)*consistencyCheckRateBurstFactor,\n\t\tquotapool.WithMinimumWait(consistencyCheckRateMinWait))\n\n\tconsistencyCheckRate.SetOnChange(&s.ClusterSettings().SV, func() {\n\t\trate := consistencyCheckRate.Get(&s.ClusterSettings().SV)\n\t\ts.consistencyLimiter.UpdateLimit(quotapool.Limit(rate), rate*consistencyCheckRateBurstFactor)\n\t})\n\n\t// Storing suggested compactions in the store itself was deprecated with\n\t// the removal of the Compactor in 21.1. See discussion in\n\t// https://github.com/cockroachdb/cockroach/pull/55893\n\t//\n\t// TODO(bilal): Remove this code in versions after 21.1.\n\terr = s.engine.MVCCIterate(\n\t\tkeys.StoreSuggestedCompactionKeyPrefix(),\n\t\tkeys.StoreSuggestedCompactionKeyPrefix().PrefixEnd(),\n\t\tstorage.MVCCKeyIterKind,\n\t\tfunc(res storage.MVCCKeyValue) error {\n\t\t\treturn s.engine.ClearUnversioned(res.Key.Key)\n\t\t})\n\tif err != nil {\n\t\tlog.Warningf(ctx, \"error when clearing compactor keys: %s\", err)\n\t}\n\n\t// Set the started flag (for unittests).\n\tatomic.StoreInt32(&s.started, 1)\n\n\treturn nil\n}",
"func initStore(ctx context.Context, opts *Opts) (*sqlx.DB, vulnstore.Store, error) {\n\t// we are going to use pgx for more control over connection pool and\n\t// and a cleaner api around bulk inserts\n\tcfg, err := pgxpool.ParseConfig(opts.ConnString)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ConnString: %v\", err)\n\t}\n\t// set conn pool size via libvuln.Opts\n\tcfg.MaxConns = opts.MaxConnPool\n\tpool, err := pgxpool.ConnectConfig(ctx, cfg)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to create ConnPool: %v\", err)\n\t}\n\n\tdb, err := sqlx.Open(\"pgx\", opts.ConnString)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to Open db: %v\", err)\n\t}\n\n\t// do migrations if requested\n\tif opts.Migrations {\n\t\tmigrator := migrate.NewPostgresMigrator(db.DB)\n\t\tmigrator.Table = migrations.MigrationTable\n\t\terr := migrator.Exec(migrate.Up, migrations.Migrations...)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to perform migrations: %w\", err)\n\t\t}\n\t}\n\n\tstore := postgres.NewVulnStore(db, pool)\n\treturn db, store, nil\n}",
"func NewStore(init StoreInit) (s *Store, err error) {\r\n\tvar initialCapacity int\r\n\tif utils.IsSet(init.InitCapacity) {\r\n\t\tinitialCapacity = init.InitCapacity\r\n\t} else {\r\n\t\tinitialCapacity = len(init.Args)\r\n\t}\r\n\r\n\tlocalStore := Store{\r\n\t\tstore: make(map[string]string, initialCapacity),\r\n\t\tparent: init.Parent,\r\n\t}\r\n\r\n\tfor _, arg := range init.Args {\r\n\t\tkey, value, err := splitArgument(arg)\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\r\n\t\tif value, err = encode.ConvertStringToUtf8(value); err != nil {\r\n\t\t\treturn nil, fmt.Errorf(\"Error converting value for key '%v' to UTF-8: %v\", key, err)\r\n\t\t}\r\n\r\n\t\tif !localStore.hasKey(key) {\r\n\t\t\tlocalStore.Set(key, value)\r\n\t\t} else {\r\n\t\t\treturn nil, fmt.Errorf(\"Duplicate key '%v' found\", key)\r\n\t\t}\r\n\t}\r\n\r\n\treturn &localStore, nil\r\n}",
"func (a *SecretAnalyzer) Init(opt analyzer.AnalyzerOptions) error {\n\tif opt.SecretScannerOption.ConfigPath == a.configPath && !lo.IsEmpty(a.scanner) {\n\t\t// This check is for tools importing Trivy and customize analyzers\n\t\t// Never reach here in Trivy OSS\n\t\treturn nil\n\t}\n\tconfigPath := opt.SecretScannerOption.ConfigPath\n\tc, err := secret.ParseConfig(configPath)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"secret config error: %w\", err)\n\t}\n\ta.scanner = secret.NewScanner(c)\n\ta.configPath = configPath\n\treturn nil\n}",
"func Init(ctx *context.T, opts flags.VtraceFlags) (*context.T, error) {\n\tnctx := vtrace.WithManager(ctx, manager{})\n\tstore, err := NewStore(opts)\n\tif err != nil {\n\t\treturn ctx, err\n\t}\n\treturn context.WithValue(nctx, storeKey, store), nil\n}",
"func Init(storageType int) DataStore {\n\tswitch storageType {\n\tcase INMEMORY:\n\t\tstorage := new(storeInMem)\n\t\treturn DataStore(storage)\n\tdefault:\n\t\tlog.Println(\"Invalid-storage-type\")\n\t\treturn nil\n\t}\n}",
"func init() {\n flag.Parse()\n configFile := filepath.Join(*ConfigDirectory, \"store.json\")\n if _, err := os.Stat(configFile); err == nil {\n config, err := ioutil.ReadFile(configFile)\n if err != nil {\n log.Printf(\"ERROR: Error opening store config: %s\", err)\n return\n }\n err = json.Unmarshal(config, StoreConfig)\n if err != nil {\n log.Printf(\"ERROR: Error parsing store config: %s\", err)\n return\n }\n } else {\n log.Printf(\"WARNING: Could not find configuration file store.json in %s\", *ConfigDirectory)\n }\n RegisterRobot(\"/store\", func() (robot Robot) { return new(StoreBot) })\n}",
"func NewStore(log logger.Entry, cfg Config) (*Store, error) {\n\n\t// Open bolt database\n\t// TODO: move 0644 to Config\n\tdb, err := bolt.Open(cfg.File, 0644, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.WithField(\"config\", cfg).Debug(\"Create store\")\n\ts := Store{\n\t\tBucket: []byte(cfg.Bucket),\n\t\tNumberKey: []byte(cfg.NumberKey),\n\t\tSettingsKey: []byte(cfg.SettingsKey),\n\t\tdb: db,\n\t\tlog: log,\n\t}\n\treturn &s, nil\n\n}",
"func (o *oosSecretStore) Init(_ context.Context, metadata secretstores.Metadata) error {\n\tmeta, err := o.getParameterStoreMetadata(metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := o.getClient(meta)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.client = client\n\n\treturn nil\n}",
"func InitFromConfig(ctx context.Context, cfg Config) (*Store, error) {\n\tctx, cancel := context.WithTimeout(ctx, time.Second*30)\n\tdefer cancel()\n\n\tstore, err := NewStore(ctx, cfg.Path, log.CounterWrapper(\n\t\tnil, // delegate, let it fallback to DefaultWrapper\n\t\tparserFailures,\n\t))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn store, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ReactionDelete Handle when a reaction is deleted from a message
|
func (b *Bot) ReactionDelete(s *discordgo.Session, event *discordgo.MessageReactionRemove) {
if f, ok := b.Commands.ReactionRemoveCommands[event.Emoji.Name]; ok {
f(b, s, event)
}
}
|
[
"func HandleDeleteRemindCommand(ctx context.Context, s *discordgo.Session, m *discordgo.MessageCreate, content []string) {\n\tuserID := fmt.Sprintf(\"%s-%s\", m.Author.Username, m.Author.ID)\n\n\terr := models.DeleteRemind(ctx, content[1], userID)\n\n\tif err != nil {\n\t\ts.ChannelMessageSend(m.ChannelID, fmt.Sprintf(\"%s\", err))\n\t\ts.MessageReactionAdd(m.ChannelID, m.ID, \"❌\")\n\t\treturn\n\t}\n\ts.MessageReactionAdd(m.ChannelID, m.ID, \"✅\")\n}",
"func (c *Client) DeleteReaction(ctx context.Context, messageID, reactionType, userID string) (*ReactionResponse, error) {\n\tswitch {\n\tcase messageID == \"\":\n\t\treturn nil, errors.New(\"message ID is empty\")\n\tcase reactionType == \"\":\n\t\treturn nil, errors.New(\"reaction type is empty\")\n\tcase userID == \"\":\n\t\treturn nil, errors.New(\"user ID is empty\")\n\t}\n\n\tp := path.Join(\"messages\", url.PathEscape(messageID), \"reaction\", url.PathEscape(reactionType))\n\n\tparams := url.Values{}\n\tparams.Set(\"user_id\", userID)\n\n\tvar resp ReactionResponse\n\terr := c.makeRequest(ctx, http.MethodDelete, p, params, nil, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.Message == nil {\n\t\treturn nil, errors.New(\"unexpected error: response message nil\")\n\t}\n\n\treturn &resp, nil\n}",
"func handleMsgDelete(ctx sdk.Context, k Keeper, msg *MsgDelete) (*sdk.Result, error) {\n\tif err := k.Delete(ctx, msg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\tsdk.EventTypeMessage,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyModule, ModuleName),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String()),\n\t\t),\n\t)\n\n\treturn &sdk.Result{Events: ctx.EventManager().Events()}, nil\n}",
"func ReactionDelete(\n\tconnections connection.Service,\n\tobjects object.Service,\n\treactions reaction.Service,\n) ReactionDeleteFunc {\n\treturn func(\n\t\tcurrentApp *app.App,\n\t\torigin, postID uint64,\n\t\treactionType reaction.Type,\n\t) error {\n\t\tp, err := PostFetch(objects)(currentApp, postID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := isPostVisible(connections, currentApp, p.Object, origin); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trs, err := reactions.Query(currentApp.Namespace(), reaction.QueryOptions{\n\t\t\tDeleted: &defaultDeleted,\n\t\t\tObjectIDs: []uint64{\n\t\t\t\tpostID,\n\t\t\t},\n\t\t\tOwnerIDs: []uint64{\n\t\t\t\torigin,\n\t\t\t},\n\t\t\tTypes: []reaction.Type{\n\t\t\t\treactionType,\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(rs) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\treaction := rs[0]\n\t\treaction.Deleted = true\n\n\t\t_, err = reactions.Put(currentApp.Namespace(), reaction)\n\n\t\treturn err\n\t}\n}",
"func (ch *Channel) DeleteReaction(ctx context.Context, messageID, reactionType, userID string) (*ReactionResponse, error) {\n\treturn ch.client.DeleteReaction(ctx, messageID, reactionType, userID)\n}",
"func Delete(s *discordgo.Session, m *discordgo.MessageCreate) {\n}",
"func messageReactionRemove(session *discordgo.Session, reaction *discordgo.MessageReactionRemove) {\n\n\t// Bot permissions\n\tbotPermissions, err := session.State.UserChannelPermissions(session.State.User.ID, reaction.ChannelID)\n\n\t// Return if unable to check bot permissions\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\t// Return if bot does not have permission to manage roles\n\tif botPermissions&discordgo.PermissionManageRoles == 0 {\n\t\tsession.ChannelMessage(reaction.ChannelID, \"<@\"+reaction.UserID+\"> I don't have permission to manage roles.\")\n\t\treturn\n\t}\n\n\tfor _, reactionRoleMessage := range reactionrole.Messages {\n\t\tif reaction.MessageID == reactionRoleMessage {\n\t\t\tfor _, reactionRoleCatagory := range reactionrole.Catagories {\n\t\t\t\tfor _, reactionRole := range reactionRoleCatagory.Role {\n\t\t\t\t\tif reactionRole.Emoji.ID == reaction.Emoji.ID {\n\t\t\t\t\t\tsession.GuildMemberRoleRemove(reaction.GuildID, reaction.UserID, reactionRole.ID)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"func (p *Plugin) ReceiveReactionRemoved(reactionRemoved slack.Reaction) {\n}",
"func (c *Config) handleActionDeleteMessage(client MQTT.Client, message MQTT.Message) {\n\tactionsToBeDeleted := []actionmanager.Action{}\n\terr := json.Unmarshal(message.Payload(), &actionsToBeDeleted)\n\tif err != nil {\n\t\tklog.Errorf(\"Error in unmarshalling: %s\", err)\n\t}\n\tfor _, actionToBeDeleted := range actionsToBeDeleted {\n\t\tactionExists := false\n\t\tfor index, action := range c.ActionManager.Actions {\n\t\t\tif strings.EqualFold(action.Name, actionToBeDeleted.Name) {\n\t\t\t\tactionExists = true\n\t\t\t\tcopy(c.ActionManager.Actions[index:], c.ActionManager.Actions[index+1:])\n\t\t\t\tc.ActionManager.Actions = c.ActionManager.Actions[:len(c.ActionManager.Actions)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tconfiguration.Config.ActionManager = c.ActionManager\n\t\tif !actionExists {\n\t\t\tklog.Errorf(\"Action: %s did not exist\", actionToBeDeleted.Name)\n\t\t} else {\n\t\t\tklog.Infof(\"Action: %s has been deleted \", actionToBeDeleted.Name)\n\t\t}\n\t}\n}",
"func (s *session) handleDELE(args []string) error {\n\treturn s.withMessageDo(args[0], func(msgId uint64) error {\n\t\ts.markedDeleted[msgId] = struct{}{}\n\t\treturn s.respondOK(\"message %d deleted\", msgId)\n\t})\n}",
"func (l *Logger) OnMessageDelete(ds *discordgo.Session, md *discordgo.MessageDelete) {\n\tif l.LogDeletes == false {\n\t\treturn\n\t}\n\n\t// TODO: Create separate log for bots.\n\tif md.Author.ID == ds.State.User.ID {\n\t\treturn\n\t}\n\n\tlog.Printf(\"%+v\", md)\n\tlog.Printf(\"%+v\", md.Message)\n\n\t// TODO: Implement delete logging\n\tembed := message.GetDefaultEmbed()\n\tembed.Title = \"Message Deleted\"\n\tembed.Description = fmt.Sprintf(\"Message Deleted: %s\", md.Content)\n\n\tmessage.SendEmbed(ds, l.ChannelID, embed)\n}",
"func DeleteReaction(ctx context.Context, opts *ReactionOptions) error {\n\treaction := &Reaction{\n\t\tType: opts.Type,\n\t\tUserID: opts.DoerID,\n\t\tIssueID: opts.IssueID,\n\t\tCommentID: opts.CommentID,\n\t}\n\n\tsess := db.GetEngine(ctx).Where(\"original_author_id = 0\")\n\tif opts.CommentID == -1 {\n\t\treaction.CommentID = 0\n\t\tsess.MustCols(\"comment_id\")\n\t}\n\n\t_, err := sess.Delete(reaction)\n\treturn err\n}",
"func (s *Storage) updateReactionTargetOnDelete(ctx context.Context, convID chat1.ConversationID,\n\tuid gregor1.UID, reactionMsg *chat1.MessageUnboxed) (*chat1.MessageUnboxed, bool, Error) {\n\ts.Debug(ctx, \"updateReactionTargetOnDelete: reationMsg: %v\", reactionMsg)\n\n\tif reactionMsg.Valid().MessageBody.IsNil() {\n\t\treturn nil, false, nil\n\t}\n\n\ttargetMsgID := reactionMsg.Valid().MessageBody.Reaction().MessageID\n\ttargetMsg, err := s.getMessage(ctx, convID, uid, targetMsgID)\n\tif err != nil || targetMsg == nil {\n\t\treturn nil, false, err\n\t}\n\tif targetMsg.IsValid() {\n\t\tmvalid := targetMsg.Valid()\n\t\treactionIDs := []chat1.MessageID{}\n\t\tfor _, msgID := range mvalid.ServerHeader.ReactionIDs {\n\t\t\tif msgID != reactionMsg.GetMessageID() {\n\t\t\t\treactionIDs = append(reactionIDs, msgID)\n\t\t\t}\n\t\t}\n\t\tupdated := len(mvalid.ServerHeader.ReactionIDs) != len(reactionIDs)\n\t\tmvalid.ServerHeader.ReactionIDs = reactionIDs\n\t\tnewMsg := chat1.NewMessageUnboxedWithValid(mvalid)\n\t\treturn &newMsg, updated, nil\n\t}\n\treturn nil, false, nil\n}",
"func (r reaction) Removed(discord client.Client, event Event) error {\n\treturn r.execute(discord, event, r.onRemoved)\n}",
"func DeleteMessageHandle(db interface{}) func(server.Request) (handler.Response, error) {\n\n\treturn func(req server.Request) (handler.Response, error) {\n\n\t\t// params from /message/id/:messageId\n\t\tmessageId := req.GetParamByName(\"messageId\")\n\t\tif messageId == \"\" {\n\t\t\terrorMessage := fmt.Sprintf(\"Message Id is required!\")\n\t\t\treturn handler.Response{StatusCode: http.StatusBadRequest, Body: utils.MarshalError(\"messageIdRequired\", errorMessage)}, nil\n\t\t}\n\t\tfmt.Printf(\"\\n Message ID: %s\", messageId)\n\t\tmessageUUID, uuidErr := uuid.FromString(messageId)\n\t\tif uuidErr != nil {\n\t\t\terrorMessage := fmt.Sprintf(\"UUID Error %s\", uuidErr.Error())\n\t\t\treturn handler.Response{StatusCode: http.StatusInternalServerError, Body: utils.MarshalError(\"uuidError\", errorMessage)}, nil\n\t\t}\n\t\tfmt.Printf(\"\\n Message UUID: %s\", messageUUID)\n\t\t// Create service\n\t\tmessageService, serviceErr := service.NewMessageService(db)\n\t\tif serviceErr != nil {\n\t\t\terrorMessage := fmt.Sprintf(\"Message Service Error %s\", serviceErr.Error())\n\t\t\treturn handler.Response{StatusCode: http.StatusInternalServerError, Body: utils.MarshalError(\"messageServiceError\", errorMessage)}, nil\n\n\t\t}\n\n\t\tif err := messageService.DeleteMessageByOwner(req.UserID, messageUUID); err != nil {\n\t\t\terrorMessage := fmt.Sprintf(\"Delete Message Error %s\", err.Error())\n\t\t\treturn handler.Response{StatusCode: http.StatusInternalServerError, Body: utils.MarshalError(\"deleteMessageError\", errorMessage)}, nil\n\n\t\t}\n\n\t\treturn handler.Response{\n\t\t\tBody: []byte(`{\"success\": true}`),\n\t\t\tStatusCode: http.StatusOK,\n\t\t}, nil\n\t}\n}",
"func (shr socketHandlerRegister) MessageReactionRemove(handler HandlerMessageReactionRemove, moreHandlers ...HandlerMessageReactionRemove) {\n\tshr.evtName = EvtMessageReactionRemove\n\tshr.handlers = append(shr.handlers, handler)\n\tfor _, h := range moreHandlers {\n\t\tshr.handlers = append(shr.handlers, h)\n\t}\n\tshr.build()\n}",
"func MessageBotReactionRemove(s *discordgo.Session, m *discordgo.Message, emojis ...string) {\n\tfor _, emoji := range emojis {\n\t\ts.MessageReactionRemove(m.ChannelID, m.ID, emoji, s.State.Ready.User.ID)\n\t}\n}",
"func EventCommissaireDeleteHandler(w http.ResponseWriter, r *http.Request) {\n\tvalidToken := true //checkJwt(w,r)\n\tif (validToken) {\n\t\tvars := mux.Vars(r)\n\t\teventID := vars[\"eventID\"]\n\t\trcID := vars[\"commissaireID\"]\n\t\tw.Header().Set(\"Content-Type\", \"application/json;charset=UTF-8\")\n\t\n\t\tif !IsValidUUID(eventID) {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tif !IsValidUCIID(rcID){\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\n\t\terr := m.DeleteRaceCommissaire(eventID, rcID, connection(), DATABASE, RACECOMMISSAIRE)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t}\n\t\terr = m.DeleteEventCommissaire(eventID, rcID, connection(), DATABASE, EVENTS)\n\t\tif err != nil{\n\t\t\tfmt.Println(fmt.Errorf(\"%s\", err))\n\t\t}\n\t\tcomms, err := m.GetRaceCommissairesList(eventID, connection(), DATABASE, RACECOMMISSAIRE)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusOK)\t\t\n\t\t}\n\t\tif err := json.NewEncoder(w).Encode(comms); err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t}\n}",
"func (t *TelemetryPreMitigationRequest) HandleDelete(request Request, customer *models.Customer) (res Response, err error) {\n\tlog.WithField(\"request\", request).Debug(\"[DELETE] receive message\")\n\tvar errMsg string\n\t// Check Uri-Path cuid, tmid for telemetry pre-mitigation request\n\tcuid, tmid, _, err := messages.ParseTelemetryPreMitigationUriPath(request.PathInfo)\n\tif err != nil {\n\t\terrMsg = fmt.Sprintf(\"Failed to parse Uri-Path, error: %s\", err)\n\t\tlog.Error(errMsg)\n\t\tres = Response {\n\t\t\tType: common.NonConfirmable,\n\t\t\tCode: common.BadRequest,\n\t\t\tBody: errMsg,\n\t\t}\n\t\treturn res, nil\n\t}\n\tif cuid == \"\" {\n\t\terrMsg = \"Missing required Uri-Path Parameter cuid.\"\n\t\tlog.Error(errMsg)\n\t\tres = Response {\n\t\t\tType: common.NonConfirmable,\n\t\t\tCode: common.BadRequest,\n\t\t\tBody: errMsg,\n\t\t}\n\t\treturn res, nil\n\t}\n\tif tmid != nil {\n\t\tlog.Debug(\"Delete one telemetry pre-mitigation\")\n\t\ttelePreMitigation, err := models.GetTelemetryPreMitigationByTmid(customer.Id, cuid, *tmid)\n\t\tif err != nil {\n\t\t\treturn Response{}, err\n\t\t}\n\t\turiFilterPreMitigation, err := models.GetUriFilteringTelemetryPreMitigation(customer.Id, cuid, tmid, nil)\n\t\tif err != nil {\n\t\t\treturn Response{}, err\n\t\t}\n\t\tif telePreMitigation.Id <= 0 && len(uriFilterPreMitigation) < 1{\n\t\t\terrMsg := fmt.Sprintf(\"Not found telemetry pre-mitigation with tmid = %+v\", *tmid)\n\t\t\tlog.Error(errMsg)\n\t\t\tres = Response{\n\t\t\t\tType: common.NonConfirmable,\n\t\t\t\tCode: common.NotFound,\n\t\t\t\tBody: errMsg,\n\t\t\t}\n\t\t\treturn res, nil\n\t\t}\n\t\terr = models.DeleteOneTelemetryPreMitigation(customer.Id, cuid, *tmid, telePreMitigation.Id)\n\t\tif err != nil {\n\t\t\treturn Response{}, err\n\t\t}\n\t} else {\n\t\tlog.Debug(\"Delete all telemetry pre-mitigation\")\n\t\terr = models.DeleteAllTelemetryPreMitigation(customer.Id, cuid)\n\t\tif err != nil {\n\t\t\treturn Response{}, err\n\t\t}\n\t}\n\tres = Response{\n\t\tType: common.NonConfirmable,\n\t\tCode: common.Deleted,\n\t\tBody: \"Deleted\",\n\t}\n\treturn res, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Initialize will create database connection and wire up routes
|
func (app *App) Initialize(user, password, dbname string) {
connectionString := fmt.Sprintf("user=%s password=%s dbname=%s", user, password, dbname)
var err error
app.DB, err = sql.Open("postgres", connectionString)
if err != nil {
log.Fatal(err)
}
app.Router = mux.NewRouter()
}
|
[
"func (a *App) Initialize(dbType, dbString string) {\n\tvar err error\n\ta.DB, err = gorm.Open(sqlite.Open(dbString))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ta.Engine = gin.Default()\n\ta.initializeRoutes()\n}",
"func (s *Server) Initialize(_user, _password, _dbHost string, _dbName string) {\n\tlog.Info(\"Initializing server\")\n\n\ts.Router = mux.NewRouter()\n\ts.User = s.Router.PathPrefix(AV1).Subrouter()\n\ts.Admin = s.Router.PathPrefix(AV1).Subrouter()\n\n\trdb.InitializeRethinkDB()\n\n\ts.addUserMiddleware()\n\ts.addAdminMiddleware()\n\ts.CreateRoutes()\n\n\tlog.Info(\"Server initialized correctly\")\n}",
"func init() {\n\trouter = chi.NewRouter()\n\trouter.Use(middleware.Recoverer)\n\n\tdbSource := fmt.Sprintf(\"root:%s@tcp(%s:%s)/%s?charset=utf8\", dbPass, dbHost, dbPort, dbName)\n\n\tvar err error\n\tdb, err = sql.Open(\"mysql\", dbSource)\n\n\tcatch(err)\n}",
"func (a *Server) Initialize() {\n\tstorage.AttachStorage()\n\tstorage.PopulateBeers()\n\n\ta.Router = mux.NewRouter()\n\ta.Config = a.SetupConfig()\n\ta.DB = &storage.DB\n\n\ta.SetupRoutes()\n}",
"func init() {\n\n\tctx := context.Background()\n\n\tif err := envconfig.Process(ctx, &c); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar err error\n\tdsn := fmt.Sprintf(\"user=%v password=%v dbname=%v port=%v\", c.Dbusername, c.Dbpassword, c.Dbdatabase, c.Dbport)\n\tmodels.Db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})\n\tif err != nil {\n\t\tfmt.Println(\"Gorm open error : \", err)\n\t\treturn\n\t}\n\tfmt.Println(\"Connected to database\")\n\tmodels.Db.AutoMigrate(&models.User{})\n}",
"func InitializeDb() {\n\tdbPort, err := strconv.Atoi(os.Getenv(\"DB_PORT\"))\n\tif err != nil {\n\t\tlog.Fatal(\"Database port is not valid\")\n\t}\n\n\tdbConnString := fmt.Sprintf(\n\t\t\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\",\n\t\tos.Getenv(\"DB_HOST\"),\n\t\tdbPort,\n\t\tos.Getenv(\"DB_USER\"),\n\t\tos.Getenv(\"DB_PASS\"),\n\t\tos.Getenv(\"DB_NAME\"),\n\t)\n\n\tDB, err = sql.Open(\"postgres\", dbConnString)\n\tif err != nil {\n\t\tlog.Fatal(\"Could not connect to db- \", err)\n\t}\n}",
"func init() {\r\n\tCandidates = ConnectDB(\"Candidates\")\r\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 InitializeDatabase() {\n\tvar err error\n\tconnectionString := os.Getenv(\"POSTGRES_CONNECTION_STRING\")\n\n\tif connectionString == \"\" {\n\t\tconnectionString = \"user=crudwizard password=crudwizard dbname=crudwizard sslmode=disable\"\n\t}\n\n\tDatabase, err = gorm.Open(\"postgres\", connectionString)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvalidations.RegisterCallbacks(Database)\n\n\tDatabase.LogMode(true)\n\tDatabase.AutoMigrate(&models.User{})\n\tDatabase.AutoMigrate(&models.Project{})\n\tDatabase.AutoMigrate(&models.AuthToken{})\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 (ar *Router) Init(r *router.MuxWrapper, laStore *database.LeagueAuctionDatastore, conPool *UserConnectionPool) error {\n\n\tlog.Println(\"Setup ws route\")\n\tif r == nil {\n\t\treturn errors.New(\"router wrapper object can not be nil\")\n\t}\n\tif laStore == nil {\n\t\treturn errors.New(\"laStore object can not be nil\")\n\t}\n\tif conPool == nil {\n\t\treturn errors.New(\"connection pool object can not be nil\")\n\t}\n\n\t// initialize user connection pool\n\tar.userConnPool = conPool\n\n\t//instantiate and initilaize upgrader\n\tar.upgrader = new(websocket.Upgrader)\n\t//0 sets to default number of bytes(4096 at the time of writing this code)\n\tar.upgrader.ReadBufferSize = 0\n\tar.upgrader.WriteBufferSize = 0\n\n\tar.auctionstore = laStore\n\tar.router = r\n\terr := ar.router.HandleRoute(\"/connect\", \"\", ar.UpgradeToWsHandler)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func InitDatabase() {\n\thost := os.Getenv(\"ARANGODB_HOST\")\n\tname := os.Getenv(\"ARANGODB_NAME\")\n\tuser := os.Getenv(\"ARANGODB_USER\")\n\tpass := os.Getenv(\"ARANGODB_PASS\")\n\n\tconn, err := arangohttp.NewConnection(\n\t\tarangohttp.ConnectionConfig{Endpoints: []string{host}},\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient, err := arango.NewClient(arango.ClientConfig{\n\t\tConnection: conn,\n\t\tAuthentication: arango.BasicAuthentication(user, pass),\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor {\n\t\tif exists, err := client.DatabaseExists(nil, name); err == nil {\n\t\t\tif !exists {\n\t\t\t\tdb, err = client.CreateDatabase(nil, name, nil)\n\t\t\t} else {\n\t\t\t\tdb, err = client.Database(nil, name)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second * 1)\n\t}\n\n\tmodels := []Model{\n\t\t&PriorityQueueModel{},\n\t}\n\tfor _, model := range models {\n\t\tif err := model.Create(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}",
"func init() {\n\n\t// Standard routes\n\trouter.Get(\"/backlog\", GetAllProductBackLogs)\n\trouter.Get(\"/backlog/:id\", GetProductBackLog)\n\trouter.Post(\"/backlog\", PostProductBackLog)\n\trouter.Put(\"/backlog/:id\", PutProductBackLog)\n\trouter.Delete(\"/backlog/:id\", DeleteProductBackLog)\n\n\trouter.Get(\"/backlog/:id/stories\", GetProductBackLogsAllStories)\n}",
"func (p *Service) Init() error {\n\tpasswd := p.Config.GetMapString(\"db\", \"password\", \"root\")\n\turl := fmt.Sprintf(\n\t\t\"%s:%s@%s\",\n\t\tp.Config.GetMapString(\"db\", \"user\", \"root\"),\n\t\tpasswd,\n\t\tp.Config.GetMapString(\"db\", \"url\"),\n\t)\n\tdb, err := gorm.Open(\"mysql\", url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//timeout, err := time.ParseDuration(p.Config.GetMapString(\"db\", \"connMaxLifetime\", \"2h\"))\n\t//if err != nil {\n\t//\ttimeout = 2 * time.Hour\n\t//}\n\t//db.DB().SetConnMaxLifetime(3 * time.Second)\n\n\t//fix the bug: [mysql] 2016/10/11 09:17:16 packets.go:33: unexpected EOF\n\tdb.DB().SetMaxIdleConns(0)\n\n\tlog := p.Config.GetMapBool(\"db\", \"log\", false)\n\tdb.LogMode(log)\n\tfor v := range p.Models() {\n\t\tif err := db.AutoMigrate(v.Type).Error; err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tp.db = db\n\treturn nil\n}",
"func InitDBConnection() *Database {\n\thost := viper.GetString(\"db.host\")\n\tuser := viper.GetString(\"db.user\")\n\tdbname := viper.GetString(\"db.dbname\")\n\tdbConfig := fmt.Sprintf(\"host=%s user=%s dbname=%s sslmode=disable\", host, user, dbname)\n\tdb, err := gorm.Open(\"postgres\", dbConfig)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Failed to initiate a connection to the database: %s\", err))\n\t}\n\n\tfmt.Println(\"Migrating database\")\n\tdb.AutoMigrate(&User{}, &Organization{}, &Restaurant{}, &Menu{}, &Activity{}, &OrderItem{})\n\n\treturn &Database{db}\n}",
"func InitializeDatabase(config string, log debug.Logger) {\n\tdatabaseAccess = databaseConnection{dbconfig: config, log: log}\n\tdatabaseAccess.initialize()\n}",
"func init() {\n\tschemaConfig := graphql.SchemaConfig{\n\t\tQuery: rootQuery,\n\t\tMutation: rootMutation,\n\t}\n\tschema, err = graphql.NewSchema(schemaConfig)\n\tif err != nil {\n\t\tlog.Fatal(errors.Wrap(err, \"Failed to create a new schema\"))\n\t}\n\tmuxRouter.HandleFunc(\"/graphql\", graphQLHandler)\n}",
"func initDatabases(apiRouter *mux.Router, context *Context) {\n\taddContext := func(handler contextHandlerFunc) *contextHandler {\n\t\treturn newContextHandler(context, handler)\n\t}\n\n\tdatabaseRouter := apiRouter.PathPrefix(\"/databases\").Subrouter()\n\tdatabaseRouter.Handle(\"\", addContext(handleGetDatabases)).Methods(\"GET\")\n}",
"func (r *RavelDatabase) Init(path string) error {\n\tvar err error\n\n\toptions := badger.DefaultOptions(path)\n\toptions.Logger = nil\n\toptions.SyncWrites = true\n\n\tr.Conn, err = badger.Open(options)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
HookClientConfigForWebhook construct a webhook.ClientConfig using a v1beta1.Webhook API object. webhook.ClientConfig is used to create a HookClient and the purpose of the config struct is to share that with other packages that need to create a HookClient.
|
func HookClientConfigForWebhook(w *v1beta1.Webhook) webhook.ClientConfig {
ret := webhook.ClientConfig{Name: w.Name, CABundle: w.ClientConfig.CABundle}
if w.ClientConfig.URL != nil {
ret.URL = *w.ClientConfig.URL
}
if w.ClientConfig.Service != nil {
ret.Service = &webhook.ClientConfigService{
Name: w.ClientConfig.Service.Name,
Namespace: w.ClientConfig.Service.Namespace,
}
if w.ClientConfig.Service.Path != nil {
ret.Service.Path = *w.ClientConfig.Service.Path
}
}
return ret
}
|
[
"func BuildClientConfigFor(webhookPath string, namespace, componentName string, servicePort int, mode, url string, caBundle []byte) admissionregistrationv1.WebhookClientConfig {\n\tvar (\n\t\tpath = webhookPath\n\t\tclientConfig = admissionregistrationv1.WebhookClientConfig{\n\t\t\t// can be empty if injected later on\n\t\t\tCABundle: caBundle,\n\t\t}\n\t)\n\n\tif !strings.HasPrefix(path, \"/\") {\n\t\tpath = \"/\" + path\n\t}\n\n\tswitch mode {\n\tcase ModeURL:\n\t\tclientConfig.URL = pointer.String(fmt.Sprintf(\"https://%s%s\", url, path))\n\tcase ModeURLWithServiceName:\n\t\tclientConfig.URL = pointer.String(fmt.Sprintf(\"https://%s.%s:%d%s\", PrefixedName(componentName), namespace, servicePort, path))\n\tcase ModeService:\n\t\tclientConfig.Service = &admissionregistrationv1.ServiceReference{\n\t\t\tNamespace: namespace,\n\t\t\tName: PrefixedName(componentName),\n\t\t\tPath: &path,\n\t\t}\n\t}\n\n\treturn clientConfig\n}",
"func clientConfigList(webhook runtime.Object, webhookType WebhookType) []*admissionregistrationv1beta1.WebhookClientConfig {\n\tclientConfigList := []*admissionregistrationv1beta1.WebhookClientConfig{}\n\tif webhookType == MutatingWebhook {\n\t\tmutatingWebhookConfig := mutatingWebhookConfig(webhook)\n\t\tfor i, _ := range mutatingWebhookConfig.Webhooks {\n\t\t\tclientConfig := &mutatingWebhookConfig.Webhooks[i].ClientConfig\n\t\t\tclientConfigList = append(clientConfigList, clientConfig)\n\t\t}\n\t} else if webhookType == ValidatingWebhook {\n\t\tvalidatingWebhookConfig := validatingWebhookConfig(webhook)\n\t\tfor i, _ := range validatingWebhookConfig.Webhooks {\n\t\t\tclientConfig := &validatingWebhookConfig.Webhooks[i].ClientConfig\n\t\t\tclientConfigList = append(clientConfigList, clientConfig)\n\t\t}\n\t}\n\treturn clientConfigList\n}",
"func NewWebhookConfigController(p WebhookParameters) (*WebhookConfigController, error) {\n\n\t// Configuration must be updated whenever the caBundle changes. watch the parent directory of\n\t// the target files so we can catch symlink updates of k8s secrets.\n\tfileWatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, file := range []string{p.CACertFile, p.WebhookConfigFile} {\n\t\twatchDir, _ := filepath.Split(file)\n\t\tif err := fileWatcher.Watch(watchDir); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not watch %v: %v\", file, err)\n\t\t}\n\t}\n\n\twhc := &WebhookConfigController{\n\t\tconfigWatcher: fileWatcher,\n\t\twebhookParameters: &p,\n\t\tcreateInformerWebhookSource: defaultCreateInformerWebhookSource,\n\t}\n\n\tgalleyNamespace, err := whc.webhookParameters.Clientset.CoreV1().Namespaces().Get(\n\t\twhc.webhookParameters.DeploymentAndServiceNamespace, metav1.GetOptions{})\n\tif err != nil {\n\t\tscope.Warnf(\"Could not find %s namespace to set ownerRef. \"+\n\t\t\t\"The validatingwebhookconfiguration must be deleted manually\",\n\t\t\twhc.webhookParameters.DeploymentAndServiceNamespace)\n\t} else {\n\t\twhc.ownerRefs = []metav1.OwnerReference{\n\t\t\t*metav1.NewControllerRef(\n\t\t\t\tgalleyNamespace,\n\t\t\t\tcorev1.SchemeGroupVersion.WithKind(\"Namespace\"),\n\t\t\t),\n\t\t}\n\t}\n\n\treturn whc, nil\n}",
"func NewClient(webhook, token string) (*Client, error) {\n\tif len(webhook) == 0 {\n\t\treturn nil, fmt.Errorf(\"webhook url is missing\")\n\t}\n\tif len(token) == 0 {\n\t\treturn nil, fmt.Errorf(\"token is missing\")\n\t}\n\n\tp, err := url.Parse(webhook)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"fail to parse url\")\n\t}\n\tc := &Client{\n\t\tWebhookURL: p,\n\t\tHTTPClient: &http.Client{},\n\t\tHeader: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"X-Zoom-Token\": token,\n\t\t},\n\t}\n\n\treturn c, nil\n}",
"func NewWithConfig(conf Config) (*WebhookHandler, error) {\n\th := &WebhookHandler{}\n\n\tcli, err := newClient(conf)\n\tif err != nil {\n\t\th.loggingError(\"newClient error: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tif conf.BotID == 0 {\n\t\t// get bot's id from github's current user.\n\t\tctx := context.Background()\n\t\tu, _, err := cli.Users.Get(ctx, \"\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tconf.BotID = u.GetID()\n\t\th.loggingInfo(\"botID is fetched from github: %d\", conf.BotID)\n\t}\n\n\th.client = cli\n\th.Config = conf\n\th.loggingInfo(\"initialized\")\n\treturn h, nil\n}",
"func HTTPClientConfig(fn func(c *consulapi.Config)) (*consulapi.Client, error) {\n\tconf := consulapi.DefaultConfig()\n\tfn(conf)\n\treturn consulapi.NewClient(conf)\n}",
"func (k *KubernetesClient) CreateValidatingWebhookConfiguration(webhookFile, certFile, apiKey, port string) (*admissionv1.ValidatingWebhookConfiguration, error) {\n\twebhooks := admissionv1.ValidatingWebhookConfiguration{}\n\tdata, err := ioutil.ReadFile(webhookFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treader := bytes.NewReader(data)\n\tdecoder := yaml.NewYAMLOrJSONDecoder(reader, 1024)\n\terr = decoder.Decode(&webhooks)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcertData, err := ioutil.ReadFile(certFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twebhook := &webhooks.Webhooks[0]\n\twebhook.ClientConfig.CABundle = certData\n\tip, err := GetIP()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\turl := fmt.Sprintf(\"https://%s:%s/v1/k8s/webhooks/%s/scan/validate\", ip.String(), port, apiKey)\n\twebhook.ClientConfig.URL = &url\n\n\tadmr := k.client.AdmissionregistrationV1()\n\n\tcreatedWebhookConfig, err := admr.ValidatingWebhookConfigurations().Create(context.TODO(), &webhooks, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn createdWebhookConfig, nil\n}",
"func NewWebhookConfig(URL string) WebhookConfig {\n\tcfg := WebhookConfig{}\n\tcfg.URL = URL\n\tcfg.Subscription = fmt.Sprintf(\"%s%s%d\", NonResumable, icrypto.GenTopicKey(), time.Now().UnixNano())\n\tcfg.WebhookStatus = Activated\n\tcfg.SubscriptionType = \"exclusive\"\n\tcfg.InitialPosition = \"latest\"\n\tcfg.CreatedAt = time.Now()\n\tcfg.UpdatedAt = time.Now()\n\treturn cfg\n}",
"func GetCABundleFromWebhookConfig(obj client.Object) ([]byte, error) {\n\tswitch config := obj.(type) {\n\tcase *admissionregistrationv1.MutatingWebhookConfiguration:\n\t\tfor _, webhook := range config.Webhooks {\n\t\t\tif caBundle := webhook.ClientConfig.CABundle; len(caBundle) > 0 {\n\t\t\t\treturn caBundle, nil\n\t\t\t}\n\t\t}\n\tcase *admissionregistrationv1.ValidatingWebhookConfiguration:\n\t\tfor _, webhook := range config.Webhooks {\n\t\t\tif caBundle := webhook.ClientConfig.CABundle; len(caBundle) > 0 {\n\t\t\t\treturn caBundle, nil\n\t\t\t}\n\t\t}\n\tcase *admissionregistrationv1beta1.MutatingWebhookConfiguration:\n\t\tfor _, w := range config.Webhooks {\n\t\t\tif caBundle := w.ClientConfig.CABundle; len(caBundle) > 0 {\n\t\t\t\treturn caBundle, nil\n\t\t\t}\n\t\t}\n\tcase *admissionregistrationv1beta1.ValidatingWebhookConfiguration:\n\t\tfor _, webhook := range config.Webhooks {\n\t\t\tif caBundle := webhook.ClientConfig.CABundle; len(caBundle) > 0 {\n\t\t\t\treturn caBundle, nil\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unexpected webhook config type: %T\", obj)\n\t}\n\n\treturn nil, nil\n}",
"func tlsClientConfig(cfg *rest.Config) (*tls.Config, error) {\n\tcert, err := tls.X509KeyPair(cfg.TLSClientConfig.CertData, cfg.TLSClientConfig.KeyData)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tpool := x509.NewCertPool()\n\tok := pool.AppendCertsFromPEM(cfg.TLSClientConfig.CAData)\n\tif !ok {\n\t\treturn nil, trace.BadParameter(\"failed to append certs from PEM\")\n\t}\n\n\treturn &tls.Config{\n\t\tRootCAs: pool,\n\t\tCertificates: []tls.Certificate{cert},\n\t\tClientAuth: tls.RequireAndVerifyClientCert,\n\t}, nil\n}",
"func BuildClientConfig(kubeconfig, context string) (*rest.Config, error) {\n\tif kubeconfig != \"\" {\n\t\tinfo, err := os.Stat(kubeconfig)\n\t\tif err != nil || info.Size() == 0 {\n\t\t\t// If the specified kubeconfig doesn't exists / empty file / any other error\n\t\t\t// from file stat, fall back to default\n\t\t\tkubeconfig = \"\"\n\t\t}\n\t}\n\n\t//Config loading rules:\n\t// 1. kubeconfig if it not empty string\n\t// 2. In cluster config if running in-cluster\n\t// 3. Config(s) in KUBECONFIG environment variable\n\t// 4. Use $HOME/.kube/config\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tloadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig\n\tloadingRules.ExplicitPath = kubeconfig\n\tconfigOverrides := &clientcmd.ConfigOverrides{\n\t\tClusterDefaults: clientcmd.ClusterDefaults,\n\t\tCurrentContext: context,\n\t}\n\n\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides).ClientConfig()\n}",
"func NewClientConfig(s *state.State, host kubeone.HostConfig) (*clientv3.Config, error) {\n\tsshconn, err := s.Connector.Connect(host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgrpcDialer, err := sshtunnel.NewGRPCDialer(s.Connector, host)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create grpc tunnel dialer\")\n\t}\n\n\ttlsConf, err := LoadTLSConfig(sshconn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &clientv3.Config{\n\t\tEndpoints: []string{fmt.Sprintf(\"%s:2379\", host.PrivateAddress)},\n\t\tTLS: tlsConf,\n\t\tContext: s.Context,\n\t\tDialTimeout: 5 * time.Second,\n\t\tDialOptions: []grpc.DialOption{\n\t\t\tgrpc.WithBlock(),\n\t\t\tgrpcDialer,\n\t\t},\n\t}, nil\n}",
"func populateClientConfig(config *Config) *Config {\n\tif config == nil {\n\t\tconfig = &Config{}\n\t}\n\tversions := config.Versions\n\tif len(versions) == 0 {\n\t\tversions = protocol.SupportedVersions\n\t}\n\n\thandshakeTimeout := protocol.DefaultHandshakeTimeout\n\tif config.HandshakeTimeout != 0 {\n\t\thandshakeTimeout = config.HandshakeTimeout\n\t}\n\tidleTimeout := protocol.DefaultIdleTimeout\n\tif config.IdleTimeout != 0 {\n\t\tidleTimeout = config.IdleTimeout\n\t}\n\n\tmaxReceiveStreamFlowControlWindow := config.MaxReceiveStreamFlowControlWindow\n\tif maxReceiveStreamFlowControlWindow == 0 {\n\t\tmaxReceiveStreamFlowControlWindow = protocol.DefaultMaxReceiveStreamFlowControlWindowClient\n\t}\n\tmaxReceiveConnectionFlowControlWindow := config.MaxReceiveConnectionFlowControlWindow\n\tif maxReceiveConnectionFlowControlWindow == 0 {\n\t\tmaxReceiveConnectionFlowControlWindow = protocol.DefaultMaxReceiveConnectionFlowControlWindowClient\n\t}\n\n\treturn &Config{\n\t\tVersions: versions,\n\t\tHandshakeTimeout: handshakeTimeout,\n\t\tIdleTimeout: idleTimeout,\n\t\tRequestConnectionIDTruncation: config.RequestConnectionIDTruncation,\n\t\tMaxReceiveStreamFlowControlWindow: maxReceiveStreamFlowControlWindow,\n\t\tMaxReceiveConnectionFlowControlWindow: maxReceiveConnectionFlowControlWindow,\n\t\tKeepAlive: config.KeepAlive,\n\t\tCacheHandshake: config.CacheHandshake,\n\t\tCreatePaths: config.CreatePaths,\n\t}\n}",
"func CreateWebhookListener(config,\n\tremoteConfig *rest.Config,\n\tscheme *runtime.Scheme,\n\ttlsKeyFile, tlsCrtFile string,\n\tcreateService bool) (*WebhookListener, error) {\n\tif klog.V(utils.QuiteLogLel) {\n\t\tfnName := utils.GetFnName()\n\t\tklog.Infof(\"Entering: %v()\", fnName)\n\n\t\tdefer klog.Infof(\"Exiting: %v()\", fnName)\n\t}\n\n\tvar err error\n\n\tdynamicClient := dynamic.NewForConfigOrDie(config)\n\n\tl := &WebhookListener{\n\t\tDynamicClient: dynamicClient,\n\t\tlocalConfig: config,\n\t}\n\n\t// The user-provided key and cert files take precedence over the default provided files if both sets exist.\n\tif _, err := os.Stat(defaultKeyFile); err == nil {\n\t\tl.TLSKeyFile = defaultKeyFile\n\t}\n\n\tif _, err := os.Stat(defaultCrtFile); err == nil {\n\t\tl.TLSCrtFile = defaultCrtFile\n\t}\n\n\tif _, err := os.Stat(tlsKeyFile); err == nil {\n\t\tl.TLSKeyFile = tlsKeyFile\n\t}\n\n\tif _, err := os.Stat(tlsCrtFile); err == nil {\n\t\tl.TLSCrtFile = tlsCrtFile\n\t}\n\n\tl.LocalClient, err = client.New(config, client.Options{})\n\n\tif err != nil {\n\t\tklog.Error(\"Failed to initialize client to update local status. error: \", err)\n\t\treturn nil, err\n\t}\n\n\tl.RemoteClient = l.LocalClient\n\tif remoteConfig != nil {\n\t\tl.RemoteClient, err = client.New(remoteConfig, client.Options{})\n\n\t\tif err != nil {\n\t\t\tklog.Error(\"Failed to initialize client to update remote status. error: \", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif createService {\n\t\tnamespace, err := getOperatorNamespace()\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Create the webhook listener service only when the subscription controller runs in hub mode.\n\t\terr = createWebhookListnerService(l.LocalClient, namespace)\n\n\t\tif err != nil {\n\t\t\tklog.Error(\"Failed to create a service for Git webhook listener. error: \", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn l, err\n}",
"func BuildClientConfig(kubeConfigPath string, clusterName string) (*rest.Config, error) {\n\toverrides := clientcmd.ConfigOverrides{}\n\t// Override the cluster name if provided.\n\tif clusterName != \"\" {\n\t\toverrides.Context.Cluster = clusterName\n\t}\n\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeConfigPath},\n\t\t&overrides).ClientConfig()\n}",
"func NewWebhooksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*WebhooksClient, error) {\n\tcl, err := arm.NewClient(internal.ModuleName+\"/armcontainerregistry.WebhooksClient\", internal.ModuleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &WebhooksClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}",
"func createValidatingWebhookConfiguration(hook webhooks.Webhook) admissionregv1.ValidatingWebhookConfiguration {\n\tfailPolicy := hook.FailurePolicy()\n\ttimeout := hook.TimeoutSeconds()\n\tmatchPolicy := hook.MatchPolicy()\n\tsideEffects := hook.SideEffects()\n\n\treturn admissionregv1.ValidatingWebhookConfiguration{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ValidatingWebhookConfiguration\",\n\t\t\tAPIVersion: \"admissionregistration.k8s.io/v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"sre-%s\", hook.Name()),\n\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"managed.openshift.io/inject-cabundle-from\": fmt.Sprintf(\"%s/webhook-cert\", *namespace),\n\t\t\t\t// TODO(lseelye): Leave out until Until 4.4 when openshift-ca-operator\n\t\t\t\t// supports ValidatingWebhookConfigurations, so as to not fight against\n\t\t\t\t// that operator once 4.4 lands.\n\t\t\t\t//\t// For openshift/service-ca-operator\n\t\t\t\t//\t\"service.beta.openshift.io/inject-cabundle\": \"true\",\n\t\t\t},\n\t\t},\n\t\tWebhooks: []admissionregv1.ValidatingWebhook{\n\t\t\t{\n\t\t\t\tAdmissionReviewVersions: []string{\"v1beta1\"},\n\t\t\t\tTimeoutSeconds: &timeout,\n\t\t\t\tSideEffects: &sideEffects,\n\t\t\t\tMatchPolicy: &matchPolicy,\n\t\t\t\tName: fmt.Sprintf(\"%s.managed.openshift.io\", hook.Name()),\n\t\t\t\tFailurePolicy: &failPolicy,\n\t\t\t\tClientConfig: admissionregv1.WebhookClientConfig{\n\t\t\t\t\tService: &admissionregv1.ServiceReference{\n\t\t\t\t\t\tNamespace: *namespace,\n\t\t\t\t\t\tPath: pointer.StringPtr(hook.GetURI()),\n\t\t\t\t\t\tName: serviceName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tRules: hook.Rules(),\n\t\t\t},\n\t\t},\n\t}\n}",
"func GRPCClientFromConfig(cfg config.View, prefix string) (*grpc.ClientConn, error) {\n\tclientParams := &ClientParams{\n\t\tHostname: cfg.GetString(prefix + \".hostname\"),\n\t\tPort: cfg.GetInt(prefix + \".grpcport\"),\n\t\tEnableRPCLogging: cfg.GetBool(configNameEnableRPCLogging),\n\t\tEnableMetrics: cfg.GetBool(telemetry.ConfigNameEnableMetrics),\n\t}\n\n\t// If TLS support is enabled in the config, fill in the trusted certificates for decrpting server certificate.\n\tif cfg.GetString(configNameClientTrustedCertificatePath) != \"\" {\n\t\t_, err := os.Stat(cfg.GetString(configNameClientTrustedCertificatePath))\n\t\tif err != nil {\n\t\t\tclientLogger.WithError(err).Error(\"trusted certificate file may not exists.\")\n\t\t\treturn nil, err\n\t\t}\n\n\t\tclientParams.TrustedCertificate, err = ioutil.ReadFile(cfg.GetString(configNameClientTrustedCertificatePath))\n\t\tif err != nil {\n\t\t\tclientLogger.WithError(err).Error(\"failed to read tls trusted certificate to establish a secure grpc client.\")\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn GRPCClientFromParams(clientParams)\n}",
"func rebuildWebhookConfigHelper(\n\tcaFile, webhookConfigFile, webhookName string,\n\townerRefs []metav1.OwnerReference,\n) (*v1beta1.ValidatingWebhookConfiguration, error) {\n\t// load and validate configuration\n\twebhookConfigData, err := ioutil.ReadFile(webhookConfigFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar webhookConfig v1beta1.ValidatingWebhookConfiguration\n\tif err := yaml.Unmarshal(webhookConfigData, &webhookConfig); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not decode validatingwebhookconfiguration from %v: %v\",\n\t\t\twebhookConfigFile, err)\n\t}\n\n\t// fill in missing defaults to minimize desired vs. actual diffs later.\n\tfor i := 0; i < len(webhookConfig.Webhooks); i++ {\n\t\tif webhookConfig.Webhooks[i].FailurePolicy == nil {\n\t\t\tfailurePolicy := v1beta1.Fail\n\t\t\twebhookConfig.Webhooks[i].FailurePolicy = &failurePolicy\n\t\t}\n\t\tif webhookConfig.Webhooks[i].NamespaceSelector == nil {\n\t\t\twebhookConfig.Webhooks[i].NamespaceSelector = &metav1.LabelSelector{}\n\t\t}\n\t}\n\n\t// the webhook name is fixed at startup time\n\twebhookConfig.Name = webhookName\n\n\t// update ownerRefs so configuration is cleaned up when the galley's namespace is deleted.\n\twebhookConfig.OwnerReferences = ownerRefs\n\n\tin, err := os.Open(caFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ca bundle from %v: %v\", caFile, err)\n\t}\n\tdefer in.Close() // nolint: errcheck\n\n\tcaPem, err := loadCaCertPem(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// patch the ca-cert into the user provided configuration\n\tfor i := range webhookConfig.Webhooks {\n\t\twebhookConfig.Webhooks[i].ClientConfig.CABundle = caPem\n\t}\n\n\treturn &webhookConfig, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Write writes len(b) bytes to memory. It returns the number of bytes written and an error, if any. Write returns a nonnil error when n != len(b).
|
func (m *Memory) Write(b []byte) (n int, err error) {
if m == nil {
return 0, os.ErrInvalid
}
if len(b) > len(m.buf) {
n = len(m.buf)
} else {
n = len(b)
}
for i := 0; i < n; i++ {
m.buf[i] = b[i]
}
m.buf = m.buf[n:]
return n, nil
}
|
[
"func (b *Writer) Write(buf []byte) (n int, err error)",
"func (writer *FileWriter) Write(b []byte) (n int, err error) {\n\tbyteLen := len(b)\n\n\t// notify the detector before actually writing to prevent overrunning\n\t// any implementation specific thresholds which may be set\n\twriter.rollDetector.NotifyWrite(byteLen)\n\n\tif writer.rollDetector.ShouldRoll() {\n\t\twriter.roller.Roll(writer.file)\n\t\twriter.Init()\n\t}\n\n\tif byteLen > writer.bufferSize {\n\t\t// Break up messages that exceed the downstream buffer length,\n\t\t// using a bytes.Buffer since it's easy. This may result in an\n\t\t// undesirable amount of allocations, but the assumption is that\n\t\t// bursts of too-long messages are rare.\n\t\tbuf := bytes.NewBuffer(b)\n\t\tfor buf.Len() > 0 {\n\t\t\twriter.file.Write(buf.Next(writer.bufferSize))\n\t\t\twriter.file.Write([]byte(NL))\n\t\t}\n\t} else {\n\t\twriter.file.Write(b)\n\t\twriter.file.Write([]byte(NL))\n\t}\n\n\treturn byteLen, nil\n}",
"func (b *Bytes) Write(p []byte) (int, error) {\n\tn := b.Len()\n\tb.grow(n + len(p))\n\tcopy((*b.p)[n:], p)\n\treturn len(p), nil\n}",
"func (b *SafeBuffer) Write(p []byte) (n int, err error) {\n\tb.m.Lock()\n\tdefer b.m.Unlock()\n\treturn b.b.Write(p)\n}",
"func (e errorConnection) Write(b []byte) (n int, err error) {\n\treturn 0, e.err\n}",
"func (c *conn) Write(b []byte) (int, error) {\n\tc.wonce.Do(c.sleepLatency)\n\n\tvar total int64\n\tfor len(b) > 0 {\n\t\tvar max int64\n\n\t\tn, err := c.wb.FillThrottle(func(remaining int64) (int64, error) {\n\t\t\tmax = remaining\n\t\t\tif l := int64(len(b)); remaining >= l {\n\t\t\t\tmax = l\n\t\t\t}\n\n\t\t\tn, err := c.Conn.Write(b[:max])\n\t\t\treturn int64(n), err\n\t\t})\n\n\t\ttotal += n\n\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tlog.Errorf(\"trafficshape: failed write: %v\", err)\n\t\t\t}\n\t\t\treturn int(total), err\n\t\t}\n\n\t\tb = b[max:]\n\t}\n\n\treturn int(total), nil\n}",
"func (bw *BlockWriter) Write(b []byte) (int, error) {\n\tvar blockFull bool\n\tif bw.offset >= bw.blockSize {\n\t\treturn 0, ErrEndOfBlock\n\t} else if (bw.offset + int64(len(b))) > bw.blockSize {\n\t\tblockFull = true\n\t\tb = b[:bw.blockSize-bw.offset]\n\t}\n\n\tif bw.stream == nil {\n\t\terr := bw.connectNext()\n\t\t// TODO: handle failures, set up recovery pipeline\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\t// TODO: handle failures, set up recovery pipeline\n\tn, err := bw.stream.Write(b)\n\tbw.offset += int64(n)\n\tif err == nil && blockFull {\n\t\terr = ErrEndOfBlock\n\t}\n\n\treturn n, err\n}",
"func (f errorWriter) Write(p []byte) (int, error) {\n\treturn f.n, errorWriterErr\n}",
"func (bw *BlockWriter) Write(b []byte) (int, error) {\n\tvar blockFull bool\n\tif bw.Offset >= bw.BlockSize {\n\t\treturn 0, ErrEndOfBlock\n\t} else if (bw.Offset + int64(len(b))) > bw.BlockSize {\n\t\tblockFull = true\n\t\tb = b[:bw.BlockSize-bw.Offset]\n\t}\n\n\tif bw.stream == nil {\n\t\terr := bw.connectNext()\n\t\t// TODO: handle failures, set up recovery pipeline\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\t// TODO: handle failures, set up recovery pipeline\n\tn, err := bw.stream.Write(b)\n\tbw.Offset += int64(n)\n\tif err == nil && blockFull {\n\t\terr = ErrEndOfBlock\n\t}\n\n\treturn n, err\n}",
"func (b *ByteBuffer) Write(p []byte) (int, error) {\n\tb.B = append(b.B, p...)\n\treturn len(p), nil\n}",
"func (p *PacketConn) Write(b []byte) (n int, err error) {\n\tn, err = unix.Write(p.fd, b)\n\tif err != nil {\n\t\treturn\n\t}\n\tif n != len(b) {\n\t\terr = io.ErrShortWrite\n\t}\n\n\treturn\n}",
"func (w WriterFunc) Write(b []byte) (int, error) {\n\treturn w(b)\n}",
"func (f *MockFile) Write(b []byte) (int, error) {\n\tif f.fs.WithWriteError {\n\t\treturn 0, errors.New(\"mock write error\")\n\t}\n\tif f.closed {\n\t\treturn 0, errors.New(\"mock file is closed\")\n\t}\n\treturn f.Buffer.Write(b)\n}",
"func (m *MockNetpollWriter) Write(b []byte) (n int, err error) {\n\treturn\n}",
"func (mlog *MultiLogger) Write(b []byte) (n int, err error) {\n\tmlog.qerr <- libbytes.Copy(b)\n\treturn len(b), nil\n}",
"func (foo *Flusher) Write(b []byte) (int, error) {\n\tcount, err := foo.w.Write(b)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tif err := foo.w.Flush(); err != nil {\n\t\treturn -1, err\n\t}\n\treturn count, err\n}",
"func (mc *MockConn) Write(b []byte) (n int, err error) {\n\tif mc.closed {\n\t\treturn 0, errors.New(\"Connection closed.\")\n\t}\n\n\tdata := make([]byte, len(b))\n\tcopy(data, b)\n\tmc.sendChan <- data\n\treturn len(b), nil\n}",
"func (b *ByteBuffer) Write(p []byte) (int, error) {\n\tb.Buf = append(b.Buf, p...)\n\treturn len(p), nil\n}",
"func (f *File) Write(b []byte) (n int, err error) {\n\tswitch f.fd {\n\tcase Stdout.fd, Stderr.fd:\n\t\tfor _, c := range b {\n\t\t\tputchar(c)\n\t\t}\n\t\treturn len(b), nil\n\tdefault:\n\t\treturn 0, errUnsupported\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ProvidersAWS : Define the aws provider function
|
func ProvidersAWS(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(awsResources); err != nil {
panic(err)
}
}
|
[
"func NewAWSProvider(dryRun bool) (Provider, error) {\n\tconfig := aws.NewConfig()\n\n\tsession, err := session.NewSessionWithOptions(session.Options{\n\t\tConfig: *config,\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprovider := &AWSProvider{\n\t\tClient: route53.New(session),\n\t\tDryRun: dryRun,\n\t}\n\n\treturn provider, nil\n}",
"func ResolveAWSProvider(commons ...Common) *AWSProvider {\n\tvar profile, region, role, version *string\n\tvar accountID *json.Number\n\tvar additionalRegions []string\n\tvar additionalProviders map[string]*AWSProvider\n\n\tfor _, c := range commons {\n\t\tif c.Providers != nil && c.Providers.AWS != nil {\n\t\t\tp := c.Providers.AWS\n\n\t\t\t// Profile and Role are mutually exclusive, so if one is set then we set the other to\n\t\t\t// nil Our validations in validateAWSProviderAuth will assure that they are not\n\t\t\t// both set in the same stuct.\n\t\t\tif p.Profile != nil {\n\t\t\t\tprofile = p.Profile\n\t\t\t\trole = nil\n\t\t\t} else if p.Role != nil {\n\t\t\t\trole = p.Role\n\t\t\t\tprofile = nil\n\t\t\t}\n\n\t\t\tif p.Region != nil {\n\t\t\t\tregion = p.Region\n\t\t\t}\n\n\t\t\tif p.Version != nil {\n\t\t\t\tversion = p.Version\n\t\t\t}\n\n\t\t\tif p.AccountID != nil {\n\t\t\t\taccountID = p.AccountID\n\t\t\t}\n\n\t\t\tif p.AdditionalRegions != nil {\n\t\t\t\tadditionalRegions = p.AdditionalRegions\n\t\t\t}\n\n\t\t\tif p.AdditionalProviders != nil {\n\t\t\t\tadditionalProviders = p.AdditionalProviders\n\t\t\t}\n\t\t}\n\t}\n\n\tif profile != nil || role != nil || region != nil || version != nil {\n\t\treturn &AWSProvider{\n\t\t\tProfile: profile,\n\t\t\tRegion: region,\n\t\t\tRole: role,\n\t\t\tCommonProvider: CommonProvider{\n\t\t\t\tEnabled: defaultEnabled(true),\n\t\t\t\tVersion: version,\n\t\t\t},\n\n\t\t\t// optional fields\n\t\t\tAccountID: accountID,\n\t\t\tAdditionalRegions: additionalRegions,\n\t\t\tAdditionalProviders: additionalProviders,\n\t\t}\n\t}\n\treturn nil\n}",
"func AWSFactory(service string) AWS {\n\tservice = strings.ToLower(service)\n\tswitch service {\n\tcase \"rds\":\n\t\treturn rdsService{\n\t\t\tsvc: rds.New(sess, updateCredentials(sess)),\n\t\t}\n\tcase \"elasti\":\n\t\treturn elastiService{\n\t\t\tsvc: elasticache.New(sess, updateCredentials(sess)),\n\t\t}\n\tdefault:\n\t\treturn nil\n\t}\n}",
"func (p *AWS) Initialize(config *types.ProviderConfig) error {\n\tp.Storage = &S3{}\n\n\tif config.Zone == \"\" {\n\t\treturn errors.New(\"zone missing\")\n\t}\n\n\terr := loadAWSCreds()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, err := session.NewSession(\n\t\t&aws.Config{\n\t\t\tRegion: aws.String(stripZone(config.Zone)),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.session = session\n\tp.dnsService = route53.New(session)\n\tp.ec2 = ec2.New(session)\n\tp.volumeService = ebs.New(session,\n\t\taws.NewConfig().\n\t\t\tWithRegion(stripZone(config.Zone)).\n\t\t\tWithMaxRetries(7))\n\n\t_, err = p.ec2.DescribeRegions(&ec2.DescribeRegionsInput{RegionNames: aws.StringSlice([]string{stripZone(config.Zone)})})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"region with name %v is invalid\", config.Zone)\n\t}\n\n\treturn nil\n}",
"func ec2Provider(providers []ProviderPayload) *ProviderPayload {\n\tfor _, provider := range providers {\n\t\tif provider.Name == providerEc2 {\n\t\t\treturn &provider\n\t\t}\n\t}\n\tlog.Fatal(\"ec2 provider is missing\")\n\treturn nil\n}",
"func FromEnv() *AWSProvider {\n\tp := &AWSProvider{\n\t\tRegion: os.Getenv(\"AWS_REGION\"),\n\t\tEndpoint: os.Getenv(\"AWS_ENDPOINT\"),\n\t\tBuildCluster: os.Getenv(\"BUILD_CLUSTER\"),\n\t\tCloudformationTopic: os.Getenv(\"CLOUDFORMATION_TOPIC\"),\n\t\tCluster: os.Getenv(\"CLUSTER\"),\n\t\tCustomTopic: os.Getenv(\"CUSTOM_TOPIC\"),\n\t\tDevelopment: os.Getenv(\"DEVELOPMENT\") == \"true\",\n\t\tDynamoBuilds: os.Getenv(\"DYNAMO_BUILDS\"),\n\t\tDynamoReleases: os.Getenv(\"DYNAMO_RELEASES\"),\n\t\tEncryptionKey: os.Getenv(\"ENCRYPTION_KEY\"),\n\t\tFargate: os.Getenv(\"FARGATE\") == \"Yes\",\n\t\tInternal: os.Getenv(\"INTERNAL\") == \"Yes\",\n\t\tLogBucket: os.Getenv(\"LOG_BUCKET\"),\n\t\tNotificationHost: os.Getenv(\"NOTIFICATION_HOST\"),\n\t\tNotificationTopic: os.Getenv(\"NOTIFICATION_TOPIC\"),\n\t\tPassword: os.Getenv(\"PASSWORD\"),\n\t\tRack: os.Getenv(\"RACK\"),\n\t\tRegistryHost: os.Getenv(\"REGISTRY_HOST\"),\n\t\tRelease: os.Getenv(\"RELEASE\"),\n\t\tSecurityGroup: os.Getenv(\"SECURITY_GROUP\"),\n\t\tSettingsBucket: os.Getenv(\"SETTINGS_BUCKET\"),\n\t\tSubnets: os.Getenv(\"SUBNETS\"),\n\t\tSubnetsPrivate: os.Getenv(\"SUBNETS_PRIVATE\"),\n\t\tVpc: os.Getenv(\"VPC\"),\n\t\tVpcCidr: os.Getenv(\"VPCCIDR\"),\n\t}\n\n\treturn p\n}",
"func Provider(cfg Config) *AppConfig {\n\tc, err := config.LoadDefaultConfig(context.TODO())\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tif cfg.AWSRegion != \"\" {\n\t\tc.Region = cfg.AWSRegion\n\t}\n\n\t// Check if AWS Access Key ID and Secret Key are specified.\n\tif cfg.AWSAccessKeyID != \"\" && cfg.AWSSecretAccessKey != \"\" {\n\t\tc.Credentials = credentials.NewStaticCredentialsProvider(cfg.AWSAccessKeyID, cfg.AWSSecretAccessKey, \"\")\n\t}\n\n\t// Check if AWS Role ARN is present.\n\tif cfg.AWSRoleARN != \"\" {\n\t\tstsSvc := sts.NewFromConfig(c)\n\t\tcredentials := stscreds.NewAssumeRoleProvider(stsSvc, cfg.AWSRoleARN)\n\t\tc.Credentials = aws.NewCredentialsCache(credentials)\n\t}\n\tclient := appconfig.NewFromConfig(c)\n\n\treturn &AppConfig{client: client, config: cfg}\n}",
"func awsConnect(i *AwsInfo) *s3.Bucket {\n\tAWSAuth := aws.Auth{\n\t\tAccessKey: i.AccessKey,\n\t\tSecretKey: i.SecretKey,\n\t}\n\tregion := aws.USEast\n\tconnection := s3.New(AWSAuth, region)\n\n\treturn connection.Bucket(i.Bucket)\n}",
"func AWSFuncs(f map[string]interface{}) {\n\tf2 := CreateAWSFuncs(context.Background())\n\tfor k, v := range f2 {\n\t\tf[k] = v\n\t}\n}",
"func NewAWS(crypto appencryption.AEAD, preferredRegion string, arnMap map[string]string) (*AWSKMS, error) {\n\treturn newAWS(crypto, preferredRegion, awsARNMap(arnMap))\n}",
"func newAWSCloud(config io.Reader, awsServices Services) (*Cloud, error) {\n\t// We have some state in the Cloud object - in particular the attaching map\n\t// Log so that if we are building multiple Cloud objects, it is obvious!\n\tglog.Infof(\"Building AWS cloudprovider\")\n\n\t// Register handler for ECR credentials\n\t// Register regions, in particular for ECR credentials\n\tonce.Do(func() {\n\t\tRecognizeWellKnownRegions()\n\t})\n\n\tmetadata, err := awsServices.Metadata()\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"error creating AWS metadata client: %v\", err)\n\t}\n\n\tcfg, err := readAWSCloudConfig(config, metadata)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"unable to read AWS cloud provider config file: %v\", err)\n\t}\n\n\tzone := cfg.Global.Zone\n\tif len(zone) <= 1 {\n\t\treturn nil, errors.Errorf(\"invalid AWS zone in config file: %s\", zone)\n\t}\n\tregionName, err := azToRegion(zone)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !cfg.Global.DisableStrictZoneCheck {\n\t\tvalid := isRegionValid(regionName)\n\t\tif !valid {\n\t\t\treturn nil, errors.Errorf(\"not a valid AWS zone (unknown region): %s\", zone)\n\t\t}\n\t} else {\n\t\tglog.Warningf(\"Strict AWS zone checking is disabled. Proceeding with zone: %s\", zone)\n\t}\n\n\tec2, err := awsServices.Compute(regionName)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"error creating AWS EC2 client: %v\", err)\n\t}\n\n\telb, err := awsServices.LoadBalancing(regionName)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"error creating AWS ELB client: %v\", err)\n\t}\n\n\tawsCloud := &Cloud{\n\t\tec2: ec2,\n\t\telb: elb,\n\t\tmetadata: metadata,\n\t\tcfg: cfg,\n\t\tregion: regionName,\n\t}\n\n\tselfAWSInstance, err := awsCloud.buildSelfAWSInstance()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tawsCloud.selfAWSInstance = selfAWSInstance\n\tawsCloud.vpcID = selfAWSInstance.vpcID\n\n\tfilterTags := map[string]string{}\n\tif cfg.Global.KubernetesClusterTag != \"\" {\n\t\tfilterTags[TagNameKubernetesCluster] = cfg.Global.KubernetesClusterTag\n\t} else {\n\t\t// TODO: Clean up double-API query\n\t\tinfo, err := selfAWSInstance.describeInstance()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, tag := range info.Tags {\n\t\t\tif orEmpty(tag.Key) == TagNameKubernetesCluster {\n\t\t\t\tfilterTags[TagNameKubernetesCluster] = orEmpty(tag.Value)\n\t\t\t}\n\t\t}\n\t}\n\n\tif filterTags[TagNameKubernetesCluster] == \"\" {\n\t\tglog.Errorf(\"Tag %q not found; Kubernetes may behave unexpectedly.\", TagNameKubernetesCluster)\n\t}\n\n\tawsCloud.filterTags = filterTags\n\tif len(filterTags) > 0 {\n\t\tglog.Infof(\"AWS cloud filtering on tags: %v\", filterTags)\n\t} else {\n\t\tglog.Infof(\"AWS cloud - no tag filtering\")\n\t}\n\n\treturn awsCloud, nil\n}",
"func NewAWS(ctx arn.Ctx, r ...Router) *AWS {\n\troot := append(ChainRouter{STSRouter{}}, r...)\n\tw := &AWS{\n\t\tCtxRouter: CtxRouter{arn.Ctx{}: &root},\n\t\tCtx: ctx,\n\t}\n\tw.Cfg = awsmock.Config(func(q *aws.Request) {\n\t\tw.mu.Lock()\n\t\tdefer w.mu.Unlock()\n\t\tif q := w.newRequest(q); !w.Route(q) {\n\t\t\tpanic(\"mock: \" + q.Name() + \" not handled\")\n\t\t}\n\t})\n\tw.Cfg.Region = ctx.Region\n\tw.Cfg.Credentials = w.UserCreds(\"\", \"alice\")\n\treturn w\n}",
"func BuildAwsCloudProvider(awsManager *AwsManager, resourceLimiter *cloudprovider.ResourceLimiter) (cloudprovider.CloudProvider, error) {\n\taws := &awsCloudProvider{\n\t\tawsManager: awsManager,\n\t\tresourceLimiter: resourceLimiter,\n\t}\n\treturn aws, nil\n}",
"func AWSNS() *Funcs {\n\treturn &Funcs{}\n}",
"func commonIniProvider(providerName string, config *aws.Config, filename, profilename string) *Provider {\n\n\t// Opens an ini file with the filename passed in for shared credentials\n\t// If fails, returns error\n\tini, err := ini.OpenFile(filename)\n\tif err != nil {\n\t\te := awserr.New(\"SharedCredentialsOpenError\", \"Shared Credentials Open Error\", err)\n\t\tlogFromConfigHelper(config, \"<DEBUG>\", \"<IBM IAM PROVIDER BUILD>\", providerName, e)\n\t\treturn &Provider{\n\t\t\tproviderName: SharedConfProviderName,\n\t\t\tErrorStatus: e,\n\t\t}\n\t}\n\n\t// Gets section of the shared credentials ini file\n\t// If fails, returns error\n\tiniProfile, ok := ini.GetSection(profilename)\n\tif !ok {\n\t\te := awserr.New(\"SharedCredentialsProfileNotFound\",\n\t\t\t\"Shared Credentials Section '\"+profilename+\"' not Found in file '\"+filename+\"'\", nil)\n\t\tlogFromConfigHelper(config, \"<DEBUG>\", \"<IBM IAM PROVIDER BUILD>\", providerName, e)\n\t\treturn &Provider{\n\t\t\tproviderName: SharedConfProviderName,\n\t\t\tErrorStatus: e,\n\t\t}\n\t}\n\n\t// Populaute the IBM IAM Credential values\n\tapiKey := iniProfile.String(\"ibm_api_key_id\")\n\tserviceInstanceID := iniProfile.String(\"ibm_service_instance_id\")\n\tauthEndPoint := iniProfile.String(\"ibm_auth_endpoint\")\n\n\treturn NewProvider(providerName, config, apiKey, authEndPoint, serviceInstanceID, nil)\n}",
"func initAWSSvc() *s3.S3 {\n\tsess, err := session.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\tsdkLoadConfig := os.Getenv(\"AWS_SDK_LOAD_CONFIG\")\n\tif sdkLoadConfig != \"true\" {\n\t\tlog.Fatal(`Env var \"AWS_SDK_LOAD_CONFIG\" needs to be true to read credentials.\\n\\n Run \"export AWS_SDK_LOAD_CONFIG=true\" to fix this. Aborting run.`)\n\t}\n\n\treturn s3.New(sess)\n}",
"func AWScreds(akey, skey, region string) {\n\tWriteConfigFiles(\"access_key\",akey,CPath,\"aws\")\n\tWriteConfigFiles(\"secret_key\",skey,CPath,\"aws\")\n\tWriteConfigFiles(\"region\",region,CPath,\"aws\")\n}",
"func ImageCredsWithAWSAuth(lookup func() ImageCreds, logger log.Logger, config AWSRegistryConfig) (func() error, func() ImageCreds) {\n\t// only ever do the preflight check once; all subsequent calls\n\t// will succeed trivially, so the first caller should pay\n\t// attention to the return value.\n\tvar preflightOnce sync.Once\n\t// it's possible to fail the pre-flight check, but still apply the\n\t// constraints given in the config. `okToUseAWS` is true if using\n\t// the AWS API to get credentials is expected to work.\n\tvar okToUseAWS bool\n\n\tpreflight := func() error {\n\t\tvar preflightErr error\n\t\tpreflightOnce.Do(func() {\n\n\t\t\tdefer func() {\n\t\t\t\tlogger.Log(\"info\", \"restricting ECR registry scans\",\n\t\t\t\t\t\"regions\", fmt.Sprintf(\"%v\", config.Regions),\n\t\t\t\t\t\"include-ids\", fmt.Sprintf(\"%v\", config.AccountIDs),\n\t\t\t\t\t\"exclude-ids\", fmt.Sprintf(\"%v\", config.BlockIDs))\n\t\t\t}()\n\n\t\t\tif config.Regions != nil {\n\t\t\t\tokToUseAWS = true\n\t\t\t\tlogger.Log(\"info\", \"using regions from local config\")\n\t\t\t} else {\n\t\t\t\t// This forces the AWS SDK to load config, so we can get\n\t\t\t\t// the default region if it's there.\n\t\t\t\tsess := session.Must(session.NewSessionWithOptions(session.Options{\n\t\t\t\t\tSharedConfigState: session.SharedConfigEnable,\n\t\t\t\t}))\n\t\t\t\t// Always try to connect to the metadata service, so we\n\t\t\t\t// can fail fast if it's not available.\n\t\t\t\tec2 := ec2metadata.New(sess)\n\t\t\t\tmetadataRegion, err := ec2.Region()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpreflightErr = err\n\t\t\t\t\tif config.Regions == nil {\n\t\t\t\t\t\tconfig.Regions = []string{}\n\t\t\t\t\t}\n\t\t\t\t\tlogger.Log(\"error\", \"fetching region for AWS\", \"err\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tokToUseAWS = true\n\n\t\t\t\tclusterRegion := *sess.Config.Region\n\t\t\t\tregionSource := \"local config\"\n\t\t\t\tif clusterRegion == \"\" {\n\t\t\t\t\t// no region set in config; in that case, use what we got from the EC2 metadata service\n\t\t\t\t\tclusterRegion = metadataRegion\n\t\t\t\t\tregionSource = \"EC2 metadata service\"\n\t\t\t\t}\n\t\t\t\tlogger.Log(\"info\", \"detected cluster region\", \"source\", regionSource, \"region\", clusterRegion)\n\t\t\t\tconfig.Regions = []string{clusterRegion}\n\t\t\t}\n\t\t})\n\t\treturn preflightErr\n\t}\n\n\tawsCreds := NoCredentials()\n\n\t// this has the expiry time from the last request made per region. We request new tokens whenever\n\t// - we don't have credentials for the particular registry URL\n\t// - the credentials have expired\n\t// and when we do, we get new tokens for all account IDs in the\n\t// region that we've seen. This means that credentials are\n\t// fetched, and expire, per region.\n\tregionExpire := map[string]time.Time{}\n\t// we can get an error when refreshing the credentials; to avoid\n\t// spamming the log, keep track of failed refreshes.\n\tregionEmbargo := map[string]time.Time{}\n\n\t// should this registry be scanned?\n\tvar shouldScan func(string, string) bool\n\tif config.AccountIDs == nil {\n\t\tshouldScan = func(region, accountID string) bool {\n\t\t\treturn contains(config.Regions, region) && !contains(config.BlockIDs, accountID)\n\t\t}\n\t} else {\n\t\tshouldScan = func(region, accountID string) bool {\n\t\t\treturn contains(config.Regions, region) && contains(config.AccountIDs, accountID) && !contains(config.BlockIDs, accountID)\n\t\t}\n\t}\n\n\tensureCreds := func(domain, region, accountID string, now time.Time) error {\n\t\t// if we had an error getting a token before, don't try again\n\t\t// until the embargo has passed\n\t\tif embargo, ok := regionEmbargo[region]; ok {\n\t\t\tif embargo.After(now) {\n\t\t\t\treturn nil // i.e., fail silently\n\t\t\t}\n\t\t\tdelete(regionEmbargo, region)\n\t\t}\n\n\t\t// if we don't have the entry at all, we need to get a\n\t\t// token. NB we can't check the inverse and return early,\n\t\t// since if the creds do exist, we need to check their expiry.\n\t\tif c := awsCreds.credsFor(domain); c == (creds{}) {\n\t\t\tgoto refresh\n\t\t}\n\n\t\t// otherwise, check if the tokens have expired\n\t\tif expiry, ok := regionExpire[region]; !ok || expiry.Before(now) {\n\t\t\tgoto refresh\n\t\t}\n\n\t\t// the creds exist and are before the use-by; nothing to be done.\n\t\treturn nil\n\n\trefresh:\n\t\t// unconditionally append the sought-after account, and let\n\t\t// the AWS API figure out if it's a duplicate.\n\t\taccountIDs := append(allAccountIDsInRegion(awsCreds.Hosts(), region), accountID)\n\t\tlogger.Log(\"info\", \"attempting to refresh auth tokens\", \"region\", region, \"account-ids\", strings.Join(accountIDs, \", \"))\n\t\tregionCreds, expiry, err := fetchAWSCreds(region, accountIDs)\n\t\tif err != nil {\n\t\t\tregionEmbargo[region] = now.Add(embargoDuration)\n\t\t\tlogger.Log(\"error\", \"fetching credentials for AWS region\", \"region\", region, \"err\", err, \"embargo\", embargoDuration)\n\t\t\treturn err\n\t\t}\n\t\tregionExpire[region] = expiry\n\t\tawsCreds.Merge(regionCreds)\n\t\treturn nil\n\t}\n\n\tlookupECR := func() ImageCreds {\n\t\timageCreds := lookup()\n\n\t\tfor name, creds := range imageCreds {\n\t\t\tdomain := name.Domain\n\t\t\tif !validECRHost(domain) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbits := strings.Split(domain, \".\")\n\t\t\tif bits[1] != \"dkr\" || bits[2] != \"ecr\" {\n\t\t\t\tlogger.Log(\"warning\", \"AWS registry domain not in expected format <account-id>.dkr.ecr.<region>.amazonaws.<extension>\", \"domain\", domain)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taccountID := bits[0]\n\t\t\tregion := bits[3]\n\n\t\t\t// Before deciding whether an image is included, we need to establish the included regions,\n\t\t\t// and whether we can use the AWS API to get credentials. But we don't need to log any problem\n\t\t\t// that arises _unless_ there's an image that ends up being included in the scanning.\n\t\t\tpreflightErr := preflight()\n\n\t\t\tif !shouldScan(region, accountID) {\n\t\t\t\tdelete(imageCreds, name)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif preflightErr != nil {\n\t\t\t\tlogger.Log(\"warning\", \"AWS auth implied by ECR image, but AWS API is not available. You can ignore this if you are providing credentials some other way (e.g., through imagePullSecrets)\", \"image\", name.String(), \"err\", preflightErr)\n\t\t\t}\n\n\t\t\tif okToUseAWS {\n\t\t\t\tif err := ensureCreds(domain, region, accountID, time.Now()); err != nil {\n\t\t\t\t\tlogger.Log(\"warning\", \"unable to ensure credentials for ECR\", \"domain\", domain, \"err\", err)\n\t\t\t\t}\n\t\t\t\tnewCreds := NoCredentials()\n\t\t\t\tnewCreds.Merge(awsCreds)\n\t\t\t\tnewCreds.Merge(creds)\n\t\t\t\timageCreds[name] = newCreds\n\t\t\t}\n\t\t}\n\t\treturn imageCreds\n\t}\n\n\treturn preflight, lookupECR\n}",
"func AWSInit() {\n\tawsRegion = os.Getenv(\"AWS_REGION\")\n\tif awsRegion == \"\" {\n\t\tlog.Debugf(\"AWS_REGION environment variable is not set. Using default region: %s\", DefaultAWSRegion)\n\t\tawsRegion = DefaultAWSRegion\n\t} else {\n\t\tlog.Debugf(\"AWS_REGION set to: %s\", awsRegion)\n\t}\n\n\tkey := fmt.Sprintf(\"%s_AWS_ACCESS_KEY_ID\", ServiceName)\n\tawsAccessKeyID = os.Getenv(key)\n\tif awsAccessKeyID == \"\" {\n\t\tlog.Fatalf(\"Unable to load %s - value not set in environment. Exiting...\", key)\n\t}\n\tlog.Debugf(\"Loaded %s: %s...\", key, awsAccessKeyID[:5])\n\n\tkey = fmt.Sprintf(\"%s_AWS_SECRET_ACCESS_KEY\", ServiceName)\n\tawsSecretAccessKey = os.Getenv(key)\n\tif awsSecretAccessKey == \"\" {\n\t\tlog.Fatalf(\"Unable to load %s - value not set in environment. Exiting...\", key)\n\t}\n\tlog.Debugf(\"Loaded %s: %s...\", key, awsSecretAccessKey[:5])\n\n\tkey = fmt.Sprintf(\"%s_AWS_SESSION_TOKEN\", ServiceName)\n\tawsSessionToken = os.Getenv(key)\n\tif awsSessionToken != \"\" {\n\t\tlog.Debugf(\"Loaded %s: %s...\", key, awsSessionToken[:5])\n\t}\n\n\tif err := startCloudWatchSession(); err != nil {\n\t\tlog.Fatalf(\"Error starting the AWS CloudWatch session - Error: %s\", err.Error())\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ResourceAWS : Define the aws resource function
|
func ResourceAWS(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
ResourceName := vars["ResourceName"]
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(awsResources[ResourceName]); err != nil {
panic(err)
}
}
|
[
"func resourceAwsLambdaFunctionCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).lambdaconn\n\n\tfunctionName := d.Get(\"function_name\").(string)\n\treservedConcurrentExecutions := d.Get(\"reserved_concurrent_executions\").(int)\n\tiamRole := d.Get(\"role\").(string)\n\n\tlog.Printf(\"[DEBUG] Creating Lambda Function %s with role %s\", functionName, iamRole)\n\n\tfilename, hasFilename := d.GetOk(\"filename\")\n\ts3Bucket, bucketOk := d.GetOk(\"s3_bucket\")\n\ts3Key, keyOk := d.GetOk(\"s3_key\")\n\ts3ObjectVersion, versionOk := d.GetOk(\"s3_object_version\")\n\n\tif !hasFilename && !bucketOk && !keyOk && !versionOk {\n\t\treturn errors.New(\"filename or s3_* attributes must be set\")\n\t}\n\n\tvar functionCode *lambda.FunctionCode\n\tif hasFilename {\n\t\t// Grab an exclusive lock so that we're only reading one function into\n\t\t// memory at a time.\n\t\t// See https://github.com/hashicorp/terraform/issues/9364\n\t\tawsMutexKV.Lock(awsMutexLambdaKey)\n\t\tdefer awsMutexKV.Unlock(awsMutexLambdaKey)\n\t\tfile, err := loadFileContent(filename.(string))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to load %q: %s\", filename.(string), err)\n\t\t}\n\t\tfunctionCode = &lambda.FunctionCode{\n\t\t\tZipFile: file,\n\t\t}\n\t} else {\n\t\tif !bucketOk || !keyOk {\n\t\t\treturn errors.New(\"s3_bucket and s3_key must all be set while using S3 code source\")\n\t\t}\n\t\tfunctionCode = &lambda.FunctionCode{\n\t\t\tS3Bucket: aws.String(s3Bucket.(string)),\n\t\t\tS3Key: aws.String(s3Key.(string)),\n\t\t}\n\t\tif versionOk {\n\t\t\tfunctionCode.S3ObjectVersion = aws.String(s3ObjectVersion.(string))\n\t\t}\n\t}\n\n\tparams := &lambda.CreateFunctionInput{\n\t\tCode: functionCode,\n\t\tDescription: aws.String(d.Get(\"description\").(string)),\n\t\tFunctionName: aws.String(functionName),\n\t\tHandler: aws.String(d.Get(\"handler\").(string)),\n\t\tMemorySize: aws.Int64(int64(d.Get(\"memory_size\").(int))),\n\t\tRole: aws.String(iamRole),\n\t\tRuntime: aws.String(d.Get(\"runtime\").(string)),\n\t\tTimeout: aws.Int64(int64(d.Get(\"timeout\").(int))),\n\t\tPublish: aws.Bool(d.Get(\"publish\").(bool)),\n\t}\n\n\tif v, ok := d.GetOk(\"dead_letter_config\"); ok {\n\t\tdlcMaps := v.([]interface{})\n\t\tif len(dlcMaps) == 1 { // Schema guarantees either 0 or 1\n\t\t\t// Prevent panic on nil dead_letter_config. See GH-14961\n\t\t\tif dlcMaps[0] == nil {\n\t\t\t\treturn fmt.Errorf(\"Nil dead_letter_config supplied for function: %s\", functionName)\n\t\t\t}\n\t\t\tdlcMap := dlcMaps[0].(map[string]interface{})\n\t\t\tparams.DeadLetterConfig = &lambda.DeadLetterConfig{\n\t\t\t\tTargetArn: aws.String(dlcMap[\"target_arn\"].(string)),\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"vpc_config\"); ok {\n\n\t\tconfigs := v.([]interface{})\n\t\tconfig, ok := configs[0].(map[string]interface{})\n\n\t\tif !ok {\n\t\t\treturn errors.New(\"vpc_config is <nil>\")\n\t\t}\n\n\t\tif config != nil {\n\t\t\tvar subnetIds []*string\n\t\t\tfor _, id := range config[\"subnet_ids\"].(*schema.Set).List() {\n\t\t\t\tsubnetIds = append(subnetIds, aws.String(id.(string)))\n\t\t\t}\n\n\t\t\tvar securityGroupIds []*string\n\t\t\tfor _, id := range config[\"security_group_ids\"].(*schema.Set).List() {\n\t\t\t\tsecurityGroupIds = append(securityGroupIds, aws.String(id.(string)))\n\t\t\t}\n\n\t\t\tparams.VpcConfig = &lambda.VpcConfig{\n\t\t\t\tSubnetIds: subnetIds,\n\t\t\t\tSecurityGroupIds: securityGroupIds,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"tracing_config\"); ok {\n\t\ttracingConfig := v.([]interface{})\n\t\ttracing := tracingConfig[0].(map[string]interface{})\n\t\tparams.TracingConfig = &lambda.TracingConfig{\n\t\t\tMode: aws.String(tracing[\"mode\"].(string)),\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"environment\"); ok {\n\t\tenvironments := v.([]interface{})\n\t\tenvironment, ok := environments[0].(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn errors.New(\"At least one field is expected inside environment\")\n\t\t}\n\n\t\tif environmentVariables, ok := environment[\"variables\"]; ok {\n\t\t\tvariables := readEnvironmentVariables(environmentVariables.(map[string]interface{}))\n\n\t\t\tparams.Environment = &lambda.Environment{\n\t\t\t\tVariables: aws.StringMap(variables),\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"kms_key_arn\"); ok {\n\t\tparams.KMSKeyArn = aws.String(v.(string))\n\t}\n\n\tif v, exists := d.GetOk(\"tags\"); exists {\n\t\tparams.Tags = tagsFromMapGeneric(v.(map[string]interface{}))\n\t}\n\n\t// IAM profiles can take ~10 seconds to propagate in AWS:\n\t// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console\n\t// Error creating Lambda function: InvalidParameterValueException: The role defined for the task cannot be assumed by Lambda.\n\terr := resource.Retry(10*time.Minute, func() *resource.RetryError {\n\t\t_, err := conn.CreateFunction(params)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[DEBUG] Error creating Lambda Function: %s\", err)\n\n\t\t\tif isAWSErr(err, \"InvalidParameterValueException\", \"The role defined for the function cannot be assumed by Lambda\") {\n\t\t\t\tlog.Printf(\"[DEBUG] Received %s, retrying CreateFunction\", err)\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t\tif isAWSErr(err, \"InvalidParameterValueException\", \"The provided execution role does not have permissions\") {\n\t\t\t\tlog.Printf(\"[DEBUG] Received %s, retrying CreateFunction\", err)\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t\tif isAWSErr(err, \"InvalidParameterValueException\", \"Your request has been throttled by EC2\") {\n\t\t\t\tlog.Printf(\"[DEBUG] Received %s, retrying CreateFunction\", err)\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\n\t\t\treturn resource.NonRetryableError(err)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating Lambda function: %s\", err)\n\t}\n\n\tif reservedConcurrentExecutions > 0 {\n\n\t\tlog.Printf(\"[DEBUG] Setting Concurrency to %d for the Lambda Function %s\", reservedConcurrentExecutions, functionName)\n\n\t\tconcurrencyParams := &lambda.PutFunctionConcurrencyInput{\n\t\t\tFunctionName: aws.String(functionName),\n\t\t\tReservedConcurrentExecutions: aws.Int64(int64(reservedConcurrentExecutions)),\n\t\t}\n\n\t\t_, err := conn.PutFunctionConcurrency(concurrencyParams)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error setting concurrency for Lambda %s: %s\", functionName, err)\n\t\t}\n\t}\n\n\td.SetId(d.Get(\"function_name\").(string))\n\n\treturn resourceAwsLambdaFunctionRead(d, meta)\n}",
"func resourceAwsLambdaFunctionRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).lambdaconn\n\n\tlog.Printf(\"[DEBUG] Fetching Lambda Function: %s\", d.Id())\n\n\tparams := &lambda.GetFunctionInput{\n\t\tFunctionName: aws.String(d.Get(\"function_name\").(string)),\n\t}\n\n\tgetFunctionOutput, err := conn.GetFunction(params)\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == \"ResourceNotFoundException\" && !d.IsNewResource() {\n\t\t\td.SetId(\"\")\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\t// getFunctionOutput.Code.Location is a pre-signed URL pointing at the zip\n\t// file that we uploaded when we created the resource. You can use it to\n\t// download the code from AWS. The other part is\n\t// getFunctionOutput.Configuration which holds metadata.\n\n\tfunction := getFunctionOutput.Configuration\n\t// TODO error checking / handling on the Set() calls.\n\td.Set(\"arn\", function.FunctionArn)\n\td.Set(\"description\", function.Description)\n\td.Set(\"handler\", function.Handler)\n\td.Set(\"memory_size\", function.MemorySize)\n\td.Set(\"last_modified\", function.LastModified)\n\td.Set(\"role\", function.Role)\n\td.Set(\"runtime\", function.Runtime)\n\td.Set(\"timeout\", function.Timeout)\n\td.Set(\"kms_key_arn\", function.KMSKeyArn)\n\td.Set(\"tags\", tagsToMapGeneric(getFunctionOutput.Tags))\n\n\tconfig := flattenLambdaVpcConfigResponse(function.VpcConfig)\n\tlog.Printf(\"[INFO] Setting Lambda %s VPC config %#v from API\", d.Id(), config)\n\tvpcSetErr := d.Set(\"vpc_config\", config)\n\tif vpcSetErr != nil {\n\t\treturn fmt.Errorf(\"Failed setting vpc_config: %s\", vpcSetErr)\n\t}\n\n\td.Set(\"source_code_hash\", function.CodeSha256)\n\n\tif err := d.Set(\"environment\", flattenLambdaEnvironment(function.Environment)); err != nil {\n\t\tlog.Printf(\"[ERR] Error setting environment for Lambda Function (%s): %s\", d.Id(), err)\n\t}\n\n\tif function.DeadLetterConfig != nil && function.DeadLetterConfig.TargetArn != nil {\n\t\td.Set(\"dead_letter_config\", []interface{}{\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"target_arn\": *function.DeadLetterConfig.TargetArn,\n\t\t\t},\n\t\t})\n\t} else {\n\t\td.Set(\"dead_letter_config\", []interface{}{})\n\t}\n\n\tif function.TracingConfig != nil {\n\t\td.Set(\"tracing_config\", []interface{}{\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"mode\": *function.TracingConfig.Mode,\n\t\t\t},\n\t\t})\n\t}\n\n\t// List is sorted from oldest to latest\n\t// so this may get costly over time :'(\n\tvar lastVersion, lastQualifiedArn string\n\terr = listVersionsByFunctionPages(conn, &lambda.ListVersionsByFunctionInput{\n\t\tFunctionName: function.FunctionName,\n\t\tMaxItems: aws.Int64(10000),\n\t}, func(p *lambda.ListVersionsByFunctionOutput, lastPage bool) bool {\n\t\tif lastPage {\n\t\t\tlast := p.Versions[len(p.Versions)-1]\n\t\t\tlastVersion = *last.Version\n\t\t\tlastQualifiedArn = *last.FunctionArn\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.Set(\"version\", lastVersion)\n\td.Set(\"qualified_arn\", lastQualifiedArn)\n\n\td.Set(\"invoke_arn\", buildLambdaInvokeArn(*function.FunctionArn, meta.(*AWSClient).region))\n\n\tif getFunctionOutput.Concurrency != nil {\n\t\td.Set(\"reserved_concurrent_executions\", getFunctionOutput.Concurrency.ReservedConcurrentExecutions)\n\t} else {\n\t\td.Set(\"reserved_concurrent_executions\", nil)\n\t}\n\n\treturn nil\n}",
"func ubuntuAMICustomResource(ctx context.Context,\n\tevent spartaCFResources.CloudFormationLambdaEvent) (map[string]interface{}, error) {\n\tlogger, _ := ctx.Value(sparta.ContextKeyLogger).(*logrus.Logger)\n\tlambdaCtx, _ := awsLambdaCtx.FromContext(ctx)\n\n\topResults := make(map[string]interface{})\n\tvar opErr error\n\tif event.RequestType == \"Create\" {\n\n\t\t// Setup the common filters\n\t\tdescribeImageFilters := []*ec2.Filter{}\n\t\tdescribeImageFilters = append(describeImageFilters, &ec2.Filter{\n\t\t\tName: aws.String(\"name\"),\n\t\t\tValues: []*string{aws.String(\"*hvm-ssd/ubuntu-xenial-16.04-amd64-server*\")},\n\t\t})\n\t\tdescribeImageFilters = append(describeImageFilters, &ec2.Filter{\n\t\t\tName: aws.String(\"root-device-type\"),\n\t\t\tValues: []*string{aws.String(\"ebs\")},\n\t\t})\n\t\tdescribeImageFilters = append(describeImageFilters, &ec2.Filter{\n\t\t\tName: aws.String(\"architecture\"),\n\t\t\tValues: []*string{aws.String(\"x86_64\")},\n\t\t})\n\t\tdescribeImageFilters = append(describeImageFilters, &ec2.Filter{\n\t\t\tName: aws.String(\"virtualization-type\"),\n\t\t\tValues: []*string{aws.String(\"hvm\")},\n\t\t})\n\n\t\t// Get the HVM AMIs\n\t\tparams := &ec2.DescribeImagesInput{\n\t\t\tFilters: describeImageFilters,\n\t\t\tOwners: []*string{aws.String(\"099720109477\")},\n\t\t}\n\t\tlogger, _ := ctx.Value(sparta.ContextKeyLogger).(*logrus.Logger)\n\t\tec2Svc := ec2.New(spartaAWS.NewSession(logger))\n\t\tdescribeImagesOutput, describeImagesOutputErr := ec2Svc.DescribeImages(params)\n\t\tif nil != describeImagesOutputErr {\n\t\t\treturn nil, describeImagesOutputErr\n\t\t}\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"DescribeImagesOutput\": describeImagesOutput,\n\t\t\t\"DescribeImagesOutputErr\": describeImagesOutputErr,\n\t\t}).Info(\"Results\")\n\n\t\tamiID, amiIDErr := mostRecentImageID(describeImagesOutput.Images)\n\t\tif nil != amiIDErr {\n\t\t\treturn nil, amiIDErr\n\t\t}\n\n\t\t// Set the HVM type\n\t\topResults = map[string]interface{}{\n\t\t\t\"HVM\": amiID,\n\t\t}\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"Outputs\": opResults,\n\t\t}).Info(\"CustomResource outputs\")\n\t}\n\n\tcfErr := spartaCFResources.SendCloudFormationResponse(lambdaCtx,\n\t\t&event,\n\t\topResults,\n\t\topErr,\n\t\tlogger)\n\tif opErr == nil {\n\t\topErr = cfErr\n\t}\n\treturn opResults, opErr\n}",
"func resourceAwsLambdaFunctionUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).lambdaconn\n\n\td.Partial(true)\n\n\tarn := d.Get(\"arn\").(string)\n\tif tagErr := setTagsLambda(conn, d, arn); tagErr != nil {\n\t\treturn tagErr\n\t}\n\td.SetPartial(\"tags\")\n\n\tconfigReq := &lambda.UpdateFunctionConfigurationInput{\n\t\tFunctionName: aws.String(d.Id()),\n\t}\n\n\tconfigUpdate := false\n\tif d.HasChange(\"description\") {\n\t\tconfigReq.Description = aws.String(d.Get(\"description\").(string))\n\t\tconfigUpdate = true\n\t}\n\tif d.HasChange(\"handler\") {\n\t\tconfigReq.Handler = aws.String(d.Get(\"handler\").(string))\n\t\tconfigUpdate = true\n\t}\n\tif d.HasChange(\"memory_size\") {\n\t\tconfigReq.MemorySize = aws.Int64(int64(d.Get(\"memory_size\").(int)))\n\t\tconfigUpdate = true\n\t}\n\tif d.HasChange(\"role\") {\n\t\tconfigReq.Role = aws.String(d.Get(\"role\").(string))\n\t\tconfigUpdate = true\n\t}\n\tif d.HasChange(\"timeout\") {\n\t\tconfigReq.Timeout = aws.Int64(int64(d.Get(\"timeout\").(int)))\n\t\tconfigUpdate = true\n\t}\n\tif d.HasChange(\"kms_key_arn\") {\n\t\tconfigReq.KMSKeyArn = aws.String(d.Get(\"kms_key_arn\").(string))\n\t\tconfigUpdate = true\n\t}\n\tif d.HasChange(\"dead_letter_config\") {\n\t\tdlcMaps := d.Get(\"dead_letter_config\").([]interface{})\n\t\tif len(dlcMaps) == 1 { // Schema guarantees either 0 or 1\n\t\t\tdlcMap := dlcMaps[0].(map[string]interface{})\n\t\t\tconfigReq.DeadLetterConfig = &lambda.DeadLetterConfig{\n\t\t\t\tTargetArn: aws.String(dlcMap[\"target_arn\"].(string)),\n\t\t\t}\n\t\t\tconfigUpdate = true\n\t\t}\n\t}\n\tif d.HasChange(\"tracing_config\") {\n\t\ttracingConfig := d.Get(\"tracing_config\").([]interface{})\n\t\tif len(tracingConfig) == 1 { // Schema guarantees either 0 or 1\n\t\t\tconfig := tracingConfig[0].(map[string]interface{})\n\t\t\tconfigReq.TracingConfig = &lambda.TracingConfig{\n\t\t\t\tMode: aws.String(config[\"mode\"].(string)),\n\t\t\t}\n\t\t\tconfigUpdate = true\n\t\t}\n\t}\n\tif d.HasChange(\"vpc_config\") {\n\t\tvpcConfigRaw := d.Get(\"vpc_config\").([]interface{})\n\t\tvpcConfig, ok := vpcConfigRaw[0].(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn errors.New(\"vpc_config is <nil>\")\n\t\t}\n\n\t\tif vpcConfig != nil {\n\t\t\tvar subnetIds []*string\n\t\t\tfor _, id := range vpcConfig[\"subnet_ids\"].(*schema.Set).List() {\n\t\t\t\tsubnetIds = append(subnetIds, aws.String(id.(string)))\n\t\t\t}\n\n\t\t\tvar securityGroupIds []*string\n\t\t\tfor _, id := range vpcConfig[\"security_group_ids\"].(*schema.Set).List() {\n\t\t\t\tsecurityGroupIds = append(securityGroupIds, aws.String(id.(string)))\n\t\t\t}\n\n\t\t\tconfigReq.VpcConfig = &lambda.VpcConfig{\n\t\t\t\tSubnetIds: subnetIds,\n\t\t\t\tSecurityGroupIds: securityGroupIds,\n\t\t\t}\n\t\t\tconfigUpdate = true\n\t\t}\n\t}\n\n\tif d.HasChange(\"runtime\") {\n\t\tconfigReq.Runtime = aws.String(d.Get(\"runtime\").(string))\n\t\tconfigUpdate = true\n\t}\n\tif d.HasChange(\"environment\") {\n\t\tif v, ok := d.GetOk(\"environment\"); ok {\n\t\t\tenvironments := v.([]interface{})\n\t\t\tenvironment, ok := environments[0].(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn errors.New(\"At least one field is expected inside environment\")\n\t\t\t}\n\n\t\t\tif environmentVariables, ok := environment[\"variables\"]; ok {\n\t\t\t\tvariables := readEnvironmentVariables(environmentVariables.(map[string]interface{}))\n\n\t\t\t\tconfigReq.Environment = &lambda.Environment{\n\t\t\t\t\tVariables: aws.StringMap(variables),\n\t\t\t\t}\n\t\t\t\tconfigUpdate = true\n\t\t\t}\n\t\t} else {\n\t\t\tconfigReq.Environment = &lambda.Environment{\n\t\t\t\tVariables: aws.StringMap(map[string]string{}),\n\t\t\t}\n\t\t\tconfigUpdate = true\n\t\t}\n\t}\n\n\tif configUpdate {\n\t\tlog.Printf(\"[DEBUG] Send Update Lambda Function Configuration request: %#v\", configReq)\n\n\t\terr := resource.Retry(10*time.Minute, func() *resource.RetryError {\n\t\t\t_, err := conn.UpdateFunctionConfiguration(configReq)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[DEBUG] Received error modifying Lambda Function Configuration %s: %s\", d.Id(), err)\n\n\t\t\t\tif isAWSErr(err, \"InvalidParameterValueException\", \"Your request has been throttled by EC2, please make sure you have enough API rate limit.\") {\n\t\t\t\t\tlog.Printf(\"[DEBUG] Received %s, retrying UpdateFunctionConfiguration\", err)\n\t\t\t\t\treturn resource.RetryableError(err)\n\t\t\t\t}\n\t\t\t\treturn resource.NonRetryableError(err)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error modifying Lambda Function Configuration %s: %s\", d.Id(), err)\n\t\t}\n\n\t\td.SetPartial(\"description\")\n\t\td.SetPartial(\"handler\")\n\t\td.SetPartial(\"memory_size\")\n\t\td.SetPartial(\"role\")\n\t\td.SetPartial(\"timeout\")\n\t}\n\n\tif d.HasChange(\"filename\") || d.HasChange(\"source_code_hash\") || d.HasChange(\"s3_bucket\") || d.HasChange(\"s3_key\") || d.HasChange(\"s3_object_version\") {\n\t\tcodeReq := &lambda.UpdateFunctionCodeInput{\n\t\t\tFunctionName: aws.String(d.Id()),\n\t\t\tPublish: aws.Bool(d.Get(\"publish\").(bool)),\n\t\t}\n\n\t\tif v, ok := d.GetOk(\"filename\"); ok {\n\t\t\t// Grab an exclusive lock so that we're only reading one function into\n\t\t\t// memory at a time.\n\t\t\t// See https://github.com/hashicorp/terraform/issues/9364\n\t\t\tawsMutexKV.Lock(awsMutexLambdaKey)\n\t\t\tdefer awsMutexKV.Unlock(awsMutexLambdaKey)\n\t\t\tfile, err := loadFileContent(v.(string))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Unable to load %q: %s\", v.(string), err)\n\t\t\t}\n\t\t\tcodeReq.ZipFile = file\n\t\t} else {\n\t\t\ts3Bucket, _ := d.GetOk(\"s3_bucket\")\n\t\t\ts3Key, _ := d.GetOk(\"s3_key\")\n\t\t\ts3ObjectVersion, versionOk := d.GetOk(\"s3_object_version\")\n\n\t\t\tcodeReq.S3Bucket = aws.String(s3Bucket.(string))\n\t\t\tcodeReq.S3Key = aws.String(s3Key.(string))\n\t\t\tif versionOk {\n\t\t\t\tcodeReq.S3ObjectVersion = aws.String(s3ObjectVersion.(string))\n\t\t\t}\n\t\t}\n\n\t\tlog.Printf(\"[DEBUG] Send Update Lambda Function Code request: %#v\", codeReq)\n\n\t\t_, err := conn.UpdateFunctionCode(codeReq)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error modifying Lambda Function Code %s: %s\", d.Id(), err)\n\t\t}\n\n\t\td.SetPartial(\"filename\")\n\t\td.SetPartial(\"source_code_hash\")\n\t\td.SetPartial(\"s3_bucket\")\n\t\td.SetPartial(\"s3_key\")\n\t\td.SetPartial(\"s3_object_version\")\n\t}\n\n\tif d.HasChange(\"reserved_concurrent_executions\") {\n\t\tnc := d.Get(\"reserved_concurrent_executions\")\n\n\t\tif nc.(int) > 0 {\n\t\t\tlog.Printf(\"[DEBUG] Updating Concurrency to %d for the Lambda Function %s\", nc.(int), d.Id())\n\n\t\t\tconcurrencyParams := &lambda.PutFunctionConcurrencyInput{\n\t\t\t\tFunctionName: aws.String(d.Id()),\n\t\t\t\tReservedConcurrentExecutions: aws.Int64(int64(d.Get(\"reserved_concurrent_executions\").(int))),\n\t\t\t}\n\n\t\t\t_, err := conn.PutFunctionConcurrency(concurrencyParams)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error setting concurrency for Lambda %s: %s\", d.Id(), err)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Printf(\"[DEBUG] Removing Concurrency for the Lambda Function %s\", d.Id())\n\n\t\t\tdeleteConcurrencyParams := &lambda.DeleteFunctionConcurrencyInput{\n\t\t\t\tFunctionName: aws.String(d.Id()),\n\t\t\t}\n\t\t\t_, err := conn.DeleteFunctionConcurrency(deleteConcurrencyParams)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error setting concurrency for Lambda %s: %s\", d.Id(), err)\n\t\t\t}\n\t\t}\n\t}\n\n\td.Partial(false)\n\n\treturn resourceAwsLambdaFunctionRead(d, meta)\n}",
"func lambdaDecorator(customResourceAMILookupName string) sparta.TemplateDecorator {\n\n\treturn func(serviceName string,\n\t\tlambdaResourceName string,\n\t\tlambdaResource gocf.LambdaFunction,\n\t\tresourceMetadata map[string]interface{},\n\t\tS3Bucket string,\n\t\tS3Key string,\n\t\tbuildID string,\n\t\ttemplate *gocf.Template,\n\t\tcontext map[string]interface{},\n\t\tlogger *logrus.Logger) error {\n\n\t\t// Create the launch configuration with Metadata to download the ZIP file, unzip it & launch the\n\t\t// golang binary...\n\t\tec2SecurityGroupResourceName := sparta.CloudFormationResourceName(\"SpartaOmegaSecurityGroup\",\n\t\t\t\"SpartaOmegaSecurityGroup\")\n\t\tasgLaunchConfigurationName := sparta.CloudFormationResourceName(\"SpartaOmegaASGLaunchConfig\",\n\t\t\t\"SpartaOmegaASGLaunchConfig\")\n\t\tasgResourceName := sparta.CloudFormationResourceName(\"SpartaOmegaASG\",\n\t\t\t\"SpartaOmegaASG\")\n\t\tec2InstanceRoleName := sparta.CloudFormationResourceName(\"SpartaOmegaEC2InstanceRole\",\n\t\t\t\"SpartaOmegaEC2InstanceRole\")\n\t\tec2InstanceProfileName := sparta.CloudFormationResourceName(\"SpartaOmegaEC2InstanceProfile\",\n\t\t\t\"SpartaOmegaEC2InstanceProfile\")\n\n\t\t//////////////////////////////////////////////////////////////////////////////\n\t\t// 1 - Create the security group for the SpartaOmega EC2 instance\n\t\tec2SecurityGroup := &gocf.EC2SecurityGroup{\n\t\t\tGroupDescription: gocf.String(\"SpartaOmega Security Group\"),\n\t\t\tSecurityGroupIngress: &gocf.EC2SecurityGroupIngressPropertyList{\n\t\t\t\tgocf.EC2SecurityGroupIngressProperty{\n\t\t\t\t\tCidrIP: gocf.String(\"0.0.0.0/0\"),\n\t\t\t\t\tIPProtocol: gocf.String(\"tcp\"),\n\t\t\t\t\tFromPort: gocf.Integer(HTTPServerPort),\n\t\t\t\t\tToPort: gocf.Integer(HTTPServerPort),\n\t\t\t\t},\n\t\t\t\tgocf.EC2SecurityGroupIngressProperty{\n\t\t\t\t\tCidrIP: gocf.String(\"0.0.0.0/0\"),\n\t\t\t\t\tIPProtocol: gocf.String(\"tcp\"),\n\t\t\t\t\tFromPort: gocf.Integer(22),\n\t\t\t\t\tToPort: gocf.Integer(22),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\ttemplate.AddResource(ec2SecurityGroupResourceName, ec2SecurityGroup)\n\t\t//////////////////////////////////////////////////////////////////////////////\n\t\t// 2 - Create the ASG and associate the userdata with the EC2 init\n\t\t// EC2 Instance Role...\n\t\tstatements := sparta.CommonIAMStatements.Core\n\n\t\t// Add the statement that allows us to fetch the S3 object with this compiled\n\t\t// binary\n\t\tstatements = append(statements, spartaIAM.PolicyStatement{\n\t\t\tEffect: \"Allow\",\n\t\t\tAction: []string{\"s3:GetObject\"},\n\t\t\tResource: gocf.String(fmt.Sprintf(\"arn:aws:s3:::%s/%s\", S3Bucket, S3Key)),\n\t\t})\n\t\tiamPolicyList := gocf.IAMRolePolicyList{}\n\t\tiamPolicyList = append(iamPolicyList,\n\t\t\tgocf.IAMRolePolicy{\n\t\t\t\tPolicyDocument: sparta.ArbitraryJSONObject{\n\t\t\t\t\t\"Version\": \"2012-10-17\",\n\t\t\t\t\t\"Statement\": statements,\n\t\t\t\t},\n\t\t\t\tPolicyName: gocf.String(\"EC2Policy\"),\n\t\t\t},\n\t\t)\n\t\tec2InstanceRole := &gocf.IAMRole{\n\t\t\tAssumeRolePolicyDocument: sparta.AssumePolicyDocument,\n\t\t\tPolicies: &iamPolicyList,\n\t\t}\n\t\ttemplate.AddResource(ec2InstanceRoleName, ec2InstanceRole)\n\n\t\t// Create the instance profile\n\t\tec2InstanceProfile := &gocf.IAMInstanceProfile{\n\t\t\tPath: gocf.String(\"/\"),\n\t\t\tRoles: gocf.StringList(gocf.Ref(ec2InstanceRoleName)),\n\t\t}\n\t\ttemplate.AddResource(ec2InstanceProfileName, ec2InstanceProfile)\n\n\t\t//Now setup the properties map, expand the userdata, and attach it...\n\t\tuserDataProps := map[string]interface{}{\n\t\t\t\"S3Bucket\": S3Bucket,\n\t\t\t\"S3Key\": S3Key,\n\t\t\t\"SpartaBinaryName\": sparta.SpartaBinaryName,\n\t\t\t\"ServiceName\": serviceName,\n\t\t}\n\n\t\tuserDataTemplateInput, userDataTemplateInputErr := resources.FSString(false,\n\t\t\t\"/resources/source/userdata.sh\")\n\t\tif nil != userDataTemplateInputErr {\n\t\t\treturn userDataTemplateInputErr\n\t\t}\n\t\tuserDataExpression, userDataExpressionErr := spartaCF.ConvertToTemplateExpression(strings.NewReader(userDataTemplateInput), userDataProps)\n\t\tif nil != userDataExpressionErr {\n\t\t\treturn userDataExpressionErr\n\t\t}\n\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"Parameters\": userDataProps,\n\t\t\t\"Expanded\": userDataExpression,\n\t\t}).Debug(\"Expanded userdata\")\n\n\t\tasgLaunchConfigurationResource := &gocf.AutoScalingLaunchConfiguration{\n\t\t\tImageID: gocf.GetAtt(customResourceAMILookupName, \"HVM\"),\n\t\t\tInstanceType: gocf.String(\"t2.micro\"),\n\t\t\tKeyName: gocf.String(SSHKeyName),\n\t\t\tIamInstanceProfile: gocf.Ref(ec2InstanceProfileName).String(),\n\t\t\tUserData: gocf.Base64(userDataExpression),\n\t\t\tSecurityGroups: gocf.StringList(gocf.GetAtt(ec2SecurityGroupResourceName, \"GroupId\")),\n\t\t}\n\n\t\tlaunchConfigResource := template.AddResource(asgLaunchConfigurationName,\n\t\t\tasgLaunchConfigurationResource)\n\t\tlaunchConfigResource.DependsOn = append(launchConfigResource.DependsOn,\n\t\t\tcustomResourceAMILookupName)\n\n\t\t// Create the ASG\n\t\tasgResource := &gocf.AutoScalingAutoScalingGroup{\n\t\t\t// Empty Region is equivalent to all region AZs\n\t\t\t// Ref: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getavailabilityzones.html\n\t\t\tAvailabilityZones: gocf.GetAZs(gocf.String(\"\")),\n\t\t\tLaunchConfigurationName: gocf.Ref(asgLaunchConfigurationName).String(),\n\t\t\tMaxSize: gocf.String(\"1\"),\n\t\t\tMinSize: gocf.String(\"1\"),\n\t\t}\n\t\ttemplate.AddResource(asgResourceName, asgResource)\n\t\treturn nil\n\t}\n}",
"func ResourceServiceEndpointAws() *schema.Resource {\n\tr := genBaseServiceEndpointResource(flattenServiceEndpointAws, expandServiceEndpointAws)\n\tr.Schema[\"access_key_id\"] = &schema.Schema{\n\t\tType: schema.TypeString,\n\t\tRequired: true,\n\t\tDefaultFunc: schema.EnvDefaultFunc(\"AZDO_AWS_SERVICE_CONNECTION_ACCESS_KEY_ID\", nil),\n\t\tDescription: \"The AWS access key ID for signing programmatic requests.\",\n\t}\n\tr.Schema[\"secret_access_key\"] = &schema.Schema{\n\t\tType: schema.TypeString,\n\t\tRequired: true,\n\t\tDefaultFunc: schema.EnvDefaultFunc(\"AZDO_AWS_SERVICE_CONNECTION_SECRET_ACCESS_KEY\", nil),\n\t\tDescription: \"The AWS secret access key for signing programmatic requests.\",\n\t\tSensitive: true,\n\t\tDiffSuppressFunc: tfhelper.DiffFuncSuppressSecretChanged,\n\t}\n\tsaSecretHashKey, saSecretHashSchema := tfhelper.GenerateSecreteMemoSchema(\"secret_access_key\")\n\tr.Schema[saSecretHashKey] = saSecretHashSchema\n\tr.Schema[\"session_token\"] = &schema.Schema{\n\t\tType: schema.TypeString,\n\t\tOptional: true,\n\t\tDefaultFunc: schema.EnvDefaultFunc(\"AZDO_AWS_SERVICE_CONNECTION_SESSION_TOKEN\", nil),\n\t\tDescription: \"The AWS session token for signing programmatic requests.\",\n\t\tSensitive: true,\n\t\tDiffSuppressFunc: tfhelper.DiffFuncSuppressSecretChanged,\n\t}\n\tstSecretHashKey, stSecretHashSchema := tfhelper.GenerateSecreteMemoSchema(\"session_token\")\n\tr.Schema[stSecretHashKey] = stSecretHashSchema\n\tr.Schema[\"role_to_assume\"] = &schema.Schema{\n\t\tType: schema.TypeString,\n\t\tOptional: true,\n\t\tDefaultFunc: schema.EnvDefaultFunc(\"AZDO_AWS_SERVICE_CONNECTION_RTA\", nil),\n\t\tDescription: \"The Amazon Resource Name (ARN) of the role to assume.\",\n\t}\n\tr.Schema[\"role_session_name\"] = &schema.Schema{\n\t\tType: schema.TypeString,\n\t\tOptional: true,\n\t\tDefaultFunc: schema.EnvDefaultFunc(\"AZDO_AWS_SERVICE_CONNECTION_RSN\", nil),\n\t\tDescription: \"Optional identifier for the assumed role session.\",\n\t}\n\tr.Schema[\"external_id\"] = &schema.Schema{\n\t\tType: schema.TypeString,\n\t\tOptional: true,\n\t\tDefaultFunc: schema.EnvDefaultFunc(\"AZDO_AWS_SERVICE_CONNECTION_EXTERNAL_ID\", nil),\n\t\tDescription: \"A unique identifier that is used by third parties when assuming roles in their customers' accounts, aka cross-account role access.\",\n\t}\n\treturn r\n}",
"func TagResource(awsSession *session.Session, resource string, nametag string, timestamp string) (err error) {\n\tclient := ec2.New(awsSession)\n\n\t// set up the params for tagging\n\tparams := &ec2.CreateTagsInput{\n\t\tResources: []*string{\n\t\t\taws.String(resource),\n\t\t},\n\t\tTags: []*ec2.Tag{\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Name\"),\n\t\t\t\tValue: aws.String(nametag),\n\t\t\t},\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Date\"),\n\t\t\t\tValue: aws.String(timestamp),\n\t\t\t},\n\t\t},\n\t}\n\n\t// actually call AWS with the command to tag. Return value is an empty {} on success, so all we care about is the error.\n\t_, err = client.CreateTags(params)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tdefault:\n\t\t\t\terr = errors.Wrapf(aerr, \"failed to create tags\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.Wrapf(aerr, \"failed to create tags\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn err\n}",
"func AWSScale() {\n\tSetClusterName()\n\t// Scale the AWS infrastructure\n\tfmt.Printf(\"\\t\\t===============Starting AWS Scaling====================\\n\\n\")\n\tsshUser, osLabel := distSelect()\n\tprepareConfigFiles(osLabel)\n\tprovisioner.ExecuteTerraform(\"apply\", \"./inventory/\"+common.Name+\"/provisioner/\")\n\tmvHost := exec.Command(\"mv\", \"./inventory/hosts\", \"./inventory/\"+common.Name+\"/provisioner/hosts\")\n\tmvHost.Run()\n\tmvHost.Wait()\n\t// waiting for Infrastructure\n\ttime.Sleep(30)\n\t// Scale the Kubernetes cluster\n\tfmt.Printf(\"\\n\\n\\t\\t===============Starting Kubernetes Scaling====================\\n\\n\")\n\t_, err := os.Stat(\"./inventory/\" + common.Name + \"/provisioner/hosts\")\n\tcommon.ErrorCheck(\"No host file found.\", err)\n\tcpHost := exec.Command(\"cp\", \"./inventory/\"+common.Name+\"/provisioner/hosts\", \"./inventory/\"+common.Name+\"/installer/hosts\")\n\tcpHost.Run()\n\tcpHost.Wait()\n\tinstaller.RunPlaybook(\"./inventory/\"+common.Name+\"/installer/\", \"scale.yml\", sshUser, osLabel)\n\n\treturn\n}",
"func CreateStackResources(stackID string, subscription dynamodb.APISubscription) error {\n\n\t// Create a new CloudFormation template\n\ttemplate := cloudformation.NewTemplate()\n\n\t//Generate GUID\n\tid := stackID\n\n\ttags := []tags.Tag{\n\t\ttags.Tag{\n\t\t\tKey: \"Product\",\n\t\t\tValue: \"MaxEdge\",\n\t\t},\n\t\t// tags.Tag{\n\t\t// \tKey: \"Subscription_ID\",\n\t\t// \tValue: subscription.Name,\n\t\t// },\n\t}\n\n\t// AWS ECS Prpoperties\n\tvarRequiresCompatibilities := []string{\"FARGATE\"}\n\n\t// Lambda Environment Variables //\n\n\t// AWS Account ID\n\tvar varAwsAccountID = os.Getenv(\"AWS_ACCOUNT_ID\")\n\n\t// Task Definition\n\tvar varExecutionRoleArn = os.Getenv(\"EXECUTION_ROLE\")\n\tvar varTaskRoleArn = os.Getenv(\"TASK_ROLE\")\n\tvar varEcsTaskDefinitionRef = os.Getenv(\"CLOUDFORMATION_TASK_DEFINITION_REF\")\n\n\t// Container Definition\n\tvar varImage = os.Getenv(\"CONTAINER_IMAGE\")\n\n\t//Network Definition\n\tvar varSecurityGroup = os.Getenv(\"SECURITY_GROUP\")\n\tvar varSubnet1 = os.Getenv(\"SUBNET_1\")\n\tvar varSubnet2 = os.Getenv(\"SUBNET_2\")\n\tvar varSubnet3 = os.Getenv(\"SUBNET_3\")\n\n\t//ECS Service\n\tvar varClusterName = os.Getenv(\"CLUSTER_NAME\")\n\tvar varEcsRef = os.Getenv(\"CLOUDFORMATION_ECS_SERVICE_REF\")\n\n\t//Secret\n\tvar varSecretRef = os.Getenv(\"CLOUDFORMATION_SECRET_REF\")\n\n\t// Create IAM User\n\ttemplate.Resources[\"IAMUSER\"] = &iam.User{\n\t\tUserName: string(id),\n\t\tTags: tags,\n\t}\n\n\t// Assigning the subscribers ID to a string so it can be added to the policy\n\tbucket := fmt.Sprintf(\"\\\"arn:aws:s3:::maxedgecloudtocloudpoc-sandbox/%s/*\\\"\", id)\n\tvar roleName string = \"ROLE_\" + id\n\tvar policyName string = \"Policy\" + id\n\n\t// S3 GetObject policy for the created IAM user for a subscription\n\t// User will assume the role\n\t// Action is to Assume the sts role\n\ttemplate.Resources[\"IAMPolicy\"] = &iam.Policy{\n\t\tPolicyName: policyName,\n\t\tPolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"sts:AssumeRole\\\",\\\"Resource\\\":\\\"arn:aws:iam::\" + varAwsAccountID + \":role/\" + roleName + \"\\\"}]}\"),\n\t\tUsers: []string{id},\n\t\tAWSCloudFormationDependsOn: []string{\"IAMUSER\"},\n\t}\n\n\tp := iam.Role_Policy{\n\t\tPolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"s3:GetObject\\\",\\\"Resource\\\":\" + bucket + \"}]}\"),\n\t\tPolicyName: id,\n\t}\n\n\t// Assume Role or Trust Policy\n\ttemplate.Resources[\"IAMROLE\"] = &iam.Role{\n\t\tAssumeRolePolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Principal\\\":{\\\"AWS\\\": \\\"arn:aws:iam::\" + varAwsAccountID + \":user/\" + id + \"\\\"},\\\"Action\\\":[\\\"sts:AssumeRole\\\"]}]}\"),\n\t\tRoleName: roleName,\n\t\tPolicies: []iam.Role_Policy{p},\n\t\tAWSCloudFormationDependsOn: []string{\"IAMUSER\"},\n\t\tTags: tags,\n\t}\n\n\t// Task Definition Secret - sets the value for the container based on what was\n\t// created in the template.\n\tTaskDefSecret := []ecs.TaskDefinition_Secret{}\n\tvarTaskDefSecret := ecs.TaskDefinition_Secret{\n\t\t//Referance to the ARNs created when the secret is created\n\t\tName: cloudformation.Ref(varSecretRef),\n\t\tValueFrom: cloudformation.Ref(varSecretRef),\n\t}\n\tTaskDefSecret = append(TaskDefSecret, varTaskDefSecret)\n\n\t// TargetName come from the DynamoDB table and stores the cloud platform\n\t// endpoint for the data destination\n\tgroup := \"/MaxEdge/CloudToCloud/\" + subscription.Target\n\n\tcwLog := &ecs.TaskDefinition_LogConfiguration{\n\t\tLogDriver: \"awslogs\",\n\t\tOptions: map[string]string{\"awslogs-create-group\": \"true\", \"awslogs-group\": group, \"awslogs-region\": \"us-east-1\", \"awslogs-stream-prefix\": id},\n\t}\n\n\t//Task Definition Container Definition - Setting properties\n\tTaskDefConDef := []ecs.TaskDefinition_ContainerDefinition{}\n\tvarTaskDef := ecs.TaskDefinition_ContainerDefinition{\n\t\tImage: varImage,\n\t\tName: id,\n\t\tSecrets: TaskDefSecret,\n\t\tLogConfiguration: cwLog,\n\t}\n\tTaskDefConDef = append(TaskDefConDef, varTaskDef)\n\n\t// Create an Amazon ECS Task Definition - Setting properties\n\ttemplate.Resources[varEcsTaskDefinitionRef] = &ecs.TaskDefinition{\n\t\tExecutionRoleArn: varExecutionRoleArn,\n\t\tTaskRoleArn: varTaskRoleArn,\n\t\tMemory: \"1024\",\n\t\tNetworkMode: \"awsvpc\",\n\t\tRequiresCompatibilities: varRequiresCompatibilities,\n\t\tCpu: \"512\",\n\t\tContainerDefinitions: TaskDefConDef,\n\t\tTags: tags,\n\t}\n\n\t// ECS Service Network configuration\n\tsnc := &ecs.Service_NetworkConfiguration{\n\t\tAwsvpcConfiguration: &ecs.Service_AwsVpcConfiguration{\n\n\t\t\t// Required to access ECR\n\t\t\tAssignPublicIp: \"ENABLED\",\n\t\t\t// The Security Group needs to allow traffic via port :443\n\t\t\tSecurityGroups: []string{varSecurityGroup},\n\t\t\tSubnets: []string{varSubnet1, varSubnet2, varSubnet3},\n\t\t},\n\t}\n\n\t// Create Amazon ECS Service\n\ttemplate.Resources[varEcsRef] = &ecs.Service{\n\t\tLaunchType: \"FARGATE\",\n\t\tCluster: varClusterName,\n\t\tTaskDefinition: cloudformation.Ref(varEcsTaskDefinitionRef),\n\t\tServiceName: id,\n\t\tDesiredCount: 1,\n\t\tNetworkConfiguration: snc,\n\t\tSchedulingStrategy: \"REPLICA\",\n\t\tTags: tags,\n\t\tPropagateTags: \"TASK_DEFINITION\",\n\t}\n\n\t// Create an Amazon Secret\n\ttemplate.Resources[varSecretRef] = &secretsmanager.Secret{\n\t\tName: id,\n\t\tDescription: \"Metadata for companies\",\n\t\tTags: tags,\n\t}\n\n\t// Get JSON form of AWS CloudFormation template\n\tj, err := template.JSON()\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to generate JSON: %s\\n\", err)\n\t\treturn err\n\t}\n\tfmt.Printf(\"Template creation for %s Done.\\n\", id)\n\tfmt.Println(\"=====\")\n\tfmt.Println(\"Generated template:\")\n\tfmt.Printf(\"%s\\n\", string(j))\n\tfmt.Println(\"=====\")\n\n\t// Initialize a session that the SDK uses to load\n\t// credentials from the shared credentials file ~/.aws/credentials\n\t// and configuration from the shared configuration file ~/.aws/config.\n\t// https://docs.aws.amazon.com/sdk-for-go/api/aws/session/\n\tsess := session.Must(session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t}))\n\n\t// Create the stack\n\terr = createStackFromBody(sess, j, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func resourceVolterraAwsTgwSite() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceVolterraAwsTgwSiteCreate,\n\t\tRead: resourceVolterraAwsTgwSiteRead,\n\t\tUpdate: resourceVolterraAwsTgwSiteUpdate,\n\t\tDelete: resourceVolterraAwsTgwSiteDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\"annotations\": {\n\t\t\t\tType: schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"description\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"disable\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"labels\": {\n\t\t\t\tType: schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"namespace\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"aws_parameters\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"aws_certified_hw\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"aws_region\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"az_nodes\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"aws_az_name\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"inside_subnet\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"existing_subnet_id\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"subnet_param\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv4\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv6\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"reserved_inside_subnet\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"disk_size\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"outside_subnet\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"existing_subnet_id\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"subnet_param\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv4\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv6\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"workload_subnet\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"existing_subnet_id\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"subnet_param\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv4\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv6\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\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\n\t\t\t\t\t\t\"assisted\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"aws_cred\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\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\n\t\t\t\t\t\t\"disk_size\": {\n\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"instance_type\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"disable_internet_vip\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"enable_internet_vip\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"new_vpc\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"allocate_ipv6\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"autogenerate\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"name_tag\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"primary_ipv4\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\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\n\t\t\t\t\t\t\"vpc_id\": {\n\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"ssh_key\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"existing_tgw\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"tgw_asn\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"tgw_id\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"volterra_site_asn\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\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\n\t\t\t\t\t\t\"new_tgw\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"system_generated\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"user_assigned\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"tgw_asn\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"volterra_site_asn\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\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\n\t\t\t\t\t\t\"no_worker_nodes\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"nodes_per_az\": {\n\n\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"total_nodes\": {\n\n\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"block_all_services\": {\n\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"blocked_services\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"blocked_sevice\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"dns\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"ssh\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"web_user_interface\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"network_type\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\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\n\t\t\t\"default_blocked_services\": {\n\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"coordinates\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"latitude\": {\n\t\t\t\t\t\t\tType: schema.TypeFloat,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"longitude\": {\n\t\t\t\t\t\t\tType: schema.TypeFloat,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"direct_connect_disabled\": {\n\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"direct_connect_enabled\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"auto_asn\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"custom_asn\": {\n\n\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"cloud_aggregated_prefix\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"dc_connect_aggregated_prefix\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"hosted_vifs\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"site_registration_over_direct_connect\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"cloudlink_network_name\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"site_registration_over_internet\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"vif_list\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"vif_id\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"other_region\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"same_as_site_region\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"vifs\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"manual_gw\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"standard_vifs\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"log_receiver\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"logs_streaming_disabled\": {\n\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"offline_survivability_mode\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"enable_offline_survivability_mode\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_offline_survivability_mode\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"os\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"default_os_version\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"operating_system_version\": {\n\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"performance_enhancement_mode\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"perf_mode_l3_enhanced\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"jumbo\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"no_jumbo\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\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\n\t\t\t\t\t\t\"perf_mode_l7_enhanced\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"sw\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"default_sw_version\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"volterra_software_version\": {\n\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"tags\": {\n\t\t\t\tType: schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"tgw_security\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"active_east_west_service_policies\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"service_policies\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\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\n\t\t\t\t\t\t\"east_west_service_policy_allow_all\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_east_west_policy\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"active_forward_proxy_policies\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"forward_proxy_policies\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\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\n\t\t\t\t\t\t\"forward_proxy_allow_all\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_forward_proxy\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"active_enhanced_firewall_policies\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"enhanced_firewall_policies\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\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\n\t\t\t\t\t\t\"active_network_policies\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"network_policies\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\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\n\t\t\t\t\t\t\"no_network_policy\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"vn_config\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"allowed_vip_port\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"custom_ports\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"port_ranges\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"disable_allowed_vip_port\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"use_http_https_port\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"use_http_port\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"use_https_port\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\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\n\t\t\t\t\t\t\"allowed_vip_port_sli\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"custom_ports\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"port_ranges\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"disable_allowed_vip_port\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"use_http_https_port\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"use_http_port\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"use_https_port\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\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\n\t\t\t\t\t\t\"dc_cluster_group_inside_vn\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\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\n\t\t\t\t\t\t\"dc_cluster_group_outside_vn\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\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\n\t\t\t\t\t\t\"no_dc_cluster_group\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"global_network_list\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"global_network_connections\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"sli_to_global_dr\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"global_vn\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"kind\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"slo_to_global_dr\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"global_vn\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"kind\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"disable_forward_proxy\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"enable_forward_proxy\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"connection_timeout\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"max_connect_attempts\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"no_interception\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"tls_intercept\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"enable_for_all_domains\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"policy\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"interception_rules\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"domain_match\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"exact_value\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"regex_value\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"suffix_value\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"disable_interception\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"enable_interception\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"custom_certificate\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"certificate_url\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"description\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"custom_hash_algorithms\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"hash_algorithms\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"disable_ocsp_stapling\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"use_system_defaults\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"private_key\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"blindfold_secret_info_internal\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"decryption_provider\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"location\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"store_provider\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"secret_encoding_type\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"blindfold_secret_info\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"decryption_provider\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"location\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"store_provider\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"clear_secret_info\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"provider\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"url\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"vault_secret_info\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"key\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"location\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"provider\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"secret_encoding\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"version\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"wingman_secret_info\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"volterra_certificate\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"trusted_ca_url\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"volterra_trusted_ca\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"white_listed_ports\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"white_listed_prefixes\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\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\n\t\t\t\t\t\t\"no_global_network\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"inside_static_routes\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"static_route_list\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"custom_static_route\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"attrs\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"labels\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeMap,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"nexthop\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"interface\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"kind\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"nexthop_address\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv4\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"addr\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv6\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"addr\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"type\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"subnets\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv4\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"plen\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"prefix\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv6\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"plen\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"prefix\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"simple_static_route\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\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\n\t\t\t\t\t\t\"no_inside_static_routes\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_outside_static_routes\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"outside_static_routes\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"static_route_list\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"custom_static_route\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"attrs\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"labels\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeMap,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"nexthop\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"interface\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"kind\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"nexthop_address\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv4\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"addr\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv6\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"addr\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"type\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"subnets\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv4\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"plen\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"prefix\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv6\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"plen\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"prefix\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"simple_static_route\": {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\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\n\t\t\t\t\t\t\"sm_connection_public_ip\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"sm_connection_pvt_ip\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"vpc_attachments\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"vpc_list\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"labels\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeMap,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"vpc_id\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}",
"func (p *AWS) Initialize(config *types.ProviderConfig) error {\n\tp.Storage = &S3{}\n\n\tif config.Zone == \"\" {\n\t\treturn errors.New(\"zone missing\")\n\t}\n\n\terr := loadAWSCreds()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, err := session.NewSession(\n\t\t&aws.Config{\n\t\t\tRegion: aws.String(stripZone(config.Zone)),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.session = session\n\tp.dnsService = route53.New(session)\n\tp.ec2 = ec2.New(session)\n\tp.volumeService = ebs.New(session,\n\t\taws.NewConfig().\n\t\t\tWithRegion(stripZone(config.Zone)).\n\t\t\tWithMaxRetries(7))\n\n\t_, err = p.ec2.DescribeRegions(&ec2.DescribeRegionsInput{RegionNames: aws.StringSlice([]string{stripZone(config.Zone)})})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"region with name %v is invalid\", config.Zone)\n\t}\n\n\treturn nil\n}",
"func makeARN(resource string) arn.ARN {\n\treturn arn.ARN{\n\t\tPartition: \"aws\",\n\t\tService: \"sqs\",\n\t\tRegion: \"us-fake-0\",\n\t\tAccountID: \"123456789012\",\n\t\tResource: resource,\n\t}\n}",
"func AWSFuncs(f map[string]interface{}) {\n\tf2 := CreateAWSFuncs(context.Background())\n\tfor k, v := range f2 {\n\t\tf[k] = v\n\t}\n}",
"func AWScreds(akey, skey, region string) {\n\tWriteConfigFiles(\"access_key\",akey,CPath,\"aws\")\n\tWriteConfigFiles(\"secret_key\",skey,CPath,\"aws\")\n\tWriteConfigFiles(\"region\",region,CPath,\"aws\")\n}",
"func AWSFactory(service string) AWS {\n\tservice = strings.ToLower(service)\n\tswitch service {\n\tcase \"rds\":\n\t\treturn rdsService{\n\t\t\tsvc: rds.New(sess, updateCredentials(sess)),\n\t\t}\n\tcase \"elasti\":\n\t\treturn elastiService{\n\t\t\tsvc: elasticache.New(sess, updateCredentials(sess)),\n\t\t}\n\tdefault:\n\t\treturn nil\n\t}\n}",
"func ServiceTagFunction(serviceName string) string {\n\tswitch serviceName {\n\tcase \"acm\":\n\t\treturn \"AddTagsToCertificate\"\n\tcase \"acmpca\":\n\t\treturn \"TagCertificateAuthority\"\n\tcase \"cloudtrail\":\n\t\treturn \"AddTags\"\n\tcase \"cloudwatchlogs\":\n\t\treturn \"TagLogGroup\"\n\tcase \"databasemigrationservice\":\n\t\treturn \"AddTagsToResource\"\n\tcase \"datapipeline\":\n\t\treturn \"AddTags\"\n\tcase \"directoryservice\":\n\t\treturn \"AddTagsToResource\"\n\tcase \"docdb\":\n\t\treturn \"AddTagsToResource\"\n\tcase \"ec2\":\n\t\treturn \"CreateTags\"\n\tcase \"elasticache\":\n\t\treturn \"AddTagsToResource\"\n\tcase \"elasticbeanstalk\":\n\t\treturn \"UpdateTagsForResource\"\n\tcase \"elasticsearchservice\":\n\t\treturn \"AddTags\"\n\tcase \"elb\":\n\t\treturn \"AddTags\"\n\tcase \"elbv2\":\n\t\treturn \"AddTags\"\n\tcase \"emr\":\n\t\treturn \"AddTags\"\n\tcase \"firehose\":\n\t\treturn \"TagDeliveryStream\"\n\tcase \"glacier\":\n\t\treturn \"AddTagsToVault\"\n\tcase \"kinesis\":\n\t\treturn \"AddTagsToStream\"\n\tcase \"kinesisvideo\":\n\t\treturn \"TagStream\"\n\tcase \"medialive\":\n\t\treturn \"CreateTags\"\n\tcase \"mq\":\n\t\treturn \"CreateTags\"\n\tcase \"neptune\":\n\t\treturn \"AddTagsToResource\"\n\tcase \"rds\":\n\t\treturn \"AddTagsToResource\"\n\tcase \"redshift\":\n\t\treturn \"CreateTags\"\n\tcase \"resourcegroups\":\n\t\treturn \"Tag\"\n\tcase \"route53\":\n\t\treturn \"ChangeTagsForResource\"\n\tcase \"sagemaker\":\n\t\treturn \"AddTags\"\n\tcase \"sqs\":\n\t\treturn \"TagQueue\"\n\tcase \"ssm\":\n\t\treturn \"AddTagsToResource\"\n\tcase \"storagegateway\":\n\t\treturn \"AddTagsToResource\"\n\tcase \"workspaces\":\n\t\treturn \"CreateTags\"\n\tdefault:\n\t\treturn \"TagResource\"\n\t}\n}",
"func resourceAliasCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {\n\tvar diags diag.Diagnostics\n\tconn := meta.(*conns.AWSClient).LambdaConn(ctx)\n\n\tfunctionName := d.Get(\"function_name\").(string)\n\taliasName := d.Get(\"name\").(string)\n\n\tlog.Printf(\"[DEBUG] Creating Lambda alias: alias %s for function %s\", aliasName, functionName)\n\n\tparams := &lambda.CreateAliasInput{\n\t\tDescription: aws.String(d.Get(\"description\").(string)),\n\t\tFunctionName: aws.String(functionName),\n\t\tFunctionVersion: aws.String(d.Get(\"function_version\").(string)),\n\t\tName: aws.String(aliasName),\n\t\tRoutingConfig: expandAliasRoutingConfiguration(d.Get(\"routing_config\").([]interface{})),\n\t}\n\n\taliasConfiguration, err := conn.CreateAliasWithContext(ctx, params)\n\tif err != nil {\n\t\treturn sdkdiag.AppendErrorf(diags, \"creating Lambda alias: %s\", err)\n\t}\n\n\td.SetId(aws.StringValue(aliasConfiguration.AliasArn))\n\n\treturn append(diags, resourceAliasRead(ctx, d, meta)...)\n}",
"func resourceVolterraAwsTgwSiteCreate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*APIClient)\n\n\tcreateMeta := &ves_io_schema.ObjectCreateMetaType{}\n\tcreateSpec := &ves_io_schema_views_aws_tgw_site.CreateSpecType{}\n\tcreateReq := &ves_io_schema_views_aws_tgw_site.CreateRequest{\n\t\tMetadata: createMeta,\n\t\tSpec: createSpec,\n\t}\n\n\tif v, ok := d.GetOk(\"annotations\"); ok && !isIntfNil(v) {\n\n\t\tms := map[string]string{}\n\n\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\tval := v.(string)\n\t\t\tms[k] = val\n\t\t}\n\t\tcreateMeta.Annotations = ms\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Description =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"disable\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Disable =\n\t\t\tv.(bool)\n\t}\n\n\tif v, ok := d.GetOk(\"labels\"); ok && !isIntfNil(v) {\n\n\t\tms := map[string]string{}\n\n\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\tval := v.(string)\n\t\t\tms[k] = val\n\t\t}\n\t\tcreateMeta.Labels = ms\n\t}\n\n\tif v, ok := d.GetOk(\"name\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Name =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"namespace\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Namespace =\n\t\t\tv.(string)\n\t}\n\n\t//aws_parameters\n\tif v, ok := d.GetOk(\"aws_parameters\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.(*schema.Set).List()\n\t\tawsParameters := &ves_io_schema_views_aws_tgw_site.ServicesVPCType{}\n\t\tcreateSpec.AwsParameters = awsParameters\n\t\tfor _, set := range sl {\n\t\t\tawsParametersMapStrToI := set.(map[string]interface{})\n\n\t\t\tif w, ok := awsParametersMapStrToI[\"aws_certified_hw\"]; ok && !isIntfNil(w) {\n\t\t\t\tawsParameters.AwsCertifiedHw = w.(string)\n\t\t\t}\n\n\t\t\tif w, ok := awsParametersMapStrToI[\"aws_region\"]; ok && !isIntfNil(w) {\n\t\t\t\tawsParameters.AwsRegion = w.(string)\n\t\t\t}\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"az_nodes\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tazNodes := make([]*ves_io_schema_views.AWSVPCTwoInterfaceNodeType, len(sl))\n\t\t\t\tawsParameters.AzNodes = azNodes\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\tazNodes[i] = &ves_io_schema_views.AWSVPCTwoInterfaceNodeType{}\n\t\t\t\t\tazNodesMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\tif w, ok := azNodesMapStrToI[\"aws_az_name\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\tazNodes[i].AwsAzName = w.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tchoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := azNodesMapStrToI[\"inside_subnet\"]; ok && !isIntfNil(v) && !choiceTypeFound {\n\n\t\t\t\t\t\tchoiceTypeFound = true\n\t\t\t\t\t\tchoiceInt := &ves_io_schema_views.AWSVPCTwoInterfaceNodeType_InsideSubnet{}\n\t\t\t\t\t\tchoiceInt.InsideSubnet = &ves_io_schema_views.CloudSubnetType{}\n\t\t\t\t\t\tazNodes[i].Choice = choiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tchoiceTypeFound := false\n\n\t\t\t\t\t\t\tif v, ok := cs[\"existing_subnet_id\"]; ok && !isIntfNil(v) && !choiceTypeFound {\n\n\t\t\t\t\t\t\t\tchoiceTypeFound = true\n\t\t\t\t\t\t\t\tchoiceIntNew := &ves_io_schema_views.CloudSubnetType_ExistingSubnetId{}\n\n\t\t\t\t\t\t\t\tchoiceInt.InsideSubnet.Choice = choiceIntNew\n\n\t\t\t\t\t\t\t\tchoiceIntNew.ExistingSubnetId = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"subnet_param\"]; ok && !isIntfNil(v) && !choiceTypeFound {\n\n\t\t\t\t\t\t\t\tchoiceTypeFound = true\n\t\t\t\t\t\t\t\tchoiceIntNew := &ves_io_schema_views.CloudSubnetType_SubnetParam{}\n\t\t\t\t\t\t\t\tchoiceIntNew.SubnetParam = &ves_io_schema_views.CloudSubnetParamType{}\n\t\t\t\t\t\t\t\tchoiceInt.InsideSubnet.Choice = choiceIntNew\n\n\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"ipv4\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tchoiceIntNew.SubnetParam.Ipv4 = v.(string)\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"ipv6\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tchoiceIntNew.SubnetParam.Ipv6 = v.(string)\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := azNodesMapStrToI[\"reserved_inside_subnet\"]; ok && !isIntfNil(v) && !choiceTypeFound {\n\n\t\t\t\t\t\tchoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tchoiceInt := &ves_io_schema_views.AWSVPCTwoInterfaceNodeType_ReservedInsideSubnet{}\n\t\t\t\t\t\t\tchoiceInt.ReservedInsideSubnet = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tazNodes[i].Choice = choiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif w, ok := azNodesMapStrToI[\"disk_size\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\tazNodes[i].DiskSize = uint32(w.(int))\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := azNodesMapStrToI[\"outside_subnet\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\toutsideSubnet := &ves_io_schema_views.CloudSubnetType{}\n\t\t\t\t\t\tazNodes[i].OutsideSubnet = outsideSubnet\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\toutsideSubnetMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tchoiceTypeFound := false\n\n\t\t\t\t\t\t\tif v, ok := outsideSubnetMapStrToI[\"existing_subnet_id\"]; ok && !isIntfNil(v) && !choiceTypeFound {\n\n\t\t\t\t\t\t\t\tchoiceTypeFound = true\n\t\t\t\t\t\t\t\tchoiceInt := &ves_io_schema_views.CloudSubnetType_ExistingSubnetId{}\n\n\t\t\t\t\t\t\t\toutsideSubnet.Choice = choiceInt\n\n\t\t\t\t\t\t\t\tchoiceInt.ExistingSubnetId = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := outsideSubnetMapStrToI[\"subnet_param\"]; ok && !isIntfNil(v) && !choiceTypeFound {\n\n\t\t\t\t\t\t\t\tchoiceTypeFound = true\n\t\t\t\t\t\t\t\tchoiceInt := &ves_io_schema_views.CloudSubnetType_SubnetParam{}\n\t\t\t\t\t\t\t\tchoiceInt.SubnetParam = &ves_io_schema_views.CloudSubnetParamType{}\n\t\t\t\t\t\t\t\toutsideSubnet.Choice = choiceInt\n\n\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"ipv4\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tchoiceInt.SubnetParam.Ipv4 = v.(string)\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"ipv6\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tchoiceInt.SubnetParam.Ipv6 = v.(string)\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := azNodesMapStrToI[\"workload_subnet\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tworkloadSubnet := &ves_io_schema_views.CloudSubnetType{}\n\t\t\t\t\t\tazNodes[i].WorkloadSubnet = workloadSubnet\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tworkloadSubnetMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tchoiceTypeFound := false\n\n\t\t\t\t\t\t\tif v, ok := workloadSubnetMapStrToI[\"existing_subnet_id\"]; ok && !isIntfNil(v) && !choiceTypeFound {\n\n\t\t\t\t\t\t\t\tchoiceTypeFound = true\n\t\t\t\t\t\t\t\tchoiceInt := &ves_io_schema_views.CloudSubnetType_ExistingSubnetId{}\n\n\t\t\t\t\t\t\t\tworkloadSubnet.Choice = choiceInt\n\n\t\t\t\t\t\t\t\tchoiceInt.ExistingSubnetId = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := workloadSubnetMapStrToI[\"subnet_param\"]; ok && !isIntfNil(v) && !choiceTypeFound {\n\n\t\t\t\t\t\t\t\tchoiceTypeFound = true\n\t\t\t\t\t\t\t\tchoiceInt := &ves_io_schema_views.CloudSubnetType_SubnetParam{}\n\t\t\t\t\t\t\t\tchoiceInt.SubnetParam = &ves_io_schema_views.CloudSubnetParamType{}\n\t\t\t\t\t\t\t\tworkloadSubnet.Choice = choiceInt\n\n\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"ipv4\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tchoiceInt.SubnetParam.Ipv4 = v.(string)\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"ipv6\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tchoiceInt.SubnetParam.Ipv6 = v.(string)\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tdeploymentTypeFound := false\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"assisted\"]; ok && !isIntfNil(v) && !deploymentTypeFound {\n\n\t\t\t\tdeploymentTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tdeploymentInt := &ves_io_schema_views_aws_tgw_site.ServicesVPCType_Assisted{}\n\t\t\t\t\tdeploymentInt.Assisted = &ves_io_schema.Empty{}\n\t\t\t\t\tawsParameters.Deployment = deploymentInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"aws_cred\"]; ok && !isIntfNil(v) && !deploymentTypeFound {\n\n\t\t\t\tdeploymentTypeFound = true\n\t\t\t\tdeploymentInt := &ves_io_schema_views_aws_tgw_site.ServicesVPCType_AwsCred{}\n\t\t\t\tdeploymentInt.AwsCred = &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tawsParameters.Deployment = deploymentInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tdeploymentInt.AwsCred.Name = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tdeploymentInt.AwsCred.Namespace = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"tenant\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tdeploymentInt.AwsCred.Tenant = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif w, ok := awsParametersMapStrToI[\"disk_size\"]; ok && !isIntfNil(w) {\n\t\t\t\tawsParameters.DiskSize = uint32(w.(int))\n\t\t\t}\n\n\t\t\tif w, ok := awsParametersMapStrToI[\"instance_type\"]; ok && !isIntfNil(w) {\n\t\t\t\tawsParameters.InstanceType = w.(string)\n\t\t\t}\n\n\t\t\tinternetVipChoiceTypeFound := false\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"disable_internet_vip\"]; ok && !isIntfNil(v) && !internetVipChoiceTypeFound {\n\n\t\t\t\tinternetVipChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tinternetVipChoiceInt := &ves_io_schema_views_aws_tgw_site.ServicesVPCType_DisableInternetVip{}\n\t\t\t\t\tinternetVipChoiceInt.DisableInternetVip = &ves_io_schema.Empty{}\n\t\t\t\t\tawsParameters.InternetVipChoice = internetVipChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"enable_internet_vip\"]; ok && !isIntfNil(v) && !internetVipChoiceTypeFound {\n\n\t\t\t\tinternetVipChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tinternetVipChoiceInt := &ves_io_schema_views_aws_tgw_site.ServicesVPCType_EnableInternetVip{}\n\t\t\t\t\tinternetVipChoiceInt.EnableInternetVip = &ves_io_schema.Empty{}\n\t\t\t\t\tawsParameters.InternetVipChoice = internetVipChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tserviceVpcChoiceTypeFound := false\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"new_vpc\"]; ok && !isIntfNil(v) && !serviceVpcChoiceTypeFound {\n\n\t\t\t\tserviceVpcChoiceTypeFound = true\n\t\t\t\tserviceVpcChoiceInt := &ves_io_schema_views_aws_tgw_site.ServicesVPCType_NewVpc{}\n\t\t\t\tserviceVpcChoiceInt.NewVpc = &ves_io_schema_views.AWSVPCParamsType{}\n\t\t\t\tawsParameters.ServiceVpcChoice = serviceVpcChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"allocate_ipv6\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tserviceVpcChoiceInt.NewVpc.AllocateIpv6 = v.(bool)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tnameChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := cs[\"autogenerate\"]; ok && !isIntfNil(v) && !nameChoiceTypeFound {\n\n\t\t\t\t\t\tnameChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tnameChoiceInt := &ves_io_schema_views.AWSVPCParamsType_Autogenerate{}\n\t\t\t\t\t\t\tnameChoiceInt.Autogenerate = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tserviceVpcChoiceInt.NewVpc.NameChoice = nameChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"name_tag\"]; ok && !isIntfNil(v) && !nameChoiceTypeFound {\n\n\t\t\t\t\t\tnameChoiceTypeFound = true\n\t\t\t\t\t\tnameChoiceInt := &ves_io_schema_views.AWSVPCParamsType_NameTag{}\n\n\t\t\t\t\t\tserviceVpcChoiceInt.NewVpc.NameChoice = nameChoiceInt\n\n\t\t\t\t\t\tnameChoiceInt.NameTag = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"primary_ipv4\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tserviceVpcChoiceInt.NewVpc.PrimaryIpv4 = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"vpc_id\"]; ok && !isIntfNil(v) && !serviceVpcChoiceTypeFound {\n\n\t\t\t\tserviceVpcChoiceTypeFound = true\n\t\t\t\tserviceVpcChoiceInt := &ves_io_schema_views_aws_tgw_site.ServicesVPCType_VpcId{}\n\n\t\t\t\tawsParameters.ServiceVpcChoice = serviceVpcChoiceInt\n\n\t\t\t\tserviceVpcChoiceInt.VpcId = v.(string)\n\n\t\t\t}\n\n\t\t\tif w, ok := awsParametersMapStrToI[\"ssh_key\"]; ok && !isIntfNil(w) {\n\t\t\t\tawsParameters.SshKey = w.(string)\n\t\t\t}\n\n\t\t\ttgwChoiceTypeFound := false\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"existing_tgw\"]; ok && !isIntfNil(v) && !tgwChoiceTypeFound {\n\n\t\t\t\ttgwChoiceTypeFound = true\n\t\t\t\ttgwChoiceInt := &ves_io_schema_views_aws_tgw_site.ServicesVPCType_ExistingTgw{}\n\t\t\t\ttgwChoiceInt.ExistingTgw = &ves_io_schema_views_aws_tgw_site.ExistingTGWType{}\n\t\t\t\tawsParameters.TgwChoice = tgwChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"tgw_asn\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\ttgwChoiceInt.ExistingTgw.TgwAsn = uint32(v.(int))\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"tgw_id\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\ttgwChoiceInt.ExistingTgw.TgwId = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"volterra_site_asn\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\ttgwChoiceInt.ExistingTgw.VolterraSiteAsn = uint32(v.(int))\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"new_tgw\"]; ok && !isIntfNil(v) && !tgwChoiceTypeFound {\n\n\t\t\t\ttgwChoiceTypeFound = true\n\t\t\t\ttgwChoiceInt := &ves_io_schema_views_aws_tgw_site.ServicesVPCType_NewTgw{}\n\t\t\t\ttgwChoiceInt.NewTgw = &ves_io_schema_views_aws_tgw_site.TGWParamsType{}\n\t\t\t\tawsParameters.TgwChoice = tgwChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tasnChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := cs[\"system_generated\"]; ok && !isIntfNil(v) && !asnChoiceTypeFound {\n\n\t\t\t\t\t\tasnChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tasnChoiceInt := &ves_io_schema_views_aws_tgw_site.TGWParamsType_SystemGenerated{}\n\t\t\t\t\t\t\tasnChoiceInt.SystemGenerated = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\ttgwChoiceInt.NewTgw.AsnChoice = asnChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"user_assigned\"]; ok && !isIntfNil(v) && !asnChoiceTypeFound {\n\n\t\t\t\t\t\tasnChoiceTypeFound = true\n\t\t\t\t\t\tasnChoiceInt := &ves_io_schema_views_aws_tgw_site.TGWParamsType_UserAssigned{}\n\t\t\t\t\t\tasnChoiceInt.UserAssigned = &ves_io_schema_views_aws_tgw_site.TGWAssignedASNType{}\n\t\t\t\t\t\ttgwChoiceInt.NewTgw.AsnChoice = asnChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"tgw_asn\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tasnChoiceInt.UserAssigned.TgwAsn = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"volterra_site_asn\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tasnChoiceInt.UserAssigned.VolterraSiteAsn = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tworkerNodesTypeFound := false\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"no_worker_nodes\"]; ok && !isIntfNil(v) && !workerNodesTypeFound {\n\n\t\t\t\tworkerNodesTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tworkerNodesInt := &ves_io_schema_views_aws_tgw_site.ServicesVPCType_NoWorkerNodes{}\n\t\t\t\t\tworkerNodesInt.NoWorkerNodes = &ves_io_schema.Empty{}\n\t\t\t\t\tawsParameters.WorkerNodes = workerNodesInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"nodes_per_az\"]; ok && !isIntfNil(v) && !workerNodesTypeFound {\n\n\t\t\t\tworkerNodesTypeFound = true\n\t\t\t\tworkerNodesInt := &ves_io_schema_views_aws_tgw_site.ServicesVPCType_NodesPerAz{}\n\n\t\t\t\tawsParameters.WorkerNodes = workerNodesInt\n\n\t\t\t\tworkerNodesInt.NodesPerAz = uint32(v.(int))\n\n\t\t\t}\n\n\t\t\tif v, ok := awsParametersMapStrToI[\"total_nodes\"]; ok && !isIntfNil(v) && !workerNodesTypeFound {\n\n\t\t\t\tworkerNodesTypeFound = true\n\t\t\t\tworkerNodesInt := &ves_io_schema_views_aws_tgw_site.ServicesVPCType_TotalNodes{}\n\n\t\t\t\tawsParameters.WorkerNodes = workerNodesInt\n\n\t\t\t\tworkerNodesInt.TotalNodes = uint32(v.(int))\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//blocked_services_choice\n\n\tblockedServicesChoiceTypeFound := false\n\n\tif v, ok := d.GetOk(\"block_all_services\"); ok && !blockedServicesChoiceTypeFound {\n\n\t\tblockedServicesChoiceTypeFound = true\n\n\t\tif v.(bool) {\n\t\t\tblockedServicesChoiceInt := &ves_io_schema_views_aws_tgw_site.CreateSpecType_BlockAllServices{}\n\t\t\tblockedServicesChoiceInt.BlockAllServices = &ves_io_schema.Empty{}\n\t\t\tcreateSpec.BlockedServicesChoice = blockedServicesChoiceInt\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"blocked_services\"); ok && !blockedServicesChoiceTypeFound {\n\n\t\tblockedServicesChoiceTypeFound = true\n\t\tblockedServicesChoiceInt := &ves_io_schema_views_aws_tgw_site.CreateSpecType_BlockedServices{}\n\t\tblockedServicesChoiceInt.BlockedServices = &ves_io_schema_fleet.BlockedServicesListType{}\n\t\tcreateSpec.BlockedServicesChoice = blockedServicesChoiceInt\n\n\t\tsl := v.(*schema.Set).List()\n\t\tfor _, set := range sl {\n\t\t\tcs := set.(map[string]interface{})\n\n\t\t\tif v, ok := cs[\"blocked_sevice\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tblockedSevice := make([]*ves_io_schema_fleet.BlockedServices, len(sl))\n\t\t\t\tblockedServicesChoiceInt.BlockedServices.BlockedSevice = blockedSevice\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\tblockedSevice[i] = &ves_io_schema_fleet.BlockedServices{}\n\t\t\t\t\tblockedSeviceMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\tblockedServicesValueTypeChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := blockedSeviceMapStrToI[\"dns\"]; ok && !isIntfNil(v) && !blockedServicesValueTypeChoiceTypeFound {\n\n\t\t\t\t\t\tblockedServicesValueTypeChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tblockedServicesValueTypeChoiceInt := &ves_io_schema_fleet.BlockedServices_Dns{}\n\t\t\t\t\t\t\tblockedServicesValueTypeChoiceInt.Dns = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tblockedSevice[i].BlockedServicesValueTypeChoice = blockedServicesValueTypeChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := blockedSeviceMapStrToI[\"ssh\"]; ok && !isIntfNil(v) && !blockedServicesValueTypeChoiceTypeFound {\n\n\t\t\t\t\t\tblockedServicesValueTypeChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tblockedServicesValueTypeChoiceInt := &ves_io_schema_fleet.BlockedServices_Ssh{}\n\t\t\t\t\t\t\tblockedServicesValueTypeChoiceInt.Ssh = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tblockedSevice[i].BlockedServicesValueTypeChoice = blockedServicesValueTypeChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := blockedSeviceMapStrToI[\"web_user_interface\"]; ok && !isIntfNil(v) && !blockedServicesValueTypeChoiceTypeFound {\n\n\t\t\t\t\t\tblockedServicesValueTypeChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tblockedServicesValueTypeChoiceInt := &ves_io_schema_fleet.BlockedServices_WebUserInterface{}\n\t\t\t\t\t\t\tblockedServicesValueTypeChoiceInt.WebUserInterface = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tblockedSevice[i].BlockedServicesValueTypeChoice = blockedServicesValueTypeChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := blockedSeviceMapStrToI[\"network_type\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tblockedSevice[i].NetworkType = ves_io_schema.VirtualNetworkType(ves_io_schema.VirtualNetworkType_value[v.(string)])\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"default_blocked_services\"); ok && !blockedServicesChoiceTypeFound {\n\n\t\tblockedServicesChoiceTypeFound = true\n\n\t\tif v.(bool) {\n\t\t\tblockedServicesChoiceInt := &ves_io_schema_views_aws_tgw_site.CreateSpecType_DefaultBlockedServices{}\n\t\t\tblockedServicesChoiceInt.DefaultBlockedServices = &ves_io_schema.Empty{}\n\t\t\tcreateSpec.BlockedServicesChoice = blockedServicesChoiceInt\n\t\t}\n\n\t}\n\n\t//coordinates\n\tif v, ok := d.GetOk(\"coordinates\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.(*schema.Set).List()\n\t\tcoordinates := &ves_io_schema_site.Coordinates{}\n\t\tcreateSpec.Coordinates = coordinates\n\t\tfor _, set := range sl {\n\t\t\tcoordinatesMapStrToI := set.(map[string]interface{})\n\n\t\t\tif w, ok := coordinatesMapStrToI[\"latitude\"]; ok && !isIntfNil(w) {\n\t\t\t\tcoordinates.Latitude = float32(w.(float64))\n\t\t\t}\n\n\t\t\tif w, ok := coordinatesMapStrToI[\"longitude\"]; ok && !isIntfNil(w) {\n\t\t\t\tcoordinates.Longitude = float32(w.(float64))\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//direct_connect_choice\n\n\tdirectConnectChoiceTypeFound := false\n\n\tif v, ok := d.GetOk(\"direct_connect_disabled\"); ok && !directConnectChoiceTypeFound {\n\n\t\tdirectConnectChoiceTypeFound = true\n\n\t\tif v.(bool) {\n\t\t\tdirectConnectChoiceInt := &ves_io_schema_views_aws_tgw_site.CreateSpecType_DirectConnectDisabled{}\n\t\t\tdirectConnectChoiceInt.DirectConnectDisabled = &ves_io_schema.Empty{}\n\t\t\tcreateSpec.DirectConnectChoice = directConnectChoiceInt\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"direct_connect_enabled\"); ok && !directConnectChoiceTypeFound {\n\n\t\tdirectConnectChoiceTypeFound = true\n\t\tdirectConnectChoiceInt := &ves_io_schema_views_aws_tgw_site.CreateSpecType_DirectConnectEnabled{}\n\t\tdirectConnectChoiceInt.DirectConnectEnabled = &ves_io_schema_views.DirectConnectConfigType{}\n\t\tcreateSpec.DirectConnectChoice = directConnectChoiceInt\n\n\t\tsl := v.(*schema.Set).List()\n\t\tfor _, set := range sl {\n\t\t\tcs := set.(map[string]interface{})\n\n\t\t\tasnChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"auto_asn\"]; ok && !isIntfNil(v) && !asnChoiceTypeFound {\n\n\t\t\t\tasnChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tasnChoiceInt := &ves_io_schema_views.DirectConnectConfigType_AutoAsn{}\n\t\t\t\t\tasnChoiceInt.AutoAsn = &ves_io_schema.Empty{}\n\t\t\t\t\tdirectConnectChoiceInt.DirectConnectEnabled.AsnChoice = asnChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"custom_asn\"]; ok && !isIntfNil(v) && !asnChoiceTypeFound {\n\n\t\t\t\tasnChoiceTypeFound = true\n\t\t\t\tasnChoiceInt := &ves_io_schema_views.DirectConnectConfigType_CustomAsn{}\n\n\t\t\t\tdirectConnectChoiceInt.DirectConnectEnabled.AsnChoice = asnChoiceInt\n\n\t\t\t\tasnChoiceInt.CustomAsn = uint32(v.(int))\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"cloud_aggregated_prefix\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tdirectConnectChoiceInt.DirectConnectEnabled.CloudAggregatedPrefix = ls\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"dc_connect_aggregated_prefix\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tdirectConnectChoiceInt.DirectConnectEnabled.DcConnectAggregatedPrefix = ls\n\n\t\t\t}\n\n\t\t\tvifChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"hosted_vifs\"]; ok && !isIntfNil(v) && !vifChoiceTypeFound {\n\n\t\t\t\tvifChoiceTypeFound = true\n\t\t\t\tvifChoiceInt := &ves_io_schema_views.DirectConnectConfigType_HostedVifs{}\n\t\t\t\tvifChoiceInt.HostedVifs = &ves_io_schema_views.HostedVIFConfigType{}\n\t\t\t\tdirectConnectChoiceInt.DirectConnectEnabled.VifChoice = vifChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tconnectivityOptionsTypeFound := false\n\n\t\t\t\t\tif v, ok := cs[\"site_registration_over_direct_connect\"]; ok && !isIntfNil(v) && !connectivityOptionsTypeFound {\n\n\t\t\t\t\t\tconnectivityOptionsTypeFound = true\n\t\t\t\t\t\tconnectivityOptionsInt := &ves_io_schema_views.HostedVIFConfigType_SiteRegistrationOverDirectConnect{}\n\t\t\t\t\t\tconnectivityOptionsInt.SiteRegistrationOverDirectConnect = &ves_io_schema_views.CloudLinkADNType{}\n\t\t\t\t\t\tvifChoiceInt.HostedVifs.ConnectivityOptions = connectivityOptionsInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"cloudlink_network_name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tconnectivityOptionsInt.SiteRegistrationOverDirectConnect.CloudlinkNetworkName = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"site_registration_over_internet\"]; ok && !isIntfNil(v) && !connectivityOptionsTypeFound {\n\n\t\t\t\t\t\tconnectivityOptionsTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tconnectivityOptionsInt := &ves_io_schema_views.HostedVIFConfigType_SiteRegistrationOverInternet{}\n\t\t\t\t\t\t\tconnectivityOptionsInt.SiteRegistrationOverInternet = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tvifChoiceInt.HostedVifs.ConnectivityOptions = connectivityOptionsInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"vif_list\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tvifList := make([]*ves_io_schema_views.VifRegionConfig, len(sl))\n\t\t\t\t\t\tvifChoiceInt.HostedVifs.VifList = vifList\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tvifList[i] = &ves_io_schema_views.VifRegionConfig{}\n\t\t\t\t\t\t\tvifListMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif w, ok := vifListMapStrToI[\"vif_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tvifList[i].VifId = w.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tvifRegionChoiceTypeFound := false\n\n\t\t\t\t\t\t\tif v, ok := vifListMapStrToI[\"other_region\"]; ok && !isIntfNil(v) && !vifRegionChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tvifRegionChoiceTypeFound = true\n\t\t\t\t\t\t\t\tvifRegionChoiceInt := &ves_io_schema_views.VifRegionConfig_OtherRegion{}\n\n\t\t\t\t\t\t\t\tvifList[i].VifRegionChoice = vifRegionChoiceInt\n\n\t\t\t\t\t\t\t\tvifRegionChoiceInt.OtherRegion = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := vifListMapStrToI[\"same_as_site_region\"]; ok && !isIntfNil(v) && !vifRegionChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tvifRegionChoiceTypeFound = true\n\n\t\t\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\t\t\tvifRegionChoiceInt := &ves_io_schema_views.VifRegionConfig_SameAsSiteRegion{}\n\t\t\t\t\t\t\t\t\tvifRegionChoiceInt.SameAsSiteRegion = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\t\t\tvifList[i].VifRegionChoice = vifRegionChoiceInt\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"vifs\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvifChoiceInt.HostedVifs.Vifs = ls\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"manual_gw\"]; ok && !isIntfNil(v) && !vifChoiceTypeFound {\n\n\t\t\t\tvifChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tvifChoiceInt := &ves_io_schema_views.DirectConnectConfigType_ManualGw{}\n\t\t\t\t\tvifChoiceInt.ManualGw = &ves_io_schema.Empty{}\n\t\t\t\t\tdirectConnectChoiceInt.DirectConnectEnabled.VifChoice = vifChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"standard_vifs\"]; ok && !isIntfNil(v) && !vifChoiceTypeFound {\n\n\t\t\t\tvifChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tvifChoiceInt := &ves_io_schema_views.DirectConnectConfigType_StandardVifs{}\n\t\t\t\t\tvifChoiceInt.StandardVifs = &ves_io_schema.Empty{}\n\t\t\t\t\tdirectConnectChoiceInt.DirectConnectEnabled.VifChoice = vifChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//logs_receiver_choice\n\n\tlogsReceiverChoiceTypeFound := false\n\n\tif v, ok := d.GetOk(\"log_receiver\"); ok && !logsReceiverChoiceTypeFound {\n\n\t\tlogsReceiverChoiceTypeFound = true\n\t\tlogsReceiverChoiceInt := &ves_io_schema_views_aws_tgw_site.CreateSpecType_LogReceiver{}\n\t\tlogsReceiverChoiceInt.LogReceiver = &ves_io_schema_views.ObjectRefType{}\n\t\tcreateSpec.LogsReceiverChoice = logsReceiverChoiceInt\n\n\t\tsl := v.(*schema.Set).List()\n\t\tfor _, set := range sl {\n\t\t\tcs := set.(map[string]interface{})\n\n\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tlogsReceiverChoiceInt.LogReceiver.Name = v.(string)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tlogsReceiverChoiceInt.LogReceiver.Namespace = v.(string)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"tenant\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tlogsReceiverChoiceInt.LogReceiver.Tenant = v.(string)\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"logs_streaming_disabled\"); ok && !logsReceiverChoiceTypeFound {\n\n\t\tlogsReceiverChoiceTypeFound = true\n\n\t\tif v.(bool) {\n\t\t\tlogsReceiverChoiceInt := &ves_io_schema_views_aws_tgw_site.CreateSpecType_LogsStreamingDisabled{}\n\t\t\tlogsReceiverChoiceInt.LogsStreamingDisabled = &ves_io_schema.Empty{}\n\t\t\tcreateSpec.LogsReceiverChoice = logsReceiverChoiceInt\n\t\t}\n\n\t}\n\n\t//offline_survivability_mode\n\tif v, ok := d.GetOk(\"offline_survivability_mode\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.(*schema.Set).List()\n\t\tofflineSurvivabilityMode := &ves_io_schema_views.OfflineSurvivabilityModeType{}\n\t\tcreateSpec.OfflineSurvivabilityMode = offlineSurvivabilityMode\n\t\tfor _, set := range sl {\n\t\t\tofflineSurvivabilityModeMapStrToI := set.(map[string]interface{})\n\n\t\t\tofflineSurvivabilityModeChoiceTypeFound := false\n\n\t\t\tif v, ok := offlineSurvivabilityModeMapStrToI[\"enable_offline_survivability_mode\"]; ok && !isIntfNil(v) && !offlineSurvivabilityModeChoiceTypeFound {\n\n\t\t\t\tofflineSurvivabilityModeChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tofflineSurvivabilityModeChoiceInt := &ves_io_schema_views.OfflineSurvivabilityModeType_EnableOfflineSurvivabilityMode{}\n\t\t\t\t\tofflineSurvivabilityModeChoiceInt.EnableOfflineSurvivabilityMode = &ves_io_schema.Empty{}\n\t\t\t\t\tofflineSurvivabilityMode.OfflineSurvivabilityModeChoice = offlineSurvivabilityModeChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := offlineSurvivabilityModeMapStrToI[\"no_offline_survivability_mode\"]; ok && !isIntfNil(v) && !offlineSurvivabilityModeChoiceTypeFound {\n\n\t\t\t\tofflineSurvivabilityModeChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tofflineSurvivabilityModeChoiceInt := &ves_io_schema_views.OfflineSurvivabilityModeType_NoOfflineSurvivabilityMode{}\n\t\t\t\t\tofflineSurvivabilityModeChoiceInt.NoOfflineSurvivabilityMode = &ves_io_schema.Empty{}\n\t\t\t\t\tofflineSurvivabilityMode.OfflineSurvivabilityModeChoice = offlineSurvivabilityModeChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//os\n\tif v, ok := d.GetOk(\"os\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.(*schema.Set).List()\n\t\tos := &ves_io_schema_views.OperatingSystemType{}\n\t\tcreateSpec.Os = os\n\t\tfor _, set := range sl {\n\t\t\tosMapStrToI := set.(map[string]interface{})\n\n\t\t\toperatingSystemVersionChoiceTypeFound := false\n\n\t\t\tif v, ok := osMapStrToI[\"default_os_version\"]; ok && !isIntfNil(v) && !operatingSystemVersionChoiceTypeFound {\n\n\t\t\t\toperatingSystemVersionChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\toperatingSystemVersionChoiceInt := &ves_io_schema_views.OperatingSystemType_DefaultOsVersion{}\n\t\t\t\t\toperatingSystemVersionChoiceInt.DefaultOsVersion = &ves_io_schema.Empty{}\n\t\t\t\t\tos.OperatingSystemVersionChoice = operatingSystemVersionChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := osMapStrToI[\"operating_system_version\"]; ok && !isIntfNil(v) && !operatingSystemVersionChoiceTypeFound {\n\n\t\t\t\toperatingSystemVersionChoiceTypeFound = true\n\t\t\t\toperatingSystemVersionChoiceInt := &ves_io_schema_views.OperatingSystemType_OperatingSystemVersion{}\n\n\t\t\t\tos.OperatingSystemVersionChoice = operatingSystemVersionChoiceInt\n\n\t\t\t\toperatingSystemVersionChoiceInt.OperatingSystemVersion = v.(string)\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//performance_enhancement_mode\n\tif v, ok := d.GetOk(\"performance_enhancement_mode\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.(*schema.Set).List()\n\t\tperformanceEnhancementMode := &ves_io_schema_views.PerformanceEnhancementModeType{}\n\t\tcreateSpec.PerformanceEnhancementMode = performanceEnhancementMode\n\t\tfor _, set := range sl {\n\t\t\tperformanceEnhancementModeMapStrToI := set.(map[string]interface{})\n\n\t\t\tperfModeChoiceTypeFound := false\n\n\t\t\tif v, ok := performanceEnhancementModeMapStrToI[\"perf_mode_l3_enhanced\"]; ok && !isIntfNil(v) && !perfModeChoiceTypeFound {\n\n\t\t\t\tperfModeChoiceTypeFound = true\n\t\t\t\tperfModeChoiceInt := &ves_io_schema_views.PerformanceEnhancementModeType_PerfModeL3Enhanced{}\n\t\t\t\tperfModeChoiceInt.PerfModeL3Enhanced = &ves_io_schema_views.L3PerformanceEnhancementType{}\n\t\t\t\tperformanceEnhancementMode.PerfModeChoice = perfModeChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tperfModeChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := cs[\"jumbo\"]; ok && !isIntfNil(v) && !perfModeChoiceTypeFound {\n\n\t\t\t\t\t\tperfModeChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tperfModeChoiceIntNew := &ves_io_schema_views.L3PerformanceEnhancementType_Jumbo{}\n\t\t\t\t\t\t\tperfModeChoiceIntNew.Jumbo = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tperfModeChoiceInt.PerfModeL3Enhanced.PerfModeChoice = perfModeChoiceIntNew\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"no_jumbo\"]; ok && !isIntfNil(v) && !perfModeChoiceTypeFound {\n\n\t\t\t\t\t\tperfModeChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tperfModeChoiceIntNew := &ves_io_schema_views.L3PerformanceEnhancementType_NoJumbo{}\n\t\t\t\t\t\t\tperfModeChoiceIntNew.NoJumbo = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tperfModeChoiceInt.PerfModeL3Enhanced.PerfModeChoice = perfModeChoiceIntNew\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := performanceEnhancementModeMapStrToI[\"perf_mode_l7_enhanced\"]; ok && !isIntfNil(v) && !perfModeChoiceTypeFound {\n\n\t\t\t\tperfModeChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tperfModeChoiceInt := &ves_io_schema_views.PerformanceEnhancementModeType_PerfModeL7Enhanced{}\n\t\t\t\t\tperfModeChoiceInt.PerfModeL7Enhanced = &ves_io_schema.Empty{}\n\t\t\t\t\tperformanceEnhancementMode.PerfModeChoice = perfModeChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//sw\n\tif v, ok := d.GetOk(\"sw\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.(*schema.Set).List()\n\t\tsw := &ves_io_schema_views.VolterraSoftwareType{}\n\t\tcreateSpec.Sw = sw\n\t\tfor _, set := range sl {\n\t\t\tswMapStrToI := set.(map[string]interface{})\n\n\t\t\tvolterraSwVersionChoiceTypeFound := false\n\n\t\t\tif v, ok := swMapStrToI[\"default_sw_version\"]; ok && !isIntfNil(v) && !volterraSwVersionChoiceTypeFound {\n\n\t\t\t\tvolterraSwVersionChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tvolterraSwVersionChoiceInt := &ves_io_schema_views.VolterraSoftwareType_DefaultSwVersion{}\n\t\t\t\t\tvolterraSwVersionChoiceInt.DefaultSwVersion = &ves_io_schema.Empty{}\n\t\t\t\t\tsw.VolterraSwVersionChoice = volterraSwVersionChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := swMapStrToI[\"volterra_software_version\"]; ok && !isIntfNil(v) && !volterraSwVersionChoiceTypeFound {\n\n\t\t\t\tvolterraSwVersionChoiceTypeFound = true\n\t\t\t\tvolterraSwVersionChoiceInt := &ves_io_schema_views.VolterraSoftwareType_VolterraSoftwareVersion{}\n\n\t\t\t\tsw.VolterraSwVersionChoice = volterraSwVersionChoiceInt\n\n\t\t\t\tvolterraSwVersionChoiceInt.VolterraSoftwareVersion = v.(string)\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//tags\n\tif v, ok := d.GetOk(\"tags\"); ok && !isIntfNil(v) {\n\n\t\tms := map[string]string{}\n\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\tms[k] = v.(string)\n\t\t}\n\t\tcreateSpec.Tags = ms\n\t}\n\n\t//tgw_security\n\tif v, ok := d.GetOk(\"tgw_security\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.(*schema.Set).List()\n\t\ttgwSecurity := &ves_io_schema_views_aws_tgw_site.SecurityConfigType{}\n\t\tcreateSpec.TgwSecurity = tgwSecurity\n\t\tfor _, set := range sl {\n\t\t\ttgwSecurityMapStrToI := set.(map[string]interface{})\n\n\t\t\teastWestServicePolicyChoiceTypeFound := false\n\n\t\t\tif v, ok := tgwSecurityMapStrToI[\"active_east_west_service_policies\"]; ok && !isIntfNil(v) && !eastWestServicePolicyChoiceTypeFound {\n\n\t\t\t\teastWestServicePolicyChoiceTypeFound = true\n\t\t\t\teastWestServicePolicyChoiceInt := &ves_io_schema_views_aws_tgw_site.SecurityConfigType_ActiveEastWestServicePolicies{}\n\t\t\t\teastWestServicePolicyChoiceInt.ActiveEastWestServicePolicies = &ves_io_schema_views_aws_tgw_site.ActiveServicePoliciesType{}\n\t\t\t\ttgwSecurity.EastWestServicePolicyChoice = eastWestServicePolicyChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"service_policies\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tservicePoliciesInt := make([]*ves_io_schema_views.ObjectRefType, len(sl))\n\t\t\t\t\t\teastWestServicePolicyChoiceInt.ActiveEastWestServicePolicies.ServicePolicies = servicePoliciesInt\n\t\t\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\t\t\tspMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\t\t\tservicePoliciesInt[i] = &ves_io_schema_views.ObjectRefType{}\n\n\t\t\t\t\t\t\tif v, ok := spMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tservicePoliciesInt[i].Name = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := spMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tservicePoliciesInt[i].Namespace = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := spMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tservicePoliciesInt[i].Tenant = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := tgwSecurityMapStrToI[\"east_west_service_policy_allow_all\"]; ok && !isIntfNil(v) && !eastWestServicePolicyChoiceTypeFound {\n\n\t\t\t\teastWestServicePolicyChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\teastWestServicePolicyChoiceInt := &ves_io_schema_views_aws_tgw_site.SecurityConfigType_EastWestServicePolicyAllowAll{}\n\t\t\t\t\teastWestServicePolicyChoiceInt.EastWestServicePolicyAllowAll = &ves_io_schema.Empty{}\n\t\t\t\t\ttgwSecurity.EastWestServicePolicyChoice = eastWestServicePolicyChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := tgwSecurityMapStrToI[\"no_east_west_policy\"]; ok && !isIntfNil(v) && !eastWestServicePolicyChoiceTypeFound {\n\n\t\t\t\teastWestServicePolicyChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\teastWestServicePolicyChoiceInt := &ves_io_schema_views_aws_tgw_site.SecurityConfigType_NoEastWestPolicy{}\n\t\t\t\t\teastWestServicePolicyChoiceInt.NoEastWestPolicy = &ves_io_schema.Empty{}\n\t\t\t\t\ttgwSecurity.EastWestServicePolicyChoice = eastWestServicePolicyChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tforwardProxyChoiceTypeFound := false\n\n\t\t\tif v, ok := tgwSecurityMapStrToI[\"active_forward_proxy_policies\"]; ok && !isIntfNil(v) && !forwardProxyChoiceTypeFound {\n\n\t\t\t\tforwardProxyChoiceTypeFound = true\n\t\t\t\tforwardProxyChoiceInt := &ves_io_schema_views_aws_tgw_site.SecurityConfigType_ActiveForwardProxyPolicies{}\n\t\t\t\tforwardProxyChoiceInt.ActiveForwardProxyPolicies = &ves_io_schema_network_firewall.ActiveForwardProxyPoliciesType{}\n\t\t\t\ttgwSecurity.ForwardProxyChoice = forwardProxyChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"forward_proxy_policies\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tforwardProxyPoliciesInt := make([]*ves_io_schema_views.ObjectRefType, len(sl))\n\t\t\t\t\t\tforwardProxyChoiceInt.ActiveForwardProxyPolicies.ForwardProxyPolicies = forwardProxyPoliciesInt\n\t\t\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\t\t\tfppMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\t\t\tforwardProxyPoliciesInt[i] = &ves_io_schema_views.ObjectRefType{}\n\n\t\t\t\t\t\t\tif v, ok := fppMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tforwardProxyPoliciesInt[i].Name = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := fppMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tforwardProxyPoliciesInt[i].Namespace = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := fppMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tforwardProxyPoliciesInt[i].Tenant = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := tgwSecurityMapStrToI[\"forward_proxy_allow_all\"]; ok && !isIntfNil(v) && !forwardProxyChoiceTypeFound {\n\n\t\t\t\tforwardProxyChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tforwardProxyChoiceInt := &ves_io_schema_views_aws_tgw_site.SecurityConfigType_ForwardProxyAllowAll{}\n\t\t\t\t\tforwardProxyChoiceInt.ForwardProxyAllowAll = &ves_io_schema.Empty{}\n\t\t\t\t\ttgwSecurity.ForwardProxyChoice = forwardProxyChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := tgwSecurityMapStrToI[\"no_forward_proxy\"]; ok && !isIntfNil(v) && !forwardProxyChoiceTypeFound {\n\n\t\t\t\tforwardProxyChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tforwardProxyChoiceInt := &ves_io_schema_views_aws_tgw_site.SecurityConfigType_NoForwardProxy{}\n\t\t\t\t\tforwardProxyChoiceInt.NoForwardProxy = &ves_io_schema.Empty{}\n\t\t\t\t\ttgwSecurity.ForwardProxyChoice = forwardProxyChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tnetworkPolicyChoiceTypeFound := false\n\n\t\t\tif v, ok := tgwSecurityMapStrToI[\"active_enhanced_firewall_policies\"]; ok && !isIntfNil(v) && !networkPolicyChoiceTypeFound {\n\n\t\t\t\tnetworkPolicyChoiceTypeFound = true\n\t\t\t\tnetworkPolicyChoiceInt := &ves_io_schema_views_aws_tgw_site.SecurityConfigType_ActiveEnhancedFirewallPolicies{}\n\t\t\t\tnetworkPolicyChoiceInt.ActiveEnhancedFirewallPolicies = &ves_io_schema_network_firewall.ActiveEnhancedFirewallPoliciesType{}\n\t\t\t\ttgwSecurity.NetworkPolicyChoice = networkPolicyChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"enhanced_firewall_policies\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tenhancedFirewallPoliciesInt := make([]*ves_io_schema_views.ObjectRefType, len(sl))\n\t\t\t\t\t\tnetworkPolicyChoiceInt.ActiveEnhancedFirewallPolicies.EnhancedFirewallPolicies = enhancedFirewallPoliciesInt\n\t\t\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\t\t\tefpMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\t\t\tenhancedFirewallPoliciesInt[i] = &ves_io_schema_views.ObjectRefType{}\n\n\t\t\t\t\t\t\tif v, ok := efpMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tenhancedFirewallPoliciesInt[i].Name = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := efpMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tenhancedFirewallPoliciesInt[i].Namespace = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := efpMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tenhancedFirewallPoliciesInt[i].Tenant = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := tgwSecurityMapStrToI[\"active_network_policies\"]; ok && !isIntfNil(v) && !networkPolicyChoiceTypeFound {\n\n\t\t\t\tnetworkPolicyChoiceTypeFound = true\n\t\t\t\tnetworkPolicyChoiceInt := &ves_io_schema_views_aws_tgw_site.SecurityConfigType_ActiveNetworkPolicies{}\n\t\t\t\tnetworkPolicyChoiceInt.ActiveNetworkPolicies = &ves_io_schema_network_firewall.ActiveNetworkPoliciesType{}\n\t\t\t\ttgwSecurity.NetworkPolicyChoice = networkPolicyChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"network_policies\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tnetworkPoliciesInt := make([]*ves_io_schema_views.ObjectRefType, len(sl))\n\t\t\t\t\t\tnetworkPolicyChoiceInt.ActiveNetworkPolicies.NetworkPolicies = networkPoliciesInt\n\t\t\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\t\t\tnpMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\t\t\tnetworkPoliciesInt[i] = &ves_io_schema_views.ObjectRefType{}\n\n\t\t\t\t\t\t\tif v, ok := npMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tnetworkPoliciesInt[i].Name = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := npMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tnetworkPoliciesInt[i].Namespace = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := npMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tnetworkPoliciesInt[i].Tenant = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := tgwSecurityMapStrToI[\"no_network_policy\"]; ok && !isIntfNil(v) && !networkPolicyChoiceTypeFound {\n\n\t\t\t\tnetworkPolicyChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnetworkPolicyChoiceInt := &ves_io_schema_views_aws_tgw_site.SecurityConfigType_NoNetworkPolicy{}\n\t\t\t\t\tnetworkPolicyChoiceInt.NoNetworkPolicy = &ves_io_schema.Empty{}\n\t\t\t\t\ttgwSecurity.NetworkPolicyChoice = networkPolicyChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//vn_config\n\tif v, ok := d.GetOk(\"vn_config\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.(*schema.Set).List()\n\t\tvnConfig := &ves_io_schema_views_aws_tgw_site.VnConfiguration{}\n\t\tcreateSpec.VnConfig = vnConfig\n\t\tfor _, set := range sl {\n\t\t\tvnConfigMapStrToI := set.(map[string]interface{})\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"allowed_vip_port\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tallowedVipPort := &ves_io_schema_views.AllowedVIPPorts{}\n\t\t\t\tvnConfig.AllowedVipPort = allowedVipPort\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tallowedVipPortMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\tportChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := allowedVipPortMapStrToI[\"custom_ports\"]; ok && !isIntfNil(v) && !portChoiceTypeFound {\n\n\t\t\t\t\t\tportChoiceTypeFound = true\n\t\t\t\t\t\tportChoiceInt := &ves_io_schema_views.AllowedVIPPorts_CustomPorts{}\n\t\t\t\t\t\tportChoiceInt.CustomPorts = &ves_io_schema_views.CustomPorts{}\n\t\t\t\t\t\tallowedVipPort.PortChoice = portChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"port_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tportChoiceInt.CustomPorts.PortRanges = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := allowedVipPortMapStrToI[\"disable_allowed_vip_port\"]; ok && !isIntfNil(v) && !portChoiceTypeFound {\n\n\t\t\t\t\t\tportChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tportChoiceInt := &ves_io_schema_views.AllowedVIPPorts_DisableAllowedVipPort{}\n\t\t\t\t\t\t\tportChoiceInt.DisableAllowedVipPort = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tallowedVipPort.PortChoice = portChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := allowedVipPortMapStrToI[\"use_http_https_port\"]; ok && !isIntfNil(v) && !portChoiceTypeFound {\n\n\t\t\t\t\t\tportChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tportChoiceInt := &ves_io_schema_views.AllowedVIPPorts_UseHttpHttpsPort{}\n\t\t\t\t\t\t\tportChoiceInt.UseHttpHttpsPort = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tallowedVipPort.PortChoice = portChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := allowedVipPortMapStrToI[\"use_http_port\"]; ok && !isIntfNil(v) && !portChoiceTypeFound {\n\n\t\t\t\t\t\tportChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tportChoiceInt := &ves_io_schema_views.AllowedVIPPorts_UseHttpPort{}\n\t\t\t\t\t\t\tportChoiceInt.UseHttpPort = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tallowedVipPort.PortChoice = portChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := allowedVipPortMapStrToI[\"use_https_port\"]; ok && !isIntfNil(v) && !portChoiceTypeFound {\n\n\t\t\t\t\t\tportChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tportChoiceInt := &ves_io_schema_views.AllowedVIPPorts_UseHttpsPort{}\n\t\t\t\t\t\t\tportChoiceInt.UseHttpsPort = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tallowedVipPort.PortChoice = portChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"allowed_vip_port_sli\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tallowedVipPortSli := &ves_io_schema_views.AllowedVIPPorts{}\n\t\t\t\tvnConfig.AllowedVipPortSli = allowedVipPortSli\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tallowedVipPortSliMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\tportChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := allowedVipPortSliMapStrToI[\"custom_ports\"]; ok && !isIntfNil(v) && !portChoiceTypeFound {\n\n\t\t\t\t\t\tportChoiceTypeFound = true\n\t\t\t\t\t\tportChoiceInt := &ves_io_schema_views.AllowedVIPPorts_CustomPorts{}\n\t\t\t\t\t\tportChoiceInt.CustomPorts = &ves_io_schema_views.CustomPorts{}\n\t\t\t\t\t\tallowedVipPortSli.PortChoice = portChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"port_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tportChoiceInt.CustomPorts.PortRanges = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := allowedVipPortSliMapStrToI[\"disable_allowed_vip_port\"]; ok && !isIntfNil(v) && !portChoiceTypeFound {\n\n\t\t\t\t\t\tportChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tportChoiceInt := &ves_io_schema_views.AllowedVIPPorts_DisableAllowedVipPort{}\n\t\t\t\t\t\t\tportChoiceInt.DisableAllowedVipPort = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tallowedVipPortSli.PortChoice = portChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := allowedVipPortSliMapStrToI[\"use_http_https_port\"]; ok && !isIntfNil(v) && !portChoiceTypeFound {\n\n\t\t\t\t\t\tportChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tportChoiceInt := &ves_io_schema_views.AllowedVIPPorts_UseHttpHttpsPort{}\n\t\t\t\t\t\t\tportChoiceInt.UseHttpHttpsPort = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tallowedVipPortSli.PortChoice = portChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := allowedVipPortSliMapStrToI[\"use_http_port\"]; ok && !isIntfNil(v) && !portChoiceTypeFound {\n\n\t\t\t\t\t\tportChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tportChoiceInt := &ves_io_schema_views.AllowedVIPPorts_UseHttpPort{}\n\t\t\t\t\t\t\tportChoiceInt.UseHttpPort = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tallowedVipPortSli.PortChoice = portChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := allowedVipPortSliMapStrToI[\"use_https_port\"]; ok && !isIntfNil(v) && !portChoiceTypeFound {\n\n\t\t\t\t\t\tportChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tportChoiceInt := &ves_io_schema_views.AllowedVIPPorts_UseHttpsPort{}\n\t\t\t\t\t\t\tportChoiceInt.UseHttpsPort = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\tallowedVipPortSli.PortChoice = portChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tdcClusterGroupChoiceTypeFound := false\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"dc_cluster_group_inside_vn\"]; ok && !isIntfNil(v) && !dcClusterGroupChoiceTypeFound {\n\n\t\t\t\tdcClusterGroupChoiceTypeFound = true\n\t\t\t\tdcClusterGroupChoiceInt := &ves_io_schema_views_aws_tgw_site.VnConfiguration_DcClusterGroupInsideVn{}\n\t\t\t\tdcClusterGroupChoiceInt.DcClusterGroupInsideVn = &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tvnConfig.DcClusterGroupChoice = dcClusterGroupChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tdcClusterGroupChoiceInt.DcClusterGroupInsideVn.Name = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tdcClusterGroupChoiceInt.DcClusterGroupInsideVn.Namespace = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"tenant\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tdcClusterGroupChoiceInt.DcClusterGroupInsideVn.Tenant = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"dc_cluster_group_outside_vn\"]; ok && !isIntfNil(v) && !dcClusterGroupChoiceTypeFound {\n\n\t\t\t\tdcClusterGroupChoiceTypeFound = true\n\t\t\t\tdcClusterGroupChoiceInt := &ves_io_schema_views_aws_tgw_site.VnConfiguration_DcClusterGroupOutsideVn{}\n\t\t\t\tdcClusterGroupChoiceInt.DcClusterGroupOutsideVn = &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tvnConfig.DcClusterGroupChoice = dcClusterGroupChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tdcClusterGroupChoiceInt.DcClusterGroupOutsideVn.Name = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tdcClusterGroupChoiceInt.DcClusterGroupOutsideVn.Namespace = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"tenant\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tdcClusterGroupChoiceInt.DcClusterGroupOutsideVn.Tenant = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"no_dc_cluster_group\"]; ok && !isIntfNil(v) && !dcClusterGroupChoiceTypeFound {\n\n\t\t\t\tdcClusterGroupChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tdcClusterGroupChoiceInt := &ves_io_schema_views_aws_tgw_site.VnConfiguration_NoDcClusterGroup{}\n\t\t\t\t\tdcClusterGroupChoiceInt.NoDcClusterGroup = &ves_io_schema.Empty{}\n\t\t\t\t\tvnConfig.DcClusterGroupChoice = dcClusterGroupChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tglobalNetworkChoiceTypeFound := false\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"global_network_list\"]; ok && !isIntfNil(v) && !globalNetworkChoiceTypeFound {\n\n\t\t\t\tglobalNetworkChoiceTypeFound = true\n\t\t\t\tglobalNetworkChoiceInt := &ves_io_schema_views_aws_tgw_site.VnConfiguration_GlobalNetworkList{}\n\t\t\t\tglobalNetworkChoiceInt.GlobalNetworkList = &ves_io_schema_views.GlobalNetworkConnectionListType{}\n\t\t\t\tvnConfig.GlobalNetworkChoice = globalNetworkChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"global_network_connections\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tglobalNetworkConnections := make([]*ves_io_schema_views.GlobalNetworkConnectionType, len(sl))\n\t\t\t\t\t\tglobalNetworkChoiceInt.GlobalNetworkList.GlobalNetworkConnections = globalNetworkConnections\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tglobalNetworkConnections[i] = &ves_io_schema_views.GlobalNetworkConnectionType{}\n\t\t\t\t\t\t\tglobalNetworkConnectionsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tconnectionChoiceTypeFound := false\n\n\t\t\t\t\t\t\tif v, ok := globalNetworkConnectionsMapStrToI[\"sli_to_global_dr\"]; ok && !isIntfNil(v) && !connectionChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tconnectionChoiceTypeFound = true\n\t\t\t\t\t\t\t\tconnectionChoiceInt := &ves_io_schema_views.GlobalNetworkConnectionType_SliToGlobalDr{}\n\t\t\t\t\t\t\t\tconnectionChoiceInt.SliToGlobalDr = &ves_io_schema_views.GlobalConnectorType{}\n\t\t\t\t\t\t\t\tglobalNetworkConnections[i].ConnectionChoice = connectionChoiceInt\n\n\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"global_vn\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\tglobalVn := &ves_io_schema_views.ObjectRefType{}\n\t\t\t\t\t\t\t\t\t\tconnectionChoiceInt.SliToGlobalDr.GlobalVn = globalVn\n\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\tglobalVnMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := globalVnMapStrToI[\"name\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tglobalVn.Name = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := globalVnMapStrToI[\"namespace\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tglobalVn.Namespace = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := globalVnMapStrToI[\"tenant\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tglobalVn.Tenant = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := globalNetworkConnectionsMapStrToI[\"slo_to_global_dr\"]; ok && !isIntfNil(v) && !connectionChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tconnectionChoiceTypeFound = true\n\t\t\t\t\t\t\t\tconnectionChoiceInt := &ves_io_schema_views.GlobalNetworkConnectionType_SloToGlobalDr{}\n\t\t\t\t\t\t\t\tconnectionChoiceInt.SloToGlobalDr = &ves_io_schema_views.GlobalConnectorType{}\n\t\t\t\t\t\t\t\tglobalNetworkConnections[i].ConnectionChoice = connectionChoiceInt\n\n\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"global_vn\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\tglobalVn := &ves_io_schema_views.ObjectRefType{}\n\t\t\t\t\t\t\t\t\t\tconnectionChoiceInt.SloToGlobalDr.GlobalVn = globalVn\n\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\tglobalVnMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := globalVnMapStrToI[\"name\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tglobalVn.Name = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := globalVnMapStrToI[\"namespace\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tglobalVn.Namespace = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := globalVnMapStrToI[\"tenant\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tglobalVn.Tenant = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tforwardProxyChoiceTypeFound := false\n\n\t\t\t\t\t\t\tif v, ok := globalNetworkConnectionsMapStrToI[\"disable_forward_proxy\"]; ok && !isIntfNil(v) && !forwardProxyChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tforwardProxyChoiceTypeFound = true\n\n\t\t\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\t\t\tforwardProxyChoiceInt := &ves_io_schema_views.GlobalNetworkConnectionType_DisableForwardProxy{}\n\t\t\t\t\t\t\t\t\tforwardProxyChoiceInt.DisableForwardProxy = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\t\t\tglobalNetworkConnections[i].ForwardProxyChoice = forwardProxyChoiceInt\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := globalNetworkConnectionsMapStrToI[\"enable_forward_proxy\"]; ok && !isIntfNil(v) && !forwardProxyChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tforwardProxyChoiceTypeFound = true\n\t\t\t\t\t\t\t\tforwardProxyChoiceInt := &ves_io_schema_views.GlobalNetworkConnectionType_EnableForwardProxy{}\n\t\t\t\t\t\t\t\tforwardProxyChoiceInt.EnableForwardProxy = &ves_io_schema.ForwardProxyConfigType{}\n\t\t\t\t\t\t\t\tglobalNetworkConnections[i].ForwardProxyChoice = forwardProxyChoiceInt\n\n\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"connection_timeout\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tforwardProxyChoiceInt.EnableForwardProxy.ConnectionTimeout = uint32(v.(int))\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"max_connect_attempts\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tforwardProxyChoiceInt.EnableForwardProxy.MaxConnectAttempts = uint32(v.(int))\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceTypeFound := false\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"no_interception\"]; ok && !isIntfNil(v) && !tlsInterceptionChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceTypeFound = true\n\n\t\t\t\t\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceInt := &ves_io_schema.ForwardProxyConfigType_NoInterception{}\n\t\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceInt.NoInterception = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\t\t\t\t\tforwardProxyChoiceInt.EnableForwardProxy.TlsInterceptionChoice = tlsInterceptionChoiceInt\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"tls_intercept\"]; ok && !isIntfNil(v) && !tlsInterceptionChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceTypeFound = true\n\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceInt := &ves_io_schema.ForwardProxyConfigType_TlsIntercept{}\n\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceInt.TlsIntercept = &ves_io_schema.TlsInterceptionType{}\n\t\t\t\t\t\t\t\t\t\tforwardProxyChoiceInt.EnableForwardProxy.TlsInterceptionChoice = tlsInterceptionChoiceInt\n\n\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\tinterceptionPolicyChoiceTypeFound := false\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"enable_for_all_domains\"]; ok && !isIntfNil(v) && !interceptionPolicyChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\tinterceptionPolicyChoiceTypeFound = true\n\n\t\t\t\t\t\t\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tinterceptionPolicyChoiceInt := &ves_io_schema.TlsInterceptionType_EnableForAllDomains{}\n\t\t\t\t\t\t\t\t\t\t\t\t\tinterceptionPolicyChoiceInt.EnableForAllDomains = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceInt.TlsIntercept.InterceptionPolicyChoice = interceptionPolicyChoiceInt\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"policy\"]; ok && !isIntfNil(v) && !interceptionPolicyChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\tinterceptionPolicyChoiceTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\tinterceptionPolicyChoiceInt := &ves_io_schema.TlsInterceptionType_Policy{}\n\t\t\t\t\t\t\t\t\t\t\t\tinterceptionPolicyChoiceInt.Policy = &ves_io_schema.TlsInterceptionPolicy{}\n\t\t\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceInt.TlsIntercept.InterceptionPolicyChoice = interceptionPolicyChoiceInt\n\n\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"interception_rules\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tinterceptionRules := make([]*ves_io_schema.TlsInterceptionRule, len(sl))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tinterceptionPolicyChoiceInt.Policy.InterceptionRules = interceptionRules\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tinterceptionRules[i] = &ves_io_schema.TlsInterceptionRule{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tinterceptionRulesMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := interceptionRulesMapStrToI[\"domain_match\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainMatch := &ves_io_schema.DomainType{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tinterceptionRules[i].DomainMatch = domainMatch\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainMatchMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainChoiceTypeFound := false\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := domainMatchMapStrToI[\"exact_value\"]; ok && !isIntfNil(v) && !domainChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainChoiceTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainChoiceInt := &ves_io_schema.DomainType_ExactValue{}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainMatch.DomainChoice = domainChoiceInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainChoiceInt.ExactValue = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := domainMatchMapStrToI[\"regex_value\"]; ok && !isIntfNil(v) && !domainChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainChoiceTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainChoiceInt := &ves_io_schema.DomainType_RegexValue{}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainMatch.DomainChoice = domainChoiceInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainChoiceInt.RegexValue = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := domainMatchMapStrToI[\"suffix_value\"]; ok && !isIntfNil(v) && !domainChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainChoiceTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainChoiceInt := &ves_io_schema.DomainType_SuffixValue{}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainMatch.DomainChoice = domainChoiceInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdomainChoiceInt.SuffixValue = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tenableDisableChoiceTypeFound := false\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := interceptionRulesMapStrToI[\"disable_interception\"]; ok && !isIntfNil(v) && !enableDisableChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tenableDisableChoiceTypeFound = true\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tenableDisableChoiceInt := &ves_io_schema.TlsInterceptionRule_DisableInterception{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tenableDisableChoiceInt.DisableInterception = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tinterceptionRules[i].EnableDisableChoice = enableDisableChoiceInt\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := interceptionRulesMapStrToI[\"enable_interception\"]; ok && !isIntfNil(v) && !enableDisableChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tenableDisableChoiceTypeFound = true\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tenableDisableChoiceInt := &ves_io_schema.TlsInterceptionRule_EnableInterception{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tenableDisableChoiceInt.EnableInterception = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tinterceptionRules[i].EnableDisableChoice = enableDisableChoiceInt\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tsigningCertChoiceTypeFound := false\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"custom_certificate\"]; ok && !isIntfNil(v) && !signingCertChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\tsigningCertChoiceTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\tsigningCertChoiceInt := &ves_io_schema.TlsInterceptionType_CustomCertificate{}\n\t\t\t\t\t\t\t\t\t\t\t\tsigningCertChoiceInt.CustomCertificate = &ves_io_schema.TlsCertificateType{}\n\t\t\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceInt.TlsIntercept.SigningCertChoice = signingCertChoiceInt\n\n\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"certificate_url\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsigningCertChoiceInt.CustomCertificate.CertificateUrl = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"description\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsigningCertChoiceInt.CustomCertificate.Description = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tocspStaplingChoiceTypeFound := false\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"custom_hash_algorithms\"]; ok && !isIntfNil(v) && !ocspStaplingChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tocspStaplingChoiceTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tocspStaplingChoiceInt := &ves_io_schema.TlsCertificateType_CustomHashAlgorithms{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tocspStaplingChoiceInt.CustomHashAlgorithms = &ves_io_schema.HashAlgorithms{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsigningCertChoiceInt.CustomCertificate.OcspStaplingChoice = ocspStaplingChoiceInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"hash_algorithms\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thash_algorithmsList := []ves_io_schema.HashAlgorithm{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, j := range v.([]interface{}) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thash_algorithmsList = append(hash_algorithmsList, ves_io_schema.HashAlgorithm(ves_io_schema.HashAlgorithm_value[j.(string)]))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tocspStaplingChoiceInt.CustomHashAlgorithms.HashAlgorithms = hash_algorithmsList\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"disable_ocsp_stapling\"]; ok && !isIntfNil(v) && !ocspStaplingChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tocspStaplingChoiceTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_ = v\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"use_system_defaults\"]; ok && !isIntfNil(v) && !ocspStaplingChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tocspStaplingChoiceTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_ = v\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"private_key\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tprivateKey := &ves_io_schema.SecretType{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsigningCertChoiceInt.CustomCertificate.PrivateKey = privateKey\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprivateKeyMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := privateKeyMapStrToI[\"blindfold_secret_info_internal\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tblindfoldSecretInfoInternal := &ves_io_schema.BlindfoldSecretInfoType{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprivateKey.BlindfoldSecretInfoInternal = blindfoldSecretInfoInternal\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tblindfoldSecretInfoInternalMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif w, ok := blindfoldSecretInfoInternalMapStrToI[\"decryption_provider\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tblindfoldSecretInfoInternal.DecryptionProvider = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif w, ok := blindfoldSecretInfoInternalMapStrToI[\"location\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tblindfoldSecretInfoInternal.Location = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif w, ok := blindfoldSecretInfoInternalMapStrToI[\"store_provider\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tblindfoldSecretInfoInternal.StoreProvider = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := privateKeyMapStrToI[\"secret_encoding_type\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprivateKey.SecretEncodingType = ves_io_schema.SecretEncodingType(ves_io_schema.SecretEncodingType_value[v.(string)])\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofTypeFound := false\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := privateKeyMapStrToI[\"blindfold_secret_info\"]; ok && !isIntfNil(v) && !secretInfoOneofTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt := &ves_io_schema.SecretType_BlindfoldSecretInfo{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.BlindfoldSecretInfo = &ves_io_schema.BlindfoldSecretInfoType{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprivateKey.SecretInfoOneof = secretInfoOneofInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"decryption_provider\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.BlindfoldSecretInfo.DecryptionProvider = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"location\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.BlindfoldSecretInfo.Location = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"store_provider\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.BlindfoldSecretInfo.StoreProvider = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := privateKeyMapStrToI[\"clear_secret_info\"]; ok && !isIntfNil(v) && !secretInfoOneofTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt := &ves_io_schema.SecretType_ClearSecretInfo{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.ClearSecretInfo = &ves_io_schema.ClearSecretInfoType{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprivateKey.SecretInfoOneof = secretInfoOneofInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"provider\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.ClearSecretInfo.Provider = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"url\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.ClearSecretInfo.Url = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := privateKeyMapStrToI[\"vault_secret_info\"]; ok && !isIntfNil(v) && !secretInfoOneofTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt := &ves_io_schema.SecretType_VaultSecretInfo{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.VaultSecretInfo = &ves_io_schema.VaultSecretInfoType{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprivateKey.SecretInfoOneof = secretInfoOneofInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"key\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.VaultSecretInfo.Key = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"location\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.VaultSecretInfo.Location = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"provider\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.VaultSecretInfo.Provider = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"secret_encoding\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.VaultSecretInfo.SecretEncoding = ves_io_schema.SecretEncodingType(ves_io_schema.SecretEncodingType_value[v.(string)])\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"version\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.VaultSecretInfo.Version = uint32(v.(int))\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := privateKeyMapStrToI[\"wingman_secret_info\"]; ok && !isIntfNil(v) && !secretInfoOneofTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt := &ves_io_schema.SecretType_WingmanSecretInfo{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.WingmanSecretInfo = &ves_io_schema.WingmanSecretInfoType{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprivateKey.SecretInfoOneof = secretInfoOneofInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecretInfoOneofInt.WingmanSecretInfo.Name = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"volterra_certificate\"]; ok && !isIntfNil(v) && !signingCertChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\tsigningCertChoiceTypeFound = true\n\n\t\t\t\t\t\t\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsigningCertChoiceInt := &ves_io_schema.TlsInterceptionType_VolterraCertificate{}\n\t\t\t\t\t\t\t\t\t\t\t\t\tsigningCertChoiceInt.VolterraCertificate = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceInt.TlsIntercept.SigningCertChoice = signingCertChoiceInt\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\ttrustedCaChoiceTypeFound := false\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"trusted_ca_url\"]; ok && !isIntfNil(v) && !trustedCaChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\ttrustedCaChoiceTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\ttrustedCaChoiceInt := &ves_io_schema.TlsInterceptionType_TrustedCaUrl{}\n\n\t\t\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceInt.TlsIntercept.TrustedCaChoice = trustedCaChoiceInt\n\n\t\t\t\t\t\t\t\t\t\t\t\ttrustedCaChoiceInt.TrustedCaUrl = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"volterra_trusted_ca\"]; ok && !isIntfNil(v) && !trustedCaChoiceTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\ttrustedCaChoiceTypeFound = true\n\n\t\t\t\t\t\t\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttrustedCaChoiceInt := &ves_io_schema.TlsInterceptionType_VolterraTrustedCa{}\n\t\t\t\t\t\t\t\t\t\t\t\t\ttrustedCaChoiceInt.VolterraTrustedCa = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\t\t\t\t\t\t\ttlsInterceptionChoiceInt.TlsIntercept.TrustedCaChoice = trustedCaChoiceInt\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"white_listed_ports\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tls := make([]uint32, len(v.([]interface{})))\n\t\t\t\t\t\t\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\t\t\t\t\t\t\tls[i] = uint32(v.(int))\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tforwardProxyChoiceInt.EnableForwardProxy.WhiteListedPorts = ls\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"white_listed_prefixes\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\t\t\t\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\t\t\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tforwardProxyChoiceInt.EnableForwardProxy.WhiteListedPrefixes = ls\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"no_global_network\"]; ok && !isIntfNil(v) && !globalNetworkChoiceTypeFound {\n\n\t\t\t\tglobalNetworkChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tglobalNetworkChoiceInt := &ves_io_schema_views_aws_tgw_site.VnConfiguration_NoGlobalNetwork{}\n\t\t\t\t\tglobalNetworkChoiceInt.NoGlobalNetwork = &ves_io_schema.Empty{}\n\t\t\t\t\tvnConfig.GlobalNetworkChoice = globalNetworkChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tinsideStaticRouteChoiceTypeFound := false\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"inside_static_routes\"]; ok && !isIntfNil(v) && !insideStaticRouteChoiceTypeFound {\n\n\t\t\t\tinsideStaticRouteChoiceTypeFound = true\n\t\t\t\tinsideStaticRouteChoiceInt := &ves_io_schema_views_aws_tgw_site.VnConfiguration_InsideStaticRoutes{}\n\t\t\t\tinsideStaticRouteChoiceInt.InsideStaticRoutes = &ves_io_schema_views.SiteStaticRoutesListType{}\n\t\t\t\tvnConfig.InsideStaticRouteChoice = insideStaticRouteChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"static_route_list\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tstaticRouteList := make([]*ves_io_schema_views.SiteStaticRoutesType, len(sl))\n\t\t\t\t\t\tinsideStaticRouteChoiceInt.InsideStaticRoutes.StaticRouteList = staticRouteList\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tstaticRouteList[i] = &ves_io_schema_views.SiteStaticRoutesType{}\n\t\t\t\t\t\t\tstaticRouteListMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tconfigModeChoiceTypeFound := false\n\n\t\t\t\t\t\t\tif v, ok := staticRouteListMapStrToI[\"custom_static_route\"]; ok && !isIntfNil(v) && !configModeChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tconfigModeChoiceTypeFound = true\n\t\t\t\t\t\t\t\tconfigModeChoiceInt := &ves_io_schema_views.SiteStaticRoutesType_CustomStaticRoute{}\n\t\t\t\t\t\t\t\tconfigModeChoiceInt.CustomStaticRoute = &ves_io_schema.StaticRouteType{}\n\t\t\t\t\t\t\t\tstaticRouteList[i].ConfigModeChoice = configModeChoiceInt\n\n\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"attrs\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tattrsList := []ves_io_schema.RouteAttrType{}\n\t\t\t\t\t\t\t\t\t\tfor _, j := range v.([]interface{}) {\n\t\t\t\t\t\t\t\t\t\t\tattrsList = append(attrsList, ves_io_schema.RouteAttrType(ves_io_schema.RouteAttrType_value[j.(string)]))\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tconfigModeChoiceInt.CustomStaticRoute.Attrs = attrsList\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"labels\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tms := map[string]string{}\n\t\t\t\t\t\t\t\t\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\t\t\t\t\t\t\t\t\tms[k] = v.(string)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tconfigModeChoiceInt.CustomStaticRoute.Labels = ms\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"nexthop\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\tnexthop := &ves_io_schema.NextHopType{}\n\t\t\t\t\t\t\t\t\t\tconfigModeChoiceInt.CustomStaticRoute.Nexthop = nexthop\n\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\tnexthopMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := nexthopMapStrToI[\"interface\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\t\t\t\t\t\t\tintfInt := make([]*ves_io_schema.ObjectRefType, len(sl))\n\t\t\t\t\t\t\t\t\t\t\t\tnexthop.Interface = intfInt\n\t\t\t\t\t\t\t\t\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tiMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i] = &ves_io_schema.ObjectRefType{}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i].Kind = \"network_interface\"\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := iMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i].Name = v.(string)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := iMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i].Namespace = v.(string)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := iMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i].Tenant = v.(string)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := iMapToStrVal[\"uid\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i].Uid = v.(string)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := nexthopMapStrToI[\"nexthop_address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\tnexthopAddress := &ves_io_schema.IpAddressType{}\n\t\t\t\t\t\t\t\t\t\t\t\tnexthop.NexthopAddress = nexthopAddress\n\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\tnexthopAddressMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tverTypeFound := false\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := nexthopAddressMapStrToI[\"ipv4\"]; ok && !isIntfNil(v) && !verTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt := &ves_io_schema.IpAddressType_Ipv4{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv4 = &ves_io_schema.Ipv4AddressType{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnexthopAddress.Ver = verInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"addr\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv4.Addr = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := nexthopAddressMapStrToI[\"ipv6\"]; ok && !isIntfNil(v) && !verTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt := &ves_io_schema.IpAddressType_Ipv6{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv6 = &ves_io_schema.Ipv6AddressType{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnexthopAddress.Ver = verInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"addr\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv6.Addr = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := nexthopMapStrToI[\"type\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\tnexthop.Type = ves_io_schema.NextHopTypes(ves_io_schema.NextHopTypes_value[v.(string)])\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"subnets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\t\t\t\t\tsubnets := make([]*ves_io_schema.IpSubnetType, len(sl))\n\t\t\t\t\t\t\t\t\t\tconfigModeChoiceInt.CustomStaticRoute.Subnets = subnets\n\t\t\t\t\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\tsubnets[i] = &ves_io_schema.IpSubnetType{}\n\t\t\t\t\t\t\t\t\t\t\tsubnetsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\tverTypeFound := false\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := subnetsMapStrToI[\"ipv4\"]; ok && !isIntfNil(v) && !verTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\tverTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\tverInt := &ves_io_schema.IpSubnetType_Ipv4{}\n\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv4 = &ves_io_schema.Ipv4SubnetType{}\n\t\t\t\t\t\t\t\t\t\t\t\tsubnets[i].Ver = verInt\n\n\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"plen\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv4.Plen = uint32(v.(int))\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"prefix\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv4.Prefix = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := subnetsMapStrToI[\"ipv6\"]; ok && !isIntfNil(v) && !verTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\tverTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\tverInt := &ves_io_schema.IpSubnetType_Ipv6{}\n\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv6 = &ves_io_schema.Ipv6SubnetType{}\n\t\t\t\t\t\t\t\t\t\t\t\tsubnets[i].Ver = verInt\n\n\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"plen\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv6.Plen = uint32(v.(int))\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"prefix\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv6.Prefix = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := staticRouteListMapStrToI[\"simple_static_route\"]; ok && !isIntfNil(v) && !configModeChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tconfigModeChoiceTypeFound = true\n\t\t\t\t\t\t\t\tconfigModeChoiceInt := &ves_io_schema_views.SiteStaticRoutesType_SimpleStaticRoute{}\n\n\t\t\t\t\t\t\t\tstaticRouteList[i].ConfigModeChoice = configModeChoiceInt\n\n\t\t\t\t\t\t\t\tconfigModeChoiceInt.SimpleStaticRoute = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"no_inside_static_routes\"]; ok && !isIntfNil(v) && !insideStaticRouteChoiceTypeFound {\n\n\t\t\t\tinsideStaticRouteChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tinsideStaticRouteChoiceInt := &ves_io_schema_views_aws_tgw_site.VnConfiguration_NoInsideStaticRoutes{}\n\t\t\t\t\tinsideStaticRouteChoiceInt.NoInsideStaticRoutes = &ves_io_schema.Empty{}\n\t\t\t\t\tvnConfig.InsideStaticRouteChoice = insideStaticRouteChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\toutsideStaticRouteChoiceTypeFound := false\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"no_outside_static_routes\"]; ok && !isIntfNil(v) && !outsideStaticRouteChoiceTypeFound {\n\n\t\t\t\toutsideStaticRouteChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\toutsideStaticRouteChoiceInt := &ves_io_schema_views_aws_tgw_site.VnConfiguration_NoOutsideStaticRoutes{}\n\t\t\t\t\toutsideStaticRouteChoiceInt.NoOutsideStaticRoutes = &ves_io_schema.Empty{}\n\t\t\t\t\tvnConfig.OutsideStaticRouteChoice = outsideStaticRouteChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"outside_static_routes\"]; ok && !isIntfNil(v) && !outsideStaticRouteChoiceTypeFound {\n\n\t\t\t\toutsideStaticRouteChoiceTypeFound = true\n\t\t\t\toutsideStaticRouteChoiceInt := &ves_io_schema_views_aws_tgw_site.VnConfiguration_OutsideStaticRoutes{}\n\t\t\t\toutsideStaticRouteChoiceInt.OutsideStaticRoutes = &ves_io_schema_views.SiteStaticRoutesListType{}\n\t\t\t\tvnConfig.OutsideStaticRouteChoice = outsideStaticRouteChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"static_route_list\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tstaticRouteList := make([]*ves_io_schema_views.SiteStaticRoutesType, len(sl))\n\t\t\t\t\t\toutsideStaticRouteChoiceInt.OutsideStaticRoutes.StaticRouteList = staticRouteList\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tstaticRouteList[i] = &ves_io_schema_views.SiteStaticRoutesType{}\n\t\t\t\t\t\t\tstaticRouteListMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tconfigModeChoiceTypeFound := false\n\n\t\t\t\t\t\t\tif v, ok := staticRouteListMapStrToI[\"custom_static_route\"]; ok && !isIntfNil(v) && !configModeChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tconfigModeChoiceTypeFound = true\n\t\t\t\t\t\t\t\tconfigModeChoiceInt := &ves_io_schema_views.SiteStaticRoutesType_CustomStaticRoute{}\n\t\t\t\t\t\t\t\tconfigModeChoiceInt.CustomStaticRoute = &ves_io_schema.StaticRouteType{}\n\t\t\t\t\t\t\t\tstaticRouteList[i].ConfigModeChoice = configModeChoiceInt\n\n\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"attrs\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tattrsList := []ves_io_schema.RouteAttrType{}\n\t\t\t\t\t\t\t\t\t\tfor _, j := range v.([]interface{}) {\n\t\t\t\t\t\t\t\t\t\t\tattrsList = append(attrsList, ves_io_schema.RouteAttrType(ves_io_schema.RouteAttrType_value[j.(string)]))\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tconfigModeChoiceInt.CustomStaticRoute.Attrs = attrsList\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"labels\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tms := map[string]string{}\n\t\t\t\t\t\t\t\t\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\t\t\t\t\t\t\t\t\tms[k] = v.(string)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tconfigModeChoiceInt.CustomStaticRoute.Labels = ms\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"nexthop\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\tnexthop := &ves_io_schema.NextHopType{}\n\t\t\t\t\t\t\t\t\t\tconfigModeChoiceInt.CustomStaticRoute.Nexthop = nexthop\n\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\tnexthopMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := nexthopMapStrToI[\"interface\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\t\t\t\t\t\t\tintfInt := make([]*ves_io_schema.ObjectRefType, len(sl))\n\t\t\t\t\t\t\t\t\t\t\t\tnexthop.Interface = intfInt\n\t\t\t\t\t\t\t\t\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tiMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i] = &ves_io_schema.ObjectRefType{}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i].Kind = \"network_interface\"\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := iMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i].Name = v.(string)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := iMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i].Namespace = v.(string)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := iMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i].Tenant = v.(string)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := iMapToStrVal[\"uid\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tintfInt[i].Uid = v.(string)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := nexthopMapStrToI[\"nexthop_address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\tnexthopAddress := &ves_io_schema.IpAddressType{}\n\t\t\t\t\t\t\t\t\t\t\t\tnexthop.NexthopAddress = nexthopAddress\n\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\tnexthopAddressMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tverTypeFound := false\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := nexthopAddressMapStrToI[\"ipv4\"]; ok && !isIntfNil(v) && !verTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt := &ves_io_schema.IpAddressType_Ipv4{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv4 = &ves_io_schema.Ipv4AddressType{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnexthopAddress.Ver = verInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"addr\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv4.Addr = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := nexthopAddressMapStrToI[\"ipv6\"]; ok && !isIntfNil(v) && !verTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt := &ves_io_schema.IpAddressType_Ipv6{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv6 = &ves_io_schema.Ipv6AddressType{}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnexthopAddress.Ver = verInt\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"addr\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv6.Addr = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := nexthopMapStrToI[\"type\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\tnexthop.Type = ves_io_schema.NextHopTypes(ves_io_schema.NextHopTypes_value[v.(string)])\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"subnets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\t\t\t\t\tsubnets := make([]*ves_io_schema.IpSubnetType, len(sl))\n\t\t\t\t\t\t\t\t\t\tconfigModeChoiceInt.CustomStaticRoute.Subnets = subnets\n\t\t\t\t\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\tsubnets[i] = &ves_io_schema.IpSubnetType{}\n\t\t\t\t\t\t\t\t\t\t\tsubnetsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\tverTypeFound := false\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := subnetsMapStrToI[\"ipv4\"]; ok && !isIntfNil(v) && !verTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\tverTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\tverInt := &ves_io_schema.IpSubnetType_Ipv4{}\n\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv4 = &ves_io_schema.Ipv4SubnetType{}\n\t\t\t\t\t\t\t\t\t\t\t\tsubnets[i].Ver = verInt\n\n\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"plen\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv4.Plen = uint32(v.(int))\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"prefix\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv4.Prefix = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif v, ok := subnetsMapStrToI[\"ipv6\"]; ok && !isIntfNil(v) && !verTypeFound {\n\n\t\t\t\t\t\t\t\t\t\t\t\tverTypeFound = true\n\t\t\t\t\t\t\t\t\t\t\t\tverInt := &ves_io_schema.IpSubnetType_Ipv6{}\n\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv6 = &ves_io_schema.Ipv6SubnetType{}\n\t\t\t\t\t\t\t\t\t\t\t\tsubnets[i].Ver = verInt\n\n\t\t\t\t\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"plen\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv6.Plen = uint32(v.(int))\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif v, ok := cs[\"prefix\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tverInt.Ipv6.Prefix = v.(string)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := staticRouteListMapStrToI[\"simple_static_route\"]; ok && !isIntfNil(v) && !configModeChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tconfigModeChoiceTypeFound = true\n\t\t\t\t\t\t\t\tconfigModeChoiceInt := &ves_io_schema_views.SiteStaticRoutesType_SimpleStaticRoute{}\n\n\t\t\t\t\t\t\t\tstaticRouteList[i].ConfigModeChoice = configModeChoiceInt\n\n\t\t\t\t\t\t\t\tconfigModeChoiceInt.SimpleStaticRoute = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tsiteMeshGroupChoiceTypeFound := false\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"sm_connection_public_ip\"]; ok && !isIntfNil(v) && !siteMeshGroupChoiceTypeFound {\n\n\t\t\t\tsiteMeshGroupChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tsiteMeshGroupChoiceInt := &ves_io_schema_views_aws_tgw_site.VnConfiguration_SmConnectionPublicIp{}\n\t\t\t\t\tsiteMeshGroupChoiceInt.SmConnectionPublicIp = &ves_io_schema.Empty{}\n\t\t\t\t\tvnConfig.SiteMeshGroupChoice = siteMeshGroupChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := vnConfigMapStrToI[\"sm_connection_pvt_ip\"]; ok && !isIntfNil(v) && !siteMeshGroupChoiceTypeFound {\n\n\t\t\t\tsiteMeshGroupChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tsiteMeshGroupChoiceInt := &ves_io_schema_views_aws_tgw_site.VnConfiguration_SmConnectionPvtIp{}\n\t\t\t\t\tsiteMeshGroupChoiceInt.SmConnectionPvtIp = &ves_io_schema.Empty{}\n\t\t\t\t\tvnConfig.SiteMeshGroupChoice = siteMeshGroupChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//vpc_attachments\n\tif v, ok := d.GetOk(\"vpc_attachments\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.(*schema.Set).List()\n\t\tvpcAttachments := &ves_io_schema_views_aws_tgw_site.VPCAttachmentListType{}\n\t\tcreateSpec.VpcAttachments = vpcAttachments\n\t\tfor _, set := range sl {\n\t\t\tvpcAttachmentsMapStrToI := set.(map[string]interface{})\n\n\t\t\tif v, ok := vpcAttachmentsMapStrToI[\"vpc_list\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tvpcList := make([]*ves_io_schema_views_aws_tgw_site.VPCAttachmentType, len(sl))\n\t\t\t\tvpcAttachments.VpcList = vpcList\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\tvpcList[i] = &ves_io_schema_views_aws_tgw_site.VPCAttachmentType{}\n\t\t\t\t\tvpcListMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\tif w, ok := vpcListMapStrToI[\"labels\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\tms := map[string]string{}\n\t\t\t\t\t\tfor k, v := range w.(map[string]interface{}) {\n\t\t\t\t\t\t\tms[k] = v.(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvpcList[i].Labels = ms\n\t\t\t\t\t}\n\n\t\t\t\t\tif w, ok := vpcListMapStrToI[\"vpc_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\tvpcList[i].VpcId = w.(string)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tlog.Printf(\"[DEBUG] Creating Volterra AwsTgwSite object with struct: %+v\", createReq)\n\n\tcreateAwsTgwSiteResp, err := client.CreateObject(context.Background(), ves_io_schema_views_aws_tgw_site.ObjectType, createReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating AwsTgwSite: %s\", err)\n\t}\n\td.SetId(createAwsTgwSiteResp.GetObjSystemMetadata().GetUid())\n\n\treturn resourceVolterraAwsTgwSiteRead(d, meta)\n}",
"func ensureIAMRoleForCustomResource(awsPrincipalName string,\n\tsourceArn *gocf.StringExpr,\n\ttemplate *gocf.Template,\n\tlogger *logrus.Logger) (string, error) {\n\n\tvar principalActions []string\n\tswitch awsPrincipalName {\n\tcase cloudformationresources.SNSLambdaEventSource:\n\t\tprincipalActions = PushSourceConfigurationActions.SNSLambdaEventSource\n\tcase cloudformationresources.S3LambdaEventSource:\n\t\tprincipalActions = PushSourceConfigurationActions.S3LambdaEventSource\n\tcase cloudformationresources.SESLambdaEventSource:\n\t\tprincipalActions = PushSourceConfigurationActions.SESLambdaEventSource\n\tcase cloudformationresources.CloudWatchLogsLambdaEventSource:\n\t\tprincipalActions = PushSourceConfigurationActions.CloudWatchLogsLambdaEventSource\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Unsupported principal for IAM role creation: %s\", awsPrincipalName)\n\t}\n\n\t// What's the stable IAMRoleName?\n\tresourceBaseName := fmt.Sprintf(\"CustomResource%sIAMRole\", awsPrincipalToService(awsPrincipalName))\n\tstableRoleName := CloudFormationResourceName(resourceBaseName, awsPrincipalName)\n\n\t// Ensure it exists, then check to see if this Source ARN is already specified...\n\t// Checking equality with Stringable?\n\n\t// Create a new Role\n\tvar existingIAMRole *gocf.IAMRole\n\texistingResource, exists := template.Resources[stableRoleName]\n\tlogger.WithFields(logrus.Fields{\n\t\t\"PrincipalActions\": principalActions,\n\t\t\"SourceArn\": sourceArn,\n\t}).Debug(\"Ensuring IAM Role results\")\n\n\tif !exists {\n\t\t// Insert the IAM role here. We'll walk the policies data in the next section\n\t\t// to make sure that the sourceARN we have is in the list\n\t\tstatements := CommonIAMStatements.Core\n\n\t\tiamPolicyList := gocf.IAMRolePolicyList{}\n\t\tiamPolicyList = append(iamPolicyList,\n\t\t\tgocf.IAMRolePolicy{\n\t\t\t\tPolicyDocument: ArbitraryJSONObject{\n\t\t\t\t\t\"Version\": \"2012-10-17\",\n\t\t\t\t\t\"Statement\": statements,\n\t\t\t\t},\n\t\t\t\tPolicyName: gocf.String(fmt.Sprintf(\"%sPolicy\", stableRoleName)),\n\t\t\t},\n\t\t)\n\n\t\texistingIAMRole = &gocf.IAMRole{\n\t\t\tAssumeRolePolicyDocument: AssumePolicyDocument,\n\t\t\tPolicies: &iamPolicyList,\n\t\t}\n\t\ttemplate.AddResource(stableRoleName, existingIAMRole)\n\n\t\t// Create a new IAM Role resource\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"RoleName\": stableRoleName,\n\t\t}).Debug(\"Inserting IAM Role\")\n\t} else {\n\t\texistingIAMRole = existingResource.Properties.(*gocf.IAMRole)\n\t}\n\n\t// Walk the existing statements\n\tif nil != existingIAMRole.Policies {\n\t\tfor _, eachPolicy := range *existingIAMRole.Policies {\n\t\t\tpolicyDoc := eachPolicy.PolicyDocument.(ArbitraryJSONObject)\n\t\t\tstatements := policyDoc[\"Statement\"]\n\t\t\tfor _, eachStatement := range statements.([]spartaIAM.PolicyStatement) {\n\t\t\t\tif sourceArn.String() == eachStatement.Resource.String() {\n\n\t\t\t\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\t\t\t\"RoleName\": stableRoleName,\n\t\t\t\t\t\t\"SourceArn\": sourceArn.String(),\n\t\t\t\t\t}).Debug(\"SourceArn already exists for IAM Policy\")\n\t\t\t\t\treturn stableRoleName, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"RoleName\": stableRoleName,\n\t\t\t\"Action\": principalActions,\n\t\t\t\"Resource\": sourceArn,\n\t\t}).Debug(\"Inserting Actions for configuration ARN\")\n\n\t\t// Add this statement to the first policy, iff the actions are non-empty\n\t\tif len(principalActions) > 0 {\n\t\t\trootPolicy := (*existingIAMRole.Policies)[0]\n\t\t\trootPolicyDoc := rootPolicy.PolicyDocument.(ArbitraryJSONObject)\n\t\t\trootPolicyStatements := rootPolicyDoc[\"Statement\"].([]spartaIAM.PolicyStatement)\n\t\t\trootPolicyDoc[\"Statement\"] = append(rootPolicyStatements, spartaIAM.PolicyStatement{\n\t\t\t\tEffect: \"Allow\",\n\t\t\t\tAction: principalActions,\n\t\t\t\tResource: sourceArn,\n\t\t\t})\n\t\t}\n\n\t\treturn stableRoleName, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"Unable to find Policies entry for IAM role: %s\", stableRoleName)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
MysqlConnect return sql.DB connection
|
func MysqlConnect() *sql.DB {
db, err := sql.Open("mysql", "root:mysql@/go-cms")
err = db.Ping()
if err != nil {
fmt.Println(err.Error())
panic(err.Error()) // proper error handling instead of panic in your app
}
return db
}
|
[
"func MysqlConnect(configName string) *gorm.DB {\n\tmysql := LoadDBConfig(configName)\n\tconnectionString := mysql.User + \":\" + mysql.Password + \"@tcp(\" + mysql.Host + \":\" + strconv.Itoa(mysql.Port) + \")/\" + mysql.DBName + \"?charset=utf8&parseTime=True&loc=Local\"\n\tconnection, err := gorm.Open(\"mysql\", connectionString)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"Connection Established\")\n\n\tif mysql.DebugMode {\n\t\treturn connection.Debug()\n\t}\n\n\treturn connection\n}",
"func MysqlConnect(configName string) *gorm.DB {\n\tconnection, err := gorm.Open(\"mysql\", \"docker:docker@tcp(db:3306)/kevin?charset=utf8&parseTime=True&loc=Local\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn connection\n}",
"func DbConnect() (db *sql.DB) {\n\tdb, err := sql.Open(\"mysql\", \"root:root@tcp(127.0.0.1:3308)/ecommerce\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn db\n}",
"func MysqlConnect() (*gorm.DB, error) {\n\tconfig := aws.Config{\n\t\tRegion: aws.String(os.Getenv(\"DB_BUCKET_REGION\")),\n\t}\n\tsess := session.Must(session.NewSession(&config))\n\n\tsvc := s3.New(sess)\n\tfmt.Println(\"accessing bucket: \" + os.Getenv(\"DB_BUCKET\") + \"/\" + os.Getenv(\"DB_BUCKET_KEY\"))\n\ts3Output, err := svc.GetObject(&s3.GetObjectInput{\n\t\tBucket: aws.String(os.Getenv(\"DB_BUCKET\")),\n\t\tKey: aws.String(os.Getenv(\"DB_BUCKET_KEY\")),\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(s3Output.Body)\n\tconBytes := buf.Bytes()\n\n\tvar connection DB\n\tjson.Unmarshal(conBytes, &connection)\n\n\tfmt.Println(\"accessing database\")\n\n\tdb, err := gorm.Open(\"mysql\", connection.User+\":\"+connection.Password+\"@(\"+connection.Host+\":\"+connection.Port+\")\"+\"/\"+connection.Db+\"?charset=utf8&parseTime=True\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}",
"func Connect(c *Config) (*sql.DB, error) {\n\n\tdb, err := sql.Open(\"sqlserver\", generateConnectionString(c))\n\tif err != nil {\n\t\tlog.Fatal(\"Error creating connection pool: \" + err.Error())\n\t}\n\treturn db, nil\n}",
"func ConnectMySQL(connectionInfo *DatabaseConnection) (*sql.DB, error) {\n\t/*\n\t * Create the connection\n\t */\n\tlog.Println(\"INFO - Connecting to MySQL database...\")\n\n\tdb, err := sql.Open(\"mysql\", connectionInfo.ToString())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttemp := os.Getenv(\"max_connections\")\n\tif temp == \"\" {\n\t\ttemp = \"151\"\n\t}\n\n\tmaxConnections, _ := strconv.Atoi(temp)\n\n\tdb.SetMaxIdleConns(maxConnections)\n\tdb.SetMaxOpenConns(maxConnections)\n\n\treturn db, nil\n}",
"func OpenMysql(driverName, dataSourceName string) (db *MysqlDB, err error) {\n var db2 *sql.DB\n db2, err = sql.Open(driverName, dataSourceName)\n if err != nil {\n return\n }\n db = &MysqlDB{}\n db.DB.DB = *db2\n return\n}",
"func Dbcon() (db *sql.DB, err error) {\n\tdb, err = sql.Open(\"mysql\", \"mremmalex:password@tcp(localhost:3306)/backendtest\")\n\treturn db, err\n}",
"func MysqlConn() *sqlx.DB {\n\treturn dbConn\n}",
"func SQLConnect(name, passwd, address, dbname string) (*sql.DB, error) {\r\n\turl := name + \":\" + passwd + \"@tcp(\" + address + \":3306)/\" + dbname\r\n\tdb, err := sql.Open(\"mysql\", url)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn db, nil\r\n}",
"func ConnectMySQL() (*MySQL, error) {\n\tdb, err := sql.Open(\"mysql\", \"root:admin@tcp(localhost:3306)/Todo_db\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(\"connected to mySql\")\n\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(\"pinged mySql\")\n\n\treturn &MySQL{db}, nil\n}",
"func MysqlConn() *gorm.DB {\n\treturn mysqlConn\n}",
"func connect(dsn string) *sql.DB {\n\tdb, err := sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Set the maximum number of idle connections in the pool. Setting this\n\t// to less than or equal to 0 will mean that no idle connections are retained.\n\tdb.SetMaxIdleConns(5)\n\n\tif err := db.Ping(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn db\n}",
"func connectDb(sqlConfig *dbutil.ActiveSqlConfig, isolation string) (_ *sqlx.DB, rerr error) {\n\t// Open db connection from config,\n\tconn, err := sqlConfig.NewSqlDBConn(isolation)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error opening database connection: %v\", err)\n\t}\n\t// Create sqlx DB.\n\tdb := sqlx.NewDb(conn, \"mysql\")\n\t// Try to close DB on error.\n\tdefer func() {\n\t\tif rerr != nil {\n\t\t\trerr = lib.MergeErrors(rerr, db.Close(), \"; \")\n\t\t}\n\t}()\n\n\t// Ping db to check connection.\n\tif err := db.Ping(); err != nil {\n\t\treturn nil, fmt.Errorf(\"error connecting to database: %v\", err)\n\t}\n\n\treturn db, nil\n}",
"func GetConnect() *pg.DB {\n\tparsedURL, err := url.Parse(os.Getenv(\"DATABASE_URL\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t//parsedURL += \"?sslmode=prefer\"\n\t\n\ttlsConfig := &tls.Config{\n InsecureSkipVerify: true,\n // ServerName: \"localhost\",\n }\n\n\tpgOptions := &pg.Options{\n\t\tUser: parsedURL.User.Username(),\n\t\tDatabase: parsedURL.Path[1:],\n\t\tAddr: parsedURL.Host,\n\t\tTLSConfig: tlsConfig,\n\t}\n\n\tif password, ok := parsedURL.User.Password(); ok {\n\t\tpgOptions.Password = password\n\t}\n\n\treturn pg.Connect(pgOptions)\n}",
"func DBCon() *sql.DB {\n\tdbCfg := readConfig()\n\n\t// dbconnection string format: \"username:password@tcp(127.0.0.1:3306)/test\"\n\tdb, err := sql.Open(\"mysql\", fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s\", dbCfg.usr, dbCfg.pass,\n\t\tdbCfg.host, dbCfg.port, dbCfg.dbname))\n\n\tif err != nil {\n\t\tlog.Fatal(\"(ERR) Database connection configuration is not satisfied: \", err)\n\t}\n\n\t// You can set the connection details here if you are using only this application for the database\n\t/*db.SetMaxOpenConns(25)\n\tdb.SetMaxIdleConns(25)\n\tdb.SetConnMaxLifetime(5 * time.Minute)*/\n\n\t// In Go, connection doesn't mean that it is connected successfully so you need to ping the database if the\n\t// connection is really available with the given config\n\tctx, cancelfunc := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelfunc()\n\terr = db.PingContext(ctx)\n\tif err != nil {\n\t\tlog.Fatalf(\"(ERR) Database: %s with host: %s is not reachable: %s\", dbCfg.dbname, dbCfg.host,\n\t\t\terr.Error())\n\t}\n\n\treturn db\n\n}",
"func ConnectMe() (db *sql.DB, err error) {\n\tgodotenv.Load()\n\tconnString := fmt.Sprintf(\"server=%s;user id=%s;password=%s;port=%s;database=%s;\",\n\t\tutilities.GoDotEnvVariable(\"Server\"), utilities.GoDotEnvVariable(\"user\"), utilities.GoDotEnvVariable(\"Password\"), utilities.GoDotEnvVariable(\"Port\"), utilities.GoDotEnvVariable(\"Database\"))\n\tdb, err = sql.Open(\"sqlserver\", connString)\n\tctx := context.Background()\n\terr = db.PingContext(ctx)\n\treturn db, err\n}",
"func connectDB(cfg *config.DB) error{\n\turi := fmt.Sprintf(\"%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True\", cfg.User, cfg.Password, cfg.Address, cfg.Name)\n\tconn, err := gorm.Open(dialect, uri)\n\tif err != nil{\n\t\treturn err\n\t}\n\tdefaultDB = &DB{conn}\n\tdefaultDB.DB.DB().SetMaxIdleConns(cfg.MaxIdleConn)\n\tdefaultDB.DB.DB().SetMaxOpenConns(cfg.MaxOpenConn)\n\tdefaultDB.DB.DB().SetConnMaxLifetime(cfg.MaxConnLifetime)\n\tdefaultDB.DB.LogMode(cfg.Debug)\n\n\treturn nil\n}",
"func ConnectDB() *sql.DB {\n\n\t// connString := fmt.Sprintf(\"%s/%s/@//****:****/%s\",\n\t// dbusername,\n\t// dbpassword,\n\t// dbsid)\n\n\t// db, err := sql.Open(\"goracle\", connString)\n\tdb, err := sql.Open(\n\t\t\"godror\", \"plnadmin/plnadmin@apkt_dev\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn db\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SelectAllFromPost return slice Post
|
func SelectAllFromPost() []Post {
db := MysqlConnect()
defer db.Close()
results, err := db.Query("SELECT * FROM post")
if err != nil {
panic(err.Error())
}
var result []Post
for results.Next() {
var post Post
err = results.Scan(&post.ID, &post.Title, &post.Description, &post.Post,
&post.Date, &post.Author, &post.Thumbnail, &post.Categories)
if err != nil {
panic(err.Error())
}
result = append(result, post)
}
return result
}
|
[
"func (q postQuery) All(ctx context.Context, exec boil.ContextExecutor) (PostSlice, error) {\n\tvar o []*Post\n\n\terr := q.Bind(ctx, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"orm: failed to assign all query results to Post slice\")\n\t}\n\n\tif len(postAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}",
"func (p *Storage) SelectPosts(ctx context.Context, query *entities.PostQuery) ([]*entities.Post, error) {\n\tvar posts []*entities.Post\n err :=p.TNT.SelectTyped(\"posts\",\"user_id\",query.Offset,query.Limit, tarantool.IterGe,[]interface{}{query.UserID},&posts)\n if err != nil {\n \treturn nil, err\n\t}\n\treturn posts, err\n}",
"func (pq *PostQuery) All(ctx context.Context) ([]*Post, error) {\n\tctx = setContextOp(ctx, pq.ctx, \"All\")\n\tif err := pq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\tqr := querierAll[[]*Post, *PostQuery]()\n\treturn withInterceptors[[]*Post](ctx, pq, qr, pq.inters)\n}",
"func (s *MockStore) GetPostRange(begin, length int) (ps []Post, err error) {\n\tfor i := begin; i > 0; i-- {\n\t\tif len(ps) == length {\n\t\t\tbreak\n\t\t}\n\t\tp, ok := s.mem[i]\n\t\tif ok {\n\t\t\tps = append(ps, p)\n\t\t}\n\t}\n\treturn ps, err\n}",
"func GetAllPost(w http.ResponseWriter, r *http.Request) {\n\tpage := r.URL.Query()[\"page\"]\n\tuserID := r.URL.Query()[\"user\"]\n\n\tfilter := bson.M{}\n\tfilter[\"status\"] = bson.M{\n\t\t\"$ne\": poststatus.Deleted,\n\t}\n\n\tif len(userID) > 0 {\n\t\tuID, err := primitive.ObjectIDFromHex(userID[0])\n\t\tif err != nil {\n\t\t\tresponse.Error(w, http.StatusUnprocessableEntity, err.Error())\n\t\t\treturn\n\t\t}\n\t\tfilter[\"user_id\"] = uID\n\t}\n\n\tvar count int\n\n\tif len(page) > 0 {\n\t\tfmt.Println(\"STUFF\", len(page))\n\t\tnum, err := strconv.Atoi(page[0])\n\t\tif err != nil {\n\t\t\tresponse.Error(w, http.StatusUnprocessableEntity, err.Error())\n\t\t\treturn\n\t\t}\n\t\tcount = num\n\t} else {\n\t\tcount = 0\n\t}\n\n\tposts, err := GetAll(filter, count)\n\n\tif err != nil {\n\t\tresponse.Error(w, http.StatusUnprocessableEntity, err.Error())\n\t\treturn\n\t}\n\n\tif posts == nil {\n\t\tposts = []GetPostStruct{}\n\t}\n\n\tresponse.Success(w, r,\n\t\thttp.StatusOK,\n\t\tposts,\n\t)\n\treturn\n}",
"func (p PostService) GetAll(ctx *fiber.Ctx) ([]entity.Post, error) {\n\tpostType := ctx.Query(\"postType\", \"answer\")\n\tlimit := ctx.Query(\"limit\", \"10\")\n\tlimitInt, err := strconv.ParseInt(limit, 10, 64)\n\n\toptions := options.Find()\n\toptions.SetLimit(limitInt)\n\n\tfilter := bson.D{{Key: \"post_type\", Value: postType}}\n\tresult, err := p.postRepo.GetMany(ctx, filter, options)\n\n\tif err != nil {\n\t\treturn nil, constants.ErrInternalServer\n\t}\n\n\treturn result, nil\n}",
"func (c *Client) GetMultiple(ctx context.Context, skip uint64, take uint64) ([]domain.Post, error) {\n\tvar pst = domain.Post{}\n\tvar img = pb.Image{}\n\tr, err := c.service.GetMultiplePosts(\n\t\tctx,\n\t\t&pb.GetMultiplePostsRequest{\n\t\t\tSkip: skip,\n\t\t\tTake: take,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tposts := []domain.Post{}\n\tfor _, a := range r.Posts {\n\t\timg = *a.ContentPhoto\n\t\tpst.ContentPhoto.Name = img.Name\n\t\tposts = append(posts, domain.Post{\n\t\t\tID: bson.ObjectIdHex(a.Id),\n\t\t\tAuthor: bson.ObjectIdHex(a.Author),\n\t\t\tTopic: a.Topic,\n\t\t\tCategory: a.Category,\n\t\t\tContentText: a.ContentText,\n\t\t\tContentPhoto: pst.ContentPhoto,\n\t\t})\n\t}\n\treturn posts, nil\n}",
"func (t *RestPost) GetAll(w http.ResponseWriter, r *http.Request) {\n\tt.Log.Handle(w, r, nil, \"begin\", \"RestPost\", \"GetAll\")\n\n\t{\n\t\terr := r.ParseForm()\n\n\t\tif err != nil {\n\n\t\t\tt.Log.Handle(w, r, err, \"parseform\", \"error\", \"RestPost\", \"GetAll\")\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\n\t\t\treturn\n\t\t}\n\n\t}\n\tpostValues := r.PostForm\n\n\tt.embed.GetAll(postValues)\n\n\tw.WriteHeader(200)\n\n\tt.Log.Handle(w, r, nil, \"end\", \"RestPost\", \"GetAll\")\n\n}",
"func GetAllPost(w http.ResponseWriter, r *http.Request) {\n\tdata := srv.FindAllPost(1, 10)\n\tu.Respond(w, data.Result, data.ParamsOutput)\n}",
"func (t *RestPostDescriptor) GetAll() *ggt.MethodDescriptor { return t.methodGetAll }",
"func (db ElectionDatabase) GetPosts() ([]models.Post, error){\n postsCollection := db.Session.DB(config.MongoDbName).C(\"posts\")\n posts := []models.Post{}\n err := postsCollection.Find(nil).All(&posts)\n return posts, err\n}",
"func (pg *postsGorm) GetAll() ([]Post, error) {\n\tvar posts []Post\n\tif err := pg.db.Order(\"created_at\").Find(&posts).Error; err != nil {\n\t\treturn nil, err\n\t}\n\tfor i, v := 0, len(posts)-1; i < v; i, v = i+1, v-1 {\n\t\tposts[i], posts[v] = posts[v], posts[i]\n\t}\n\treturn posts, nil\n}",
"func (a *Assembler) slice(\n\trelatedTableName string,\n\ttableName string,\n\tpk interface{},\n\tcolumns []string,\n) ([]interface{}, error) {\n\ta.logger.WithValues(\"related\", relatedTableName, \"table\", tableName, \"columns\", columns).\n\t\tInfo(\"Retrieving data to assemble slice\")\n\trelatedEntries, err := a.rs.Get(relatedTableName, tableName, pk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstrippedEntries := []interface{}{}\n\tfor _, relatedEntry := range relatedEntries {\n\t\tstrippedEntry := a.rs.Strip(relatedEntry, columns)\n\t\tstrippedEntries = append(strippedEntries, strippedEntry)\n\t}\n\treturn strippedEntries, nil\n}",
"func (s *Substructure) posts() (docs documents) {\n\tfor _, d := range s.docs {\n\t\tif d.IsPost() {\n\t\t\tdocs = append(docs, d)\n\t\t}\n\t}\n\treturn\n}",
"func (ms *MongoStore) FetchAllShort(drafts bool) ([]*PostShort, error) {\n\tlongPost := &TextPost{}\n\tshortSlice := make([]*PostShort, 0)\n\tcol := ms.session.DB(ms.dbname).C(ms.colname)\n\titerVal := col.Find(bson.M{}).Iter()\n\tfor iterVal.Next(longPost) {\n\t\tpostShort := &PostShort{\n\t\t\tID: longPost.ID,\n\t\t\tAuthor: longPost.Author,\n\t\t\tTitle: longPost.Title,\n\t\t\tCreated: longPost.Created,\n\t\t\tEdited: longPost.Edited,\n\t\t\tPublish: longPost.Publish,\n\t\t\tDraftMode: longPost.DraftMode,\n\t\t\tTags: longPost.Tags,\n\t\t\tViews: longPost.Views,\n\t\t}\n\t\t// if drafts == true, add everything\n\t\tif drafts {\n\t\t\tshortSlice = append(shortSlice, postShort)\n\t\t} else if !postShort.DraftMode {\n\t\t\tshortSlice = append(shortSlice, postShort)\n\t\t}\n\t}\n\tif err := iterVal.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn shortSlice, nil\n}",
"func (upq *UnsavedPostQuery) All(ctx context.Context) ([]*UnsavedPost, error) {\n\tif err := upq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn upq.sqlAll(ctx)\n}",
"func (t *RestPostDescriptor) ConvertToSlice() *ggt.MethodDescriptor { return t.methodConvertToSlice }",
"func (q petQuery) All(ctx context.Context, exec boil.ContextExecutor) (PetSlice, error) {\n\tvar o []*Pet\n\n\terr := q.Bind(ctx, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"models: failed to assign all query results to Pet slice\")\n\t}\n\n\tif len(petAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}",
"func (q smallblogQuery) All(ctx context.Context, exec boil.ContextExecutor) (SmallblogSlice, error) {\n\tvar o []*Smallblog\n\n\terr := q.Bind(ctx, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"models: failed to assign all query results to Smallblog slice\")\n\t}\n\n\tif len(smallblogAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SelectFromPostByID return one row by Id
|
func SelectFromPostByID(id int) *Post {
db := MysqlConnect()
defer db.Close()
var post Post
err := db.QueryRow("SELECT * FROM post where id = ?", id).Scan(&post.ID,
&post.Title, &post.Description, &post.Post, &post.Date, &post.Author,
&post.Thumbnail, &post.Categories)
if err != nil {
panic(err.Error())
}
return &post
}
|
[
"func (repository PostRepository) FindByID(postID uint64) (model.Post, error) {\n\n\trows, err := repository.db.Query(\"select p.*, u.nick from posts p join users u on p.author_id = u.id where p.id = ?\", postID)\n\n\tif err != nil {\n\t\treturn model.Post{}, err\n\t}\n\n\tdefer rows.Close()\n\n\tvar post model.Post\n\n\tif rows.Next() {\n\n\t\terr = rows.Scan(&post.ID, &post.Title, &post.Content, &post.AuthorID, &post.Likes, &post.CreatedAt, &post.AuthorNick)\n\n\t\tif err != nil {\n\t\t\treturn model.Post{}, err\n\t\t}\n\n\t}\n\n\treturn post, nil\n}",
"func (repository Posts) GetPostbyID(postID uint64) (models.Post, error) {\n\trow, err := repository.db.Query(`\n\t\tSELECT p.*, u.username FROM posts p\n\t\tINNER JOIN users u ON u.id = p.author_id\n\t\tWHERE p.id = ?\n\t`, postID)\n\tif err != nil {\n\t\treturn models.Post{}, err\n\t}\n\tdefer row.Close()\n\n\tvar post models.Post\n\n\tif row.Next() {\n\t\tif err = row.Scan(\n\t\t\t&post.ID,\n\t\t\t&post.Title,\n\t\t\t&post.Content,\n\t\t\t&post.AuthorID,\n\t\t\t&post.Likes,\n\t\t\t&post.CreatedAt,\n\t\t\t&post.AuthorUsername,\n\t\t); err != nil {\n\t\t\treturn models.Post{}, err\n\t\t}\n\t}\n\n\treturn post, nil\n}",
"func GetPostByID(db *gorm.DB, postID int) (interface{}, string) {\n\n\tvar post []model.Post\n\tvar result []model.PostOutput\n\terr := db.Where(\"id = ?\", postID).Preload(\"Comments\").Preload(\"Likes\").Preload(\"Comments.Author\").Preload(\"Likes.Author\").Find(&post).Error\n\tif err == nil {\n\t\tuser := false\n\t\tcomment := 2\n\t\tresult = postsToPostOutput(post, user, comment)\n\t\tif len(result) > 0 {\n\t\t\treturn result[0], \"\"\n\t\t}\n\t\treturn \"\", \"Post not found\"\n\t}\n\treturn result[0], err.Error()\n}",
"func PostByID(db XODB, id int) (*Post, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, title, image_path, content, tags, category_id, ip_address, created_at, updated_at, deleted_at, create_user_id, update_user_id, delete_user_id ` +\n\t\t`FROM test.posts ` +\n\t\t`WHERE id = $1`\n\n\t// run query\n\tXOLog(sqlstr, id)\n\tp := Post{\n\t\t_exists: true,\n\t}\n\n\terr = db.QueryRow(sqlstr, id).Scan(&p.ID, &p.Title, &p.ImagePath, &p.Content, &p.Tags, &p.CategoryID, &p.IPAddress, &p.CreatedAt, &p.UpdatedAt, &p.DeletedAt, &p.CreateUserID, &p.UpdateUserID, &p.DeleteUserID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &p, nil\n}",
"func (c *PostClient) Get(ctx context.Context, id int) (*Post, error) {\n\treturn c.Query().Where(post.ID(id)).Only(ctx)\n}",
"func (ms *MongoStore) GetTextPostByID(id bson.ObjectId) (*TextPost, error) {\n\tresult := &TextPost{}\n\tcol := ms.session.DB(ms.dbname).C(ms.colname)\n\tif err := col.Find(bson.M{\"_id\": id}).One(&result); err != nil {\n\t\treturn nil, fmt.Errorf(\"error finding user: %v\", err)\n\t}\n\treturn result, nil\n}",
"func (pg *postsGorm) ByID(id uint) (*Post, error) {\n\tvar post Post\n\tdb := pg.db.Where(\"id = ?\", id)\n\terr := first(db, &post)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &post, nil\n}",
"func retrieve(id int) (post Post, err error){\n\tpost = Post{}\n\terr = Db.QueryRow(\"select id, content, author from posts where id = $1\", id).Scan(&post.Id, &post.Content, &post.Author)\n\treturn\n}",
"func (m *PostDB) OnePost(ctx context.Context, id int) (*app.Post, error) {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"post\", \"onepost\"}, time.Now())\n\n\tvar native Post\n\terr := m.Db.Scopes().Table(m.TableName()).Where(\"id = ?\", id).Find(&native).Error\n\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\tgoa.LogError(ctx, \"error getting Post\", \"error\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tview := *native.PostToPost()\n\treturn &view, err\n}",
"func GetPostByParam(getID string) (PostByIDStruct PostStr) {\n\n\tqq := OpenConnection()\n\tid, _ := primitive.ObjectIDFromHex(getID)\n\tfilter := bson.M{\"_id\": id}\n\t_ = (qq.DB.FindOne(qq.Cntx, filter)).Decode(&PostByIDStruct)\n\treturn PostByIDStruct\n}",
"func (q postQuery) One(ctx context.Context, exec boil.ContextExecutor) (*Post, error) {\n\to := &Post{}\n\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Bind(ctx, exec, o)\n\tif err != nil {\n\t\tif errors.Cause(err) == sql.ErrNoRows {\n\t\t\treturn nil, sql.ErrNoRows\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"orm: failed to execute a one query for posts\")\n\t}\n\n\tif err := o.doAfterSelectHooks(ctx, exec); err != nil {\n\t\treturn o, err\n\t}\n\n\treturn o, nil\n}",
"func (c _StoreImpl) Post_ByUserId(UserId int) (*Post, bool) {\n\to, ok := RowCacheIndex.Get(\"Post_UserId:\" + fmt.Sprintf(\"%v\", UserId))\n\tif ok {\n\t\tif obj, ok := o.(*Post); ok {\n\t\t\treturn obj, true\n\t\t}\n\t}\n\n\trow, err := NewPost_Selector().UserId_Eq(UserId).GetRow(base.DB)\n\tif err == nil {\n\t\tRowCacheIndex.Set(\"Post_UserId:\"+fmt.Sprintf(\"%v\", row.UserId), row, 0)\n\t\treturn row, true\n\t}\n\n\tXOLogErr(err)\n\treturn nil, false\n}",
"func (*controller) GetPostByID(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t// get the id from the url\n\tpostID := strings.Split(r.URL.Path, \"/\")[2]\n\n\t// cache: check/get data from the postID\n\tvar post *entity.Post = postCache.Get(postID)\n\tif post == nil {\n\t\tpost, err := postService.FindByID(postID)\n\t\tif err != nil {\n\t\t\t// cannot find id in db\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\tjson.NewEncoder(w).Encode(errors.ServiceError{Message: \"No posts found!\"})\n\t\t\treturn\n\t\t}\n\t\t// store value into cache. Set(key, value)\n\t\tpostCache.Set(postID, post)\n\t\tw.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(w).Encode(post)\n\t} else {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(w).Encode(post)\n\t}\n}",
"func GetPost(w http.ResponseWriter, r *http.Request, db *scribble.Driver) {\n\n\tparams := mux.Vars(r)\n\tposts, err := db.ReadAll(\"post\")\n\tLogError(err)\n\n\t// go through the posts and return the one that matches the request\n\tfor _, p := range posts {\n\t\tpost := Post{}\n\t\terr := json.Unmarshal([]byte(p), &post)\n\t\tLogError(err)\n\t\tif post.ID == params[\"id\"] {\n\t\t\tjson.NewEncoder(w).Encode(p)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// return an empty post if nothing can be found\n\tjson.NewEncoder(w).Encode(&Post{})\n}",
"func FindPost(ctx context.Context, exec boil.ContextExecutor, iD int64, selectCols ...string) (*Post, error) {\n\tpostObj := &Post{}\n\n\tsel := \"*\"\n\tif len(selectCols) > 0 {\n\t\tsel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), \",\")\n\t}\n\tquery := fmt.Sprintf(\n\t\t\"select %s from \\\"posts\\\" where \\\"id\\\"=$1\", sel,\n\t)\n\n\tq := queries.Raw(query, iD)\n\n\terr := q.Bind(ctx, exec, postObj)\n\tif err != nil {\n\t\tif errors.Cause(err) == sql.ErrNoRows {\n\t\t\treturn nil, sql.ErrNoRows\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"orm: unable to select from posts\")\n\t}\n\n\treturn postObj, nil\n}",
"func (ps *PostService) GetByID(ctx context.Context, id string) (post.Post, error) {\n\tctx, cancel := context.WithTimeout(ctx, waitTime*time.Second)\n\tdefer cancel()\n\n\tobjectID, err := primitive.ObjectIDFromHex(id)\n\tif err != nil {\n\t\tps.log.Error(err)\n\t\treturn post.Post{}, response.ErrInvalidID\n\t}\n\n\tp, err := ps.repository.GetByID(ctx, objectID)\n\tif err != nil {\n\t\tps.log.Error(err)\n\t\treturn post.Post{}, err\n\t}\n\n\treturn p, nil\n}",
"func GetOnePost(w http.ResponseWriter, r *http.Request) {\n\tpostID := mux.Vars(r)[\"id\"]\n\tpID, err := primitive.ObjectIDFromHex(postID)\n\tif err != nil {\n\t\tresponse.Error(w, http.StatusUnprocessableEntity, err.Error())\n\t\treturn\n\t}\n\tres, err := GetOne(bson.M{\n\t\t\"_id\": pID,\n\t})\n\tif err != nil {\n\t\tresponse.Error(w, http.StatusUnprocessableEntity, err.Error())\n\t\treturn\n\t}\n\tresponse.Success(w, r,\n\t\thttp.StatusOK,\n\t\tres,\n\t)\n\treturn\n}",
"func (post *Post) GetPostById(id ...bson.ObjectId) error {\n\tvar postId bson.ObjectId\n\tif len(id) == 0 {\n\t\tpostId = post.Id\n\t} else {\n\t\tpostId = id[0]\n\t}\n\n\terr := postSession.Clone().DB(DBName).C(\"posts\").FindId(postId).One(post)\n\treturn err\n}",
"func (bl *postBusiness) GetByID(id uint64) (*models.Post, *apperror.AppError) {\n\treturn bl.service.GetByID(id)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
mustParseInt parses the given expression as an int or returns an error.
|
func mustParseInt(expr string) (uint, error) {
num, err := strconv.Atoi(expr)
if err != nil {
return 0, fmt.Errorf("Failed to parse int from %s: %s", expr, err)
}
if num < 0 {
return 0, fmt.Errorf("Negative number (%d) not allowed: %s", num, expr)
}
return uint(num), nil
}
|
[
"func mustParseInt(rawValue, name string) int {\n\ti, err := strconv.ParseInt(rawValue, 10, 64)\n\tif err != nil {\n\t\tlog.Fatalf(\"invalid int %q for %s: %s\", rawValue, name, err)\n\t}\n\n\treturn int(i)\n}",
"func (s *Server) mustParseInt(d string) int64 {\n\ti, err := strconv.ParseInt(d, 10, 32)\n\tif err != nil {\n\t\ts.logger.Errorf(\"unable to parse input data: %v\", err)\n\t\treturn 0\n\t}\n\treturn i\n\n}",
"func mustAtoi(str string) int {\n\tret, err := strconv.Atoi(str)\n\tif err != nil {\n\t\tpanic(\"Failure parsing string to int.\")\n\t}\n\n\treturn ret\n}",
"func ParseInt(operand string) (value int, err error) {\n\ti64, err := strconv.ParseInt(operand, 0, 32)\n\treturn int(i64), err\n}",
"func (d QueryArgInt) QueryParse(val string) (interface{}, error) {\n\tif i, err := strconv.ParseInt(val, 10, 64); err == nil &&\n\t\ti <= int64(maxInt) && i >= int64(minInt) {\n\t\treturn int(i), nil\n\t}\n\treturn nil, errors.New(\"must be an int\")\n}",
"func ParseCompileEvaluateInt(exp string, vars map[string]interface{}, ctx interface{}, funcs FunctionMap, quotes []string) (map[string]interface{}, int, error) {\n\n\tvars, value, err := ParseCompileEvaluate(exp, vars, ctx, funcs, quotes)\n\tif err != nil {\n\t\treturn vars, 0, err\n\t}\n\n\tswitch value.(type) {\n\tcase int:\n\t\treturn vars, value.(int), nil\n\t}\n\n\treturn vars, 0, errors.New(\"ParseCompileEvaluateInt evaluation returns invalid type \" + fmt.Sprint(reflect.TypeOf(value)) + \"\")\n\n}",
"func (p *parser) parseInteger() (int, error) {\n\ti := p.i\n\tstart := i\n\tfor i < len(p.s) && '0' <= p.s[i] && p.s[i] <= '9' {\n\t\ti++\n\t}\n\tif i == start {\n\t\treturn 0, errors.New(\"expected integer, but didn't find it\")\n\t}\n\tp.i = i\n\n\tval, err := strconv.Atoi(p.s[start:i])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn val, nil\n}",
"func checkInteger(expr ast.Expr, env Env) (aexpr Expr, i int, ok bool, checkErrs []error) {\n\taexpr, checkErrs = CheckExpr(expr, env)\n\tif checkErrs != nil && !aexpr.IsConst() {\n\t\treturn aexpr, 0, false, checkErrs\n\t}\n\tt, err := expectSingleType(aexpr)\n\tif err != nil {\n\t\treturn aexpr, 0, false, append(checkErrs, err)\n\t}\n\n\tvar ii int64\n\tif ct, ok := t.(ConstType); ok {\n\t\tc, moreErrs := promoteConstToTyped(ct, constValue(aexpr.Const()), intType, aexpr)\n\t\tif moreErrs != nil {\n\t\t\tcheckErrs = append(checkErrs, moreErrs...)\n\t\t}\n\t\tv := reflect.Value(c)\n\t\tif v.IsValid() {\n\t\t\tii = v.Int()\n\t\t} else {\n\t\t\treturn aexpr, 0, false, checkErrs\n\t\t}\n\t} else {\n\t\tswitch t.Kind() {\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\tif aexpr.IsConst() {\n\t\t\t\tii = aexpr.Const().Int()\n\t\t\t}\n\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\tif aexpr.IsConst() {\n\t\t\t\tii = int64(aexpr.Const().Uint())\n\t\t\t}\n\t\tdefault:\n\t\t\treturn aexpr, 0, false, checkErrs\n\t\t}\n\t}\n\treturn aexpr, int(ii), true, checkErrs\n}",
"func MustInt(c *gin.Context, key string) int {\n\tif strv := c.Query(key); strv != \"\" {\n\t\tv, e := strconv.Atoi(strv)\n\t\tif e != nil {\n\t\t\tpanic(e)\n\t\t}\n\t\treturn v\n\t} else {\n\t\tpanic(fmt.Sprintf(\"cannot get value of param [%s]\", key))\n\t}\n}",
"func mustAtoi(value string) int {\n\tresult, err := strconv.Atoi(value)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn result\n}",
"func validateInt(ctx *generationContext, fieldname string, meta *fieldMetadata, bitSize int) {\n\tctx.addVariable(fmt.Sprintf(\"field_%s_s\", fieldname), \"string\")\n\tctx.addVariable(\"ok\", \"bool\")\n\tctx.addVariable(fmt.Sprintf(\"field_%s\", fieldname), \"int64\")\n\tctx.addVariable(\"err\", \"error\")\n\n\tctx.write(\"\\tfield_%s_s, ok = data[\\\"%s\\\"]\\n\", fieldname, fieldname)\n\tctx.write(\"\\tif ok {\\n\")\n\tctx.write(\"\\t\\tfield_%s, err = strconv.ParseInt(field_%s_s, 0, %d)\\n\", fieldname, fieldname, bitSize)\n\tctx.write(\"\\t\\tif err != nil {\\n\")\n\tctx.write(\"\\t\\t\\treturn nil, err\\n\")\n\tctx.write(\"\\t\\t}\\n\")\n\n\tif meta.max != \"\" {\n\t\tctx.addImport(\"errors\")\n\t\tctx.write(\"\\t\\tif field_%s > %s {\\n\", fieldname, meta.max)\n\t\tctx.write(\"\\t\\t\\treturn nil, errors.New(\\\"%s can be at most %s\\\")\\n\", fieldname, meta.max)\n\t\tctx.write(\"\\t\\t}\\n\")\n\t}\n\tif meta.min != \"\" {\n\t\tctx.addImport(\"errors\")\n\t\tctx.write(\"\\t\\tif field_%s < %s {\\n\", fieldname, meta.min)\n\t\tctx.write(\"\\t\\t\\treturn nil, errors.New(\\\"%s must be at least %s\\\")\\n\", fieldname, meta.min)\n\t\tctx.write(\"\\t\\t}\\n\")\n\t}\n\n\t// Have to cast since ParseInt returns an int64.\n\tif bitSize == 0 {\n\t\tctx.write(\"\\t\\tret.%s = int(field_%s)\\n\", fieldname, fieldname)\n\t} else if bitSize != 64 {\n\t\tctx.write(\"\\t\\tret.%s = int%d(field_%s)\\n\", fieldname, bitSize, fieldname)\n\t} else {\n\t\tctx.write(\"\\t\\tret.%s = field_%s\\n\", fieldname, fieldname)\n\t}\n\n\tctx.write(\"\\t} else {\\n\")\n\n\tif meta.def != nil {\n\t\tctx.write(\"\\t\\t// %s is optional.\\n\", fieldname)\n\t\tif *meta.def == \"\" {\n\t\t\tctx.write(\"\\t\\t// Zero value already set.\\n\")\n\t\t} else {\n\t\t\tctx.write(\"\\t\\tret.%s = %s\\n\", fieldname, *meta.def)\n\t\t}\n\t} else {\n\t\tctx.addImport(\"errors\")\n\t\tctx.write(\"\\t\\treturn nil, errors.New(\\\"%s is required\\\")\\n\", fieldname)\n\t}\n\n\tctx.write(\"\\t}\\n\")\n}",
"func (p *ErrParser) ParseInt(s string) int {\n\ti64, err := strconv.ParseInt(s, 10, 64)\n\tif err != nil {\n\t\tp.err = err\n\t}\n\treturn int(i64)\n}",
"func (p *parser) ParseInt(v string) int {\n\n\tif p.err != nil {\n\t\treturn 0\n\t}\n\n\tvalue, err := strconv.Atoi(v)\n\tif err != nil {\n\t\tp.err = err\n\t\treturn 0\n\t}\n\n\treturn value\n}",
"func ValidateInt(s *string) int {\n\tfor {\n\t\tif _, err := fmt.Scanln(s); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tv, err := strconv.Atoi(*s)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t} else {\n\t\t\treturn v\n\t\t}\n\t}\n}",
"func requireOneInt(parse func(i int64) (Command, error)) Parser {\n\treturn requireNParams(1, func(tokens []string) (Command, error) {\n\t\ti, err := strconv.ParseInt(tokens[0], 0, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid parameter type: %w\", err)\n\t\t}\n\t\treturn parse(i)\n\t})\n}",
"func ParseInt(s string) (int, error) {\n\tif s = strings.TrimSpace(s); s != \"\" {\n\t\treturn strconv.Atoi(s)\n\t}\n\treturn 0, nil\n}",
"func (state *luaState) CheckInteger(arg int) int64 {\n\ti, ok := state.ToIntegerX(arg)\n\tif !ok {\n\t\tstate.intError(arg)\n\t}\n\treturn i\n}",
"func intOrFail(debugName string, rawValue string) int64 {\n\tvalue, err := strconv.ParseInt(rawValue, 10, 64)\n\tif err != nil {\n\t\tframework.Failf(\"Failed parsing value %v from the string '%v' as an integer\", debugName, rawValue)\n\t}\n\treturn value\n}",
"func verifyIntValue(values map[string]interface{}, tag string, want int) error {\n\tgot := framework.FetchInt(values, tag)\n\tif got != want {\n\t\treturn fmt.Errorf(\"%s: %d, want %d\", tag, got, want)\n\t}\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
getBits sets all bits in the range [min, max], modulo the given step size.
|
func getBits(min, max, step uint) uint64 {
var bits uint64
// If step is 1, use shifts.
if step == 1 {
return ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min)
}
// Else, use a simple loop.
for i := min; i <= max; i += step {
bits |= 1 << i
}
return bits
}
|
[
"func getBits(min, max, step uint64) uint64 {\n\tvar bits uint64\n\t// If step is 1, use shifts.\n\tif step == 1 {\n\t\treturn ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min)\n\t}\n\n\t// Else, use a simple loop.\n\tfor i := min; i <= max; i += step {\n\t\tbits |= 1 << i\n\t}\n\treturn bits\n}",
"func Range(low, high, step int) Bits {\n\tvar b Bits\n\tif low < 0 {\n\t\tlow = 0\n\t}\n\tif high > 63 {\n\t\thigh = 63\n\t}\n\tfor n := low; n <= high; n += step {\n\t\tb = b.Set(n)\n\t}\n\treturn b\n}",
"func NewSetBits(nBit int) []uintptr {\n\tdata := NewClearBits(nBit)\n\tSetInterval(data, 0, nBit)\n\treturn data\n}",
"func IntSetBits(z *big.Int, abs []big.Word,) *big.Int",
"func (b Bits) SetBits(nums ...int) {\n\tfor _, p := range nums {\n\t\tb.SetBit(p, 1)\n\t}\n}",
"func fillingBitsSlice(slice []uint8, size int) []uint8 {\n\tfor len(slice) < size {\n\t\tslice = append(slice, 0)\n\t}\n\n\treturn slice\n}",
"func (ba *FilterBitArray) SetRange(begin uint, end uint) {\n\t// Location of i in the array index is floor(i/byte_size) + 1. If it exceeds the\n\t// current byte array, we'll make a new one large enough to include the\n\t// specified bit-index\n\tstartByteIndex := ba.byteIndex(begin)\n\tendByteIndex := ba.byteIndex(end)\n\n\tif end >= ba.Capacity() {\n\t\tba.expand(endByteIndex + 1)\n\t}\n\n\tfirstByteMask := byteMask << (begin % byteSize)\n\tlastByteMask := byteMask >> ((byteSize - end - 1) % byteSize)\n\n\tif startByteIndex == endByteIndex {\n\t\t(*ba)[startByteIndex] |= (firstByteMask & lastByteMask)\n\t} else {\n\t\t(*ba)[startByteIndex] |= firstByteMask\n\t\tfor i := startByteIndex + 1; i < endByteIndex; i++ {\n\t\t\t(*ba)[i] = byteMask\n\t\t}\n\t\t(*ba)[endByteIndex] |= lastByteMask\n\t}\n}",
"func (x *Int) Bits() []Word {}",
"func (z *Int) SetBits(abs []Word) *Int {}",
"func Of(bits ...int) Bits {\n\tvar b Bits\n\tfor _, n := range bits {\n\t\tif n >= 0 && n < 64 {\n\t\t\tb = b.Set(n)\n\t\t}\n\t}\n\treturn b\n}",
"func bitMask(n0 int, n1 int) *big.Int {\n\tn := n0\n\tif n < n1 {\n\t\tn = n1\n\t}\n\tif n < 0 {\n\t\tpanic(\"unreachable\")\n\t} else if n > (1 << 30) {\n\t\tpanic(\"interval: input is too large\")\n\t}\n\n\tif n < len(smallBitMasks) {\n\t\treturn smallBitMasks[n]\n\t}\n\tz := big.NewInt(1)\n\tz = z.Lsh(z, uint(n))\n\tz = z.Sub(z, one)\n\treturn z\n}",
"func (x *int512) ShiftLimbs(a *int512, s uint) *int512 {\n\tk := s / int64Size\n\tswitch k {\n\tcase 0:\n\t\t*x = *a\n\tcase 1:\n\t\t*x = int512{0, a[0], a[1], a[2], a[3], a[4], a[5], a[6]}\n\tcase 2:\n\t\t*x = int512{0, 0, a[0], a[1], a[2], a[3], a[4], a[5]}\n\tcase 3:\n\t\t*x = int512{0, 0, 0, a[0], a[1], a[2], a[3], a[4]}\n\tcase 4:\n\t\t*x = int512{0, 0, 0, 0, a[0], a[1], a[2], a[3]}\n\tcase 5:\n\t\t*x = int512{0, 0, 0, 0, 0, a[0], a[1], a[2]}\n\tcase 6:\n\t\t*x = int512{0, 0, 0, 0, 0, 0, a[0], a[1]}\n\tcase 7:\n\t\t*x = int512{0, 0, 0, 0, 0, 0, 0, a[0]}\n\tdefault:\n\t\t*x = int512{}\n\t}\n\treturn x\n}",
"func (dac *DAC) bitRange() (int, int) {\n\tif dac.Signed {\n\t\treturn -(1 << (dac.Bits - 1)), 1<<(dac.Bits-1) - 1\n\t}\n\treturn 0, 1<<dac.Bits - 1\n}",
"func (b *Bitset) SetBits() []int {\n\tbitlen := b.bitlength\n\tindices := make([]int, 0, b.bitlength)\n\tfor i := 0; i < bitlen; i++ {\n\t\tif b.IsSet(i) {\n\t\t\tindices = append(indices, i)\n\t\t}\n\t}\n\treturn indices\n}",
"func loadBits(val uint32, n uint) (uint32, int) {\n\treturn val >> n, int(val & uint32((1<<n)-1))\n}",
"func (s *fseEncoder) setBits(transform []byte) {\n\tif s.reUsed || s.preDefined {\n\t\treturn\n\t}\n\tif s.useRLE {\n\t\tif transform == nil {\n\t\t\ts.ct.symbolTT[s.rleVal].outBits = s.rleVal\n\t\t\ts.maxBits = s.rleVal\n\t\t\treturn\n\t\t}\n\t\ts.maxBits = transform[s.rleVal]\n\t\ts.ct.symbolTT[s.rleVal].outBits = s.maxBits\n\t\treturn\n\t}\n\tif transform == nil {\n\t\tfor i := range s.ct.symbolTT[:s.symbolLen] {\n\t\t\ts.ct.symbolTT[i].outBits = uint8(i)\n\t\t}\n\t\ts.maxBits = uint8(s.symbolLen - 1)\n\t\treturn\n\t}\n\ts.maxBits = 0\n\tfor i, v := range transform[:s.symbolLen] {\n\t\ts.ct.symbolTT[i].outBits = v\n\t\tif v > s.maxBits {\n\t\t\t// We could assume bits always going up, but we play safe.\n\t\t\ts.maxBits = v\n\t\t}\n\t}\n}",
"func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error) {\n\tif fromBits < 1 || fromBits > 8 || toBits < 1 || toBits > 8 {\n\t\treturn nil, ErrInvalidBitGroups{}\n\t}\n\n\t// Determine the maximum size the resulting array can have after base\n\t// conversion, so that we can size it a single time. This might be off\n\t// by a byte depending on whether padding is used or not and if the input\n\t// data is a multiple of both fromBits and toBits, but we ignore that and\n\t// just size it to the maximum possible.\n\tmaxSize := len(data)*int(fromBits)/int(toBits) + 1\n\n\t// The final bytes, each byte encoding toBits bits.\n\tregrouped := make([]byte, 0, maxSize)\n\n\t// Keep track of the next byte we create and how many bits we have\n\t// added to it out of the toBits goal.\n\tnextByte := byte(0)\n\tfilledBits := uint8(0)\n\n\tfor _, b := range data {\n\n\t\t// Discard unused bits.\n\t\tb <<= 8 - fromBits\n\n\t\t// How many bits remaining to extract from the input data.\n\t\tremFromBits := fromBits\n\t\tfor remFromBits > 0 {\n\t\t\t// How many bits remaining to be added to the next byte.\n\t\t\tremToBits := toBits - filledBits\n\n\t\t\t// The number of bytes to next extract is the minimum of\n\t\t\t// remFromBits and remToBits.\n\t\t\ttoExtract := remFromBits\n\t\t\tif remToBits < toExtract {\n\t\t\t\ttoExtract = remToBits\n\t\t\t}\n\n\t\t\t// Add the next bits to nextByte, shifting the already\n\t\t\t// added bits to the left.\n\t\t\tnextByte = (nextByte << toExtract) | (b >> (8 - toExtract))\n\n\t\t\t// Discard the bits we just extracted and get ready for\n\t\t\t// next iteration.\n\t\t\tb <<= toExtract\n\t\t\tremFromBits -= toExtract\n\t\t\tfilledBits += toExtract\n\n\t\t\t// If the nextByte is completely filled, we add it to\n\t\t\t// our regrouped bytes and start on the next byte.\n\t\t\tif filledBits == toBits {\n\t\t\t\tregrouped = append(regrouped, nextByte)\n\t\t\t\tfilledBits = 0\n\t\t\t\tnextByte = 0\n\t\t\t}\n\t\t}\n\t}\n\n\t// We pad any unfinished group if specified.\n\tif pad && filledBits > 0 {\n\t\tnextByte <<= toBits - filledBits\n\t\tregrouped = append(regrouped, nextByte)\n\t\tfilledBits = 0\n\t\tnextByte = 0\n\t}\n\n\t// Any incomplete group must be <= 4 bits, and all zeroes.\n\tif filledBits > 0 && (filledBits > 4 || nextByte != 0) {\n\t\treturn nil, ErrInvalidIncompleteGroup{}\n\t}\n\n\treturn regrouped, nil\n}",
"func (b Bits) Set(n int) Bits {\n\treturn b | (1 << uint64(n))\n}",
"func powers(base int, limit int, f func(int)) {\n if base == 1 {\n f(base)\n } else {\n for i := 1; i <= limit; i *= base {\n f(i)\n }\n }\t\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewKafkaProducer returns a new writer for writing messages to a given topic.
|
func NewKafkaProducer(kafkaAddress, topic string) (*kafka.Writer, error) {
conn, err := kafka.Dial("tcp", kafkaAddress)
if err != nil {
return nil, err
}
err = conn.CreateTopics(kafka.TopicConfig{
Topic: topic,
NumPartitions: 6,
ReplicationFactor: 1,
})
if err != nil {
return nil, err
}
return kafka.NewWriter(kafka.WriterConfig{
Brokers: []string{kafkaAddress},
Topic: topic,
Balancer: &kafka.LeastBytes{},
RequiredAcks: 1,
CompressionCodec: &compress.SnappyCodec,
}), nil
}
|
[
"func newKafkaProducer() *kafka.Writer {\n\treturn &kafka.Writer{\n\t\tAddr: kafka.TCP(kafkaAddr),\n\t\tTopic: topic,\n\t\tBalancer: &kafka.LeastBytes{},\n\t}\n}",
"func NewProducer(brokers string) *kafkago.Writer {\n\treturn kafkago.NewWriter(kafkago.WriterConfig{\n\t\tBrokers: []string{brokers},\n\t\tTopic: viper.GetString(\"kafka.topic\"),\n\t\tBalancer: &kafkago.Hash{},\n\t\tBatchTimeout: time.Duration(100) * time.Millisecond,\n\t\tQueueCapacity: 10000,\n\t\tBatchSize: 1000000,\n\t\t// Async doesn't allow us to know if message has been successfully sent to Kafka.\n\t\t// Async: true,\n\t})\n}",
"func NewWriter(topicName string) *kafka.Writer {\r\n\tbrokerUrls := Config.GetStringSlice(\"kafka.producer.brokerUrls\")\r\n\tw := kafka.NewWriter(kafka.WriterConfig{\r\n\t\tBrokers: brokerUrls,\r\n\t\tTopic: topicName,\r\n\t\tBalancer: &kafka.LeastBytes{},\r\n\t\tDialer: dialer,\r\n\t})\r\n\treturn w\r\n}",
"func NewKafkaWriter(kwc *KWConfig) (*kafka.Producer, error) {\n\tproducer, err := kafka.NewProducer(&kafka.ConfigMap{\n\t\t\"bootstrap.servers\": kwc.Broker,\n\t\t\"compression.codec\": kwc.Compression,\n\t\t\"batch.num.messages\": kwc.BatchMsgNum,\n\t\t\"go.batch.producer\": true,\n\t\t\"go.delivery.reports\": false,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn producer, nil\n}",
"func NewProducer(sc *services.Control, conf cfg.Config, _ string, chainID string, eventType EventType) (*Producer, error) {\n\tsock, err := socket.Dial(getSocketName(conf.Producer.IPCRoot, conf.NetworkID, chainID, eventType))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\twriter, err := newBufferedWriter(sc, GetTopicName(conf.NetworkID, chainID, eventType), conf.NetworkID, chainID)\n\tif err != nil {\n\t\t_ = sock.Close()\n\t\treturn nil, err\n\t}\n\n\tp := &Producer{\n\t\tchainID: chainID,\n\t\teventType: eventType,\n\t\twriteBuffer: writer,\n\t\tsc: sc,\n\t\tsock: sock,\n\t\tmetricProcessedCountKey: fmt.Sprintf(\"produce_records_processed_%s_%s\", chainID, eventType),\n\t\tmetricSuccessCountKey: fmt.Sprintf(\"produce_records_success_%s_%s\", chainID, eventType),\n\t\tmetricFailureCountKey: fmt.Sprintf(\"produce_records_failure_%s_%s\", chainID, eventType),\n\t\tid: fmt.Sprintf(\"producer %d %s %s\", conf.NetworkID, chainID, eventType),\n\t}\n\tmetrics.Prometheus.CounterInit(p.metricProcessedCountKey, \"records processed\")\n\tmetrics.Prometheus.CounterInit(p.metricSuccessCountKey, \"records success\")\n\tmetrics.Prometheus.CounterInit(p.metricFailureCountKey, \"records failure\")\n\tsc.InitProduceMetrics()\n\n\treturn p, nil\n}",
"func NewProducer(bootstrapServer string) (*Producer, error) {\n\tproducer, err := kafka.NewProducer(&kafka.ConfigMap{\n\t\t\"bootstrap.servers\": bootstrapServer,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Producer{producer}, nil\n}",
"func New(ctx context.Context, cfg config.Producer, lg *zap.Logger, inChan telemetry.ExtDSChan) producer.Producer {\n\n\treturn &Kafka{\n\t\tctx: ctx,\n\t\tcfg: cfg,\n\t\tch: inChan,\n\t\tlogger: lg,\n\t}\n}",
"func NewKafkaProducer(topic string, brokerList []string, config *sarama.ProducerConfig) *KafkaProducer {\n\tclient, err := sarama.NewClient(uuid.New(), brokerList, sarama.NewClientConfig())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tproducer, err := sarama.NewProducer(client, config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &KafkaProducer{topic, brokerList, client, producer}\n}",
"func NewWriter(brokerURLs []string, topicName string) *kafka.Writer {\n\tw := kafka.NewWriter(kafka.WriterConfig{\n\t\tBrokers: brokerURLs,\n\t\tTopic: topicName,\n\t\tBalancer: &kafka.LeastBytes{},\n\t\tDialer: dialer,\n\t})\n\treturn w\n}",
"func GetProducer(bootstrapServers string, topic string, batchSize int, acks int, ssl bool) *kafka.Writer {\n\n\tdialer := kafkadialer.GetDialer(ssl)\n\n\treturn kafka.NewWriter(kafka.WriterConfig{\n\t\tBrokers: strings.Split(bootstrapServers, \",\"),\n\t\tTopic: topic,\n\t\tBalancer: &kafka.LeastBytes{},\n\t\tBatchSize: batchSize,\n\t\tBatchTimeout: 2 * time.Second,\n\t\t// Balancer: &kafka.Hash{},\n\t\tRequiredAcks: acks,\n\t\tDialer: &dialer,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tReadTimeout: 10 * time.Second,\n\t})\n\n}",
"func NewKafka(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {\n\tk, err := writer.NewKafka(conf.Kafka, log, stats)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar w Type\n\tif conf.Kafka.MaxInFlight == 1 {\n\t\tw, err = NewWriter(\n\t\t\tTypeKafka, k, log, stats,\n\t\t)\n\t} else {\n\t\tw, err = NewAsyncWriter(\n\t\t\tTypeKafka, conf.Kafka.MaxInFlight, k, log, stats,\n\t\t)\n\t}\n\tif bconf := conf.Kafka.Batching; err == nil && !bconf.IsNoop() {\n\t\tpolicy, err := batch.NewPolicy(bconf, mgr, log.NewModule(\".batching\"), metrics.Namespaced(stats, \"batching\"))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to construct batch policy: %v\", err)\n\t\t}\n\t\tw = NewBatcher(policy, w, log, stats)\n\t}\n\treturn w, err\n}",
"func NewProducer() *Producer {\n\tkingpin.Parse()\n\tconf := sarama.NewConfig()\n\tconf.Producer.RequiredAcks = sarama.WaitForLocal //i have no replicas so wait for all is good\n\tconf.Producer.Retry.Max = *maxRetry\n\tconf.Producer.Return.Successes = true\n\n\tprod, err := sarama.NewSyncProducer(*brokerList, conf)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &Producer{\n\t\tprod,\n\t\t*topic,\n\t}\n}",
"func (k *Kafka) NewTopic() string {\n\tif k.admin == nil {\n\t\tpanic(\"cannot create topic with closed kafkatest.Kafka instance\")\n\t}\n\ttopic := randomName(\"kafkatest-\")\n\tif err := k.admin.CreateTopic(topic, &sarama.TopicDetail{\n\t\tNumPartitions: 1,\n\t\tReplicationFactor: 1,\n\t}, false); err != nil {\n\t\tpanic(fmt.Errorf(\"cannot create topic %q: %v\", topic, err))\n\t}\n\tk.topics = append(k.topics, topic)\n\treturn topic\n}",
"func NewKafkaBEWriter(brokers []string, config *sarama.Config, topic string) (WriteCloser, error) {\n\tif config == nil {\n\t\tconfig = sarama.NewConfig()\n\t}\n\n\tproducer, err := sarama.NewSyncProducer(brokers, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &KafkaBEWriter{\n\t\t\tproducer: producer,\n\t\t\ttopic: topic,\n\t\t},\n\t\tnil\n}",
"func New_kafka_producer(brokers []string) (sarama.SyncProducer, error) {\n\tif len(brokers) == 0 {\n\t\terr := errors.New(\"Invalid broker information provided\")\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tlog.Infof(\"RequestProcessor: new_kafka_producer: start\")\n\tconfig := sarama.NewConfig()\n\tconfig.Producer.RequiredAcks = sarama.WaitForAll\n\tconfig.Producer.Retry.Max = 10\n\tlog.Infof(\"Producer Config: %v\\n\", config)\n\tproducer, err := sarama.NewSyncProducer(brokers, config)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to start Sarama producer: %s\", err)\n\t\treturn nil, err\n\t}\n\tlog.Infof(\"RequestProcessor: new_kafka_producer: end\")\n\treturn producer, nil\n}",
"func GetKafkaWriter(kafkaBrokerUrls []string, clientID string, topic string) *kafka.Writer {\n\tdialer := &kafka.Dialer{\n\t\tTimeout: 10 * time.Second,\n\t\tClientID: clientID,\n\t}\n\n\tconfig := kafka.WriterConfig{\n\t\tBrokers: kafkaBrokerUrls,\n\t\tTopic: topic,\n\t\tBalancer: &kafka.LeastBytes{},\n\t\tDialer: dialer,\n\t\tWriteTimeout: 1 * time.Second,\n\t\tReadTimeout: 1 * time.Second,\n\t\tBatchSize: 20,\n\t\tBatchTimeout: 50 * time.Millisecond,\n\t\tAsync: true,\n\t}\n\treturn kafka.NewWriter(config)\n}",
"func KafkaWriter(topicName string) *kafka.Writer {\n\n\tif topicName == \"\" {\n\t\tlog.Println(\"KafkaWriter's topicName cannot be empty\")\n\t\treturn nil\n\t}\n\n\tif len(kafkaWriterOnce) == 0 {\n\t\tkafkaWriterOnce = make(map[string]bool, 15)\n\t\tkafkaWriterConnections = make(map[string]*kafka.Writer, 15)\n\t}\n\n\tkafkaWriterOnceMutex.Lock()\n\tif !kafkaWriterOnce[topicName] {\n\t\tkafkaWriterOnce[topicName] = true\n\n\t\tkkConnection := kafka.NewWriter(kafka.WriterConfig{\n\t\t\tBrokers: allKafkaWriterSettings[topicName].Brokers,\n\t\t\tTopic: allKafkaWriterSettings[topicName].Topic,\n\t\t\tBalancer: &kafka.LeastBytes{},\n\t\t\tBatchTimeout: 10 * time.Millisecond,\n\t\t})\n\t\tkafkaWriterConnections[topicName] = kkConnection\n\t\tkafkaWriterOnceMutex.Unlock()\n\t} else {\n\t\tkafkaWriterOnceMutex.Unlock()\n\t}\n\treturn kafkaWriterConnections[topicName]\n}",
"func newKafkaLogger(\n\tappName string,\n\tcfg *config.KafkaConfig,\n) (*KafkaLogger, error) {\n\t// Create Kafka Producer\n\tproducer, err := newKafkaProducer(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Test that we are able to query the broker on the topic. If the topic\n\t// does not already exist on the broker, this should create it.\n\t_, err = producer.GetMetadata(&cfg.Topic, false, kafkaConnectTimeoutMs)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err,\n\t\t\t\"Error Querying topic %s from Kafka broker(s)\", cfg.Topic)\n\t}\n\t// Create Kafka Logger\n\treturn &KafkaLogger{\n\t\tappName: appName,\n\t\ttopic: cfg.Topic,\n\t\tproducer: producer,\n\t}, nil\n}",
"func NewProducer() *MessageProducer {\n\treturn &MessageProducer{\n\t\tFormatter: DefaultFormatter,\n\t\tStringFormat: DefaultStringFormat,\n\t\tExtraCalldepth: 0,\n\t\tDefaultLevel: LevelDebug,\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
UnmarshalJSON unmarshall implementation for Country
|
func (country *Country) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
_, err := ByCountryStrErr(str)
if err != nil {
return err
}
*country = Country(str)
return nil
}
|
[
"func (s *ServiceCountry) 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 \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &s.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &s.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &s.Type)\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 (a *Meta_Country) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}",
"func (a *AvailableProvidersListCountry) 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\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"countryName\":\n\t\t\terr = unpopulate(val, \"CountryName\", &a.CountryName)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"providers\":\n\t\t\terr = unpopulate(val, \"Providers\", &a.Providers)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"states\":\n\t\t\terr = unpopulate(val, \"States\", &a.States)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (s *ServiceCountryListResult) 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 \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &s.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &s.Value)\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 (a *Meta_CaProvince) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}",
"func fetchCountryJSON(url string) ([]Country, error) {\n\tresp, err := http.Get(url)\t\t\t\t\t\t\t\t// GETs url\n\tif err != nil {\t\t\t\t\t\t\t\t\t\t\t\t\t\t// If it doesnt work, return error\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\tvar countryList []Country\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\trespByte := buf.Bytes()\t\t\t\t\t\t\t\t\t\t// Copy COuntry information\n\tif err := json.Unmarshal(respByte, &countryList); err != nil {\n\t\treturn nil, err\t\t\t\t\t\t\t\t\t\t\t\t\t// Return error if it fails\n\t}\n\n\treturn countryList, nil\t\t\t\t\t\t\t\t\t\t// return array of countries\n}",
"func JsonCountries() (*CountryList, error) {\n\tvar countryList CountryList\n\terr := json.Unmarshal([]byte(countries), &countryList)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &countryList, err\n}",
"func (l *JSONTimezone) UnmarshalJSON(b []byte) error {\n\t// you can now parse b as thoroughly as you want\n\tzoneString, _ := strconv.Unquote(string(b))\n\tloc, err := time.LoadLocation(zoneString)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Location = loc\n\treturn nil\n}",
"func (j *Visit) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}",
"func (s ServiceCountry) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"name\", s.Name)\n\tpopulate(objectMap, \"type\", s.Type)\n\treturn json.Marshal(objectMap)\n}",
"func (x *LocationSource) UnmarshalJSON(b []byte) error {\n\treturn jsonplugin.DefaultUnmarshalerConfig.Unmarshal(b, x)\n}",
"func (p *Place) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"address\":\n\t\t\tif v != nil {\n\t\t\t\tvar address PostalAddress\n\t\t\t\terr = json.Unmarshal(*v, &address)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.Address = &address\n\t\t\t}\n\t\tcase \"telephone\":\n\t\t\tif v != nil {\n\t\t\t\tvar telephone string\n\t\t\t\terr = json.Unmarshal(*v, &telephone)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.Telephone = &telephone\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.Name = &name\n\t\t\t}\n\t\tcase \"url\":\n\t\t\tif v != nil {\n\t\t\t\tvar URL string\n\t\t\t\terr = json.Unmarshal(*v, &URL)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.URL = &URL\n\t\t\t}\n\t\tcase \"image\":\n\t\t\tif v != nil {\n\t\t\t\tvar imageVar ImageObject\n\t\t\t\terr = json.Unmarshal(*v, &imageVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.Image = &imageVar\n\t\t\t}\n\t\tcase \"description\":\n\t\t\tif v != nil {\n\t\t\t\tvar description string\n\t\t\t\terr = json.Unmarshal(*v, &description)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.Description = &description\n\t\t\t}\n\t\tcase \"entityPresentationInfo\":\n\t\t\tif v != nil {\n\t\t\t\tvar entityPresentationInfo EntitiesEntityPresentationInfo\n\t\t\t\terr = json.Unmarshal(*v, &entityPresentationInfo)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.EntityPresentationInfo = &entityPresentationInfo\n\t\t\t}\n\t\tcase \"bingId\":\n\t\t\tif v != nil {\n\t\t\t\tvar bingID string\n\t\t\t\terr = json.Unmarshal(*v, &bingID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.BingID = &bingID\n\t\t\t}\n\t\tcase \"contractualRules\":\n\t\t\tif v != nil {\n\t\t\t\tcontractualRules, err := unmarshalBasicContractualRulesContractualRuleArray(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.ContractualRules = &contractualRules\n\t\t\t}\n\t\tcase \"webSearchUrl\":\n\t\t\tif v != nil {\n\t\t\t\tvar webSearchURL string\n\t\t\t\terr = json.Unmarshal(*v, &webSearchURL)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.WebSearchURL = &webSearchURL\n\t\t\t}\n\t\tcase \"id\":\n\t\t\tif v != nil {\n\t\t\t\tvar ID string\n\t\t\t\terr = json.Unmarshal(*v, &ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.ID = &ID\n\t\t\t}\n\t\tcase \"_type\":\n\t\t\tif v != nil {\n\t\t\t\tvar typeVar TypeBasicResponseBase\n\t\t\t\terr = json.Unmarshal(*v, &typeVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.Type = typeVar\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (a *AvailableProvidersList) 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\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"countries\":\n\t\t\terr = unpopulate(val, \"Countries\", &a.Countries)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func JSONUnmarshal(um JSONUnmarshaller) OptionFunc {\n\tif um == nil {\n\t\tum = NewJSONDecoder()\n\t}\n\treturn func(c *Currency) OptionFunc {\n\t\tprevious := c.jum\n\t\tc.jum = um\n\t\treturn JSONUnmarshal(previous)\n\t}\n}",
"func (f *FunctionSelector) UnmarshalJSON(input []byte) error {\n\tvar s string\n\terr := json.Unmarshal(input, &s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn unmarshalFromString(s, f)\n}",
"func readCountries() {\n\tif countries != nil {\n\t\treturn\n\t}\n\tcountryFile, _ := ioutil.ReadFile(\"data/countries.json\")\n\tjson.Unmarshal(countryFile, &countries)\n}",
"func (f *Feature) UnmarshalJSON(data []byte) error {\n\tif f.Feature == nil {\n\t\tf.Feature = &featurepb.Feature{}\n\t}\n\n\tm := jsonpb.Unmarshaler{}\n\tif err := m.Unmarshal(bytes.NewBuffer(data), f.Feature); err != nil {\n\t\treturn err\n\t}\n\n\tif f.Type == featurepb.Feature_EXPRESSION {\n\t\treturn f.parseExpression()\n\t}\n\n\treturn nil\n}",
"func (d UserData) UnsetCountry() m.UserData {\n\td.ModelData.Unset(models.NewFieldName(\"Country\", \"country_id\"))\n\treturn d\n}",
"func (this *Subset) UnmarshalJSON(b []byte) error {\n\treturn DestinationRuleUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
IsSet indicates if Country is set
|
func (country Country) IsSet() bool {
return len(string(country)) > 0
}
|
[
"func (me *TSupplierCountry) Set(s string) { (*xsdt.String)(me).Set(s) }",
"func (a *Meta_Country) Set(fieldName string, value interface{}) {\n\tif a.AdditionalProperties == nil {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t}\n\ta.AdditionalProperties[fieldName] = value\n}",
"func (me *TCountryCodeType) Set(s string) { (*xsdt.String)(me).Set(s) }",
"func (s UserSet) Country() m.CountrySet {\n\tres, _ := s.RecordCollection.Get(models.NewFieldName(\"Country\", \"country_id\")).(models.RecordSet).Collection().Wrap(\"Country\").(m.CountrySet)\n\treturn res\n}",
"func (m *CountryNamedLocation) SetIncludeUnknownCountriesAndRegions(value *bool)() {\n err := m.GetBackingStore().Set(\"includeUnknownCountriesAndRegions\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (currency Currency) IsSet() bool {\n\treturn len(string(currency)) > 0\n}",
"func (s UserSet) SetCountry(value m.CountrySet) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Country\", \"country_id\"), value)\n}",
"func (d UserData) HasCountry() bool {\n\treturn d.ModelData.Has(models.NewFieldName(\"Country\", \"country_id\"))\n}",
"func (o OptDate) IsSet() bool { return o.Set }",
"func (t *VSDbl) IsSet() bool {\n\treturn true\n}",
"func (o *BillingAddress) HasCountry() bool {\n\tif o != nil && o.Country != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (o *User) HasCountry() bool {\n\tif o != nil && o.Country != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (a *Account) IsSet(name string) bool {\n\t_, ok := a.fields[name]\n\treturn ok\n}",
"func (d UserData) SetCountry(value m.CountrySet) m.UserData {\n\td.ModelData.Set(models.NewFieldName(\"Country\", \"country_id\"), value)\n\treturn d\n}",
"func (m *CountryNamedLocation) SetCountriesAndRegions(value []string)() {\n err := m.GetBackingStore().Set(\"countriesAndRegions\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *VppToken) SetCountryOrRegion(value *string)() {\n m.countryOrRegion = value\n}",
"func (o OptInt) IsSet() bool { return o.Set }",
"func (o OptString) IsSet() bool { return o.Set }",
"func (m *PrinterLocation) SetCountryOrRegion(value *string)() {\n err := m.GetBackingStore().Set(\"countryOrRegion\", value)\n if err != nil {\n panic(err)\n }\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
IsCountryIn Checks there is a country in Countries
|
func (countries Countries) IsCountryIn(country string) bool {
for _, c := range countries {
if string(c) == country {
return true
}
}
return false
}
|
[
"func isCountry(str string) bool {\n\tfor _, entry := range govalidator.ISO3166List {\n\t\tif str == entry.EnglishShortName {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}",
"func CountryIn(vs ...string) predicate.Location {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Location(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(FieldCountry), v...))\n\t})\n}",
"func checkCountry(iso string, whitelist []string) bool {\n\twhitelisted := false\n\tfor i := 0; i < len(whitelist); i++ {\n\t\tif iso == whitelist[i] {\n\t\t\twhitelisted = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn whitelisted\n}",
"func (g *GeoIP2) HasCountry() (bool, error) {\n\tr, err := g.get(countryDB, \"\")\n\tif r != nil && err == nil {\n\t\treturn true, nil\n\t}\n\treturn false, err\n}",
"func (o *UserDisco) HasCountryCallingCode() bool {\n\tif o != nil && o.CountryCallingCode != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func hasValidCountryCallingCode(countryCallingCode int) bool {\n\t_, containsKey := countryCodeToRegion[countryCallingCode]\n\treturn containsKey\n}",
"func (n *Nexmo) IsSupportCountry(toCountry string) bool {\n\treturn n.countryCodeMap.exist(toCountry)\n}",
"func CountryContains(v string) predicate.Location {\n\treturn predicate.Location(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldCountry), v))\n\t})\n}",
"func (m SecurityListRequest) HasCountryOfIssue() bool {\n\treturn m.Has(tag.CountryOfIssue)\n}",
"func (o *User) HasCountry() bool {\n\tif o != nil && o.Country != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (d UserData) HasCountry() bool {\n\treturn d.ModelData.Has(models.NewFieldName(\"Country\", \"country_id\"))\n}",
"func (me TisoLanguageCodes) IsIn() bool { return me.String() == \"IN\" }",
"func addressIn(location map[string]interface{}, country string) bool {\n\tprops, ok := location[\"props\"]\n\tif !ok {\n\t\treturn false\n\t}\n\n\tc, ok := (props.(map[string]interface{}))[\"country\"]\n\tif !ok {\n\t\treturn false\n\t}\n\n\tif c == country {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func CountryContainsFold(v string) predicate.Location {\n\treturn predicate.Location(func(s *sql.Selector) {\n\t\ts.Where(sql.ContainsFold(s.C(FieldCountry), v))\n\t})\n}",
"func (m *Photo) HasCountry() bool {\n\treturn !m.UnknownCountry()\n}",
"func (o *BillingAddress) HasCountry() bool {\n\tif o != nil && o.Country != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (r Locale_Country) IsEuropeanUnionCountry(iso2CountryCode *string) (resp bool, err error) {\n\tparams := []interface{}{\n\t\tiso2CountryCode,\n\t}\n\terr = r.Session.DoRequest(\"SoftLayer_Locale_Country\", \"isEuropeanUnionCountry\", params, &r.Options, &resp)\n\treturn\n}",
"func ByCountry(country Country) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country.String()]\n\treturn\n}",
"func (o *Host) HasCountryCode() bool {\n\tif o != nil && o.CountryCode != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
UnmarshalJSON unmarshall implementation for Currency
|
func (currency *Currency) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
currencyValue, err := ByCurrencyStrErr(str)
if err != nil {
return err
}
*currency = currencyValue.Currency()
return nil
}
|
[
"func (a *Amount) UnmarshalJSON(data []byte) error {\n\tvar n json.Number\n\terr := json.Unmarshal(data, &n)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstr := string(n)\n\tif !matchNumber.MatchString(str) {\n\t\treturn fmt.Errorf(\"not a regular decimal number: %s\", str)\n\t}\n\tif strings.ContainsRune(str, '.') {\n\t\tstr, _ = util.DecimalToSatoshis(str)\n\t}\n\t*a = Amount(str)\n\treturn nil\n}",
"func (a *Amount) 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\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"currency\":\n\t\t\terr = unpopulate(val, \"Currency\", &a.Currency)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (a *Amount) UnmarshalJSON(data []byte) error {\n\tv, err := decimal.NewFromString(string(data))\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Decimal = v\n\treturn nil\n}",
"func JSONUnmarshal(um JSONUnmarshaller) OptionFunc {\n\tif um == nil {\n\t\tum = NewJSONDecoder()\n\t}\n\treturn func(c *Currency) OptionFunc {\n\t\tprevious := c.jum\n\t\tc.jum = um\n\t\treturn JSONUnmarshal(previous)\n\t}\n}",
"func (m *MonetaryCredit) 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\", m, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"Credit\":\n\t\t\terr = unpopulate(val, \"Credit\", &m.Credit)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"EffectiveDate\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"EffectiveDate\", &m.EffectiveDate)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"ExcludedMeterIds\":\n\t\t\terr = unpopulate(val, \"ExcludedMeterIDs\", &m.ExcludedMeterIDs)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"Name\":\n\t\t\terr = unpopulate(val, \"Name\", &m.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", m, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (cs *CurrenciesSparklineResponse) UnmarshalJSON(data []byte) error {\n\ttemp := struct {\n\t\tCurrency string `json:\"currency\"`\n\t\tTimestamps []time.Time `json:\"timestamps\"`\n\t\tPrices []string `json:\"prices\"`\n\t}{}\n\tif err := json.Unmarshal(data, &temp); err != nil {\n\t\treturn err\n\t}\n\tcs.Currency = temp.Currency\n\tcs.Timestamps = temp.Timestamps\n\tfor _, v := range temp.Prices {\n\t\tif price, err := strconv.ParseFloat(v, 64); err == nil {\n\t\t\tcs.Prices = append(cs.Prices, price)\n\t\t}\n\t}\n\treturn nil\n}",
"func (b *BalanceV1) UnmarshalJSON(text []byte) error {\n\ttype RawBalance map[envelopes.AssetType]json.Number\n\n\tunmarshaled := RawBalance{}\n\n\tdec := json.NewDecoder(bytes.NewReader(text))\n\terr := dec.Decode(&unmarshaled)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tretval := make(BalanceV1, len(unmarshaled))\n\t*b = retval\n\n\tfor k, v := range unmarshaled {\n\t\tvar parsed *big.Rat\n\t\tparsed, err = parseRatV1(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tretval[k] = parsed\n\t}\n\treturn nil\n}",
"func (bal *Balances) UnmarshalJSON(b []byte) error {\n\tvar br struct {\n\t\t*balances `json:\"balances,omitempty\"`\n\t}\n\tbalObj := balances{}\n\tvar err error\n\n\t// If wrapped\n\tif err = json.Unmarshal(b, &br); err == nil {\n\t\tif br.balances != nil {\n\t\t\t*bal = Balances(*br.balances)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// If not wrapped in anything\n\tif err = json.Unmarshal(b, &balObj); err == nil {\n\t\t*bal = Balances(balObj)\n\t\treturn nil\n\t}\n\n\treturn err\n}",
"func (c *Charge) UnmarshalJSON(data []byte) error {\n\ttype charge Charge\n\tvar cc charge\n\terr := json.Unmarshal(data, &cc)\n\tif err == nil {\n\t\t*c = Charge(cc)\n\t} else {\n\t\t// the id is surrounded by \"\\\" characters, so strip them\n\t\tc.ID = string(data[1 : len(data)-1])\n\t}\n\n\treturn nil\n}",
"func (b *Balance) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar balanceProperties BalanceProperties\n\t\t\t\terr = json.Unmarshal(*v, &balanceProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tb.BalanceProperties = &balanceProperties\n\t\t\t}\n\t\tcase \"id\":\n\t\t\tif v != nil {\n\t\t\t\tvar ID string\n\t\t\t\terr = json.Unmarshal(*v, &ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tb.ID = &ID\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tb.Name = &name\n\t\t\t}\n\t\tcase \"type\":\n\t\t\tif v != nil {\n\t\t\t\tvar typeVar string\n\t\t\t\terr = json.Unmarshal(*v, &typeVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tb.Type = &typeVar\n\t\t\t}\n\t\tcase \"tags\":\n\t\t\tif v != nil {\n\t\t\t\tvar tags map[string]*string\n\t\t\t\terr = json.Unmarshal(*v, &tags)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tb.Tags = tags\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func getTransaction(inputDecoder *json.Decoder, t *Transaction) (bool, error) {\n type JsonTransaction struct {\n Id string `json:\"id\"`\n Customer_id string `json:\"customer_id\"`\n Load_amount string `json:\"load_amount\"`\n Time time.Time `json:\"time\"`\n }\n var jt JsonTransaction\n\n decodeErr := inputDecoder.Decode(&jt)\n if decodeErr != nil {\n if decodeErr == io.EOF {\n return true, nil\n } else {\n return false, decodeErr\n }\n }\n t.Id = jt.Id\n t.Customer_id = jt.Customer_id\n\n // Decode string to cents.\n amountMatch := amountRe.FindStringSubmatch(jt.Load_amount)\n if len(amountMatch) != 3 {\n return false, fmt.Errorf(\n \"Amount not a valid \\\"$dollar.cents\\\" string: %v\", jt.Load_amount)\n }\n\n // 2 digits for cents is about 7 bits, so allow no more than 64-7 = 57 bits\n // for dollars.\n amountDollars, dollarsErr := strconv.ParseInt(amountMatch[1], 10, 57)\n if dollarsErr != nil {\n return false, dollarsErr\n }\n // The regex ensures this is 2 decimal digits, so parse will succeed,\n // error can be ignored.\n amountCents, _ := strconv.ParseInt(amountMatch[2], 10, 7)\n\n t.Load_amount_cents = (amountDollars * 100) + amountCents\n t.Time = jt.Time\n\n return false, nil\n}",
"func (s *SKUCost) 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 \"extendedUnit\":\n\t\t\terr = unpopulate(val, \"ExtendedUnit\", &s.ExtendedUnit)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"meterId\":\n\t\t\terr = unpopulate(val, \"MeterID\", &s.MeterID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"quantity\":\n\t\t\terr = unpopulate(val, \"Quantity\", &s.Quantity)\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 (code *Code) UnmarshalJSON(data []byte) error {\n\tvar str string\n\tif err := json.Unmarshal(data, &str); err != nil {\n\t\treturn err\n\t}\n\n\tcurrency, err := ByCodeStrErr(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*code = currency.Code()\n\n\treturn nil\n}",
"func (c *ContractIndexData) UnmarshalJSON(b []byte) (err error) {\n\tvar resp []map[string]interface{}\n\n\tif err := json.Unmarshal(b, &resp); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling: %v\", err)\n\t}\n\n\tc.Symbol = resp[0][\"symbol\"].(string)\n\tc.Price = resp[0][\"index_price\"].(float64)\n\tc.Ts = int(resp[0][\"index_ts\"].(float64))\n\n\treturn\n}",
"func (rrci *ResourceRateCardInfo) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"Currency\":\n\t\t\tif v != nil {\n\t\t\t\tvar currency string\n\t\t\t\terr = json.Unmarshal(*v, ¤cy)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\trrci.Currency = ¤cy\n\t\t\t}\n\t\tcase \"Locale\":\n\t\t\tif v != nil {\n\t\t\t\tvar locale string\n\t\t\t\terr = json.Unmarshal(*v, &locale)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\trrci.Locale = &locale\n\t\t\t}\n\t\tcase \"IsTaxIncluded\":\n\t\t\tif v != nil {\n\t\t\t\tvar isTaxIncluded bool\n\t\t\t\terr = json.Unmarshal(*v, &isTaxIncluded)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\trrci.IsTaxIncluded = &isTaxIncluded\n\t\t\t}\n\t\tcase \"OfferTerms\":\n\t\t\tif v != nil {\n\t\t\t\tofferTerms, err := unmarshalBasicOfferTermInfoArray(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\trrci.OfferTerms = &offerTerms\n\t\t\t}\n\t\tcase \"Meters\":\n\t\t\tif v != nil {\n\t\t\t\tvar meters []MeterInfo\n\t\t\t\terr = json.Unmarshal(*v, &meters)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\trrci.Meters = &meters\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (c *CouponItem) UnmarshalJSON(data []byte) error {\n\tif data == nil || len(data) == 0 {\n\t\treturn nil\n\t}\n\n\tvar objmap map[string]json.RawMessage\n\terr := json.Unmarshal(data, &objmap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, ok := objmap[\"id\"]\n\tif ok {\n\t\terr = json.Unmarshal(objmap[\"id\"], &c.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, ok = objmap[\"code\"]\n\tif ok {\n\t\terr = json.Unmarshal(objmap[\"code\"], &c.Code)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, ok = objmap[\"meta_data\"]\n\tif ok {\n\t\tc.Metadata, err = tryMarshalMetadata(objmap[\"meta_data\"])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, ok = objmap[\"discount\"]\n\tif ok {\n\t\terr = json.Unmarshal(objmap[\"discount\"], &c.Discount)\n\t\tif err != nil {\n\t\t\tc.Discount, err = tryMarshalStringAsFloat64(objmap[\"discount\"])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t_, ok = objmap[\"discount_tax\"]\n\tif ok {\n\t\terr = json.Unmarshal(objmap[\"discount_tax\"], &c.DiscountTax)\n\t\tif err != nil {\n\t\t\tc.DiscountTax, err = tryMarshalStringAsFloat64(objmap[\"discount_tax\"])\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 (u *CreditCard) UnmarshalJSON(data []byte) error {\n\tif string(data) == jsonNull {\n\t\treturn nil\n\t}\n\tvar ustr string\n\tif err := json.Unmarshal(data, &ustr); err != nil {\n\t\treturn err\n\t}\n\t*u = CreditCard(ustr)\n\treturn nil\n}",
"func (t *TaxRate) UnmarshalJSON(data []byte) error {\n\tif id, ok := ParseID(data); ok {\n\t\tt.ID = id\n\t\treturn nil\n\t}\n\n\ttype taxRate TaxRate\n\tvar v taxRate\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\n\t*t = TaxRate(v)\n\treturn nil\n}",
"func (bn *BlockNumber) UnmarshalJSON(data []byte) error {\ninput := strings.TrimSpace(string(data))\nif len(input) >= 2 && input[0] == '\"' && input[len(input)-1] == '\"' {\ninput = input[1 : len(input)-1]\n}\n\nswitch input {\ncase \"earliest\":\n*bn = EarliestBlockNumber\nreturn nil\ncase \"latest\":\n*bn = LatestBlockNumber\nreturn nil\ncase \"pending\":\n*bn = PendingBlockNumber\nreturn nil\n}\n\nblckNum, err := hexutil.DecodeUint64(input)\nif err != nil {\nreturn err\n}\nif blckNum > math.MaxInt64 {\nreturn fmt.Errorf(\"Blocknumber too high\")\n}\n\n*bn = BlockNumber(blckNum)\nreturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
IsSet indicates if Currency is set
|
func (currency Currency) IsSet() bool {
return len(string(currency)) > 0
}
|
[
"func (m NoSides) HasSettlCurrency() bool {\n\treturn m.Has(tag.SettlCurrency)\n}",
"func (country Country) IsSet() bool {\n\treturn len(string(country)) > 0\n}",
"func (t *VSDbl) IsSet() bool {\n\treturn true\n}",
"func setCurrencyFlag(f *flag.FlagSet, optional bool) *currencyFlag {\n\tc := currencyFlag{\n\t\toptional: optional,\n\t}\n\tdescription := \"Expense currency\"\n\tf.Var(&c, \"currency\", description)\n\tf.Var(&c, \"c\", description)\n\treturn &c\n}",
"func (t *VSStr) IsSet() bool {\n\treturn true\n}",
"func (m NewOrderList) HasSettlCurrency() bool {\n\treturn m.Has(tag.SettlCurrency)\n}",
"func (p *Parameters) IsSet(param string) bool {\n\tif _, ok := p.applied[param]; ok {\n\t\treturn true\n\t}\n\treturn false\n}",
"func (o OptDate) IsSet() bool { return o.Set }",
"func (o OptFloat64) IsSet() bool { return o.Set }",
"func (a *Account) IsSet(name string) bool {\n\t_, ok := a.fields[name]\n\treturn ok\n}",
"func (number Number) IsSet() bool {\n\treturn len(string(number)) > 0\n}",
"func (me *TSAFmonetaryType) Set(s string) { (*xsdt.Decimal)(me).Set(s) }",
"func (o OptInt) IsSet() bool { return o.Set }",
"func IsSet(c1, c2, c3 *Card) bool {\n\treturn PropertyAllSameOrAllDifferent(c1.shape, c2.shape, c3.shape) &&\n\t\tPropertyAllSameOrAllDifferent(c1.number, c2.number, c3.number) &&\n\t\tPropertyAllSameOrAllDifferent(c1.color, c2.color, c3.color) &&\n\t\tPropertyAllSameOrAllDifferent(c1.shading, c2.shading, c3.shading)\n}",
"func (me *TCurrencyCodeType) Set(s string) { (*xsdt.String)(me).Set(s) }",
"func (f ExtensionField) IsSet() bool {\n\treturn f.typ != nil\n}",
"func (c *PreferenceInfo) IsSet(parameter string) bool {\n\treturn util.IsSet(c.OdoSettings, parameter)\n}",
"func (o OptString) IsSet() bool { return o.Set }",
"func (ns *VersionNamespace) IsSet() bool {\n\treturn ns.config != nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
UnmarshalJSON unmarshall implementation for Code
|
func (code *Code) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
currency, err := ByCodeStrErr(str)
if err != nil {
return err
}
*code = currency.Code()
return nil
}
|
[
"func (c *Code) UnmarshalJSON(j []byte) error {\n\tvar mp jsonCode\n\tif err := json.Unmarshal(j, &mp); err != nil {\n\t\treturn err\n\t}\n\th := strings.Join(mp.Head, \"\\n\")\n\tb := strings.Join(mp.Body, \"\\n\")\n\tt := strings.Join(mp.Tail, \"\\n\")\n\tif err := c.refresh(h, b, t); err != nil {\n\t\t// TODO: revisit all this\n\t\tlog.Printf(\"Couldn't format or determine channels used: %v\", err)\n\t}\n\tc.imports = mp.Imports\n\tc.pins = mp.Pins\n\treturn nil\n}",
"func (c *Code) UnmarshalJSON(data []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn errCodeNotValid(string(data))\n\t}\n\tc2, err := Parse(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*c = *c2\n\treturn nil\n}",
"func (s ContextSerializationMethods) UnmarshalFromEasyJSONLexer(in *jlexer.Lexer, c *Context) {\n\tunmarshalFromEasyJSONLexer(in, c, false)\n}",
"func (t *TaxCode) UnmarshalJSON(data []byte) error {\n\tif id, ok := ParseID(data); ok {\n\t\tt.ID = id\n\t\treturn nil\n\t}\n\n\ttype taxCode TaxCode\n\tvar v taxCode\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\n\t*t = TaxCode(v)\n\treturn nil\n}",
"func (w *Entry) UnmarshalJSON(bb []byte) error {\n\t<<!!YOUR_CODE!!>>\n}",
"func DecodeInstruction(data []byte) (instruction *Instruction, err error) {\n\terr = json.Unmarshal(data, &instruction)\n\treturn\n}",
"func execmRawMessageUnmarshalJSON(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(*json.RawMessage).UnmarshalJSON(args[1].([]byte))\n\tp.Ret(2, ret)\n}",
"func (assembly *Assembly) UnmarshalJSON(b []byte) error {\n\ttype temp Assembly\n\tvar t struct {\n\t\ttemp\n\t}\n\n\terr := json.Unmarshal(b, &t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*assembly = Assembly(t.temp)\n\n\t// This is a read/write object, so we need to save the raw object data for later\n\tassembly.rawData = b\n\n\treturn nil\n}",
"func generateStructUnmarshalJSON(object *RamlType, discriminatedAttributes []*RamlTypeAttribute) *jen.Statement {\n\tc := jen.Line()\n\tc = c.Comment(\"UnmarshalJSON override to deserialize correct attribute types based \").Line()\n\tc = c.Comment(\"on the discriminator value\").Line()\n\tc = c.Func()\n\n\t// (obj *T)\n\tc = c.Parens(jen.Id(\"obj\").Op(\"*\").Id(object.CodeName))\n\n\t// Function name\n\tc = c.Id(\"UnmarshalJSON\").Params(jen.Id(\"data\").Index().Id(\"byte\"))\n\n\t// Return params\n\tc = c.Parens(jen.Id(\"error\"))\n\n\tc = c.Block(\n\t\tjen.Type().Id(\"Alias\").Id(object.CodeName),\n\t\tjen.If(\n\t\t\tjen.Err().Op(\":=\").Qual(\"encoding/json\", \"Unmarshal\").Call(\n\t\t\t\tjen.Id(\"data\"),\n\t\t\t\tjen.Parens(jen.Op(\"*\").Id(\"Alias\")).Parens(jen.Id(\"obj\")),\n\t\t\t),\n\t\t\tjen.Err().Op(\"!=\").Nil(),\n\t\t).Block(\n\t\t\tjen.Return(jen.Err()),\n\t\t),\n\t\tjen.CustomFunc(jen.Options{}, func(g *jen.Group) {\n\t\t\tfor _, attr := range discriminatedAttributes {\n\t\t\t\tif strings.Contains(attr.CodeName, \"/\") {\n\t\t\t\t\t// Apply on each value in struct\n\t\t\t\t} else if attr.Many {\n\t\t\t\t\t// Process regular many\n\t\t\t\t\tstmt := jen.For(jen.Id(\"i\").Op(\":=\").Range().Id(\"obj\").Dot(attr.CodeName)).Block(\n\t\t\t\t\t\tjen.Var().Err().Error(),\n\t\t\t\t\t\tjen.List(jen.Id(\"obj\").Dot(attr.CodeName).Index(jen.Id(\"i\")), jen.Err()).\n\t\t\t\t\t\t\tOp(\"=\").\n\t\t\t\t\t\t\tId(attr.TypeObject.discriminatorFunctionName()).\n\t\t\t\t\t\t\tCall(\n\t\t\t\t\t\t\t\tjen.Id(\"obj\").Dot(attr.CodeName).Index(jen.Id(\"i\")),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tjen.If(jen.Err().Op(\"!=\").Nil().Block(\n\t\t\t\t\t\t\tjen.Return(jen.Err()),\n\t\t\t\t\t\t)),\n\t\t\t\t\t)\n\t\t\t\t\tg.Add(stmt.Line())\n\n\t\t\t\t} else if attr.TypeObject != nil {\n\t\t\t\t\t// Process regular\n\t\t\t\t\tstmt := jen.If(jen.Id(\"obj\").Dot(attr.CodeName).Op(\"!=\").Nil()).Block(\n\t\t\t\t\t\tjen.Var().Err().Error(),\n\t\t\t\t\t\tjen.List(jen.Id(\"obj\").Dot(attr.CodeName), jen.Err()).\n\t\t\t\t\t\t\tOp(\"=\").\n\t\t\t\t\t\t\tId(attr.TypeObject.discriminatorFunctionName()).\n\t\t\t\t\t\t\tCall(\n\t\t\t\t\t\t\t\tjen.Id(\"obj\").Dot(attr.CodeName),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tjen.If(jen.Err().Op(\"!=\").Nil().Block(\n\t\t\t\t\t\t\tjen.Return(jen.Err()),\n\t\t\t\t\t\t)),\n\t\t\t\t\t)\n\t\t\t\t\tg.Add(stmt.Line())\n\n\t\t\t\t} else if attr.ItemsObject != nil {\n\t\t\t\t\t// Process Array type\n\t\t\t\t\tstmt := jen.For(jen.Id(\"i\").Op(\":=\").Range().Id(\"obj\").Dot(attr.CodeName)).Block(\n\t\t\t\t\t\tjen.Var().Err().Error(),\n\t\t\t\t\t\tjen.List(jen.Id(\"obj\").Dot(attr.CodeName).Index(jen.Id(\"i\")), jen.Err()).\n\t\t\t\t\t\t\tOp(\"=\").\n\t\t\t\t\t\t\tId(attr.ItemsObject.discriminatorFunctionName()).\n\t\t\t\t\t\t\tCall(\n\t\t\t\t\t\t\t\tjen.Id(\"obj\").Dot(attr.CodeName).Index(jen.Id(\"i\")),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tjen.If(jen.Err().Op(\"!=\").Nil().Block(\n\t\t\t\t\t\t\tjen.Return(jen.Err()),\n\t\t\t\t\t\t)),\n\t\t\t\t\t)\n\t\t\t\t\tg.Add(stmt.Line())\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\t\tjen.Return(jen.Nil()),\n\t)\n\n\treturn c\n}",
"func (p *PromotionCode) UnmarshalJSON(data []byte) error {\n\tif id, ok := ParseID(data); ok {\n\t\tp.ID = id\n\t\treturn nil\n\t}\n\n\ttype promotionCode PromotionCode\n\tvar v promotionCode\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\n\t*p = PromotionCode(v)\n\treturn nil\n}",
"func (s ContextSerializationMethods) UnmarshalFromEasyJSONLexerEventOutput(in *jlexer.Lexer, c *EventOutputContext) {\n\tunmarshalFromEasyJSONLexer(in, &c.Context, true)\n}",
"func (j *LuaFunction) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error {\n\tvar err error\n\tcurrentKey := ffjtLuaFunctionbase\n\t_ = currentKey\n\ttok := fflib.FFTok_init\n\twantedTok := fflib.FFTok_init\n\nmainparse:\n\tfor {\n\t\ttok = fs.Scan()\n\t\t//\tprintln(fmt.Sprintf(\"debug: tok: %v state: %v\", tok, state))\n\t\tif tok == fflib.FFTok_error {\n\t\t\tgoto tokerror\n\t\t}\n\n\t\tswitch state {\n\n\t\tcase fflib.FFParse_map_start:\n\t\t\tif tok != fflib.FFTok_left_bracket {\n\t\t\t\twantedTok = fflib.FFTok_left_bracket\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\t\t\tstate = fflib.FFParse_want_key\n\t\t\tcontinue\n\n\t\tcase fflib.FFParse_after_value:\n\t\t\tif tok == fflib.FFTok_comma {\n\t\t\t\tstate = fflib.FFParse_want_key\n\t\t\t} else if tok == fflib.FFTok_right_bracket {\n\t\t\t\tgoto done\n\t\t\t} else {\n\t\t\t\twantedTok = fflib.FFTok_comma\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\n\t\tcase fflib.FFParse_want_key:\n\t\t\t// json {} ended. goto exit. woo.\n\t\t\tif tok == fflib.FFTok_right_bracket {\n\t\t\t\tgoto done\n\t\t\t}\n\t\t\tif tok != fflib.FFTok_string {\n\t\t\t\twantedTok = fflib.FFTok_string\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\n\t\t\tkn := fs.Output.Bytes()\n\t\t\tif len(kn) <= 0 {\n\t\t\t\t// \"\" case. hrm.\n\t\t\t\tcurrentKey = ffjtLuaFunctionnosuchkey\n\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\tgoto mainparse\n\t\t\t} else {\n\t\t\t\tswitch kn[0] {\n\n\t\t\t\tcase 'a':\n\n\t\t\t\t\tif bytes.Equal(ffjKeyLuaFunctionArgList, kn) {\n\t\t\t\t\t\tcurrentKey = ffjtLuaFunctionArgList\n\t\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\t\tgoto mainparse\n\t\t\t\t\t}\n\n\t\t\t\tcase 'i':\n\n\t\t\t\t\tif bytes.Equal(ffjKeyLuaFunctionIsVarArg, kn) {\n\t\t\t\t\t\tcurrentKey = ffjtLuaFunctionIsVarArg\n\t\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\t\tgoto mainparse\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif fflib.EqualFoldRight(ffjKeyLuaFunctionArgList, kn) {\n\t\t\t\t\tcurrentKey = ffjtLuaFunctionArgList\n\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\n\t\t\t\tif fflib.EqualFoldRight(ffjKeyLuaFunctionIsVarArg, kn) {\n\t\t\t\t\tcurrentKey = ffjtLuaFunctionIsVarArg\n\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\n\t\t\t\tcurrentKey = ffjtLuaFunctionnosuchkey\n\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\tgoto mainparse\n\t\t\t}\n\n\t\tcase fflib.FFParse_want_colon:\n\t\t\tif tok != fflib.FFTok_colon {\n\t\t\t\twantedTok = fflib.FFTok_colon\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\t\t\tstate = fflib.FFParse_want_value\n\t\t\tcontinue\n\t\tcase fflib.FFParse_want_value:\n\n\t\t\tif tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null {\n\t\t\t\tswitch currentKey {\n\n\t\t\t\tcase ffjtLuaFunctionIsVarArg:\n\t\t\t\t\tgoto handle_IsVarArg\n\n\t\t\t\tcase ffjtLuaFunctionArgList:\n\t\t\t\t\tgoto handle_ArgList\n\n\t\t\t\tcase ffjtLuaFunctionnosuchkey:\n\t\t\t\t\terr = fs.SkipField(tok)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fs.WrapErr(err)\n\t\t\t\t\t}\n\t\t\t\t\tstate = fflib.FFParse_after_value\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgoto wantedvalue\n\t\t\t}\n\t\t}\n\t}\n\nhandle_IsVarArg:\n\n\t/* handler: j.IsVarArg type=bool kind=bool quoted=false*/\n\n\t{\n\t\tif tok != fflib.FFTok_bool && tok != fflib.FFTok_null {\n\t\t\treturn fs.WrapErr(fmt.Errorf(\"cannot unmarshal %s into Go value for bool\", tok))\n\t\t}\n\t}\n\n\t{\n\t\tif tok == fflib.FFTok_null {\n\n\t\t} else {\n\t\t\ttmpb := fs.Output.Bytes()\n\n\t\t\tif bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 {\n\n\t\t\t\tj.IsVarArg = true\n\n\t\t\t} else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 {\n\n\t\t\t\tj.IsVarArg = false\n\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"unexpected bytes for true/false value\")\n\t\t\t\treturn fs.WrapErr(err)\n\t\t\t}\n\n\t\t}\n\t}\n\n\tstate = fflib.FFParse_after_value\n\tgoto mainparse\n\nhandle_ArgList:\n\n\t/* handler: j.ArgList type=[]string kind=slice quoted=false*/\n\n\t{\n\n\t\t{\n\t\t\tif tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null {\n\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"cannot unmarshal %s into Go value for \", tok))\n\t\t\t}\n\t\t}\n\n\t\tif tok == fflib.FFTok_null {\n\t\t\tj.ArgList = nil\n\t\t} else {\n\n\t\t\tj.ArgList = []string{}\n\n\t\t\twantVal := true\n\n\t\t\tfor {\n\n\t\t\t\tvar tmpJArgList string\n\n\t\t\t\ttok = fs.Scan()\n\t\t\t\tif tok == fflib.FFTok_error {\n\t\t\t\t\tgoto tokerror\n\t\t\t\t}\n\t\t\t\tif tok == fflib.FFTok_right_brace {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif tok == fflib.FFTok_comma {\n\t\t\t\t\tif wantVal == true {\n\t\t\t\t\t\t// TODO(pquerna): this isn't an ideal error message, this handles\n\t\t\t\t\t\t// things like [,,,] as an array value.\n\t\t\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"wanted value token, but got token: %v\", tok))\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\twantVal = true\n\t\t\t\t}\n\n\t\t\t\t/* handler: tmpJArgList type=string kind=string quoted=false*/\n\n\t\t\t\t{\n\n\t\t\t\t\t{\n\t\t\t\t\t\tif tok != fflib.FFTok_string && tok != fflib.FFTok_null {\n\t\t\t\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"cannot unmarshal %s into Go value for string\", tok))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif tok == fflib.FFTok_null {\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\toutBuf := fs.Output.Bytes()\n\n\t\t\t\t\t\ttmpJArgList = string(string(outBuf))\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tj.ArgList = append(j.ArgList, tmpJArgList)\n\n\t\t\t\twantVal = false\n\t\t\t}\n\t\t}\n\t}\n\n\tstate = fflib.FFParse_after_value\n\tgoto mainparse\n\nwantedvalue:\n\treturn fs.WrapErr(fmt.Errorf(\"wanted value token, but got token: %v\", tok))\nwrongtokenerror:\n\treturn fs.WrapErr(fmt.Errorf(\"ffjson: wanted token: %v, but got token: %v output=%s\", wantedTok, tok, fs.Output.String()))\ntokerror:\n\tif fs.BigError != nil {\n\t\treturn fs.WrapErr(fs.BigError)\n\t}\n\terr = fs.Error.ToError()\n\tif err != nil {\n\t\treturn fs.WrapErr(err)\n\t}\n\tpanic(\"ffjson-generated: unreachable, please report bug.\")\ndone:\n\n\treturn nil\n}",
"func Unmarshal(data []byte, typ DataFormat, target interface{}) {\n\tswitch typ {\n\tcase GOB:\n\t\tbuf := bytes.NewReader(data)\n\t\tgob.NewDecoder(buf).Decode(target)\n\n\tdefault:\n\t\tif err := json.Unmarshal(data, target); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}",
"func (d *Decoder) convertCode(out []byte, typeBytePos int) ([]byte, error) {\n\t// Whether code string or code w/scope, need to reserve at least 4 bytes for\n\t// a length, as both start that way.\n\tlengthPos := len(out)\n\tout = append(out, emptyLength...)\n\n\t// Consume ':'\n\terr := d.readNameSeparator()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Consume '\"'\n\terr = d.readQuoteStart()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Make a copy of code cstring to defer writing.\n\tscratchP := d.scratchPool.Get().(*[]byte)\n\tdefer func() { d.scratchPool.Put(scratchP) }()\n\tcodeCString := (*scratchP)[0:0]\n\n\tcodeCString, err = d.convertCString(codeCString)\n\t// Code string could contain null byte because it's represented as\n\t// length-prefixed BSON string.\n\tif err != nil && err != errNullEscape {\n\t\treturn nil, err\n\t}\n\n\t// Look for value separator or object terminator.\n\tch, err := d.readAfterWS()\n\tif err != nil {\n\t\treturn nil, newReadError(err)\n\t}\n\tswitch ch {\n\tcase '}':\n\t\t// Just $code\n\t\toverwriteTypeByte(out, typeBytePos, bsonCode)\n\t\tout = append(out, codeCString...)\n\t\t// BSON code length is CString length, not including length bytes\n\t\tstrLength := len(out) - lengthPos - 4\n\t\toverwriteLength(out, lengthPos, strLength)\n\tcase ',':\n\t\t// Maybe followed by $scope\n\t\terr = d.readQuoteStart()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = d.readSpecificKey(jsonScope)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// We know it's code w/ scope: add additional length bytes for the\n\t\t// Cstring, then convert the scope object.\n\t\toverwriteTypeByte(out, typeBytePos, bsonCodeWithScope)\n\t\tstrLengthPos := len(out)\n\t\tout = append(out, emptyLength...)\n\t\tout = append(out, codeCString...)\n\t\tstrLength := len(out) - strLengthPos - 4\n\t\toverwriteLength(out, strLengthPos, strLength)\n\n\t\terr = d.readCharAfterWS('{')\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tout, err = d.convertObject(out, topContainer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// BSON code w/scope length is total length including length bytes\n\t\tcwsLength := len(out) - lengthPos\n\t\toverwriteLength(out, lengthPos, cwsLength)\n\n\t\t// Must end with document terminator\n\t\terr = d.readObjectTerminator()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\treturn nil, d.parseError([]byte{ch}, \"expected value separator or end of object\")\n\t}\n\n\treturn out, nil\n}",
"func (j *jsonNative) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error {\n\tvar err error\n\tcurrentKey := ffjtjsonNativebase\n\t_ = currentKey\n\ttok := fflib.FFTok_init\n\twantedTok := fflib.FFTok_init\n\nmainparse:\n\tfor {\n\t\ttok = fs.Scan()\n\t\t//\tprintln(fmt.Sprintf(\"debug: tok: %v state: %v\", tok, state))\n\t\tif tok == fflib.FFTok_error {\n\t\t\tgoto tokerror\n\t\t}\n\n\t\tswitch state {\n\n\t\tcase fflib.FFParse_map_start:\n\t\t\tif tok != fflib.FFTok_left_bracket {\n\t\t\t\twantedTok = fflib.FFTok_left_bracket\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\t\t\tstate = fflib.FFParse_want_key\n\t\t\tcontinue\n\n\t\tcase fflib.FFParse_after_value:\n\t\t\tif tok == fflib.FFTok_comma {\n\t\t\t\tstate = fflib.FFParse_want_key\n\t\t\t} else if tok == fflib.FFTok_right_bracket {\n\t\t\t\tgoto done\n\t\t\t} else {\n\t\t\t\twantedTok = fflib.FFTok_comma\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\n\t\tcase fflib.FFParse_want_key:\n\t\t\t// json {} ended. goto exit. woo.\n\t\t\tif tok == fflib.FFTok_right_bracket {\n\t\t\t\tgoto done\n\t\t\t}\n\t\t\tif tok != fflib.FFTok_string {\n\t\t\t\twantedTok = fflib.FFTok_string\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\n\t\t\tkn := fs.Output.Bytes()\n\t\t\tif len(kn) <= 0 {\n\t\t\t\t// \"\" case. hrm.\n\t\t\t\tcurrentKey = ffjtjsonNativenosuchkey\n\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\tgoto mainparse\n\t\t\t} else {\n\t\t\t\tswitch kn[0] {\n\n\t\t\t\tcase '_':\n\n\t\t\t\t\tif bytes.Equal(ffjKeyjsonNativeParsedRequest, kn) {\n\t\t\t\t\t\tcurrentKey = ffjtjsonNativeParsedRequest\n\t\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\t\tgoto mainparse\n\t\t\t\t\t}\n\n\t\t\t\tcase 'a':\n\n\t\t\t\t\tif bytes.Equal(ffjKeyjsonNativeAPI, kn) {\n\t\t\t\t\t\tcurrentKey = ffjtjsonNativeAPI\n\t\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\t\tgoto mainparse\n\t\t\t\t\t}\n\n\t\t\t\tcase 'b':\n\n\t\t\t\t\tif bytes.Equal(ffjKeyjsonNativeBAttr, kn) {\n\t\t\t\t\t\tcurrentKey = ffjtjsonNativeBAttr\n\t\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\t\tgoto mainparse\n\t\t\t\t\t}\n\n\t\t\t\tcase 'e':\n\n\t\t\t\t\tif bytes.Equal(ffjKeyjsonNativeExt, kn) {\n\t\t\t\t\t\tcurrentKey = ffjtjsonNativeExt\n\t\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\t\tgoto mainparse\n\t\t\t\t\t}\n\n\t\t\t\tcase 'r':\n\n\t\t\t\t\tif bytes.Equal(ffjKeyjsonNativeRequest, kn) {\n\t\t\t\t\t\tcurrentKey = ffjtjsonNativeRequest\n\t\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\t\tgoto mainparse\n\t\t\t\t\t}\n\n\t\t\t\tcase 'v':\n\n\t\t\t\t\tif bytes.Equal(ffjKeyjsonNativeVer, kn) {\n\t\t\t\t\t\tcurrentKey = ffjtjsonNativeVer\n\t\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\t\tgoto mainparse\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif fflib.EqualFoldRight(ffjKeyjsonNativeParsedRequest, kn) {\n\t\t\t\t\tcurrentKey = ffjtjsonNativeParsedRequest\n\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\n\t\t\t\tif fflib.SimpleLetterEqualFold(ffjKeyjsonNativeExt, kn) {\n\t\t\t\t\tcurrentKey = ffjtjsonNativeExt\n\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\n\t\t\t\tif fflib.SimpleLetterEqualFold(ffjKeyjsonNativeBAttr, kn) {\n\t\t\t\t\tcurrentKey = ffjtjsonNativeBAttr\n\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\n\t\t\t\tif fflib.SimpleLetterEqualFold(ffjKeyjsonNativeAPI, kn) {\n\t\t\t\t\tcurrentKey = ffjtjsonNativeAPI\n\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\n\t\t\t\tif fflib.SimpleLetterEqualFold(ffjKeyjsonNativeVer, kn) {\n\t\t\t\t\tcurrentKey = ffjtjsonNativeVer\n\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\n\t\t\t\tif fflib.EqualFoldRight(ffjKeyjsonNativeRequest, kn) {\n\t\t\t\t\tcurrentKey = ffjtjsonNativeRequest\n\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\n\t\t\t\tcurrentKey = ffjtjsonNativenosuchkey\n\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\tgoto mainparse\n\t\t\t}\n\n\t\tcase fflib.FFParse_want_colon:\n\t\t\tif tok != fflib.FFTok_colon {\n\t\t\t\twantedTok = fflib.FFTok_colon\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\t\t\tstate = fflib.FFParse_want_value\n\t\t\tcontinue\n\t\tcase fflib.FFParse_want_value:\n\n\t\t\tif tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null {\n\t\t\t\tswitch currentKey {\n\n\t\t\t\tcase ffjtjsonNativeRequest:\n\t\t\t\t\tgoto handle_Request\n\n\t\t\t\tcase ffjtjsonNativeVer:\n\t\t\t\t\tgoto handle_Ver\n\n\t\t\t\tcase ffjtjsonNativeAPI:\n\t\t\t\t\tgoto handle_API\n\n\t\t\t\tcase ffjtjsonNativeBAttr:\n\t\t\t\t\tgoto handle_BAttr\n\n\t\t\t\tcase ffjtjsonNativeExt:\n\t\t\t\t\tgoto handle_Ext\n\n\t\t\t\tcase ffjtjsonNativeParsedRequest:\n\t\t\t\t\tgoto handle_ParsedRequest\n\n\t\t\t\tcase ffjtjsonNativenosuchkey:\n\t\t\t\t\terr = fs.SkipField(tok)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fs.WrapErr(err)\n\t\t\t\t\t}\n\t\t\t\t\tstate = fflib.FFParse_after_value\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgoto wantedvalue\n\t\t\t}\n\t\t}\n\t}\n\nhandle_Request:\n\n\t/* handler: j.Request type=string kind=string quoted=false*/\n\n\t{\n\n\t\t{\n\t\t\tif tok != fflib.FFTok_string && tok != fflib.FFTok_null {\n\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"cannot unmarshal %s into Go value for string\", tok))\n\t\t\t}\n\t\t}\n\n\t\tif tok == fflib.FFTok_null {\n\n\t\t} else {\n\n\t\t\toutBuf := fs.Output.Bytes()\n\n\t\t\tj.Request = string(string(outBuf))\n\n\t\t}\n\t}\n\n\tstate = fflib.FFParse_after_value\n\tgoto mainparse\n\nhandle_Ver:\n\n\t/* handler: j.Ver type=openrtb.StringOrNumber kind=string quoted=false*/\n\n\t{\n\t\tif tok == fflib.FFTok_null {\n\n\t\t} else {\n\n\t\t\ttbuf, err := fs.CaptureField(tok)\n\t\t\tif err != nil {\n\t\t\t\treturn fs.WrapErr(err)\n\t\t\t}\n\n\t\t\terr = j.Ver.UnmarshalJSON(tbuf)\n\t\t\tif err != nil {\n\t\t\t\treturn fs.WrapErr(err)\n\t\t\t}\n\t\t}\n\t\tstate = fflib.FFParse_after_value\n\t}\n\n\tstate = fflib.FFParse_after_value\n\tgoto mainparse\n\nhandle_API:\n\n\t/* handler: j.API type=[]int kind=slice quoted=false*/\n\n\t{\n\n\t\t{\n\t\t\tif tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null {\n\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"cannot unmarshal %s into Go value for \", tok))\n\t\t\t}\n\t\t}\n\n\t\tif tok == fflib.FFTok_null {\n\t\t\tj.API = nil\n\t\t} else {\n\n\t\t\tj.API = []int{}\n\n\t\t\twantVal := true\n\n\t\t\tfor {\n\n\t\t\t\tvar tmpJAPI int\n\n\t\t\t\ttok = fs.Scan()\n\t\t\t\tif tok == fflib.FFTok_error {\n\t\t\t\t\tgoto tokerror\n\t\t\t\t}\n\t\t\t\tif tok == fflib.FFTok_right_brace {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif tok == fflib.FFTok_comma {\n\t\t\t\t\tif wantVal == true {\n\t\t\t\t\t\t// TODO(pquerna): this isn't an ideal error message, this handles\n\t\t\t\t\t\t// things like [,,,] as an array value.\n\t\t\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"wanted value token, but got token: %v\", tok))\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\twantVal = true\n\t\t\t\t}\n\n\t\t\t\t/* handler: tmpJAPI type=int kind=int quoted=false*/\n\n\t\t\t\t{\n\t\t\t\t\tif tok != fflib.FFTok_integer && tok != fflib.FFTok_null {\n\t\t\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"cannot unmarshal %s into Go value for int\", tok))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t{\n\n\t\t\t\t\tif tok == fflib.FFTok_null {\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\ttval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64)\n\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn fs.WrapErr(err)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttmpJAPI = int(tval)\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tj.API = append(j.API, tmpJAPI)\n\n\t\t\t\twantVal = false\n\t\t\t}\n\t\t}\n\t}\n\n\tstate = fflib.FFParse_after_value\n\tgoto mainparse\n\nhandle_BAttr:\n\n\t/* handler: j.BAttr type=[]int kind=slice quoted=false*/\n\n\t{\n\n\t\t{\n\t\t\tif tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null {\n\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"cannot unmarshal %s into Go value for \", tok))\n\t\t\t}\n\t\t}\n\n\t\tif tok == fflib.FFTok_null {\n\t\t\tj.BAttr = nil\n\t\t} else {\n\n\t\t\tj.BAttr = []int{}\n\n\t\t\twantVal := true\n\n\t\t\tfor {\n\n\t\t\t\tvar tmpJBAttr int\n\n\t\t\t\ttok = fs.Scan()\n\t\t\t\tif tok == fflib.FFTok_error {\n\t\t\t\t\tgoto tokerror\n\t\t\t\t}\n\t\t\t\tif tok == fflib.FFTok_right_brace {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif tok == fflib.FFTok_comma {\n\t\t\t\t\tif wantVal == true {\n\t\t\t\t\t\t// TODO(pquerna): this isn't an ideal error message, this handles\n\t\t\t\t\t\t// things like [,,,] as an array value.\n\t\t\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"wanted value token, but got token: %v\", tok))\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\twantVal = true\n\t\t\t\t}\n\n\t\t\t\t/* handler: tmpJBAttr type=int kind=int quoted=false*/\n\n\t\t\t\t{\n\t\t\t\t\tif tok != fflib.FFTok_integer && tok != fflib.FFTok_null {\n\t\t\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"cannot unmarshal %s into Go value for int\", tok))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t{\n\n\t\t\t\t\tif tok == fflib.FFTok_null {\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\ttval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64)\n\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn fs.WrapErr(err)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttmpJBAttr = int(tval)\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tj.BAttr = append(j.BAttr, tmpJBAttr)\n\n\t\t\t\twantVal = false\n\t\t\t}\n\t\t}\n\t}\n\n\tstate = fflib.FFParse_after_value\n\tgoto mainparse\n\nhandle_Ext:\n\n\t/* handler: j.Ext type=json.RawMessage kind=slice quoted=false*/\n\n\t{\n\t\tif tok == fflib.FFTok_null {\n\n\t\t\tj.Ext = nil\n\n\t\t} else {\n\n\t\t\ttbuf, err := fs.CaptureField(tok)\n\t\t\tif err != nil {\n\t\t\t\treturn fs.WrapErr(err)\n\t\t\t}\n\n\t\t\tif j.Ext == nil {\n\t\t\t\tj.Ext = new(json.RawMessage)\n\t\t\t}\n\n\t\t\terr = j.Ext.UnmarshalJSON(tbuf)\n\t\t\tif err != nil {\n\t\t\t\treturn fs.WrapErr(err)\n\t\t\t}\n\t\t}\n\t\tstate = fflib.FFParse_after_value\n\t}\n\n\tstate = fflib.FFParse_after_value\n\tgoto mainparse\n\nhandle_ParsedRequest:\n\n\t/* handler: j.ParsedRequest type=openrtb.NativeRequest kind=struct quoted=false*/\n\n\t{\n\t\tif tok == fflib.FFTok_null {\n\n\t\t\tj.ParsedRequest = nil\n\n\t\t} else {\n\n\t\t\tif j.ParsedRequest == nil {\n\t\t\t\tj.ParsedRequest = new(NativeRequest)\n\t\t\t}\n\n\t\t\terr = j.ParsedRequest.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tstate = fflib.FFParse_after_value\n\t}\n\n\tstate = fflib.FFParse_after_value\n\tgoto mainparse\n\nwantedvalue:\n\treturn fs.WrapErr(fmt.Errorf(\"wanted value token, but got token: %v\", tok))\nwrongtokenerror:\n\treturn fs.WrapErr(fmt.Errorf(\"ffjson: wanted token: %v, but got token: %v output=%s\", wantedTok, tok, fs.Output.String()))\ntokerror:\n\tif fs.BigError != nil {\n\t\treturn fs.WrapErr(fs.BigError)\n\t}\n\terr = fs.Error.ToError()\n\tif err != nil {\n\t\treturn fs.WrapErr(err)\n\t}\n\tpanic(\"ffjson-generated: unreachable, please report bug.\")\ndone:\n\n\treturn nil\n}",
"func (d *DCAccessCode) 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\", d, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &d.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (this *Simple) UnmarshalJSON(b []byte) error {\n\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}",
"func (u *TCanonicalizationMethodType) UnmarshalJSON(b []byte) error {\n\t// Declare temporary struct without functions to avoid recursive function call\n\ttype Alias TCanonicalizationMethodType\n\n\t// Copy values into temporary struct\n\ttemp := &struct {\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(u),\n\t}\n\n\t// Unmarshal JSON\n\tif err := json.Unmarshal(b, &temp); err != nil {\n\t\treturn err\n\t}\n\n\t// Decode base64 value\n\tbyteValue, err := base64.StdEncoding.DecodeString(u.XsdGoPkgCDATA)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu.XsdGoPkgCDATA = string(byteValue)\n\n\treturn nil\n}",
"func (p *FunctionalPropertyGenerator) wrapDeserializeCode(valueExisting, typeExisting jen.Code) *jen.Statement {\n\tiriCode := jen.Empty()\n\tif !p.hasURIKind() {\n\t\tiriCode = jen.If(\n\t\t\tjen.List(\n\t\t\t\tjen.Id(\"s\"),\n\t\t\t\tjen.Id(\"ok\"),\n\t\t\t).Op(\":=\").Id(\"i\").Assert(jen.String()),\n\t\t\tjen.Id(\"ok\"),\n\t\t).Block(\n\t\t\t// IRI\n\t\t\tjen.List(\n\t\t\t\tjen.Id(\"u\"),\n\t\t\t\tjen.Err(),\n\t\t\t).Op(\":=\").Qual(\"net/url\", \"Parse\").Call(jen.Id(\"s\")),\n\t\t\tjen.Commentf(\"If error exists, don't error out -- skip this and treat as unknown string ([]byte) at worst\"),\n\t\t\tjen.Commentf(\"Also, if no scheme exists, don't treat it as a URL -- net/url is greedy\"),\n\t\t\tjen.If(jen.Err().Op(\"==\").Nil().Op(\"&&\").Len(jen.Id(\"u\").Dot(\"Scheme\")).Op(\">\").Lit(0)).Block(\n\t\t\t\tjen.Id(codegen.This()).Op(\":=\").Op(\"&\").Id(p.StructName()).Values(\n\t\t\t\t\tjen.Dict{\n\t\t\t\t\t\tjen.Id(iriMember): jen.Id(\"u\"),\n\t\t\t\t\t\tjen.Id(aliasMember): jen.Id(\"alias\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\tjen.Return(\n\t\t\t\t\tjen.Id(codegen.This()),\n\t\t\t\t\tjen.Nil(),\n\t\t\t\t),\n\t\t\t),\n\t\t).Line()\n\t}\n\tif p.hasTypeKind() {\n\t\tiriCode = iriCode.If(\n\t\t\tjen.List(\n\t\t\t\tjen.Id(\"m\"),\n\t\t\t\tjen.Id(\"ok\"),\n\t\t\t).Op(\":=\").Id(\"i\").Assert(jen.Map(jen.String()).Interface()),\n\t\t\tjen.Id(\"ok\"),\n\t\t).Block(\n\t\t\ttypeExisting,\n\t\t).Line()\n\t}\n\tif p.hasValueKind() {\n\t\tiriCode = iriCode.Add(valueExisting).Line()\n\t}\n\tiriCode = iriCode.Add(\n\t\tjen.Id(codegen.This()).Op(\":=\").Op(\"&\").Id(p.StructName()).Values(\n\t\t\tjen.Dict{\n\t\t\t\tjen.Id(unknownMemberName): jen.Id(\"i\"),\n\t\t\t\tjen.Id(aliasMember): jen.Id(\"alias\"),\n\t\t\t},\n\t\t),\n\t\tjen.Line(),\n\t\tjen.Return(\n\t\t\tjen.Id(codegen.This()),\n\t\t\tjen.Nil(),\n\t\t),\n\t)\n\treturn iriCode\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
IsSet indicates if Code is set
|
func (code Code) IsSet() bool {
return len(string(code)) > 0
}
|
[
"func (o *BuildComboFormDescriptorOK) IsCode(code int) bool {\n\treturn code == 200\n}",
"func (o *SetAllocatorMetadataItemOK) IsCode(code int) bool {\n\treturn code == 200\n}",
"func (o *EconomicCode) HasCode() bool {\n\tif o != nil && o.Code != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (o *SetRoleOK) IsCode(code int) bool {\n\treturn code == 200\n}",
"func (o *CreateOrUpdateAWSSettingsCreated) IsCode(code int) bool {\n\treturn code == 201\n}",
"func (o *RegisterInfraEnvCreated) IsCode(code int) bool {\n\treturn code == 201\n}",
"func (o *NvmeSubsystemMapCreateCreated) IsCode(code int) bool {\n\treturn code == 201\n}",
"func (o *GetConstructorOK) IsCode(code int) bool {\n\treturn code == 200\n}",
"func (me *TGenderCodeType) Set(s string) { (*xsdt.Integer)(me).Set(s) }",
"func (o *NvmeSubsystemMapCollectionGetOK) IsCode(code int) bool {\n\treturn code == 200\n}",
"func (o *PortsetCreateCreated) IsCode(code int) bool {\n\treturn code == 201\n}",
"func (o *GetLocationsMultiStatus) IsCode(code int) bool {\n\treturn code == 207\n}",
"func (o *CreateRepository37Created) IsCode(code int) bool {\n\treturn code == 201\n}",
"func (o *PutACLOK) IsCode(code int) bool {\n\treturn code == 200\n}",
"func (o *AggregateScansOK) IsCode(code int) bool {\n\treturn code == 200\n}",
"func (o *CreateRepository38Created) IsCode(code int) bool {\n\treturn code == 201\n}",
"func (o *GetCustomNameByProjectIDOK) IsCode(code int) bool {\n\treturn code == 200\n}",
"func (a MissingAction) IsSet(value MissingAction) bool { return a&value != 0 }",
"func (o *MetroclusterSvmCollectionGetDefault) IsCode(code int) bool {\n\treturn o._statusCode == code\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Places returns number of digits after the dot. E.g. 2 for USD, 0 for for currencies which do not support fractions
|
func (code Code) Places() int {
return currenciesByCode[string(code)].decimalPlaces
}
|
[
"func decimalPlaces(v string) int {\n\ts := strings.Split(v, \".\")\n\tif len(s) < 2 {\n\t\treturn 0\n\t}\n\treturn len(s[1])\n}",
"func decimalPlaces(f float64) int {\n\tstr := strconv.FormatFloat(f, 'f', -1, 64)\n\tarr := strings.Split(str, \".\")\n\treturn len(arr[1])\n}",
"func WhichPrecision(quote string) int {\n\tquote = strings.ToLower(quote)\n\tswitch quote {\n\tcase \"EUR\":\n\t\treturn 2\n\tcase \"USD\":\n\t\treturn 3\n\tcase \"USDT\":\n\t\treturn 8\n\tcase \"GBP\":\n\t\treturn 2\n\tcase \"JPY\":\n\t\treturn 2\n\tcase \"CNH\":\n\t\treturn 2\n\tcase \"CNY\":\n\t\treturn 2\n\tcase \"KPW\":\n\t\treturn 2\n\tcase \"KRW\":\n\t\treturn 2\n\tcase \"CAD\":\n\t\treturn 2\n\tcase \"MXN\":\n\t\treturn 2\n\tcase \"RUB\":\n\t\treturn 2\n\tcase \"INR\":\n\t\treturn 2\n\tcase \"ILS\":\n\t\treturn 2\n\tcase \"BRL\":\n\t\treturn 2\n\tcase \"AUD\":\n\t\treturn 2\n\tcase \"SGD\":\n\t\treturn 2\n\tcase \"TWD\":\n\t\treturn 2\n\tdefault:\n\t\treturn 8\n\t}\n}",
"func (o *Currency) GetDecimalPlacesOk() (*int32, bool) {\n\tif o == nil || o.DecimalPlaces == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DecimalPlaces, true\n}",
"func FindNumberOfDecimals(locale, entry string) int {\n\tdecimalsRegex := regexp.MustCompile(\n\t\tMathDecimals[locale],\n\t)\n\tnumberRegex := regexp.MustCompile(`\\d+`)\n\n\tdecimals := numberRegex.FindString(decimalsRegex.FindString(entry))\n\tdecimalsInt, _ := strconv.Atoi(decimals)\n\n\treturn decimalsInt\n}",
"func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) {\n\t// Omit trailing zeros up to and including decimal point.\n\tw := len(buf)\n\tprint := false\n\tfor i := 0; i < prec; i++ {\n\t\tdigit := v % 10\n\t\tprint = print || digit != 0\n\t\tif print {\n\t\t\tw--\n\t\t\tbuf[w] = byte(digit) + '0'\n\t\t}\n\t\tv /= 10\n\t}\n\tif print {\n\t\tw--\n\t\tbuf[w] = '.'\n\t}\n\treturn w, v\n}",
"func (w *Wallet) PrecisionDigits() int {\n\treturn stellarPrecisionDigits\n}",
"func (o *Currency) GetDecimalPlaces() int32 {\n\tif o == nil || o.DecimalPlaces == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.DecimalPlaces\n}",
"func (o *TransactionSplit) GetCurrencyDecimalPlacesOk() (*int32, bool) {\n\tif o == nil || o.CurrencyDecimalPlaces == nil {\n\t\treturn nil, false\n\t}\n\treturn o.CurrencyDecimalPlaces, true\n}",
"func decimals(dec int64) int {\n\tif dec < 1 {\n\t\treturn 0\n\t}\n\treturn int(math.Floor(math.Log10(float64(dec))))\n}",
"func guessDecimalPoint(p *message.Printer) rune {\n // heuristic: any rune that is common to both these strings is probably a\n // decimal point. Concat the strings and find any repeated rune.\n s1 := p.Sprint(number.Decimal(1.23))\n s2 := p.Sprint(number.Decimal(4.56))\n s := s1 + s2\n return repeatingRune(s)\n}",
"func identifyFormatDecimalsPart(f string, decimals string) string {\n\n\tdecimalsPart := \"\"\n\n\tif decimals == \"0\" {\n\t\treturn decimalsPart\n\t}\n\n\trf := reverseFormat(f)\n\n\tfor _, v := range []byte(rf) {\n\t\tdecimalsPart += string(v)\n\t\tif string(v) != NUMBERPLACEHOLDER {\n\t\t\tbreak\n\t\t}\n\t}\n\tdecimalsPart = reverseFormat(decimalsPart)\n\treturn decimalsPart\n}",
"func (o *PiggyBankEvent) GetCurrencyDecimalPlaces() int32 {\n\tif o == nil || o.CurrencyDecimalPlaces == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.CurrencyDecimalPlaces\n}",
"func parsePrecision(format uintptr, args *uintptr) (_ uintptr, n int, ok bool) {\n\tfor {\n\t\tswitch c := *(*byte)(unsafe.Pointer(format)); c {\n\t\tcase '.':\n\t\t\tformat++\n\t\t\tfirst := true\n\t\t\tfor {\n\t\t\t\tswitch c := *(*byte)(unsafe.Pointer(format)); {\n\t\t\t\tcase first && c == '*':\n\t\t\t\t\tformat++\n\t\t\t\t\tn = int(VaInt32(args))\n\t\t\t\t\treturn format, n, true\n\t\t\t\tcase c >= '0' && c <= '9':\n\t\t\t\t\tformat++\n\t\t\t\t\tfirst = false\n\t\t\t\t\tn0 := n\n\t\t\t\t\tn = 10*n + (int(c) - '0')\n\t\t\t\t\tif n < n0 {\n\t\t\t\t\t\tpanic(todo(\"\"))\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn format, n, true\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\treturn format, 0, false\n\t\t}\n\t}\n}",
"func (o *PiggyBankEvent) GetCurrencyDecimalPlacesOk() (*int32, bool) {\n\tif o == nil || o.CurrencyDecimalPlaces == nil {\n\t\treturn nil, false\n\t}\n\treturn o.CurrencyDecimalPlaces, true\n}",
"func ConvertFixedPoint(amt string) (string, error) {\n\tvar v int64\n\tvar err error\n\tindex := strings.Index(amt, \".\")\n\tif index == 0 {\n\t\tamt = \"0\" + amt\n\t\tindex++\n\t}\n\tif index < 0 {\n\t\tv, err = strconv.ParseInt(amt, 10, 64)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tv *= 100000000 // Convert to Factoshis\n\t} else {\n\t\ttp := amt[:index]\n\t\tv, err = strconv.ParseInt(tp, 10, 64)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tv = v * 100000000 // Convert to Factoshis\n\n\t\tbp := amt[index+1:]\n\t\tif len(bp) > 8 {\n\t\t\tbp = bp[:8]\n\t\t}\n\t\tbpv, err := strconv.ParseInt(bp, 10, 64)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tfor i := 0; i < 8-len(bp); i++ {\n\t\t\tbpv *= 10\n\t\t}\n\t\tv += bpv\n\t}\n\treturn strconv.FormatInt(v, 10), nil\n}",
"func DropletPrecisionToDivisor(precision uint8) uint64 {\n\tif precision > droplet.Exponent {\n\t\tpanic(\"precision must be <= droplet.Exponent\")\n\t}\n\n\tn := droplet.Exponent - precision\n\tvar i uint64 = 1\n\tfor k := uint8(0); k < n; k++ {\n\t\ti = i * 10\n\t}\n\treturn i\n}",
"func byteCountDecimal(b int64) string {\n\tconst unit = 1000\n\tif b < unit {\n\t\treturn fmt.Sprintf(\"%d B\", 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 nsToFloatString(ns int64) string {\n\tif ns < 0 {\n\t\treturn \"-\" + nsToFloatString(-ns)\n\t}\n\tresult := fmt.Sprintf(\"%010d\", ns)\n\tsplit := len(result) - 9\n\tresult, decimals := result[:split], result[split:]\n\tdecimals = strings.TrimRight(decimals, \"0\")\n\tif decimals != \"\" {\n\t\tresult += \".\"\n\t\tresult += decimals\n\t}\n\treturn result\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
IsSet indicates if Number is set
|
func (number Number) IsSet() bool {
return len(string(number)) > 0
}
|
[
"func (o OptFloat64) IsSet() bool { return o.Set }",
"func (o OptInt) IsSet() bool { return o.Set }",
"func (me *TDunsNumberBaseType) Set(s string) { (*xsdt.Integer)(me).Set(s) }",
"func (me *TNumberOptionalNumberType) Set(s string) { (*xsdt.String)(me).Set(s) }",
"func (t *VSStr) IsSet() bool {\n\treturn true\n}",
"func (t *VSDbl) IsSet() bool {\n\treturn true\n}",
"func (a MissingAction) IsSet(value MissingAction) bool { return a&value != 0 }",
"func (v *DayValue) IsSet() bool {\n\treturn v.set\n}",
"func (me *TSAFPTPortugueseVatNumber) Set(s string) { (*xsdt.Integer)(me).Set(s) }",
"func (o OptDate) IsSet() bool { return o.Set }",
"func (o OptID) IsSet() bool { return o.Set }",
"func IsSet(val interface{}) (result bool) {\r\n\tif reflect.TypeOf(val) == nil {\r\n\t\treturn false\r\n\t}\r\n\tx := reflect.ValueOf(val)\r\n\tif x.Kind() == reflect.Ptr {\r\n\t\treturn !x.IsNil()\r\n\t}\r\n\treturn !x.IsZero()\r\n}",
"func (me *TNumbersType) Set(s string) { (*xsdt.String)(me).Set(s) }",
"func (currency Currency) IsSet() bool {\n\treturn len(string(currency)) > 0\n}",
"func (ba *FilterBitArray) IsSet(i uint) bool {\n\treturn (ba.ValueAt(i) != 0)\n}",
"func (v Version) IsSet() bool {\n\treturn v.Major > 0 || v.Minor > 0 || v.Patch > 0 || v.Build > 0\n}",
"func (f ExtensionField) IsSet() bool {\n\treturn f.typ != nil\n}",
"func (me *TxsdPremiseNumberNumberType) Set(s string) { (*xsdt.Nmtoken)(me).Set(s) }",
"func (o *protoObj) IsSet(field ref.Val) ref.Val {\n\tprotoFieldName, ok := field.(String)\n\tif !ok {\n\t\treturn MaybeNoSuchOverloadErr(field)\n\t}\n\tprotoFieldStr := string(protoFieldName)\n\tfd, found := o.typeDesc.FieldByName(protoFieldStr)\n\tif !found {\n\t\treturn NewErr(\"no such field '%s'\", field)\n\t}\n\tif fd.IsSet(o.value) {\n\t\treturn True\n\t}\n\treturn False\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
CurrencyByCurrency get currency by currency
|
func (currencies currencies) CurrencyByCurrency(curr string) (currency, bool) {
for _, c := range currencies {
if string(c.currency) == curr {
return c, true
}
}
return currency{}, false
}
|
[
"func ByCurrency(currency Currency) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency.String()]\n\treturn\n}",
"func (l *Ledger) GetCurrency(s string) (*Currency, bool) {\n\tfor i := range l.Currencies {\n\t\tif s == l.Currencies[i].Name {\n\t\t\treturn l.Currencies[i], false\n\t\t}\n\t}\n\tvar currency Currency\n\tcurrency.Name = s\n\tl.Currencies = append(l.Currencies, ¤cy)\n\treturn ¤cy, true\n}",
"func GetCurrency(code string) *Currency {\n\treturn currencies[code]\n}",
"func GetCurrency(code Code) (c Currency, ok bool) {\n\tok = false\n\tif !code.IsValid() {\n\t\treturn\n\t}\n\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func (h *HitBTC) GetCurrency(ctx context.Context, currency string) (Currencies, error) {\n\ttype Response struct {\n\t\tData Currencies\n\t}\n\tresp := Response{}\n\tpath := fmt.Sprintf(\"/%s/%s\", apiV2Currency, currency)\n\n\treturn resp.Data, h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp.Data)\n}",
"func Currency() *CurrencyInfo {\n\tindex := rand.Intn(len(data.Data()[\"currency\"][\"short\"]))\n\treturn &CurrencyInfo{\n\t\tShort: data.Data()[\"currency\"][\"short\"][index],\n\t\tLong: data.Data()[\"currency\"][\"long\"][index],\n\t}\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func (r Billing_Info) GetCurrency() (resp datatypes.Billing_Currency, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Billing_Info\", \"getCurrency\", nil, &r.Options, &resp)\n\treturn\n}",
"func (c *Currency) get() *Currency {\n\tif curr, ok := currencies[c.Code]; ok {\n\t\treturn curr\n\t}\n\n\treturn c.getDefault()\n}",
"func (currencies currencies) CurrencyByCode(code string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.code) == code {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func (rcv *Price) Currency() byte {\n\treturn rcv._tab.GetByte(rcv._tab.Pos + flatbuffers.UOffsetT(6))\n}",
"func GetCurrency(URL string, cli http.Client) Currency {\n\n\treq, err := http.NewRequest(http.MethodGet, URL, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treq.Header.Set(\"User-Agent\", \"Assignment\")\n\n\tres, getErr := cli.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\tcurrency := Currency{}\n\tjsonErr := json.Unmarshal(body, ¤cy)\n\tif jsonErr != nil {\n\t\tlog.Fatal(jsonErr)\n\t}\n\n\treturn currency\n}",
"func (currencies currencies) CurrencyByNumber(number string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.number) == number {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByCurrencyStr(currency string) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency]\n\treturn\n}",
"func FindCurrency(exec boil.Executor, iD int, selectCols ...string) (*Currency, error) {\n\tcurrencyObj := &Currency{}\n\n\tsel := \"*\"\n\tif len(selectCols) > 0 {\n\t\tsel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), \",\")\n\t}\n\tquery := fmt.Sprintf(\n\t\t\"select %s from \\\"currency\\\" where \\\"id\\\"=$1\", sel,\n\t)\n\n\tq := queries.Raw(query, iD)\n\n\terr := q.Bind(nil, exec, currencyObj)\n\tif err != nil {\n\t\tif errors.Cause(err) == sql.ErrNoRows {\n\t\t\treturn nil, sql.ErrNoRows\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"models: unable to select from currency\")\n\t}\n\n\treturn currencyObj, nil\n}",
"func CurrencyCode(id int) string {\n\treturn currencyCode[id]\n}",
"func GetCurrency(queryRoute string, cdc *codec.Codec) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"currency [denom]\",\n\t\tShort: \"Get currency by denom\",\n\t\tExample: \"currency xfi\",\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcliCtx := context.NewCLIContext().WithCodec(cdc)\n\n\t\t\t// prepare request\n\t\t\treq := types.CurrencyReq{Denom: args[0]}\n\n\t\t\tbz, err := cliCtx.Codec.MarshalJSON(req)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// query and parse the result\n\t\t\tres, _, err := cliCtx.QueryWithData(fmt.Sprintf(\"custom/%s/%s\", queryRoute, types.QueryCurrency), bz)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tvar out ccstorage.Currency\n\t\t\tcdc.MustUnmarshalJSON(res, &out)\n\n\t\t\treturn cliCtx.PrintOutput(out)\n\t\t},\n\t}\n\thelpers.BuildCmdHelp(cmd, []string{\n\t\t\"currency denomination symbol\",\n\t})\n\n\treturn cmd\n}",
"func Currency() string {\n\treturn randomFrom(jsonData.Currencies)\n}",
"func NewCurrency(params map[string]interface{}) *Currency {\n\tnew := new(Currency)\n\tnew.ID = int8(params[\"id\"].(int))\n\tnew.Name = params[\"name\"].(string)\n\treturn new\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
CurrencyByCode gets currency by code
|
func (currencies currencies) CurrencyByCode(code string) (currency, bool) {
for _, c := range currencies {
if string(c.code) == code {
return c, true
}
}
return currency{}, false
}
|
[
"func ByCode(code Code) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code.String()]\n\treturn\n}",
"func GetCurrency(code string) *Currency {\n\treturn currencies[code]\n}",
"func (s *Currencies) FindByCode(code string) (*models.Currency, error) {\n\tvar currency models.Currency\n\n\terr := s.db.Where(\"code = ?\", code).FirstOrInit(¤cy).Error\n\n\treturn ¤cy, err\n}",
"func CurrencyCode(id int) string {\n\treturn currencyCode[id]\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func GetCurrency(code Code) (c Currency, ok bool) {\n\tok = false\n\tif !code.IsValid() {\n\t\treturn\n\t}\n\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func ByCodeStr(code string) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func New(code string) (*Currency, error) {\n\tcode = strings.ToUpper(code)\n\tif !IsValid(code) {\n\t\treturn nil, errors.New(\"currency: code is not a valid ISO 4217 alphabetic code\")\n\t}\n\n\tcurrency := currencies[code]\n\treturn ¤cy, nil\n}",
"func (client *Client) CurrencyCode() byte {\n\treturn client.currencyCode\n}",
"func (repo *AccountTypeRepository) FindByCurrencyCode(currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"currency_code = ?\", currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func (w *RPCWallet) CurrencyCode() string {\n\tif w.params.Name == PhoreMainNetParams.Name {\n\t\treturn \"phr\"\n\t} else {\n\t\treturn \"tphr\"\n\t}\n}",
"func Find(code string) Currency {\n\tfor _, curr := range currencies {\n\t\tif curr.Code == code {\n\t\t\treturn curr\n\t\t}\n\t}\n\n\treturn XXX\n}",
"func (c FixedRatePlusPercentageCharges) GetCurrencyCode() string {\n\treturn c.currencyCode\n}",
"func ByCodeErr(code Code) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func (c *Currency) get() *Currency {\n\tif curr, ok := currencies[c.Code]; ok {\n\t\treturn curr\n\t}\n\n\treturn c.getDefault()\n}",
"func (o *PiggyBankEvent) GetCurrencyCode() string {\n\tif o == nil || o.CurrencyCode == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.CurrencyCode\n}",
"func (r *Rate) BaseCurrencyCode() string {\n\treturn r.base\n}",
"func (m *AgedAccountsPayable) SetCurrencyCode(value *string)() {\n err := m.GetBackingStore().Set(\"currencyCode\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (currencies currencies) CurrencyByNumber(number string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.number) == number {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
CurrencyByNumber gets currency by number
|
func (currencies currencies) CurrencyByNumber(number string) (currency, bool) {
for _, c := range currencies {
if string(c.number) == number {
return c, true
}
}
return currency{}, false
}
|
[
"func ByNumber(number Number) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number.String()]\n\treturn\n}",
"func ByNumberStr(number string) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number]\n\treturn\n}",
"func Currency() *CurrencyInfo {\n\tindex := rand.Intn(len(data.Data()[\"currency\"][\"short\"]))\n\treturn &CurrencyInfo{\n\t\tShort: data.Data()[\"currency\"][\"short\"][index],\n\t\tLong: data.Data()[\"currency\"][\"long\"][index],\n\t}\n}",
"func (currencies currencies) CurrencyByCurrency(curr string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.currency) == curr {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func (currencies currencies) CurrencyByCode(code string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.code) == code {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByNumberErr(number Number) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func ByNumeric(s string) (Currency, bool) {\n\tc, ok := byNumeric[s]\n\tif ok {\n\t\treturn *c, true\n\t}\n\n\treturn Currency{}, false\n}",
"func CurrencyCode(id int) string {\n\treturn currencyCode[id]\n}",
"func (c Currency) Number() ([]byte, error) {\n\tvar bufC buf\n\t_, err := c.NumberWriter(&bufC)\n\treturn bufC, err\n}",
"func GetCurrency(code string) *Currency {\n\treturn currencies[code]\n}",
"func CurrencySymbol(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {\n\tcode := in.String()\n\tif code == \"\" {\n\t\treturn pongo2.AsValue(\"\"), nil\n\t}\n\tcurrencyObj := c.Get(code)\n\treturn pongo2.AsValue(currencyObj.Symbol), nil\n}",
"func (l *Ledger) GetCurrency(s string) (*Currency, bool) {\n\tfor i := range l.Currencies {\n\t\tif s == l.Currencies[i].Name {\n\t\t\treturn l.Currencies[i], false\n\t\t}\n\t}\n\tvar currency Currency\n\tcurrency.Name = s\n\tl.Currencies = append(l.Currencies, ¤cy)\n\treturn ¤cy, true\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func ByCurrency(currency Currency) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency.String()]\n\treturn\n}",
"func NewCurrency(params map[string]interface{}) *Currency {\n\tnew := new(Currency)\n\tnew.ID = int8(params[\"id\"].(int))\n\tnew.Name = params[\"name\"].(string)\n\treturn new\n}",
"func ConvertCurrency(currBeerCode string, currBuyCode string, monto float32) float32 {\n\tvar usd float32\n\t//var clp float32\n\tusd = 819.0\n\t//clp = 1.0\n\n\t/*\n\t\tfmt.Println(\"com \" + currBeerCode + \" / \" + currBuyCode)\n\t\tfmt.Println(reflect.TypeOf(currBeerCode))\n\t\tfmt.Println(reflect.TypeOf(currBuyCode))\n\t*/\n\n\tif currBeerCode == \"USD\" && currBuyCode == \"CLP\" {\n\t\t//fmt.Println(\"conv1\")\n\t\treturn monto * usd\n\t} else if currBeerCode == \"CLP\" && currBuyCode == \"USD\" {\n\t\t//fmt.Println(\"conv2\")\n\t\treturn monto / usd\n\t} else {\n\t\t//fmt.Println(\"conv3\")\n\t\treturn monto\n\t}\n}",
"func Currency() string {\n\treturn randomFrom(jsonData.Currencies)\n}",
"func GetCurrency(code Code) (c Currency, ok bool) {\n\tok = false\n\tif !code.IsValid() {\n\t\treturn\n\t}\n\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func New(code string) (*Currency, error) {\n\tcode = strings.ToUpper(code)\n\tif !IsValid(code) {\n\t\treturn nil, errors.New(\"currency: code is not a valid ISO 4217 alphabetic code\")\n\t}\n\n\tcurrency := currencies[code]\n\treturn ¤cy, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCodeStr lookup for currency type by code
|
func ByCodeStr(code string) (c currency, ok bool) {
c, ok = currenciesByCode[code]
return
}
|
[
"func ByCode(code Code) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code.String()]\n\treturn\n}",
"func ByCodeStrErr(code string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func (currencies currencies) CurrencyByCode(code string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.code) == code {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func ByCurrencyStr(currency string) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency]\n\treturn\n}",
"func ByNumberStr(number string) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number]\n\treturn\n}",
"func InstitutionTypeByCode(code string) (string, bool) {\n\tt, ok := instType[code]\n\treturn t, ok\n}",
"func ByCodeErr(code Code) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func CurrencyCode(id int) string {\n\treturn currencyCode[id]\n}",
"func (repo *AccountTypeRepository) FindByCurrencyCode(currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"currency_code = ?\", currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func (repo *AccountTypeRepository) FindByNameAndCurrencyCode(name, currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"name = ? AND currency_code = ?\", name, currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func (s *Currencies) FindByCode(code string) (*models.Currency, error) {\n\tvar currency models.Currency\n\n\terr := s.db.Where(\"code = ?\", code).FirstOrInit(¤cy).Error\n\n\treturn ¤cy, err\n}",
"func (s *Server) providerTypeGetByCode(\n\tsess *pb.Session,\n\tcode string,\n) (*pb.ProviderType, error) {\n\treq := &pb.ProviderTypeGetByCodeRequest{\n\t\tSession: sess,\n\t\tCode: code,\n\t}\n\tmc, err := s.metaClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trec, err := mc.ProviderTypeGetByCode(context.Background(), req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pb.ProviderType{\n\t\tCode: rec.Code,\n\t\tDescription: rec.Description,\n\t}, nil\n}",
"func ByCountryStr(country string) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country]\n\treturn\n}",
"func TypeFromStr(ct string) (Type, error) {\n\tswitch ct {\n\tcase \"bitcoin\":\n\t\treturn Bitcoin, nil\n\tcase \"skycoin\":\n\t\treturn Skycoin, nil\n\tdefault:\n\t\treturn -1, fmt.Errorf(\"unknow coin type:%s\", ct)\n\t}\n}",
"func Find(code string) Currency {\n\tfor _, curr := range currencies {\n\t\tif curr.Code == code {\n\t\t\treturn curr\n\t\t}\n\t}\n\n\treturn XXX\n}",
"func (store *TypeStore) LookupCode(struct_type reflect.Type) (uint16, bool) {\n\tval, present := store.TypeCodes[struct_type]\n\treturn val, present\n}",
"func TypeRequestByCode(code string) (string, bool) {\n\tt, ok := typeRequest[code]\n\treturn t, ok\n}",
"func (sc *serverCompress) GetKindByCode(code byte) string {\n\tif value, exist := sc.codeToKind[code]; exist {\n\t\treturn value\n\t}\n\treturn \"\"\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCurrencyStr lookup for currency type by currency
|
func ByCurrencyStr(currency string) (c currency, ok bool) {
c, ok = currenciesByCurrency[currency]
return
}
|
[
"func ByCountryStr(country string) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country]\n\treturn\n}",
"func ByCodeStr(code string) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func ByNumberStr(number string) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number]\n\treturn\n}",
"func (currencies currencies) CurrencyByCurrency(curr string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.currency) == curr {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByCurrency(currency Currency) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency.String()]\n\treturn\n}",
"func ByCurrencyStrErr(currencyStr string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCurrencyErr(currencyStr Currency) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func (l *Ledger) GetCurrency(s string) (*Currency, bool) {\n\tfor i := range l.Currencies {\n\t\tif s == l.Currencies[i].Name {\n\t\t\treturn l.Currencies[i], false\n\t\t}\n\t}\n\tvar currency Currency\n\tcurrency.Name = s\n\tl.Currencies = append(l.Currencies, ¤cy)\n\treturn ¤cy, true\n}",
"func ByNumeric(s string) (Currency, bool) {\n\tc, ok := byNumeric[s]\n\tif ok {\n\t\treturn *c, true\n\t}\n\n\treturn Currency{}, false\n}",
"func ByISO(s string) (Currency, bool) {\n\tc, ok := byISO[strings.ToUpper(s)]\n\tif ok {\n\t\treturn *c, ok\n\t}\n\n\treturn Currency{}, false\n}",
"func TypeFromStr(ct string) (Type, error) {\n\tswitch ct {\n\tcase \"bitcoin\":\n\t\treturn Bitcoin, nil\n\tcase \"skycoin\":\n\t\treturn Skycoin, nil\n\tdefault:\n\t\treturn -1, fmt.Errorf(\"unknow coin type:%s\", ct)\n\t}\n}",
"func (currencies currencies) CurrencyByCode(code string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.code) == code {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func (repo *AccountTypeRepository) FindByCurrencyCode(currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"currency_code = ?\", currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func GetCurrencyFromText(s string) (currency string) {\n\tfor key, value := range currencies {\n\t\tif strings.Contains(s, key) {\n\t\t\treturn value\n\t\t}\n\t}\n\treturn\n}",
"func ByCode(code Code) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code.String()]\n\treturn\n}",
"func CurrencySymbol(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {\n\tcode := in.String()\n\tif code == \"\" {\n\t\treturn pongo2.AsValue(\"\"), nil\n\t}\n\tcurrencyObj := c.Get(code)\n\treturn pongo2.AsValue(currencyObj.Symbol), nil\n}",
"func (repo *AccountTypeRepository) FindByNameAndCurrencyCode(name, currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"name = ? AND currency_code = ?\", name, currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func CurrencyCode(id int) string {\n\treturn currencyCode[id]\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByNumberStr lookup for currency type by number
|
func ByNumberStr(number string) (c currency, ok bool) {
c, ok = currenciesByNumber[number]
return
}
|
[
"func ByNumber(number Number) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number.String()]\n\treturn\n}",
"func ByNumeric(s string) (Currency, bool) {\n\tc, ok := byNumeric[s]\n\tif ok {\n\t\treturn *c, true\n\t}\n\n\treturn Currency{}, false\n}",
"func ByNumberStrErr(number string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func ByCurrencyStr(currency string) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency]\n\treturn\n}",
"func (currencies currencies) CurrencyByNumber(number string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.number) == number {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByCodeStr(code string) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func ByNumberErr(number Number) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func FindByNumber(num int) *Country {\n\tsearch := fmt.Sprintf(\"%03d\", num)\n\tfor _, c := range countries {\n\t\tif c.ExistsNum(search) {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}",
"func TypeFromStr(ct string) (Type, error) {\n\tswitch ct {\n\tcase \"bitcoin\":\n\t\treturn Bitcoin, nil\n\tcase \"skycoin\":\n\t\treturn Skycoin, nil\n\tdefault:\n\t\treturn -1, fmt.Errorf(\"unknow coin type:%s\", ct)\n\t}\n}",
"func ByCountryStr(country string) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country]\n\treturn\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func ByCode(code Code) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code.String()]\n\treturn\n}",
"func (currencies currencies) CurrencyByCode(code string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.code) == code {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func (currencies currencies) CurrencyByCurrency(curr string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.currency) == curr {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByCurrencyStrErr(currencyStr string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCodeStrErr(code string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func CurrencySymbol(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {\n\tcode := in.String()\n\tif code == \"\" {\n\t\treturn pongo2.AsValue(\"\"), nil\n\t}\n\tcurrencyObj := c.Get(code)\n\treturn pongo2.AsValue(currencyObj.Symbol), nil\n}",
"func GetCurrencyFromText(s string) (currency string) {\n\tfor key, value := range currencies {\n\t\tif strings.Contains(s, key) {\n\t\t\treturn value\n\t\t}\n\t}\n\treturn\n}",
"func ByCurrencyErr(currencyStr Currency) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCountryStr lookup for currencies type by country
|
func ByCountryStr(country string) (c currencies, ok bool) {
c, ok = currenciesByCountry[country]
return
}
|
[
"func ByCountry(country Country) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country.String()]\n\treturn\n}",
"func ByCountryStrErr(country string) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func ByCurrencyStr(currency string) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency]\n\treturn\n}",
"func ByCodeStr(code string) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func ByCountryErr(country Country) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country.String()]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func (instance *XCountryRepo) GetByISO2Code(iso2Code string) (model.XCountry, error) {\n\treturn instance.getByField(\"iso2Code\", iso2Code)\n}",
"func ByISO(s string) (Currency, bool) {\n\tc, ok := byISO[strings.ToUpper(s)]\n\tif ok {\n\t\treturn *c, ok\n\t}\n\n\treturn Currency{}, false\n}",
"func ByNumberStr(number string) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number]\n\treturn\n}",
"func Country(countryStyle int64) string {\n\tcountry := \"\"\n\tswitch countryStyle {\n\n\tdefault:\n\n\tcase FullCountry:\n\t\tcountry = randomFrom(jsonData.Countries)\n\t\tbreak\n\n\tcase TwoCharCountry:\n\t\tcountry = randomFrom(jsonData.CountriesTwoChars)\n\t\tbreak\n\n\tcase ThreeCharCountry:\n\t\tcountry = randomFrom(jsonData.CountriesThreeChars)\n\t\tbreak\n\t}\n\treturn country\n}",
"func lookupCountry(remoteAddr string) string {\n\thost, _, _ := net.SplitHostPort(remoteAddr)\n\ta := net.ParseIP(host)\n\tif a == nil {\n\t\treturn \"id\"\n\t}\n\n\tvar rec struct {\n\t\tCountry struct {\n\t\t\tISOCode string `maxminddb:\"iso_code\"`\n\t\t} `maxminddb:\"country\"`\n\t}\n\n\terr := geoipdb.Lookup(a, &rec)\n\tif err != nil || rec.Country.ISOCode == \"\" {\n\t\treturn \"id\"\n\t}\n\n\treturn strings.ToLower(rec.Country.ISOCode)\n}",
"func (instance *XCountryRepo) GetByISO3Code(iso3Code string) (model.XCountry, error) {\n\treturn instance.getByField(\"iso3Code\", iso3Code)\n}",
"func (c CallCode) Countries() []CountryCode { //nolint:gocyclo\n\tswitch c {\n\tcase CallCode1:\n\t\treturn []CountryCode{ATF, CAN, UMI, USA}\n\tcase CallCode1808:\n\t\treturn []CountryCode{USA}\n\tcase CallCode1242:\n\t\treturn []CountryCode{BHS}\n\tcase CallCode1246:\n\t\treturn []CountryCode{BRB}\n\tcase CallCode1264:\n\t\treturn []CountryCode{AIA}\n\tcase CallCode1268:\n\t\treturn []CountryCode{ATG}\n\tcase CallCode1284:\n\t\treturn []CountryCode{VGB}\n\tcase CallCode1340:\n\t\treturn []CountryCode{VIR}\n\tcase CallCode1345:\n\t\treturn []CountryCode{CYM}\n\tcase CallCode1441:\n\t\treturn []CountryCode{BMU}\n\tcase CallCode1473:\n\t\treturn []CountryCode{GRD}\n\tcase CallCode1649:\n\t\treturn []CountryCode{TCA}\n\tcase CallCode1664:\n\t\treturn []CountryCode{MSR}\n\tcase CallCode1670:\n\t\treturn []CountryCode{MNP}\n\tcase CallCode1671:\n\t\treturn []CountryCode{GUM}\n\tcase CallCode1684:\n\t\treturn []CountryCode{ASM}\n\tcase CallCode1758:\n\t\treturn []CountryCode{LCA}\n\tcase CallCode1767:\n\t\treturn []CountryCode{DMA}\n\tcase CallCode1784:\n\t\treturn []CountryCode{VCT}\n\tcase CallCode1787, CallCode1939:\n\t\treturn []CountryCode{PRI}\n\tcase CallCode1809, CallCode1829, CallCode1849:\n\t\treturn []CountryCode{DOM}\n\tcase CallCode1868:\n\t\treturn []CountryCode{TTO}\n\tcase CallCode1869:\n\t\treturn []CountryCode{KNA}\n\tcase CallCode1876, CallCode1658:\n\t\treturn []CountryCode{JAM}\n\tcase CallCode20:\n\t\treturn []CountryCode{EGY}\n\tcase CallCode211:\n\t\treturn []CountryCode{SSD}\n\tcase CallCode212:\n\t\treturn []CountryCode{ESH, MAR}\n\tcase CallCode213:\n\t\treturn []CountryCode{DZA}\n\tcase CallCode216:\n\t\treturn []CountryCode{TUN}\n\tcase CallCode218:\n\t\treturn []CountryCode{LBY}\n\tcase CallCode220:\n\t\treturn []CountryCode{GMB}\n\tcase CallCode221:\n\t\treturn []CountryCode{SEN}\n\tcase CallCode222:\n\t\treturn []CountryCode{MRT}\n\tcase CallCode223:\n\t\treturn []CountryCode{MLI}\n\tcase CallCode224:\n\t\treturn []CountryCode{GIN}\n\tcase CallCode225:\n\t\treturn []CountryCode{CIV}\n\tcase CallCode226:\n\t\treturn []CountryCode{BFA}\n\tcase CallCode227:\n\t\treturn []CountryCode{NER}\n\tcase CallCode228:\n\t\treturn []CountryCode{TGO}\n\tcase CallCode229:\n\t\treturn []CountryCode{BEN}\n\tcase CallCode230:\n\t\treturn []CountryCode{MUS}\n\tcase CallCode231:\n\t\treturn []CountryCode{LBR}\n\tcase CallCode232:\n\t\treturn []CountryCode{SLE}\n\tcase CallCode233:\n\t\treturn []CountryCode{GHA}\n\tcase CallCode234:\n\t\treturn []CountryCode{NGA}\n\tcase CallCode235:\n\t\treturn []CountryCode{TCD}\n\tcase CallCode236:\n\t\treturn []CountryCode{CAF}\n\tcase CallCode237:\n\t\treturn []CountryCode{CMR}\n\tcase CallCode238:\n\t\treturn []CountryCode{CPV}\n\tcase CallCode239:\n\t\treturn []CountryCode{STP}\n\tcase CallCode240:\n\t\treturn []CountryCode{GNQ}\n\tcase CallCode241:\n\t\treturn []CountryCode{GAB}\n\tcase CallCode242:\n\t\treturn []CountryCode{COG}\n\tcase CallCode243:\n\t\treturn []CountryCode{COD}\n\tcase CallCode244:\n\t\treturn []CountryCode{AGO}\n\tcase CallCode245:\n\t\treturn []CountryCode{GNB}\n\tcase CallCode246:\n\t\treturn []CountryCode{IOT}\n\tcase CallCode248:\n\t\treturn []CountryCode{SYC}\n\tcase CallCode249:\n\t\treturn []CountryCode{SDN}\n\tcase CallCode250:\n\t\treturn []CountryCode{RWA}\n\tcase CallCode251:\n\t\treturn []CountryCode{ETH}\n\tcase CallCode252:\n\t\treturn []CountryCode{SOM}\n\tcase CallCode253:\n\t\treturn []CountryCode{DJI}\n\tcase CallCode254:\n\t\treturn []CountryCode{KEN}\n\tcase CallCode255:\n\t\treturn []CountryCode{TZA}\n\tcase CallCode256:\n\t\treturn []CountryCode{UGA}\n\tcase CallCode257:\n\t\treturn []CountryCode{BDI}\n\tcase CallCode258:\n\t\treturn []CountryCode{MOZ}\n\tcase CallCode260:\n\t\treturn []CountryCode{ZMB}\n\tcase CallCode261:\n\t\treturn []CountryCode{MDG}\n\tcase CallCode262:\n\t\treturn []CountryCode{MYT, REU}\n\tcase CallCode262269, CallCode262639:\n\t\treturn []CountryCode{MYT}\n\tcase CallCode263:\n\t\treturn []CountryCode{ZWE}\n\tcase CallCode264:\n\t\treturn []CountryCode{NAM}\n\tcase CallCode265:\n\t\treturn []CountryCode{MWI}\n\tcase CallCode266:\n\t\treturn []CountryCode{LSO}\n\tcase CallCode267:\n\t\treturn []CountryCode{BWA}\n\tcase CallCode268:\n\t\treturn []CountryCode{SWZ}\n\tcase CallCode269:\n\t\treturn []CountryCode{COM}\n\tcase CallCode27:\n\t\treturn []CountryCode{ZAF}\n\tcase CallCode290:\n\t\treturn []CountryCode{SHN}\n\tcase CallCode291:\n\t\treturn []CountryCode{ERI}\n\tcase CallCode297, CallCode5998:\n\t\treturn []CountryCode{ABW}\n\tcase CallCode298:\n\t\treturn []CountryCode{FRO}\n\tcase CallCode299:\n\t\treturn []CountryCode{GRL}\n\tcase CallCode30:\n\t\treturn []CountryCode{GRC}\n\tcase CallCode31:\n\t\treturn []CountryCode{NLD}\n\tcase CallCode32:\n\t\treturn []CountryCode{BEL}\n\tcase CallCode33:\n\t\treturn []CountryCode{FRA}\n\tcase CallCode34:\n\t\treturn []CountryCode{ESP}\n\tcase CallCode350:\n\t\treturn []CountryCode{GIB}\n\tcase CallCode351:\n\t\treturn []CountryCode{PRT}\n\tcase CallCode352:\n\t\treturn []CountryCode{LUX}\n\tcase CallCode353:\n\t\treturn []CountryCode{IRL}\n\tcase CallCode354:\n\t\treturn []CountryCode{ISL}\n\tcase CallCode355:\n\t\treturn []CountryCode{ALB}\n\tcase CallCode356:\n\t\treturn []CountryCode{MLT}\n\tcase CallCode357:\n\t\treturn []CountryCode{CYP}\n\tcase CallCode358:\n\t\treturn []CountryCode{ALA, FIN}\n\tcase CallCode359:\n\t\treturn []CountryCode{BGR}\n\tcase CallCode36:\n\t\treturn []CountryCode{HUN}\n\tcase CallCode370:\n\t\treturn []CountryCode{LTU}\n\tcase CallCode371:\n\t\treturn []CountryCode{LVA}\n\tcase CallCode372:\n\t\treturn []CountryCode{EST}\n\tcase CallCode373:\n\t\treturn []CountryCode{MDA}\n\tcase CallCode374:\n\t\treturn []CountryCode{ARM}\n\tcase CallCode375:\n\t\treturn []CountryCode{BLR}\n\tcase CallCode376:\n\t\treturn []CountryCode{AND}\n\tcase CallCode377:\n\t\treturn []CountryCode{MCO}\n\tcase CallCode378:\n\t\treturn []CountryCode{SMR}\n\tcase CallCode38:\n\t\treturn []CountryCode{YUG}\n\tcase CallCode380:\n\t\treturn []CountryCode{UKR}\n\tcase CallCode381:\n\t\treturn []CountryCode{SRB}\n\tcase CallCode382:\n\t\treturn []CountryCode{MNE}\n\tcase CallCode383:\n\t\treturn []CountryCode{XKX}\n\tcase CallCode385:\n\t\treturn []CountryCode{HRV}\n\tcase CallCode386:\n\t\treturn []CountryCode{SVN}\n\tcase CallCode387:\n\t\treturn []CountryCode{BIH}\n\tcase CallCode389:\n\t\treturn []CountryCode{MKD}\n\tcase CallCode39:\n\t\treturn []CountryCode{ITA, VAT}\n\tcase CallCode40:\n\t\treturn []CountryCode{ROU}\n\tcase CallCode41:\n\t\treturn []CountryCode{CHE}\n\tcase CallCode420:\n\t\treturn []CountryCode{CZE}\n\tcase CallCode421:\n\t\treturn []CountryCode{SVK}\n\tcase CallCode423:\n\t\treturn []CountryCode{LIE}\n\tcase CallCode43:\n\t\treturn []CountryCode{AUT}\n\tcase CallCode44:\n\t\treturn []CountryCode{GBR, GGY, IMN, JEY, XSC, XWA}\n\tcase CallCode45:\n\t\treturn []CountryCode{DNK}\n\tcase CallCode46:\n\t\treturn []CountryCode{SWE}\n\tcase CallCode47:\n\t\treturn []CountryCode{BVT, NOR, SJM}\n\tcase CallCode48:\n\t\treturn []CountryCode{POL}\n\tcase CallCode49:\n\t\treturn []CountryCode{DEU}\n\tcase CallCode500:\n\t\treturn []CountryCode{FLK, SGS}\n\tcase CallCode501:\n\t\treturn []CountryCode{BLZ}\n\tcase CallCode502:\n\t\treturn []CountryCode{GTM}\n\tcase CallCode503:\n\t\treturn []CountryCode{SLV}\n\tcase CallCode504:\n\t\treturn []CountryCode{HND}\n\tcase CallCode505:\n\t\treturn []CountryCode{NIC}\n\tcase CallCode506:\n\t\treturn []CountryCode{CRI}\n\tcase CallCode507:\n\t\treturn []CountryCode{PAN}\n\tcase CallCode508:\n\t\treturn []CountryCode{SPM}\n\tcase CallCode509:\n\t\treturn []CountryCode{HTI}\n\tcase CallCode51:\n\t\treturn []CountryCode{PER}\n\tcase CallCode52:\n\t\treturn []CountryCode{MEX}\n\tcase CallCode53:\n\t\treturn []CountryCode{CUB}\n\tcase CallCode54:\n\t\treturn []CountryCode{ARG}\n\tcase CallCode55:\n\t\treturn []CountryCode{BRA}\n\tcase CallCode56:\n\t\treturn []CountryCode{CHL}\n\tcase CallCode57:\n\t\treturn []CountryCode{COL}\n\tcase CallCode58:\n\t\treturn []CountryCode{VEN}\n\tcase CallCode590:\n\t\treturn []CountryCode{BLM, GLP, MAF}\n\tcase CallCode591:\n\t\treturn []CountryCode{BOL}\n\tcase CallCode592:\n\t\treturn []CountryCode{GUY}\n\tcase CallCode593:\n\t\treturn []CountryCode{ECU}\n\tcase CallCode594:\n\t\treturn []CountryCode{GUF}\n\tcase CallCode595:\n\t\treturn []CountryCode{PRY}\n\tcase CallCode596:\n\t\treturn []CountryCode{MTQ}\n\tcase CallCode597:\n\t\treturn []CountryCode{SUR}\n\tcase CallCode598:\n\t\treturn []CountryCode{URY}\n\tcase CallCode599:\n\t\treturn []CountryCode{ANT, BES, CUW}\n\tcase CallCode60:\n\t\treturn []CountryCode{MYS}\n\tcase CallCode61:\n\t\treturn []CountryCode{AUS, CXR, CCK}\n\tcase CallCode62:\n\t\treturn []CountryCode{IDN}\n\tcase CallCode63:\n\t\treturn []CountryCode{PHL}\n\tcase CallCode64:\n\t\treturn []CountryCode{NZL, PCN}\n\tcase CallCode65:\n\t\treturn []CountryCode{SGP}\n\tcase CallCode66:\n\t\treturn []CountryCode{THA}\n\tcase CallCode670:\n\t\treturn []CountryCode{TLS}\n\tcase CallCode672:\n\t\treturn []CountryCode{ATA, CCK, NFK}\n\tcase CallCode673:\n\t\treturn []CountryCode{BRN}\n\tcase CallCode674:\n\t\treturn []CountryCode{NRU}\n\tcase CallCode675:\n\t\treturn []CountryCode{PNG}\n\tcase CallCode676:\n\t\treturn []CountryCode{TON}\n\tcase CallCode677:\n\t\treturn []CountryCode{SLB}\n\tcase CallCode678:\n\t\treturn []CountryCode{VUT}\n\tcase CallCode679:\n\t\treturn []CountryCode{FJI}\n\tcase CallCode680:\n\t\treturn []CountryCode{PLW}\n\tcase CallCode681:\n\t\treturn []CountryCode{WLF}\n\tcase CallCode682:\n\t\treturn []CountryCode{COK}\n\tcase CallCode683:\n\t\treturn []CountryCode{NIU}\n\tcase CallCode685:\n\t\treturn []CountryCode{WSM}\n\tcase CallCode686:\n\t\treturn []CountryCode{KIR}\n\tcase CallCode687:\n\t\treturn []CountryCode{NCL}\n\tcase CallCode688:\n\t\treturn []CountryCode{TUV}\n\tcase CallCode689:\n\t\treturn []CountryCode{PYF}\n\tcase CallCode690:\n\t\treturn []CountryCode{TKL}\n\tcase CallCode691:\n\t\treturn []CountryCode{FSM}\n\tcase CallCode692:\n\t\treturn []CountryCode{MHL}\n\tcase CallCode7:\n\t\treturn []CountryCode{KAZ, RUS}\n\tcase CallCode1721, CallCode5995:\n\t\treturn []CountryCode{SXM}\n\tcase CallCode4779:\n\t\treturn []CountryCode{SJM}\n\tcase CallCode5993, CallCode5994, CallCode5997:\n\t\treturn []CountryCode{BES}\n\tcase CallCode993:\n\t\treturn []CountryCode{TKM}\n\tcase CallCode81:\n\t\treturn []CountryCode{JPN}\n\tcase CallCode82:\n\t\treturn []CountryCode{KOR}\n\tcase CallCode84:\n\t\treturn []CountryCode{VNM}\n\tcase CallCode850:\n\t\treturn []CountryCode{PRK}\n\tcase CallCode852:\n\t\treturn []CountryCode{HKG}\n\tcase CallCode853:\n\t\treturn []CountryCode{MAC}\n\tcase CallCode855:\n\t\treturn []CountryCode{KHM}\n\tcase CallCode856:\n\t\treturn []CountryCode{LAO}\n\tcase CallCode86:\n\t\treturn []CountryCode{CHN}\n\tcase CallCode800:\n\t\treturn []CountryCode{NonCountryInternationalFreephone}\n\tcase CallCode870:\n\t\treturn []CountryCode{NonCountryInmarsat}\n\tcase CallCode875, CallCode876, CallCode877:\n\t\treturn []CountryCode{NonCountryMaritimeMobileService}\n\tcase CallCode878:\n\t\treturn []CountryCode{NonCountryUniversalPersonalTelecommunicationsServices}\n\tcase CallCode879:\n\t\treturn []CountryCode{NonCountryNationalNonCommercialPurposes}\n\tcase CallCode880:\n\t\treturn []CountryCode{BGD}\n\tcase CallCode881:\n\t\treturn []CountryCode{NonCountryGlobalMobileSatelliteSystem}\n\tcase CallCode882, CallCode883:\n\t\treturn []CountryCode{NonCountryInternationalNetworks}\n\tcase CallCode886:\n\t\treturn []CountryCode{TWN}\n\tcase CallCode90:\n\t\treturn []CountryCode{TUR}\n\tcase CallCode91:\n\t\treturn []CountryCode{IND}\n\tcase CallCode92:\n\t\treturn []CountryCode{PAK}\n\tcase CallCode93:\n\t\treturn []CountryCode{AFG}\n\tcase CallCode94:\n\t\treturn []CountryCode{LKA}\n\tcase CallCode95:\n\t\treturn []CountryCode{MMR}\n\tcase CallCode888:\n\t\treturn []CountryCode{NonCountryDisasterRelief}\n\tcase CallCode960:\n\t\treturn []CountryCode{MDV}\n\tcase CallCode961:\n\t\treturn []CountryCode{LBN}\n\tcase CallCode962:\n\t\treturn []CountryCode{JOR}\n\tcase CallCode963:\n\t\treturn []CountryCode{SYR}\n\tcase CallCode964:\n\t\treturn []CountryCode{IRQ}\n\tcase CallCode965:\n\t\treturn []CountryCode{KWT}\n\tcase CallCode966:\n\t\treturn []CountryCode{SAU}\n\tcase CallCode967:\n\t\treturn []CountryCode{YEM}\n\tcase CallCode968:\n\t\treturn []CountryCode{OMN}\n\tcase CallCode970:\n\t\treturn []CountryCode{PSE}\n\tcase CallCode971:\n\t\treturn []CountryCode{ARE}\n\tcase CallCode972:\n\t\treturn []CountryCode{PSE}\n\tcase CallCode973:\n\t\treturn []CountryCode{BHR}\n\tcase CallCode974:\n\t\treturn []CountryCode{QAT}\n\tcase CallCode975:\n\t\treturn []CountryCode{BTN}\n\tcase CallCode976:\n\t\treturn []CountryCode{MNG}\n\tcase CallCode977:\n\t\treturn []CountryCode{NPL}\n\tcase CallCode98:\n\t\treturn []CountryCode{IRN}\n\tcase CallCode979:\n\t\treturn []CountryCode{NonCountryInternationalPremiumRateService}\n\tcase CallCode991:\n\t\treturn []CountryCode{NonCountryInternationalTelecommunicationsCorrespondenceService}\n\tcase CallCode992:\n\t\treturn []CountryCode{TJK}\n\tcase CallCode994:\n\t\treturn []CountryCode{AZE}\n\tcase CallCode995:\n\t\treturn []CountryCode{GEO}\n\tcase CallCode996:\n\t\treturn []CountryCode{KGZ}\n\tcase CallCode998:\n\t\treturn []CountryCode{UZB}\n\tcase CallCode5999:\n\t\treturn []CountryCode{CUW}\n\tcase CallCode35818:\n\t\treturn []CountryCode{ALA}\n\tcase CallCode441481:\n\t\treturn []CountryCode{GGY}\n\tcase CallCode441534:\n\t\treturn []CountryCode{JEY}\n\tcase CallCode441624:\n\t\treturn []CountryCode{IMN}\n\tcase CallCode3906698:\n\t\treturn []CountryCode{VAT}\n\tcase CallCode6189162:\n\t\treturn []CountryCode{CCK}\n\tcase CallCode6189164:\n\t\treturn []CountryCode{CXR}\n\t}\n\treturn []CountryCode{Unknown}\n}",
"func (c CallCode) Countries() []CountryCode { //nolint:gocyclo\n\tswitch c {\n\tcase CallCode1:\n\t\treturn []CountryCode{ATF, CAN, UMI, USA}\n\tcase CallCode1808:\n\t\treturn []CountryCode{USA}\n\tcase CallCode1242:\n\t\treturn []CountryCode{BHS}\n\tcase CallCode1246:\n\t\treturn []CountryCode{BRB}\n\tcase CallCode1264:\n\t\treturn []CountryCode{AIA}\n\tcase CallCode1268:\n\t\treturn []CountryCode{ATG}\n\tcase CallCode1284:\n\t\treturn []CountryCode{VGB}\n\tcase CallCode1340:\n\t\treturn []CountryCode{VIR}\n\tcase CallCode1345:\n\t\treturn []CountryCode{CYM}\n\tcase CallCode1441:\n\t\treturn []CountryCode{BMU}\n\tcase CallCode1473:\n\t\treturn []CountryCode{GRD}\n\tcase CallCode1649:\n\t\treturn []CountryCode{TCA}\n\tcase CallCode1664:\n\t\treturn []CountryCode{MSR}\n\tcase CallCode1670:\n\t\treturn []CountryCode{MNP}\n\tcase CallCode1671:\n\t\treturn []CountryCode{GUM}\n\tcase CallCode1684:\n\t\treturn []CountryCode{ASM}\n\tcase CallCode1758:\n\t\treturn []CountryCode{LCA}\n\tcase CallCode1767:\n\t\treturn []CountryCode{DMA}\n\tcase CallCode1784:\n\t\treturn []CountryCode{VCT}\n\tcase CallCode1787, CallCode1939:\n\t\treturn []CountryCode{PRI}\n\tcase CallCode1809, CallCode1829, CallCode1849:\n\t\treturn []CountryCode{DOM}\n\tcase CallCode1868:\n\t\treturn []CountryCode{TTO}\n\tcase CallCode1869:\n\t\treturn []CountryCode{KNA}\n\tcase CallCode1876, CallCode1658:\n\t\treturn []CountryCode{JAM}\n\tcase CallCode20:\n\t\treturn []CountryCode{EGY}\n\tcase CallCode211:\n\t\treturn []CountryCode{SSD}\n\tcase CallCode212:\n\t\treturn []CountryCode{ESH, MAR}\n\tcase CallCode213:\n\t\treturn []CountryCode{DZA}\n\tcase CallCode216:\n\t\treturn []CountryCode{TUN}\n\tcase CallCode218:\n\t\treturn []CountryCode{LBY}\n\tcase CallCode220:\n\t\treturn []CountryCode{GMB}\n\tcase CallCode221:\n\t\treturn []CountryCode{SEN}\n\tcase CallCode222:\n\t\treturn []CountryCode{MRT}\n\tcase CallCode223:\n\t\treturn []CountryCode{MLI}\n\tcase CallCode224:\n\t\treturn []CountryCode{GIN}\n\tcase CallCode225:\n\t\treturn []CountryCode{CIV}\n\tcase CallCode226:\n\t\treturn []CountryCode{BFA}\n\tcase CallCode227:\n\t\treturn []CountryCode{NER}\n\tcase CallCode228:\n\t\treturn []CountryCode{TGO}\n\tcase CallCode229:\n\t\treturn []CountryCode{BEN}\n\tcase CallCode230:\n\t\treturn []CountryCode{MUS}\n\tcase CallCode231:\n\t\treturn []CountryCode{LBR}\n\tcase CallCode232:\n\t\treturn []CountryCode{SLE}\n\tcase CallCode233:\n\t\treturn []CountryCode{GHA}\n\tcase CallCode234:\n\t\treturn []CountryCode{NGA}\n\tcase CallCode235:\n\t\treturn []CountryCode{TCD}\n\tcase CallCode236:\n\t\treturn []CountryCode{CAF}\n\tcase CallCode237:\n\t\treturn []CountryCode{CMR}\n\tcase CallCode238:\n\t\treturn []CountryCode{CPV}\n\tcase CallCode239:\n\t\treturn []CountryCode{STP}\n\tcase CallCode240:\n\t\treturn []CountryCode{GNQ}\n\tcase CallCode241:\n\t\treturn []CountryCode{GAB}\n\tcase CallCode242:\n\t\treturn []CountryCode{COG}\n\tcase CallCode243:\n\t\treturn []CountryCode{COD}\n\tcase CallCode244:\n\t\treturn []CountryCode{AGO}\n\tcase CallCode245:\n\t\treturn []CountryCode{GNB}\n\tcase CallCode246:\n\t\treturn []CountryCode{IOT}\n\tcase CallCode248:\n\t\treturn []CountryCode{SYC}\n\tcase CallCode249:\n\t\treturn []CountryCode{SDN}\n\tcase CallCode250:\n\t\treturn []CountryCode{RWA}\n\tcase CallCode251:\n\t\treturn []CountryCode{ETH}\n\tcase CallCode252:\n\t\treturn []CountryCode{SOM}\n\tcase CallCode253:\n\t\treturn []CountryCode{DJI}\n\tcase CallCode254:\n\t\treturn []CountryCode{KEN}\n\tcase CallCode255:\n\t\treturn []CountryCode{TZA}\n\tcase CallCode256:\n\t\treturn []CountryCode{UGA}\n\tcase CallCode257:\n\t\treturn []CountryCode{BDI}\n\tcase CallCode258:\n\t\treturn []CountryCode{MOZ}\n\tcase CallCode260:\n\t\treturn []CountryCode{ZMB}\n\tcase CallCode261:\n\t\treturn []CountryCode{MDG}\n\tcase CallCode262:\n\t\treturn []CountryCode{MYT, REU}\n\tcase CallCode262269, CallCode262639:\n\t\treturn []CountryCode{MYT}\n\tcase CallCode263:\n\t\treturn []CountryCode{ZWE}\n\tcase CallCode264:\n\t\treturn []CountryCode{NAM}\n\tcase CallCode265:\n\t\treturn []CountryCode{MWI}\n\tcase CallCode266:\n\t\treturn []CountryCode{LSO}\n\tcase CallCode267:\n\t\treturn []CountryCode{BWA}\n\tcase CallCode268:\n\t\treturn []CountryCode{SWZ}\n\tcase CallCode269:\n\t\treturn []CountryCode{COM}\n\tcase CallCode27:\n\t\treturn []CountryCode{ZAF}\n\tcase CallCode290:\n\t\treturn []CountryCode{SHN}\n\tcase CallCode291:\n\t\treturn []CountryCode{ERI}\n\tcase CallCode297, CallCode5998:\n\t\treturn []CountryCode{ABW}\n\tcase CallCode298:\n\t\treturn []CountryCode{FRO}\n\tcase CallCode299:\n\t\treturn []CountryCode{GRL}\n\tcase CallCode30:\n\t\treturn []CountryCode{GRC}\n\tcase CallCode31:\n\t\treturn []CountryCode{NLD}\n\tcase CallCode32:\n\t\treturn []CountryCode{BEL}\n\tcase CallCode33:\n\t\treturn []CountryCode{FRA}\n\tcase CallCode34:\n\t\treturn []CountryCode{ESP}\n\tcase CallCode350:\n\t\treturn []CountryCode{GIB}\n\tcase CallCode351:\n\t\treturn []CountryCode{PRT}\n\tcase CallCode352:\n\t\treturn []CountryCode{LUX}\n\tcase CallCode353:\n\t\treturn []CountryCode{IRL}\n\tcase CallCode354:\n\t\treturn []CountryCode{ISL}\n\tcase CallCode355:\n\t\treturn []CountryCode{ALB}\n\tcase CallCode356:\n\t\treturn []CountryCode{MLT}\n\tcase CallCode357:\n\t\treturn []CountryCode{CYP}\n\tcase CallCode358:\n\t\treturn []CountryCode{ALA, FIN}\n\tcase CallCode359:\n\t\treturn []CountryCode{BGR}\n\tcase CallCode36:\n\t\treturn []CountryCode{HUN}\n\tcase CallCode370:\n\t\treturn []CountryCode{LTU}\n\tcase CallCode371:\n\t\treturn []CountryCode{LVA}\n\tcase CallCode372:\n\t\treturn []CountryCode{EST}\n\tcase CallCode373:\n\t\treturn []CountryCode{MDA}\n\tcase CallCode374:\n\t\treturn []CountryCode{ARM}\n\tcase CallCode375:\n\t\treturn []CountryCode{BLR}\n\tcase CallCode376:\n\t\treturn []CountryCode{AND}\n\tcase CallCode377:\n\t\treturn []CountryCode{MCO}\n\tcase CallCode378:\n\t\treturn []CountryCode{SMR}\n\tcase CallCode38:\n\t\treturn []CountryCode{YUG}\n\tcase CallCode380:\n\t\treturn []CountryCode{UKR}\n\tcase CallCode381:\n\t\treturn []CountryCode{SRB}\n\tcase CallCode382:\n\t\treturn []CountryCode{MNE}\n\tcase CallCode383:\n\t\treturn []CountryCode{XKX}\n\tcase CallCode385:\n\t\treturn []CountryCode{HRV}\n\tcase CallCode386:\n\t\treturn []CountryCode{SVN}\n\tcase CallCode387:\n\t\treturn []CountryCode{BIH}\n\tcase CallCode389:\n\t\treturn []CountryCode{MKD}\n\tcase CallCode39:\n\t\treturn []CountryCode{ITA, VAT}\n\tcase CallCode40:\n\t\treturn []CountryCode{ROU}\n\tcase CallCode41:\n\t\treturn []CountryCode{CHE}\n\tcase CallCode420:\n\t\treturn []CountryCode{CZE}\n\tcase CallCode421:\n\t\treturn []CountryCode{SVK}\n\tcase CallCode423:\n\t\treturn []CountryCode{LIE}\n\tcase CallCode43:\n\t\treturn []CountryCode{AUT}\n\tcase CallCode44:\n\t\treturn []CountryCode{GBR, GGY, IMN, JEY, XSC, XWA}\n\tcase CallCode45:\n\t\treturn []CountryCode{DNK}\n\tcase CallCode46:\n\t\treturn []CountryCode{SWE}\n\tcase CallCode47:\n\t\treturn []CountryCode{BVT, NOR, SJM}\n\tcase CallCode48:\n\t\treturn []CountryCode{POL}\n\tcase CallCode49:\n\t\treturn []CountryCode{DEU}\n\tcase CallCode500:\n\t\treturn []CountryCode{FLK, SGS}\n\tcase CallCode501:\n\t\treturn []CountryCode{BLZ}\n\tcase CallCode502:\n\t\treturn []CountryCode{GTM}\n\tcase CallCode503:\n\t\treturn []CountryCode{SLV}\n\tcase CallCode504:\n\t\treturn []CountryCode{HND}\n\tcase CallCode505:\n\t\treturn []CountryCode{NIC}\n\tcase CallCode506:\n\t\treturn []CountryCode{CRI}\n\tcase CallCode507:\n\t\treturn []CountryCode{PAN}\n\tcase CallCode508:\n\t\treturn []CountryCode{SPM}\n\tcase CallCode509:\n\t\treturn []CountryCode{HTI}\n\tcase CallCode51:\n\t\treturn []CountryCode{PER}\n\tcase CallCode52:\n\t\treturn []CountryCode{MEX}\n\tcase CallCode53:\n\t\treturn []CountryCode{CUB}\n\tcase CallCode54:\n\t\treturn []CountryCode{ARG}\n\tcase CallCode55:\n\t\treturn []CountryCode{BRA}\n\tcase CallCode56:\n\t\treturn []CountryCode{CHL}\n\tcase CallCode57:\n\t\treturn []CountryCode{COL}\n\tcase CallCode58:\n\t\treturn []CountryCode{VEN}\n\tcase CallCode590:\n\t\treturn []CountryCode{BLM, GLP, MAF}\n\tcase CallCode591:\n\t\treturn []CountryCode{BOL}\n\tcase CallCode592:\n\t\treturn []CountryCode{GUY}\n\tcase CallCode593:\n\t\treturn []CountryCode{ECU}\n\tcase CallCode594:\n\t\treturn []CountryCode{GUF}\n\tcase CallCode595:\n\t\treturn []CountryCode{PRY}\n\tcase CallCode596:\n\t\treturn []CountryCode{MTQ}\n\tcase CallCode597:\n\t\treturn []CountryCode{SUR}\n\tcase CallCode598:\n\t\treturn []CountryCode{URY}\n\tcase CallCode599:\n\t\treturn []CountryCode{ANT, BES, CUW}\n\tcase CallCode60:\n\t\treturn []CountryCode{MYS}\n\tcase CallCode61:\n\t\treturn []CountryCode{AUS, CXR, CCK}\n\tcase CallCode62:\n\t\treturn []CountryCode{IDN}\n\tcase CallCode63:\n\t\treturn []CountryCode{PHL}\n\tcase CallCode64:\n\t\treturn []CountryCode{NZL, PCN}\n\tcase CallCode65:\n\t\treturn []CountryCode{SGP}\n\tcase CallCode66:\n\t\treturn []CountryCode{THA}\n\tcase CallCode670:\n\t\treturn []CountryCode{TLS}\n\tcase CallCode672:\n\t\treturn []CountryCode{ATA, CCK, NFK}\n\tcase CallCode673:\n\t\treturn []CountryCode{BRN}\n\tcase CallCode674:\n\t\treturn []CountryCode{NRU}\n\tcase CallCode675:\n\t\treturn []CountryCode{PNG}\n\tcase CallCode676:\n\t\treturn []CountryCode{TON}\n\tcase CallCode677:\n\t\treturn []CountryCode{SLB}\n\tcase CallCode678:\n\t\treturn []CountryCode{VUT}\n\tcase CallCode679:\n\t\treturn []CountryCode{FJI}\n\tcase CallCode680:\n\t\treturn []CountryCode{PLW}\n\tcase CallCode681:\n\t\treturn []CountryCode{WLF}\n\tcase CallCode682:\n\t\treturn []CountryCode{COK}\n\tcase CallCode683:\n\t\treturn []CountryCode{NIU}\n\tcase CallCode684:\n\t\treturn []CountryCode{WSM}\n\tcase CallCode686:\n\t\treturn []CountryCode{KIR}\n\tcase CallCode687:\n\t\treturn []CountryCode{NCL}\n\tcase CallCode688:\n\t\treturn []CountryCode{TUV}\n\tcase CallCode689:\n\t\treturn []CountryCode{PYF}\n\tcase CallCode690:\n\t\treturn []CountryCode{TKL}\n\tcase CallCode691:\n\t\treturn []CountryCode{FSM}\n\tcase CallCode692:\n\t\treturn []CountryCode{MHL}\n\tcase CallCode7:\n\t\treturn []CountryCode{KAZ, RUS}\n\tcase CallCode1721, CallCode5995:\n\t\treturn []CountryCode{SXM}\n\tcase CallCode4779:\n\t\treturn []CountryCode{SJM}\n\tcase CallCode5993, CallCode5994, CallCode5997:\n\t\treturn []CountryCode{BES}\n\tcase CallCode7370:\n\t\treturn []CountryCode{TKM}\n\tcase CallCode81:\n\t\treturn []CountryCode{JPN}\n\tcase CallCode82:\n\t\treturn []CountryCode{KOR}\n\tcase CallCode84:\n\t\treturn []CountryCode{VNM}\n\tcase CallCode850:\n\t\treturn []CountryCode{PRK}\n\tcase CallCode852:\n\t\treturn []CountryCode{HKG}\n\tcase CallCode853:\n\t\treturn []CountryCode{MAC}\n\tcase CallCode855:\n\t\treturn []CountryCode{KHM}\n\tcase CallCode856:\n\t\treturn []CountryCode{LAO}\n\tcase CallCode86:\n\t\treturn []CountryCode{CHN}\n\tcase CallCode800:\n\t\treturn []CountryCode{NonCountryInternationalFreephone}\n\tcase CallCode870:\n\t\treturn []CountryCode{NonCountryInmarsat}\n\tcase CallCode875, CallCode876, CallCode877:\n\t\treturn []CountryCode{NonCountryMaritimeMobileService}\n\tcase CallCode878:\n\t\treturn []CountryCode{NonCountryUniversalPersonalTelecommunicationsServices}\n\tcase CallCode879:\n\t\treturn []CountryCode{NonCountryNationalNonCommercialPurposes}\n\tcase CallCode880:\n\t\treturn []CountryCode{BGD}\n\tcase CallCode881:\n\t\treturn []CountryCode{NonCountryGlobalMobileSatelliteSystem}\n\tcase CallCode882, CallCode883:\n\t\treturn []CountryCode{NonCountryInternationalNetworks}\n\tcase CallCode886:\n\t\treturn []CountryCode{TWN}\n\tcase CallCode90:\n\t\treturn []CountryCode{TUR}\n\tcase CallCode91:\n\t\treturn []CountryCode{IND}\n\tcase CallCode92:\n\t\treturn []CountryCode{PAK}\n\tcase CallCode93:\n\t\treturn []CountryCode{AFG}\n\tcase CallCode94:\n\t\treturn []CountryCode{LKA}\n\tcase CallCode95:\n\t\treturn []CountryCode{MMR}\n\tcase CallCode888:\n\t\treturn []CountryCode{NonCountryDisasterRelief}\n\tcase CallCode960:\n\t\treturn []CountryCode{MDV}\n\tcase CallCode961:\n\t\treturn []CountryCode{LBN}\n\tcase CallCode962:\n\t\treturn []CountryCode{JOR}\n\tcase CallCode963:\n\t\treturn []CountryCode{SYR}\n\tcase CallCode964:\n\t\treturn []CountryCode{IRQ}\n\tcase CallCode965:\n\t\treturn []CountryCode{KWT}\n\tcase CallCode966:\n\t\treturn []CountryCode{SAU}\n\tcase CallCode967:\n\t\treturn []CountryCode{YEM}\n\tcase CallCode968:\n\t\treturn []CountryCode{OMN}\n\tcase CallCode971:\n\t\treturn []CountryCode{ARE}\n\tcase CallCode972:\n\t\treturn []CountryCode{ISR, PSE}\n\tcase CallCode973:\n\t\treturn []CountryCode{BHR}\n\tcase CallCode974:\n\t\treturn []CountryCode{QAT}\n\tcase CallCode975:\n\t\treturn []CountryCode{BTN}\n\tcase CallCode976:\n\t\treturn []CountryCode{MNG}\n\tcase CallCode977:\n\t\treturn []CountryCode{NPL}\n\tcase CallCode98:\n\t\treturn []CountryCode{IRN}\n\tcase CallCode979:\n\t\treturn []CountryCode{NonCountryInternationalPremiumRateService}\n\tcase CallCode991:\n\t\treturn []CountryCode{NonCountryInternationalTelecommunicationsCorrespondenceService}\n\tcase CallCode992:\n\t\treturn []CountryCode{TJK}\n\tcase CallCode994:\n\t\treturn []CountryCode{AZE}\n\tcase CallCode995:\n\t\treturn []CountryCode{GEO}\n\tcase CallCode996:\n\t\treturn []CountryCode{KGZ}\n\tcase CallCode998:\n\t\treturn []CountryCode{UZB}\n\tcase CallCode5999:\n\t\treturn []CountryCode{CUW}\n\tcase CallCode35818:\n\t\treturn []CountryCode{ALA}\n\tcase CallCode441481:\n\t\treturn []CountryCode{GGY}\n\tcase CallCode441534:\n\t\treturn []CountryCode{JEY}\n\tcase CallCode441624:\n\t\treturn []CountryCode{IMN}\n\tcase CallCode3906698:\n\t\treturn []CountryCode{VAT}\n\tcase CallCode6189162:\n\t\treturn []CountryCode{CCK}\n\tcase CallCode6189164:\n\t\treturn []CountryCode{CXR}\n\t}\n\treturn []CountryCode{Unknown}\n}",
"func isCountry(str string) bool {\n\tfor _, entry := range govalidator.ISO3166List {\n\t\tif str == entry.EnglishShortName {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}",
"func ByCode(code Code) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code.String()]\n\treturn\n}",
"func getCountryCode(name string) (string, error) {\n\tfor _, country := range consts.Countries {\n\t\tif strings.EqualFold(strings.ToUpper(country.Name), strings.ToUpper(name)) {\n\t\t\treturn country.Alpha3Code, nil\n\t\t}\n\t}\n\treturn \"OTH\", fmt.Errorf(\"cannot find country code for country %s\", name)\n}",
"func TypeFromStr(ct string) (Type, error) {\n\tswitch ct {\n\tcase \"bitcoin\":\n\t\treturn Bitcoin, nil\n\tcase \"skycoin\":\n\t\treturn Skycoin, nil\n\tdefault:\n\t\treturn -1, fmt.Errorf(\"unknow coin type:%s\", ct)\n\t}\n}",
"func ByCurrencyStrErr(currencyStr string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCurrency(currency Currency) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency.String()]\n\treturn\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCodeStrErr lookup for currency type by code
|
func ByCodeStrErr(code string) (c currency, err error) {
var ok bool
c, ok = currenciesByCode[code]
if !ok {
return currency{}, fmt.Errorf("'%s' is not valid ISO-4217 code", code)
}
return
}
|
[
"func ByCodeErr(code Code) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func ByCodeStr(code string) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func ByCurrencyStrErr(currencyStr string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCode(code Code) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code.String()]\n\treturn\n}",
"func ByCurrencyErr(currencyStr Currency) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByNumberStrErr(number string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func ByCountryStrErr(country string) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func CurrencyCode(id int) string {\n\treturn currencyCode[id]\n}",
"func (currencies currencies) CurrencyByCode(code string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.code) == code {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func InstitutionTypeByCode(code string) (string, bool) {\n\tt, ok := instType[code]\n\treturn t, ok\n}",
"func errorType(code int) string {\n\tif value, ok := errTypes[code]; ok {\n\t\treturn value\n\t}\n\treturn \"UnKnownError\"\n}",
"func (s *Server) providerTypeGetByCode(\n\tsess *pb.Session,\n\tcode string,\n) (*pb.ProviderType, error) {\n\treq := &pb.ProviderTypeGetByCodeRequest{\n\t\tSession: sess,\n\t\tCode: code,\n\t}\n\tmc, err := s.metaClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trec, err := mc.ProviderTypeGetByCode(context.Background(), req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pb.ProviderType{\n\t\tCode: rec.Code,\n\t\tDescription: rec.Description,\n\t}, nil\n}",
"func ByNumberErr(number Number) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func (repo *AccountTypeRepository) FindByNameAndCurrencyCode(name, currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"name = ? AND currency_code = ?\", name, currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func (repo *AccountTypeRepository) FindByCurrencyCode(currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"currency_code = ?\", currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func ByCurrencyStr(currency string) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency]\n\treturn\n}",
"func (me TCurrencyCodeType) String() string { return xsdt.String(me).String() }",
"func (o *GetRuleTypesNotFound) Code() int {\n\treturn 404\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCurrencyStrErr lookup for currency type by currency
|
func ByCurrencyStrErr(currencyStr string) (c currency, err error) {
var ok bool
c, ok = currenciesByCurrency[currencyStr]
if !ok {
return currency{}, fmt.Errorf("'%s' is not valid ISO-4217 currency", currencyStr)
}
return
}
|
[
"func ByCurrencyErr(currencyStr Currency) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCountryStrErr(country string) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func ByCurrencyStr(currency string) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency]\n\treturn\n}",
"func ByCodeStrErr(code string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func ByNumberStrErr(number string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func ByCodeErr(code Code) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func ByCountryErr(country Country) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country.String()]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func ByNumberErr(number Number) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func (currencies currencies) CurrencyByCurrency(curr string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.currency) == curr {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func (l *Ledger) GetCurrency(s string) (*Currency, bool) {\n\tfor i := range l.Currencies {\n\t\tif s == l.Currencies[i].Name {\n\t\t\treturn l.Currencies[i], false\n\t\t}\n\t}\n\tvar currency Currency\n\tcurrency.Name = s\n\tl.Currencies = append(l.Currencies, ¤cy)\n\treturn ¤cy, true\n}",
"func ByCurrency(currency Currency) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency.String()]\n\treturn\n}",
"func ByCodeStr(code string) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func CurrencySymbol(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {\n\tcode := in.String()\n\tif code == \"\" {\n\t\treturn pongo2.AsValue(\"\"), nil\n\t}\n\tcurrencyObj := c.Get(code)\n\treturn pongo2.AsValue(currencyObj.Symbol), nil\n}",
"func ByNumberStr(number string) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number]\n\treturn\n}",
"func ByCountryStr(country string) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country]\n\treturn\n}",
"func CurrencyCode(id int) string {\n\treturn currencyCode[id]\n}",
"func SuggestCurrency(currency string) (string, error) {\n\tif currency == \"\" {\n\t\treturn \"USD\", nil\n\t}\n\n\tc, validList, err := gql.QueryCurrency(currency)\n\tif err != nil {\n\t\te := fmt.Sprintf(\"Valid currency are: %q. Your input: %q\", validList, currency)\n\t\treturn \"\", errors.New(e)\n\t}\n\treturn c, nil\n}",
"func GetCurrency(code Code) (c Currency, ok bool) {\n\tok = false\n\tif !code.IsValid() {\n\t\treturn\n\t}\n\n\tc, ok = currenciesByCode[code]\n\treturn\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByNumberStrErr lookup for currency type by number
|
func ByNumberStrErr(number string) (c currency, err error) {
var ok bool
c, ok = currenciesByNumber[number]
if !ok {
return currency{}, fmt.Errorf("'%s' is not valid ISO-4217 number", number)
}
return
}
|
[
"func ByNumberErr(number Number) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func ByNumberStr(number string) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number]\n\treturn\n}",
"func ByCurrencyErr(currencyStr Currency) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCurrencyStrErr(currencyStr string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCodeStrErr(code string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func ByCodeErr(code Code) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func ByNumber(number Number) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number.String()]\n\treturn\n}",
"func ByNumeric(s string) (Currency, bool) {\n\tc, ok := byNumeric[s]\n\tif ok {\n\t\treturn *c, true\n\t}\n\n\treturn Currency{}, false\n}",
"func ByCountryStrErr(country string) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func (currencies currencies) CurrencyByNumber(number string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.number) == number {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByCurrencyStr(currency string) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency]\n\treturn\n}",
"func ByCodeStr(code string) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func Currency(query string) string {\n\tyahoo := \"http://download.finance.yahoo.com/d/quotes.csv?f=l1&e=.csv&s=\"\n\n\tparts := strings.Split(strings.TrimSpace(query), \" \")\n\tif len(parts) != 4 {\n\t\treturn \"Error - Malformed query (ex. 100 JPY in USD)\"\n\t}\n\n\tr := strings.NewReplacer(\",\", \"\", \"K\", \"e3\", \"M\", \"e6\", \"B\", \"e9\")\n\n\tmultiplier, err := strconv.ParseFloat(r.Replace(strings.ToUpper(strings.TrimSpace(parts[0]))), 64)\n\tif err != nil {\n\t\treturn \"Error - \" + err.Error()\n\t}\n\n\tfrom := checkCurrency(parts[1])\n\tto := checkCurrency(parts[3])\n\n\tqueryUrl := yahoo + from + to + \"=X\"\n\n\tresp, err := http.Get(queryUrl)\n\tif err != nil {\n\t\treturn \"Error - \" + err.Error()\n\t}\n\tdefer resp.Body.Close()\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"Error - \" + err.Error()\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn \"Error - Something went wrong\"\n\t\tfmt.Println(\"Yahoo error dump: \", string(data))\n\t}\n\n\tnumber, err := strconv.ParseFloat(strings.TrimSpace(string(data)), 64)\n\tif err != nil {\n\t\tif strings.TrimSpace(string(data)) == \"N/A\" {\n\t\t\treturn \"Error - Unknown currency\"\n\t\t}\n\t\treturn \"Error - \" + err.Error()\n\t}\n\n\treturn fmt.Sprintf(\"%s %s is \\x02%s\\x02 %s\", parts[0], from, humanize(multiplier*number), to)\n}",
"func FindByNumber(num int) *Country {\n\tsearch := fmt.Sprintf(\"%03d\", num)\n\tfor _, c := range countries {\n\t\tif c.ExistsNum(search) {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}",
"func CurrencySymbol(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {\n\tcode := in.String()\n\tif code == \"\" {\n\t\treturn pongo2.AsValue(\"\"), nil\n\t}\n\tcurrencyObj := c.Get(code)\n\treturn pongo2.AsValue(currencyObj.Symbol), nil\n}",
"func ByCountryErr(country Country) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country.String()]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func convertCardError(t stripe.ErrorCode) pb.CardErrors {\n\tlookup := map[stripe.ErrorCode]pb.CardErrors{\n\t\tstripe.IncorrectNum: pb.CardErrors_IncorrectNumber,\n\t\tstripe.InvalidNum: pb.CardErrors_InvalidNumber,\n\t\tstripe.InvalidExpM: pb.CardErrors_InvalidExpirationMonth,\n\t\tstripe.InvalidExpY: pb.CardErrors_InvalidExpirationYear,\n\t\tstripe.InvalidCvc: pb.CardErrors_InvalidCvc,\n\t\tstripe.ExpiredCard: pb.CardErrors_Expired,\n\t\tstripe.IncorrectCvc: pb.CardErrors_IncorrectCvc,\n\t\tstripe.IncorrectZip: pb.CardErrors_IncorrectZip,\n\t\tstripe.CardDeclined: pb.CardErrors_Declined,\n\t\tstripe.Missing: pb.CardErrors_Missing,\n\t\tstripe.ProcessingErr: pb.CardErrors_ProcessingError,\n\t\tstripe.RateLimit: pb.CardErrors_RateLimited,\n\t}\n\treturn lookup[t]\n}",
"func convertErrorType(t stripe.ErrorType) pb.ErrorType {\n\tlookup := map[stripe.ErrorType]pb.ErrorType{\n\t\tstripe.ErrorTypeAPI: pb.ErrorType_API,\n\t\tstripe.ErrorTypeAPIConnection: pb.ErrorType_APIConnection,\n\t\tstripe.ErrorTypeAuthentication: pb.ErrorType_Authentication,\n\t\tstripe.ErrorTypeCard: pb.ErrorType_Card,\n\t\tstripe.ErrorTypeInvalidRequest: pb.ErrorType_InvalidRequest,\n\t\tstripe.ErrorTypePermission: pb.ErrorType_Permission,\n\t\tstripe.ErrorTypeRateLimit: pb.ErrorType_RateLimit,\n\t}\n\treturn lookup[t]\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCountryStrErr lookup for currencies type by country
|
func ByCountryStrErr(country string) (c currencies, err error) {
var ok bool
c, ok = currenciesByCountry[country]
if !ok {
return nil, fmt.Errorf("'%s' is not valid ISO-4217 country", country)
}
return
}
|
[
"func ByCountryErr(country Country) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country.String()]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func ByCountryStr(country string) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country]\n\treturn\n}",
"func ByCurrencyStrErr(currencyStr string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCurrencyErr(currencyStr Currency) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCountry(country Country) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country.String()]\n\treturn\n}",
"func ByCodeStrErr(code string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func lookupCountry(remoteAddr string) string {\n\thost, _, _ := net.SplitHostPort(remoteAddr)\n\ta := net.ParseIP(host)\n\tif a == nil {\n\t\treturn \"id\"\n\t}\n\n\tvar rec struct {\n\t\tCountry struct {\n\t\t\tISOCode string `maxminddb:\"iso_code\"`\n\t\t} `maxminddb:\"country\"`\n\t}\n\n\terr := geoipdb.Lookup(a, &rec)\n\tif err != nil || rec.Country.ISOCode == \"\" {\n\t\treturn \"id\"\n\t}\n\n\treturn strings.ToLower(rec.Country.ISOCode)\n}",
"func ByCodeErr(code Code) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func isCountry(str string) bool {\n\tfor _, entry := range govalidator.ISO3166List {\n\t\tif str == entry.EnglishShortName {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}",
"func ByCurrencyStr(currency string) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency]\n\treturn\n}",
"func GetCountryData(ipString string) (Country, error) {\n\tvar country Country\n\tvar record map[string]interface{}\n\tip := net.ParseIP(ipString)\n\terr := CountryDatabase.Lookup(ip, &record)\n\tif err != nil {\n\t\tLog(log.ErrorLevel, err.Error(), flag.Lookup(\"test.v\") == nil)\n\t\treturn country, err\n\t}\n\n\t//this solution is assuming that the maxmind records will always have this uniform data structure on returning,\n\t// the way this is implemented, it allows for safe unboxing in the off-chance that there are missing map values\n\tcountryData, ok := record[\"country\"].(map[string]interface{})\n\tif !ok {\n\t\terr := fmt.Errorf(\"failed to find country value\")\n\t\tLog(log.ErrorLevel, err.Error(), flag.Lookup(\"test.v\") == nil)\n\t\treturn country, err\n\t}\n\tcountryNames, ok := countryData[\"names\"].(map[string]interface{})\n\tif !ok {\n\t\terr := fmt.Errorf(\"failed to find country names value\")\n\t\tLog(log.ErrorLevel, err.Error(), flag.Lookup(\"test.v\") == nil)\n\t\treturn country, err\n\t}\n\tname, ok := countryNames[\"en\"].(string)\n\tif !ok {\n\t\terr := fmt.Errorf(\"failed to find country name english value\")\n\t\tLog(log.ErrorLevel, err.Error(), flag.Lookup(\"test.v\") == nil)\n\t\treturn country, err\n\t}\n\n\tcountry.Name = name\n\n\t//version 1.0.0 calls for a list of regular names, so this data is supplementary; however\n\t//we may want to look toward this in the future since it seems to be a more uniform datatype,\n\t//allowing universal support for non-english users\n\tisoCode, ok := countryData[\"iso_code\"].(string)\n\tif !ok {\n\t\tcountry.IsoCode = \"UNKNOWN\"\n\t} else {\n\t\tcountry.IsoCode = isoCode\n\t}\n\n\treturn country, nil\n}",
"func getCountryCode(name string) (string, error) {\n\tfor _, country := range consts.Countries {\n\t\tif strings.EqualFold(strings.ToUpper(country.Name), strings.ToUpper(name)) {\n\t\t\treturn country.Alpha3Code, nil\n\t\t}\n\t}\n\treturn \"OTH\", fmt.Errorf(\"cannot find country code for country %s\", name)\n}",
"func ByNumberStrErr(number string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func CountryCode(s string) string {\n\tif s == \"zz\" {\n\t\treturn \"zz\"\n\t}\n\n\twords := CountryWordsRegexp.FindAllString(s, -1)\n\n\tfor i, w := range words {\n\t\tif i < len(words)-1 {\n\t\t\tsearch := strings.ToLower(w + \" \" + words[i+1])\n\n\t\t\tif code, ok := Countries[search]; ok {\n\t\t\t\treturn code\n\t\t\t}\n\t\t}\n\n\t\tsearch := strings.ToLower(w)\n\n\t\tif code, ok := Countries[search]; ok {\n\t\t\treturn code\n\t\t}\n\t}\n\n\treturn \"zz\"\n}",
"func Country(countryStyle int64) string {\n\tcountry := \"\"\n\tswitch countryStyle {\n\n\tdefault:\n\n\tcase FullCountry:\n\t\tcountry = randomFrom(jsonData.Countries)\n\t\tbreak\n\n\tcase TwoCharCountry:\n\t\tcountry = randomFrom(jsonData.CountriesTwoChars)\n\t\tbreak\n\n\tcase ThreeCharCountry:\n\t\tcountry = randomFrom(jsonData.CountriesThreeChars)\n\t\tbreak\n\t}\n\treturn country\n}",
"func (instance *XCountryRepo) GetByISO2Code(iso2Code string) (model.XCountry, error) {\n\treturn instance.getByField(\"iso2Code\", iso2Code)\n}",
"func CheckCountryCode (SenderCountryCode string, ReceiverCountryCode string) error {\n //I would rather have been mapping this, or use the API github.com/biter777/countries if i where to use country names.\n worlds := []string{\"AF\",\"AX\",\"AL\",\"DZ\",\"AS\",\"AD\",\"AO\",\"AI\",\"AQ\",\"AG\",\"AR\",\"AM\",\"AW\",\"AU\",\"AT\",\"AZ\",\"BS\",\"BH\",\"BD\",\"BB\",\"BY\",\"BE\",\"BZ\",\n \"BJ\",\"BM\",\"BT\",\"BO\",\"BA\",\"BW\",\"BV\",\"BR\",\"IO\",\"BN\",\"BG\",\"BF\",\"BI\",\"KH\",\"CM\",\"CA\",\"CV\",\"KY\",\"CF\",\"TD\",\"CL\",\"CN\",\"CX\",\n \"CC\",\"CO\",\"KM\",\"CG\",\"CD\",\"CK\",\"CR\",\"CI\",\"HR\",\"CU\",\"CY\",\"CZ\",\"DK\",\"DJ\",\"DM\",\"DO\",\"EC\",\"EG\",\"SV\",\"GQ\",\"ER\",\"EE\",\"ET\",\n \"FK\",\"FO\",\"FJ\",\"FI\",\"FR\",\"GF\",\"PF\",\"TF\",\"GA\",\"GM\",\"GE\",\"DE\",\"GH\",\"GI\",\"GR\",\"GL\",\"GD\",\"GP\",\"GU\",\"GT\",\"GG\",\"GN\",\"GW\",\n \"GY\",\"HT\",\"HM\",\"VA\",\"HN\",\"HK\",\"HU\",\"IS\",\"IN\",\"ID\",\"IR\",\"IQ\",\"IE\",\"IM\",\"IL\",\"IT\",\"JM\",\"JP\",\"JE\",\"JO\",\"KZ\",\"KE\",\"KI\",\n \"KR\",\"KW\",\"KG\",\"LA\",\"LV\",\"LB\",\"LS\",\"LR\",\"LY\",\"LI\",\"LT\",\"LU\",\"MO\",\"MK\",\"MG\",\"MW\",\"MY\",\"MV\",\"ML\",\"MT\",\"MH\",\"MQ\",\"MR\",\n \"MU\",\"YT\",\"MX\",\"FM\",\"MD\",\"MC\",\"MN\",\"ME\",\"MS\",\"MA\",\"MZ\",\"MM\",\"NA\",\"NR\",\"NP\",\"NL\",\"AN\",\"NC\",\"NZ\",\"NI\",\"NE\",\"NG\",\"NU\",\n \"NF\",\"MP\",\"NO\",\"OM\",\"PK\",\"PW\",\"PS\",\"PA\",\"PG\",\"PY\",\"PE\",\"PH\",\"PN\",\"PL\",\"PT\",\"PR\",\"QA\",\"RE\",\"RO\",\"RU\",\"RW\",\"BL\",\"SH\",\n \"KN\",\"LC\",\"MF\",\"PM\",\"VC\",\"WS\",\"SM\",\"ST\",\"SA\",\"SN\",\"RS\",\"SC\",\"SL\",\"SG\",\"SK\",\"SI\",\"SB\",\"SO\",\"ZA\",\"GS\",\"ES\",\"LK\",\"SD\",\n \"SR\",\"SJ\",\"SZ\",\"SE\",\"CH\",\"SY\",\"TW\",\"TJ\",\"TZ\",\"TH\",\"TL\",\"TG\",\"TK\",\"TO\",\"TT\",\"TN\",\"TR\",\"TM\",\"TC\",\"TV\",\"UG\",\"UA\",\"AE\",\n \"GB\",\"US\",\"UM\",\"UY\",\"UZ\",\"VU\",\"VE\",\"VN\",\"VG\",\"VI\",\"WF\",\"EH\",\"YE\",\"ZM\",\"ZW\"}\n\n i := ValidateSenderCountry(worlds, SenderCountryCode)\n k := ValidateReceiverCountry(worlds, ReceiverCountryCode)\n\n if k == true && i == true {\n return nil\n }\n\treturn errors.New(\"invalid\")\n}",
"func (c CallCode) Countries() []CountryCode { //nolint:gocyclo\n\tswitch c {\n\tcase CallCode1:\n\t\treturn []CountryCode{ATF, CAN, UMI, USA}\n\tcase CallCode1808:\n\t\treturn []CountryCode{USA}\n\tcase CallCode1242:\n\t\treturn []CountryCode{BHS}\n\tcase CallCode1246:\n\t\treturn []CountryCode{BRB}\n\tcase CallCode1264:\n\t\treturn []CountryCode{AIA}\n\tcase CallCode1268:\n\t\treturn []CountryCode{ATG}\n\tcase CallCode1284:\n\t\treturn []CountryCode{VGB}\n\tcase CallCode1340:\n\t\treturn []CountryCode{VIR}\n\tcase CallCode1345:\n\t\treturn []CountryCode{CYM}\n\tcase CallCode1441:\n\t\treturn []CountryCode{BMU}\n\tcase CallCode1473:\n\t\treturn []CountryCode{GRD}\n\tcase CallCode1649:\n\t\treturn []CountryCode{TCA}\n\tcase CallCode1664:\n\t\treturn []CountryCode{MSR}\n\tcase CallCode1670:\n\t\treturn []CountryCode{MNP}\n\tcase CallCode1671:\n\t\treturn []CountryCode{GUM}\n\tcase CallCode1684:\n\t\treturn []CountryCode{ASM}\n\tcase CallCode1758:\n\t\treturn []CountryCode{LCA}\n\tcase CallCode1767:\n\t\treturn []CountryCode{DMA}\n\tcase CallCode1784:\n\t\treturn []CountryCode{VCT}\n\tcase CallCode1787, CallCode1939:\n\t\treturn []CountryCode{PRI}\n\tcase CallCode1809, CallCode1829, CallCode1849:\n\t\treturn []CountryCode{DOM}\n\tcase CallCode1868:\n\t\treturn []CountryCode{TTO}\n\tcase CallCode1869:\n\t\treturn []CountryCode{KNA}\n\tcase CallCode1876, CallCode1658:\n\t\treturn []CountryCode{JAM}\n\tcase CallCode20:\n\t\treturn []CountryCode{EGY}\n\tcase CallCode211:\n\t\treturn []CountryCode{SSD}\n\tcase CallCode212:\n\t\treturn []CountryCode{ESH, MAR}\n\tcase CallCode213:\n\t\treturn []CountryCode{DZA}\n\tcase CallCode216:\n\t\treturn []CountryCode{TUN}\n\tcase CallCode218:\n\t\treturn []CountryCode{LBY}\n\tcase CallCode220:\n\t\treturn []CountryCode{GMB}\n\tcase CallCode221:\n\t\treturn []CountryCode{SEN}\n\tcase CallCode222:\n\t\treturn []CountryCode{MRT}\n\tcase CallCode223:\n\t\treturn []CountryCode{MLI}\n\tcase CallCode224:\n\t\treturn []CountryCode{GIN}\n\tcase CallCode225:\n\t\treturn []CountryCode{CIV}\n\tcase CallCode226:\n\t\treturn []CountryCode{BFA}\n\tcase CallCode227:\n\t\treturn []CountryCode{NER}\n\tcase CallCode228:\n\t\treturn []CountryCode{TGO}\n\tcase CallCode229:\n\t\treturn []CountryCode{BEN}\n\tcase CallCode230:\n\t\treturn []CountryCode{MUS}\n\tcase CallCode231:\n\t\treturn []CountryCode{LBR}\n\tcase CallCode232:\n\t\treturn []CountryCode{SLE}\n\tcase CallCode233:\n\t\treturn []CountryCode{GHA}\n\tcase CallCode234:\n\t\treturn []CountryCode{NGA}\n\tcase CallCode235:\n\t\treturn []CountryCode{TCD}\n\tcase CallCode236:\n\t\treturn []CountryCode{CAF}\n\tcase CallCode237:\n\t\treturn []CountryCode{CMR}\n\tcase CallCode238:\n\t\treturn []CountryCode{CPV}\n\tcase CallCode239:\n\t\treturn []CountryCode{STP}\n\tcase CallCode240:\n\t\treturn []CountryCode{GNQ}\n\tcase CallCode241:\n\t\treturn []CountryCode{GAB}\n\tcase CallCode242:\n\t\treturn []CountryCode{COG}\n\tcase CallCode243:\n\t\treturn []CountryCode{COD}\n\tcase CallCode244:\n\t\treturn []CountryCode{AGO}\n\tcase CallCode245:\n\t\treturn []CountryCode{GNB}\n\tcase CallCode246:\n\t\treturn []CountryCode{IOT}\n\tcase CallCode248:\n\t\treturn []CountryCode{SYC}\n\tcase CallCode249:\n\t\treturn []CountryCode{SDN}\n\tcase CallCode250:\n\t\treturn []CountryCode{RWA}\n\tcase CallCode251:\n\t\treturn []CountryCode{ETH}\n\tcase CallCode252:\n\t\treturn []CountryCode{SOM}\n\tcase CallCode253:\n\t\treturn []CountryCode{DJI}\n\tcase CallCode254:\n\t\treturn []CountryCode{KEN}\n\tcase CallCode255:\n\t\treturn []CountryCode{TZA}\n\tcase CallCode256:\n\t\treturn []CountryCode{UGA}\n\tcase CallCode257:\n\t\treturn []CountryCode{BDI}\n\tcase CallCode258:\n\t\treturn []CountryCode{MOZ}\n\tcase CallCode260:\n\t\treturn []CountryCode{ZMB}\n\tcase CallCode261:\n\t\treturn []CountryCode{MDG}\n\tcase CallCode262:\n\t\treturn []CountryCode{MYT, REU}\n\tcase CallCode262269, CallCode262639:\n\t\treturn []CountryCode{MYT}\n\tcase CallCode263:\n\t\treturn []CountryCode{ZWE}\n\tcase CallCode264:\n\t\treturn []CountryCode{NAM}\n\tcase CallCode265:\n\t\treturn []CountryCode{MWI}\n\tcase CallCode266:\n\t\treturn []CountryCode{LSO}\n\tcase CallCode267:\n\t\treturn []CountryCode{BWA}\n\tcase CallCode268:\n\t\treturn []CountryCode{SWZ}\n\tcase CallCode269:\n\t\treturn []CountryCode{COM}\n\tcase CallCode27:\n\t\treturn []CountryCode{ZAF}\n\tcase CallCode290:\n\t\treturn []CountryCode{SHN}\n\tcase CallCode291:\n\t\treturn []CountryCode{ERI}\n\tcase CallCode297, CallCode5998:\n\t\treturn []CountryCode{ABW}\n\tcase CallCode298:\n\t\treturn []CountryCode{FRO}\n\tcase CallCode299:\n\t\treturn []CountryCode{GRL}\n\tcase CallCode30:\n\t\treturn []CountryCode{GRC}\n\tcase CallCode31:\n\t\treturn []CountryCode{NLD}\n\tcase CallCode32:\n\t\treturn []CountryCode{BEL}\n\tcase CallCode33:\n\t\treturn []CountryCode{FRA}\n\tcase CallCode34:\n\t\treturn []CountryCode{ESP}\n\tcase CallCode350:\n\t\treturn []CountryCode{GIB}\n\tcase CallCode351:\n\t\treturn []CountryCode{PRT}\n\tcase CallCode352:\n\t\treturn []CountryCode{LUX}\n\tcase CallCode353:\n\t\treturn []CountryCode{IRL}\n\tcase CallCode354:\n\t\treturn []CountryCode{ISL}\n\tcase CallCode355:\n\t\treturn []CountryCode{ALB}\n\tcase CallCode356:\n\t\treturn []CountryCode{MLT}\n\tcase CallCode357:\n\t\treturn []CountryCode{CYP}\n\tcase CallCode358:\n\t\treturn []CountryCode{ALA, FIN}\n\tcase CallCode359:\n\t\treturn []CountryCode{BGR}\n\tcase CallCode36:\n\t\treturn []CountryCode{HUN}\n\tcase CallCode370:\n\t\treturn []CountryCode{LTU}\n\tcase CallCode371:\n\t\treturn []CountryCode{LVA}\n\tcase CallCode372:\n\t\treturn []CountryCode{EST}\n\tcase CallCode373:\n\t\treturn []CountryCode{MDA}\n\tcase CallCode374:\n\t\treturn []CountryCode{ARM}\n\tcase CallCode375:\n\t\treturn []CountryCode{BLR}\n\tcase CallCode376:\n\t\treturn []CountryCode{AND}\n\tcase CallCode377:\n\t\treturn []CountryCode{MCO}\n\tcase CallCode378:\n\t\treturn []CountryCode{SMR}\n\tcase CallCode38:\n\t\treturn []CountryCode{YUG}\n\tcase CallCode380:\n\t\treturn []CountryCode{UKR}\n\tcase CallCode381:\n\t\treturn []CountryCode{SRB}\n\tcase CallCode382:\n\t\treturn []CountryCode{MNE}\n\tcase CallCode383:\n\t\treturn []CountryCode{XKX}\n\tcase CallCode385:\n\t\treturn []CountryCode{HRV}\n\tcase CallCode386:\n\t\treturn []CountryCode{SVN}\n\tcase CallCode387:\n\t\treturn []CountryCode{BIH}\n\tcase CallCode389:\n\t\treturn []CountryCode{MKD}\n\tcase CallCode39:\n\t\treturn []CountryCode{ITA, VAT}\n\tcase CallCode40:\n\t\treturn []CountryCode{ROU}\n\tcase CallCode41:\n\t\treturn []CountryCode{CHE}\n\tcase CallCode420:\n\t\treturn []CountryCode{CZE}\n\tcase CallCode421:\n\t\treturn []CountryCode{SVK}\n\tcase CallCode423:\n\t\treturn []CountryCode{LIE}\n\tcase CallCode43:\n\t\treturn []CountryCode{AUT}\n\tcase CallCode44:\n\t\treturn []CountryCode{GBR, GGY, IMN, JEY, XSC, XWA}\n\tcase CallCode45:\n\t\treturn []CountryCode{DNK}\n\tcase CallCode46:\n\t\treturn []CountryCode{SWE}\n\tcase CallCode47:\n\t\treturn []CountryCode{BVT, NOR, SJM}\n\tcase CallCode48:\n\t\treturn []CountryCode{POL}\n\tcase CallCode49:\n\t\treturn []CountryCode{DEU}\n\tcase CallCode500:\n\t\treturn []CountryCode{FLK, SGS}\n\tcase CallCode501:\n\t\treturn []CountryCode{BLZ}\n\tcase CallCode502:\n\t\treturn []CountryCode{GTM}\n\tcase CallCode503:\n\t\treturn []CountryCode{SLV}\n\tcase CallCode504:\n\t\treturn []CountryCode{HND}\n\tcase CallCode505:\n\t\treturn []CountryCode{NIC}\n\tcase CallCode506:\n\t\treturn []CountryCode{CRI}\n\tcase CallCode507:\n\t\treturn []CountryCode{PAN}\n\tcase CallCode508:\n\t\treturn []CountryCode{SPM}\n\tcase CallCode509:\n\t\treturn []CountryCode{HTI}\n\tcase CallCode51:\n\t\treturn []CountryCode{PER}\n\tcase CallCode52:\n\t\treturn []CountryCode{MEX}\n\tcase CallCode53:\n\t\treturn []CountryCode{CUB}\n\tcase CallCode54:\n\t\treturn []CountryCode{ARG}\n\tcase CallCode55:\n\t\treturn []CountryCode{BRA}\n\tcase CallCode56:\n\t\treturn []CountryCode{CHL}\n\tcase CallCode57:\n\t\treturn []CountryCode{COL}\n\tcase CallCode58:\n\t\treturn []CountryCode{VEN}\n\tcase CallCode590:\n\t\treturn []CountryCode{BLM, GLP, MAF}\n\tcase CallCode591:\n\t\treturn []CountryCode{BOL}\n\tcase CallCode592:\n\t\treturn []CountryCode{GUY}\n\tcase CallCode593:\n\t\treturn []CountryCode{ECU}\n\tcase CallCode594:\n\t\treturn []CountryCode{GUF}\n\tcase CallCode595:\n\t\treturn []CountryCode{PRY}\n\tcase CallCode596:\n\t\treturn []CountryCode{MTQ}\n\tcase CallCode597:\n\t\treturn []CountryCode{SUR}\n\tcase CallCode598:\n\t\treturn []CountryCode{URY}\n\tcase CallCode599:\n\t\treturn []CountryCode{ANT, BES, CUW}\n\tcase CallCode60:\n\t\treturn []CountryCode{MYS}\n\tcase CallCode61:\n\t\treturn []CountryCode{AUS, CXR, CCK}\n\tcase CallCode62:\n\t\treturn []CountryCode{IDN}\n\tcase CallCode63:\n\t\treturn []CountryCode{PHL}\n\tcase CallCode64:\n\t\treturn []CountryCode{NZL, PCN}\n\tcase CallCode65:\n\t\treturn []CountryCode{SGP}\n\tcase CallCode66:\n\t\treturn []CountryCode{THA}\n\tcase CallCode670:\n\t\treturn []CountryCode{TLS}\n\tcase CallCode672:\n\t\treturn []CountryCode{ATA, CCK, NFK}\n\tcase CallCode673:\n\t\treturn []CountryCode{BRN}\n\tcase CallCode674:\n\t\treturn []CountryCode{NRU}\n\tcase CallCode675:\n\t\treturn []CountryCode{PNG}\n\tcase CallCode676:\n\t\treturn []CountryCode{TON}\n\tcase CallCode677:\n\t\treturn []CountryCode{SLB}\n\tcase CallCode678:\n\t\treturn []CountryCode{VUT}\n\tcase CallCode679:\n\t\treturn []CountryCode{FJI}\n\tcase CallCode680:\n\t\treturn []CountryCode{PLW}\n\tcase CallCode681:\n\t\treturn []CountryCode{WLF}\n\tcase CallCode682:\n\t\treturn []CountryCode{COK}\n\tcase CallCode683:\n\t\treturn []CountryCode{NIU}\n\tcase CallCode685:\n\t\treturn []CountryCode{WSM}\n\tcase CallCode686:\n\t\treturn []CountryCode{KIR}\n\tcase CallCode687:\n\t\treturn []CountryCode{NCL}\n\tcase CallCode688:\n\t\treturn []CountryCode{TUV}\n\tcase CallCode689:\n\t\treturn []CountryCode{PYF}\n\tcase CallCode690:\n\t\treturn []CountryCode{TKL}\n\tcase CallCode691:\n\t\treturn []CountryCode{FSM}\n\tcase CallCode692:\n\t\treturn []CountryCode{MHL}\n\tcase CallCode7:\n\t\treturn []CountryCode{KAZ, RUS}\n\tcase CallCode1721, CallCode5995:\n\t\treturn []CountryCode{SXM}\n\tcase CallCode4779:\n\t\treturn []CountryCode{SJM}\n\tcase CallCode5993, CallCode5994, CallCode5997:\n\t\treturn []CountryCode{BES}\n\tcase CallCode993:\n\t\treturn []CountryCode{TKM}\n\tcase CallCode81:\n\t\treturn []CountryCode{JPN}\n\tcase CallCode82:\n\t\treturn []CountryCode{KOR}\n\tcase CallCode84:\n\t\treturn []CountryCode{VNM}\n\tcase CallCode850:\n\t\treturn []CountryCode{PRK}\n\tcase CallCode852:\n\t\treturn []CountryCode{HKG}\n\tcase CallCode853:\n\t\treturn []CountryCode{MAC}\n\tcase CallCode855:\n\t\treturn []CountryCode{KHM}\n\tcase CallCode856:\n\t\treturn []CountryCode{LAO}\n\tcase CallCode86:\n\t\treturn []CountryCode{CHN}\n\tcase CallCode800:\n\t\treturn []CountryCode{NonCountryInternationalFreephone}\n\tcase CallCode870:\n\t\treturn []CountryCode{NonCountryInmarsat}\n\tcase CallCode875, CallCode876, CallCode877:\n\t\treturn []CountryCode{NonCountryMaritimeMobileService}\n\tcase CallCode878:\n\t\treturn []CountryCode{NonCountryUniversalPersonalTelecommunicationsServices}\n\tcase CallCode879:\n\t\treturn []CountryCode{NonCountryNationalNonCommercialPurposes}\n\tcase CallCode880:\n\t\treturn []CountryCode{BGD}\n\tcase CallCode881:\n\t\treturn []CountryCode{NonCountryGlobalMobileSatelliteSystem}\n\tcase CallCode882, CallCode883:\n\t\treturn []CountryCode{NonCountryInternationalNetworks}\n\tcase CallCode886:\n\t\treturn []CountryCode{TWN}\n\tcase CallCode90:\n\t\treturn []CountryCode{TUR}\n\tcase CallCode91:\n\t\treturn []CountryCode{IND}\n\tcase CallCode92:\n\t\treturn []CountryCode{PAK}\n\tcase CallCode93:\n\t\treturn []CountryCode{AFG}\n\tcase CallCode94:\n\t\treturn []CountryCode{LKA}\n\tcase CallCode95:\n\t\treturn []CountryCode{MMR}\n\tcase CallCode888:\n\t\treturn []CountryCode{NonCountryDisasterRelief}\n\tcase CallCode960:\n\t\treturn []CountryCode{MDV}\n\tcase CallCode961:\n\t\treturn []CountryCode{LBN}\n\tcase CallCode962:\n\t\treturn []CountryCode{JOR}\n\tcase CallCode963:\n\t\treturn []CountryCode{SYR}\n\tcase CallCode964:\n\t\treturn []CountryCode{IRQ}\n\tcase CallCode965:\n\t\treturn []CountryCode{KWT}\n\tcase CallCode966:\n\t\treturn []CountryCode{SAU}\n\tcase CallCode967:\n\t\treturn []CountryCode{YEM}\n\tcase CallCode968:\n\t\treturn []CountryCode{OMN}\n\tcase CallCode970:\n\t\treturn []CountryCode{PSE}\n\tcase CallCode971:\n\t\treturn []CountryCode{ARE}\n\tcase CallCode972:\n\t\treturn []CountryCode{PSE}\n\tcase CallCode973:\n\t\treturn []CountryCode{BHR}\n\tcase CallCode974:\n\t\treturn []CountryCode{QAT}\n\tcase CallCode975:\n\t\treturn []CountryCode{BTN}\n\tcase CallCode976:\n\t\treturn []CountryCode{MNG}\n\tcase CallCode977:\n\t\treturn []CountryCode{NPL}\n\tcase CallCode98:\n\t\treturn []CountryCode{IRN}\n\tcase CallCode979:\n\t\treturn []CountryCode{NonCountryInternationalPremiumRateService}\n\tcase CallCode991:\n\t\treturn []CountryCode{NonCountryInternationalTelecommunicationsCorrespondenceService}\n\tcase CallCode992:\n\t\treturn []CountryCode{TJK}\n\tcase CallCode994:\n\t\treturn []CountryCode{AZE}\n\tcase CallCode995:\n\t\treturn []CountryCode{GEO}\n\tcase CallCode996:\n\t\treturn []CountryCode{KGZ}\n\tcase CallCode998:\n\t\treturn []CountryCode{UZB}\n\tcase CallCode5999:\n\t\treturn []CountryCode{CUW}\n\tcase CallCode35818:\n\t\treturn []CountryCode{ALA}\n\tcase CallCode441481:\n\t\treturn []CountryCode{GGY}\n\tcase CallCode441534:\n\t\treturn []CountryCode{JEY}\n\tcase CallCode441624:\n\t\treturn []CountryCode{IMN}\n\tcase CallCode3906698:\n\t\treturn []CountryCode{VAT}\n\tcase CallCode6189162:\n\t\treturn []CountryCode{CCK}\n\tcase CallCode6189164:\n\t\treturn []CountryCode{CXR}\n\t}\n\treturn []CountryCode{Unknown}\n}",
"func (c CallCode) Countries() []CountryCode { //nolint:gocyclo\n\tswitch c {\n\tcase CallCode1:\n\t\treturn []CountryCode{ATF, CAN, UMI, USA}\n\tcase CallCode1808:\n\t\treturn []CountryCode{USA}\n\tcase CallCode1242:\n\t\treturn []CountryCode{BHS}\n\tcase CallCode1246:\n\t\treturn []CountryCode{BRB}\n\tcase CallCode1264:\n\t\treturn []CountryCode{AIA}\n\tcase CallCode1268:\n\t\treturn []CountryCode{ATG}\n\tcase CallCode1284:\n\t\treturn []CountryCode{VGB}\n\tcase CallCode1340:\n\t\treturn []CountryCode{VIR}\n\tcase CallCode1345:\n\t\treturn []CountryCode{CYM}\n\tcase CallCode1441:\n\t\treturn []CountryCode{BMU}\n\tcase CallCode1473:\n\t\treturn []CountryCode{GRD}\n\tcase CallCode1649:\n\t\treturn []CountryCode{TCA}\n\tcase CallCode1664:\n\t\treturn []CountryCode{MSR}\n\tcase CallCode1670:\n\t\treturn []CountryCode{MNP}\n\tcase CallCode1671:\n\t\treturn []CountryCode{GUM}\n\tcase CallCode1684:\n\t\treturn []CountryCode{ASM}\n\tcase CallCode1758:\n\t\treturn []CountryCode{LCA}\n\tcase CallCode1767:\n\t\treturn []CountryCode{DMA}\n\tcase CallCode1784:\n\t\treturn []CountryCode{VCT}\n\tcase CallCode1787, CallCode1939:\n\t\treturn []CountryCode{PRI}\n\tcase CallCode1809, CallCode1829, CallCode1849:\n\t\treturn []CountryCode{DOM}\n\tcase CallCode1868:\n\t\treturn []CountryCode{TTO}\n\tcase CallCode1869:\n\t\treturn []CountryCode{KNA}\n\tcase CallCode1876, CallCode1658:\n\t\treturn []CountryCode{JAM}\n\tcase CallCode20:\n\t\treturn []CountryCode{EGY}\n\tcase CallCode211:\n\t\treturn []CountryCode{SSD}\n\tcase CallCode212:\n\t\treturn []CountryCode{ESH, MAR}\n\tcase CallCode213:\n\t\treturn []CountryCode{DZA}\n\tcase CallCode216:\n\t\treturn []CountryCode{TUN}\n\tcase CallCode218:\n\t\treturn []CountryCode{LBY}\n\tcase CallCode220:\n\t\treturn []CountryCode{GMB}\n\tcase CallCode221:\n\t\treturn []CountryCode{SEN}\n\tcase CallCode222:\n\t\treturn []CountryCode{MRT}\n\tcase CallCode223:\n\t\treturn []CountryCode{MLI}\n\tcase CallCode224:\n\t\treturn []CountryCode{GIN}\n\tcase CallCode225:\n\t\treturn []CountryCode{CIV}\n\tcase CallCode226:\n\t\treturn []CountryCode{BFA}\n\tcase CallCode227:\n\t\treturn []CountryCode{NER}\n\tcase CallCode228:\n\t\treturn []CountryCode{TGO}\n\tcase CallCode229:\n\t\treturn []CountryCode{BEN}\n\tcase CallCode230:\n\t\treturn []CountryCode{MUS}\n\tcase CallCode231:\n\t\treturn []CountryCode{LBR}\n\tcase CallCode232:\n\t\treturn []CountryCode{SLE}\n\tcase CallCode233:\n\t\treturn []CountryCode{GHA}\n\tcase CallCode234:\n\t\treturn []CountryCode{NGA}\n\tcase CallCode235:\n\t\treturn []CountryCode{TCD}\n\tcase CallCode236:\n\t\treturn []CountryCode{CAF}\n\tcase CallCode237:\n\t\treturn []CountryCode{CMR}\n\tcase CallCode238:\n\t\treturn []CountryCode{CPV}\n\tcase CallCode239:\n\t\treturn []CountryCode{STP}\n\tcase CallCode240:\n\t\treturn []CountryCode{GNQ}\n\tcase CallCode241:\n\t\treturn []CountryCode{GAB}\n\tcase CallCode242:\n\t\treturn []CountryCode{COG}\n\tcase CallCode243:\n\t\treturn []CountryCode{COD}\n\tcase CallCode244:\n\t\treturn []CountryCode{AGO}\n\tcase CallCode245:\n\t\treturn []CountryCode{GNB}\n\tcase CallCode246:\n\t\treturn []CountryCode{IOT}\n\tcase CallCode248:\n\t\treturn []CountryCode{SYC}\n\tcase CallCode249:\n\t\treturn []CountryCode{SDN}\n\tcase CallCode250:\n\t\treturn []CountryCode{RWA}\n\tcase CallCode251:\n\t\treturn []CountryCode{ETH}\n\tcase CallCode252:\n\t\treturn []CountryCode{SOM}\n\tcase CallCode253:\n\t\treturn []CountryCode{DJI}\n\tcase CallCode254:\n\t\treturn []CountryCode{KEN}\n\tcase CallCode255:\n\t\treturn []CountryCode{TZA}\n\tcase CallCode256:\n\t\treturn []CountryCode{UGA}\n\tcase CallCode257:\n\t\treturn []CountryCode{BDI}\n\tcase CallCode258:\n\t\treturn []CountryCode{MOZ}\n\tcase CallCode260:\n\t\treturn []CountryCode{ZMB}\n\tcase CallCode261:\n\t\treturn []CountryCode{MDG}\n\tcase CallCode262:\n\t\treturn []CountryCode{MYT, REU}\n\tcase CallCode262269, CallCode262639:\n\t\treturn []CountryCode{MYT}\n\tcase CallCode263:\n\t\treturn []CountryCode{ZWE}\n\tcase CallCode264:\n\t\treturn []CountryCode{NAM}\n\tcase CallCode265:\n\t\treturn []CountryCode{MWI}\n\tcase CallCode266:\n\t\treturn []CountryCode{LSO}\n\tcase CallCode267:\n\t\treturn []CountryCode{BWA}\n\tcase CallCode268:\n\t\treturn []CountryCode{SWZ}\n\tcase CallCode269:\n\t\treturn []CountryCode{COM}\n\tcase CallCode27:\n\t\treturn []CountryCode{ZAF}\n\tcase CallCode290:\n\t\treturn []CountryCode{SHN}\n\tcase CallCode291:\n\t\treturn []CountryCode{ERI}\n\tcase CallCode297, CallCode5998:\n\t\treturn []CountryCode{ABW}\n\tcase CallCode298:\n\t\treturn []CountryCode{FRO}\n\tcase CallCode299:\n\t\treturn []CountryCode{GRL}\n\tcase CallCode30:\n\t\treturn []CountryCode{GRC}\n\tcase CallCode31:\n\t\treturn []CountryCode{NLD}\n\tcase CallCode32:\n\t\treturn []CountryCode{BEL}\n\tcase CallCode33:\n\t\treturn []CountryCode{FRA}\n\tcase CallCode34:\n\t\treturn []CountryCode{ESP}\n\tcase CallCode350:\n\t\treturn []CountryCode{GIB}\n\tcase CallCode351:\n\t\treturn []CountryCode{PRT}\n\tcase CallCode352:\n\t\treturn []CountryCode{LUX}\n\tcase CallCode353:\n\t\treturn []CountryCode{IRL}\n\tcase CallCode354:\n\t\treturn []CountryCode{ISL}\n\tcase CallCode355:\n\t\treturn []CountryCode{ALB}\n\tcase CallCode356:\n\t\treturn []CountryCode{MLT}\n\tcase CallCode357:\n\t\treturn []CountryCode{CYP}\n\tcase CallCode358:\n\t\treturn []CountryCode{ALA, FIN}\n\tcase CallCode359:\n\t\treturn []CountryCode{BGR}\n\tcase CallCode36:\n\t\treturn []CountryCode{HUN}\n\tcase CallCode370:\n\t\treturn []CountryCode{LTU}\n\tcase CallCode371:\n\t\treturn []CountryCode{LVA}\n\tcase CallCode372:\n\t\treturn []CountryCode{EST}\n\tcase CallCode373:\n\t\treturn []CountryCode{MDA}\n\tcase CallCode374:\n\t\treturn []CountryCode{ARM}\n\tcase CallCode375:\n\t\treturn []CountryCode{BLR}\n\tcase CallCode376:\n\t\treturn []CountryCode{AND}\n\tcase CallCode377:\n\t\treturn []CountryCode{MCO}\n\tcase CallCode378:\n\t\treturn []CountryCode{SMR}\n\tcase CallCode38:\n\t\treturn []CountryCode{YUG}\n\tcase CallCode380:\n\t\treturn []CountryCode{UKR}\n\tcase CallCode381:\n\t\treturn []CountryCode{SRB}\n\tcase CallCode382:\n\t\treturn []CountryCode{MNE}\n\tcase CallCode383:\n\t\treturn []CountryCode{XKX}\n\tcase CallCode385:\n\t\treturn []CountryCode{HRV}\n\tcase CallCode386:\n\t\treturn []CountryCode{SVN}\n\tcase CallCode387:\n\t\treturn []CountryCode{BIH}\n\tcase CallCode389:\n\t\treturn []CountryCode{MKD}\n\tcase CallCode39:\n\t\treturn []CountryCode{ITA, VAT}\n\tcase CallCode40:\n\t\treturn []CountryCode{ROU}\n\tcase CallCode41:\n\t\treturn []CountryCode{CHE}\n\tcase CallCode420:\n\t\treturn []CountryCode{CZE}\n\tcase CallCode421:\n\t\treturn []CountryCode{SVK}\n\tcase CallCode423:\n\t\treturn []CountryCode{LIE}\n\tcase CallCode43:\n\t\treturn []CountryCode{AUT}\n\tcase CallCode44:\n\t\treturn []CountryCode{GBR, GGY, IMN, JEY, XSC, XWA}\n\tcase CallCode45:\n\t\treturn []CountryCode{DNK}\n\tcase CallCode46:\n\t\treturn []CountryCode{SWE}\n\tcase CallCode47:\n\t\treturn []CountryCode{BVT, NOR, SJM}\n\tcase CallCode48:\n\t\treturn []CountryCode{POL}\n\tcase CallCode49:\n\t\treturn []CountryCode{DEU}\n\tcase CallCode500:\n\t\treturn []CountryCode{FLK, SGS}\n\tcase CallCode501:\n\t\treturn []CountryCode{BLZ}\n\tcase CallCode502:\n\t\treturn []CountryCode{GTM}\n\tcase CallCode503:\n\t\treturn []CountryCode{SLV}\n\tcase CallCode504:\n\t\treturn []CountryCode{HND}\n\tcase CallCode505:\n\t\treturn []CountryCode{NIC}\n\tcase CallCode506:\n\t\treturn []CountryCode{CRI}\n\tcase CallCode507:\n\t\treturn []CountryCode{PAN}\n\tcase CallCode508:\n\t\treturn []CountryCode{SPM}\n\tcase CallCode509:\n\t\treturn []CountryCode{HTI}\n\tcase CallCode51:\n\t\treturn []CountryCode{PER}\n\tcase CallCode52:\n\t\treturn []CountryCode{MEX}\n\tcase CallCode53:\n\t\treturn []CountryCode{CUB}\n\tcase CallCode54:\n\t\treturn []CountryCode{ARG}\n\tcase CallCode55:\n\t\treturn []CountryCode{BRA}\n\tcase CallCode56:\n\t\treturn []CountryCode{CHL}\n\tcase CallCode57:\n\t\treturn []CountryCode{COL}\n\tcase CallCode58:\n\t\treturn []CountryCode{VEN}\n\tcase CallCode590:\n\t\treturn []CountryCode{BLM, GLP, MAF}\n\tcase CallCode591:\n\t\treturn []CountryCode{BOL}\n\tcase CallCode592:\n\t\treturn []CountryCode{GUY}\n\tcase CallCode593:\n\t\treturn []CountryCode{ECU}\n\tcase CallCode594:\n\t\treturn []CountryCode{GUF}\n\tcase CallCode595:\n\t\treturn []CountryCode{PRY}\n\tcase CallCode596:\n\t\treturn []CountryCode{MTQ}\n\tcase CallCode597:\n\t\treturn []CountryCode{SUR}\n\tcase CallCode598:\n\t\treturn []CountryCode{URY}\n\tcase CallCode599:\n\t\treturn []CountryCode{ANT, BES, CUW}\n\tcase CallCode60:\n\t\treturn []CountryCode{MYS}\n\tcase CallCode61:\n\t\treturn []CountryCode{AUS, CXR, CCK}\n\tcase CallCode62:\n\t\treturn []CountryCode{IDN}\n\tcase CallCode63:\n\t\treturn []CountryCode{PHL}\n\tcase CallCode64:\n\t\treturn []CountryCode{NZL, PCN}\n\tcase CallCode65:\n\t\treturn []CountryCode{SGP}\n\tcase CallCode66:\n\t\treturn []CountryCode{THA}\n\tcase CallCode670:\n\t\treturn []CountryCode{TLS}\n\tcase CallCode672:\n\t\treturn []CountryCode{ATA, CCK, NFK}\n\tcase CallCode673:\n\t\treturn []CountryCode{BRN}\n\tcase CallCode674:\n\t\treturn []CountryCode{NRU}\n\tcase CallCode675:\n\t\treturn []CountryCode{PNG}\n\tcase CallCode676:\n\t\treturn []CountryCode{TON}\n\tcase CallCode677:\n\t\treturn []CountryCode{SLB}\n\tcase CallCode678:\n\t\treturn []CountryCode{VUT}\n\tcase CallCode679:\n\t\treturn []CountryCode{FJI}\n\tcase CallCode680:\n\t\treturn []CountryCode{PLW}\n\tcase CallCode681:\n\t\treturn []CountryCode{WLF}\n\tcase CallCode682:\n\t\treturn []CountryCode{COK}\n\tcase CallCode683:\n\t\treturn []CountryCode{NIU}\n\tcase CallCode684:\n\t\treturn []CountryCode{WSM}\n\tcase CallCode686:\n\t\treturn []CountryCode{KIR}\n\tcase CallCode687:\n\t\treturn []CountryCode{NCL}\n\tcase CallCode688:\n\t\treturn []CountryCode{TUV}\n\tcase CallCode689:\n\t\treturn []CountryCode{PYF}\n\tcase CallCode690:\n\t\treturn []CountryCode{TKL}\n\tcase CallCode691:\n\t\treturn []CountryCode{FSM}\n\tcase CallCode692:\n\t\treturn []CountryCode{MHL}\n\tcase CallCode7:\n\t\treturn []CountryCode{KAZ, RUS}\n\tcase CallCode1721, CallCode5995:\n\t\treturn []CountryCode{SXM}\n\tcase CallCode4779:\n\t\treturn []CountryCode{SJM}\n\tcase CallCode5993, CallCode5994, CallCode5997:\n\t\treturn []CountryCode{BES}\n\tcase CallCode7370:\n\t\treturn []CountryCode{TKM}\n\tcase CallCode81:\n\t\treturn []CountryCode{JPN}\n\tcase CallCode82:\n\t\treturn []CountryCode{KOR}\n\tcase CallCode84:\n\t\treturn []CountryCode{VNM}\n\tcase CallCode850:\n\t\treturn []CountryCode{PRK}\n\tcase CallCode852:\n\t\treturn []CountryCode{HKG}\n\tcase CallCode853:\n\t\treturn []CountryCode{MAC}\n\tcase CallCode855:\n\t\treturn []CountryCode{KHM}\n\tcase CallCode856:\n\t\treturn []CountryCode{LAO}\n\tcase CallCode86:\n\t\treturn []CountryCode{CHN}\n\tcase CallCode800:\n\t\treturn []CountryCode{NonCountryInternationalFreephone}\n\tcase CallCode870:\n\t\treturn []CountryCode{NonCountryInmarsat}\n\tcase CallCode875, CallCode876, CallCode877:\n\t\treturn []CountryCode{NonCountryMaritimeMobileService}\n\tcase CallCode878:\n\t\treturn []CountryCode{NonCountryUniversalPersonalTelecommunicationsServices}\n\tcase CallCode879:\n\t\treturn []CountryCode{NonCountryNationalNonCommercialPurposes}\n\tcase CallCode880:\n\t\treturn []CountryCode{BGD}\n\tcase CallCode881:\n\t\treturn []CountryCode{NonCountryGlobalMobileSatelliteSystem}\n\tcase CallCode882, CallCode883:\n\t\treturn []CountryCode{NonCountryInternationalNetworks}\n\tcase CallCode886:\n\t\treturn []CountryCode{TWN}\n\tcase CallCode90:\n\t\treturn []CountryCode{TUR}\n\tcase CallCode91:\n\t\treturn []CountryCode{IND}\n\tcase CallCode92:\n\t\treturn []CountryCode{PAK}\n\tcase CallCode93:\n\t\treturn []CountryCode{AFG}\n\tcase CallCode94:\n\t\treturn []CountryCode{LKA}\n\tcase CallCode95:\n\t\treturn []CountryCode{MMR}\n\tcase CallCode888:\n\t\treturn []CountryCode{NonCountryDisasterRelief}\n\tcase CallCode960:\n\t\treturn []CountryCode{MDV}\n\tcase CallCode961:\n\t\treturn []CountryCode{LBN}\n\tcase CallCode962:\n\t\treturn []CountryCode{JOR}\n\tcase CallCode963:\n\t\treturn []CountryCode{SYR}\n\tcase CallCode964:\n\t\treturn []CountryCode{IRQ}\n\tcase CallCode965:\n\t\treturn []CountryCode{KWT}\n\tcase CallCode966:\n\t\treturn []CountryCode{SAU}\n\tcase CallCode967:\n\t\treturn []CountryCode{YEM}\n\tcase CallCode968:\n\t\treturn []CountryCode{OMN}\n\tcase CallCode971:\n\t\treturn []CountryCode{ARE}\n\tcase CallCode972:\n\t\treturn []CountryCode{ISR, PSE}\n\tcase CallCode973:\n\t\treturn []CountryCode{BHR}\n\tcase CallCode974:\n\t\treturn []CountryCode{QAT}\n\tcase CallCode975:\n\t\treturn []CountryCode{BTN}\n\tcase CallCode976:\n\t\treturn []CountryCode{MNG}\n\tcase CallCode977:\n\t\treturn []CountryCode{NPL}\n\tcase CallCode98:\n\t\treturn []CountryCode{IRN}\n\tcase CallCode979:\n\t\treturn []CountryCode{NonCountryInternationalPremiumRateService}\n\tcase CallCode991:\n\t\treturn []CountryCode{NonCountryInternationalTelecommunicationsCorrespondenceService}\n\tcase CallCode992:\n\t\treturn []CountryCode{TJK}\n\tcase CallCode994:\n\t\treturn []CountryCode{AZE}\n\tcase CallCode995:\n\t\treturn []CountryCode{GEO}\n\tcase CallCode996:\n\t\treturn []CountryCode{KGZ}\n\tcase CallCode998:\n\t\treturn []CountryCode{UZB}\n\tcase CallCode5999:\n\t\treturn []CountryCode{CUW}\n\tcase CallCode35818:\n\t\treturn []CountryCode{ALA}\n\tcase CallCode441481:\n\t\treturn []CountryCode{GGY}\n\tcase CallCode441534:\n\t\treturn []CountryCode{JEY}\n\tcase CallCode441624:\n\t\treturn []CountryCode{IMN}\n\tcase CallCode3906698:\n\t\treturn []CountryCode{VAT}\n\tcase CallCode6189162:\n\t\treturn []CountryCode{CCK}\n\tcase CallCode6189164:\n\t\treturn []CountryCode{CXR}\n\t}\n\treturn []CountryCode{Unknown}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCode lookup for currency type by code
|
func ByCode(code Code) (c currency, ok bool) {
c, ok = currenciesByCode[code.String()]
return
}
|
[
"func (repo *AccountTypeRepository) FindByCurrencyCode(currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"currency_code = ?\", currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func (currencies currencies) CurrencyByCode(code string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.code) == code {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByCodeStr(code string) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func (s *Currencies) FindByCode(code string) (*models.Currency, error) {\n\tvar currency models.Currency\n\n\terr := s.db.Where(\"code = ?\", code).FirstOrInit(¤cy).Error\n\n\treturn ¤cy, err\n}",
"func (repo *AccountTypeRepository) FindByNameAndCurrencyCode(name, currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"name = ? AND currency_code = ?\", name, currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func (s *Server) providerTypeGetByCode(\n\tsess *pb.Session,\n\tcode string,\n) (*pb.ProviderType, error) {\n\treq := &pb.ProviderTypeGetByCodeRequest{\n\t\tSession: sess,\n\t\tCode: code,\n\t}\n\tmc, err := s.metaClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trec, err := mc.ProviderTypeGetByCode(context.Background(), req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pb.ProviderType{\n\t\tCode: rec.Code,\n\t\tDescription: rec.Description,\n\t}, nil\n}",
"func ByCodeErr(code Code) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func InstitutionTypeByCode(code string) (string, bool) {\n\tt, ok := instType[code]\n\treturn t, ok\n}",
"func CurrencyCode(id int) string {\n\treturn currencyCode[id]\n}",
"func GetCurrency(code Code) (c Currency, ok bool) {\n\tok = false\n\tif !code.IsValid() {\n\t\treturn\n\t}\n\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func Find(code string) Currency {\n\tfor _, curr := range currencies {\n\t\tif curr.Code == code {\n\t\t\treturn curr\n\t\t}\n\t}\n\n\treturn XXX\n}",
"func (store *TypeStore) LookupCode(struct_type reflect.Type) (uint16, bool) {\n\tval, present := store.TypeCodes[struct_type]\n\treturn val, present\n}",
"func GetCurrency(code string) *Currency {\n\treturn currencies[code]\n}",
"func TypeRequestByCode(code string) (string, bool) {\n\tt, ok := typeRequest[code]\n\treturn t, ok\n}",
"func ByCodeStrErr(code string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func (s *Currencies) FindByCodes(codes []string) ([]*models.Currency, error) {\n\tvar currencies []*models.Currency\n\n\tif err := s.db.Where(\"code IN (?)\", codes).Find(¤cies).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn currencies, nil\n}",
"func (cfg AccountsConfig) Lookup(code accountsTypes.Code) *Account {\n\tfor _, acct := range cfg.Accounts {\n\t\tif acct.Code == code {\n\t\t\treturn acct\n\t\t}\n\t}\n\treturn nil\n}",
"func New(code string) (*Currency, error) {\n\tcode = strings.ToUpper(code)\n\tif !IsValid(code) {\n\t\treturn nil, errors.New(\"currency: code is not a valid ISO 4217 alphabetic code\")\n\t}\n\n\tcurrency := currencies[code]\n\treturn ¤cy, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCurrency lookup for currency type by currency
|
func ByCurrency(currency Currency) (c currency, ok bool) {
c, ok = currenciesByCurrency[currency.String()]
return
}
|
[
"func (currencies currencies) CurrencyByCurrency(curr string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.currency) == curr {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByCurrencyStr(currency string) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency]\n\treturn\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func (l *Ledger) GetCurrency(s string) (*Currency, bool) {\n\tfor i := range l.Currencies {\n\t\tif s == l.Currencies[i].Name {\n\t\t\treturn l.Currencies[i], false\n\t\t}\n\t}\n\tvar currency Currency\n\tcurrency.Name = s\n\tl.Currencies = append(l.Currencies, ¤cy)\n\treturn ¤cy, true\n}",
"func (repo *AccountTypeRepository) FindByCurrencyCode(currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"currency_code = ?\", currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func ByCountry(country Country) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country.String()]\n\treturn\n}",
"func GetCurrency(code Code) (c Currency, ok bool) {\n\tok = false\n\tif !code.IsValid() {\n\t\treturn\n\t}\n\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func (currencies currencies) CurrencyByCode(code string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.code) == code {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByCurrencyErr(currencyStr Currency) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCountryStr(country string) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country]\n\treturn\n}",
"func (currencies currencies) CurrencyByNumber(number string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.number) == number {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByCode(code Code) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code.String()]\n\treturn\n}",
"func ByNumeric(s string) (Currency, bool) {\n\tc, ok := byNumeric[s]\n\tif ok {\n\t\treturn *c, true\n\t}\n\n\treturn Currency{}, false\n}",
"func GetCurrency(code string) *Currency {\n\treturn currencies[code]\n}",
"func CurrencySymbol(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {\n\tcode := in.String()\n\tif code == \"\" {\n\t\treturn pongo2.AsValue(\"\"), nil\n\t}\n\tcurrencyObj := c.Get(code)\n\treturn pongo2.AsValue(currencyObj.Symbol), nil\n}",
"func (repo *AccountTypeRepository) FindByNameAndCurrencyCode(name, currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"name = ? AND currency_code = ?\", name, currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func Currency() *CurrencyInfo {\n\tindex := rand.Intn(len(data.Data()[\"currency\"][\"short\"]))\n\treturn &CurrencyInfo{\n\t\tShort: data.Data()[\"currency\"][\"short\"][index],\n\t\tLong: data.Data()[\"currency\"][\"long\"][index],\n\t}\n}",
"func FindCurrency(exec boil.Executor, iD int, selectCols ...string) (*Currency, error) {\n\tcurrencyObj := &Currency{}\n\n\tsel := \"*\"\n\tif len(selectCols) > 0 {\n\t\tsel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), \",\")\n\t}\n\tquery := fmt.Sprintf(\n\t\t\"select %s from \\\"currency\\\" where \\\"id\\\"=$1\", sel,\n\t)\n\n\tq := queries.Raw(query, iD)\n\n\terr := q.Bind(nil, exec, currencyObj)\n\tif err != nil {\n\t\tif errors.Cause(err) == sql.ErrNoRows {\n\t\t\treturn nil, sql.ErrNoRows\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"models: unable to select from currency\")\n\t}\n\n\treturn currencyObj, nil\n}",
"func CurrencyCode(id int) string {\n\treturn currencyCode[id]\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByNumber lookup for currency type by number
|
func ByNumber(number Number) (c currency, ok bool) {
c, ok = currenciesByNumber[number.String()]
return
}
|
[
"func ByNumberStr(number string) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number]\n\treturn\n}",
"func (currencies currencies) CurrencyByNumber(number string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.number) == number {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByNumeric(s string) (Currency, bool) {\n\tc, ok := byNumeric[s]\n\tif ok {\n\t\treturn *c, true\n\t}\n\n\treturn Currency{}, false\n}",
"func FindByNumber(num int) *Country {\n\tsearch := fmt.Sprintf(\"%03d\", num)\n\tfor _, c := range countries {\n\t\tif c.ExistsNum(search) {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}",
"func ByNumberErr(number Number) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func ByCode(code Code) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code.String()]\n\treturn\n}",
"func ByCurrency(currency Currency) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency.String()]\n\treturn\n}",
"func (currencies currencies) CurrencyByCode(code string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.code) == code {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func (repo *AccountTypeRepository) FindByCurrencyCode(currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"currency_code = ?\", currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func (currencies currencies) CurrencyByCurrency(curr string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.currency) == curr {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByNumberStrErr(number string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func ByCurrencyStr(currency string) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency]\n\treturn\n}",
"func ByNumber(number string) (FindFilter, error) {\n\n\tnumPart := strings.TrimFunc(number, isDigit)\n\tcharPart := strings.TrimFunc(number, func(r rune) bool { return !isDigit(r) })\n\n\tn, err := strconv.Atoi(numPart)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n <= 0 && charPart == \"\" {\n\t\treturn nil, ErrInvalidHouseNumber\n\t}\n\n\treturn func(l *Location) bool {\n\t\tif charPart == \"\" {\n\t\t\treturn l.Number == n\n\t\t}\n\t\treturn l.Number == n && l.NumberChars == charPart\n\t}, nil\n}",
"func CurrencySymbol(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {\n\tcode := in.String()\n\tif code == \"\" {\n\t\treturn pongo2.AsValue(\"\"), nil\n\t}\n\tcurrencyObj := c.Get(code)\n\treturn pongo2.AsValue(currencyObj.Symbol), nil\n}",
"func ByCodeStr(code string) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func (s *Currencies) FindByCode(code string) (*models.Currency, error) {\n\tvar currency models.Currency\n\n\terr := s.db.Where(\"code = ?\", code).FirstOrInit(¤cy).Error\n\n\treturn ¤cy, err\n}",
"func Currency() *CurrencyInfo {\n\tindex := rand.Intn(len(data.Data()[\"currency\"][\"short\"]))\n\treturn &CurrencyInfo{\n\t\tShort: data.Data()[\"currency\"][\"short\"][index],\n\t\tLong: data.Data()[\"currency\"][\"long\"][index],\n\t}\n}",
"func (repo *AccountTypeRepository) FindByNameAndCurrencyCode(name, currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"name = ? AND currency_code = ?\", name, currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCountry lookup for currency type by country
|
func ByCountry(country Country) (c currencies, ok bool) {
c, ok = currenciesByCountry[country.String()]
return
}
|
[
"func ByCountryStr(country string) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country]\n\treturn\n}",
"func ByCountryErr(country Country) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country.String()]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func (instance *XCountryRepo) GetByISO2Code(iso2Code string) (model.XCountry, error) {\n\treturn instance.getByField(\"iso2Code\", iso2Code)\n}",
"func (instance *XCountryRepo) GetByISO3Code(iso3Code string) (model.XCountry, error) {\n\treturn instance.getByField(\"iso3Code\", iso3Code)\n}",
"func ByCountryStrErr(country string) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func ByCurrency(currency Currency) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency.String()]\n\treturn\n}",
"func Country(countryStyle int64) string {\n\tcountry := \"\"\n\tswitch countryStyle {\n\n\tdefault:\n\n\tcase FullCountry:\n\t\tcountry = randomFrom(jsonData.Countries)\n\t\tbreak\n\n\tcase TwoCharCountry:\n\t\tcountry = randomFrom(jsonData.CountriesTwoChars)\n\t\tbreak\n\n\tcase ThreeCharCountry:\n\t\tcountry = randomFrom(jsonData.CountriesThreeChars)\n\t\tbreak\n\t}\n\treturn country\n}",
"func lookupCountry(remoteAddr string) string {\n\thost, _, _ := net.SplitHostPort(remoteAddr)\n\ta := net.ParseIP(host)\n\tif a == nil {\n\t\treturn \"id\"\n\t}\n\n\tvar rec struct {\n\t\tCountry struct {\n\t\t\tISOCode string `maxminddb:\"iso_code\"`\n\t\t} `maxminddb:\"country\"`\n\t}\n\n\terr := geoipdb.Lookup(a, &rec)\n\tif err != nil || rec.Country.ISOCode == \"\" {\n\t\treturn \"id\"\n\t}\n\n\treturn strings.ToLower(rec.Country.ISOCode)\n}",
"func (c CallCode) Countries() []CountryCode { //nolint:gocyclo\n\tswitch c {\n\tcase CallCode1:\n\t\treturn []CountryCode{ATF, CAN, UMI, USA}\n\tcase CallCode1808:\n\t\treturn []CountryCode{USA}\n\tcase CallCode1242:\n\t\treturn []CountryCode{BHS}\n\tcase CallCode1246:\n\t\treturn []CountryCode{BRB}\n\tcase CallCode1264:\n\t\treturn []CountryCode{AIA}\n\tcase CallCode1268:\n\t\treturn []CountryCode{ATG}\n\tcase CallCode1284:\n\t\treturn []CountryCode{VGB}\n\tcase CallCode1340:\n\t\treturn []CountryCode{VIR}\n\tcase CallCode1345:\n\t\treturn []CountryCode{CYM}\n\tcase CallCode1441:\n\t\treturn []CountryCode{BMU}\n\tcase CallCode1473:\n\t\treturn []CountryCode{GRD}\n\tcase CallCode1649:\n\t\treturn []CountryCode{TCA}\n\tcase CallCode1664:\n\t\treturn []CountryCode{MSR}\n\tcase CallCode1670:\n\t\treturn []CountryCode{MNP}\n\tcase CallCode1671:\n\t\treturn []CountryCode{GUM}\n\tcase CallCode1684:\n\t\treturn []CountryCode{ASM}\n\tcase CallCode1758:\n\t\treturn []CountryCode{LCA}\n\tcase CallCode1767:\n\t\treturn []CountryCode{DMA}\n\tcase CallCode1784:\n\t\treturn []CountryCode{VCT}\n\tcase CallCode1787, CallCode1939:\n\t\treturn []CountryCode{PRI}\n\tcase CallCode1809, CallCode1829, CallCode1849:\n\t\treturn []CountryCode{DOM}\n\tcase CallCode1868:\n\t\treturn []CountryCode{TTO}\n\tcase CallCode1869:\n\t\treturn []CountryCode{KNA}\n\tcase CallCode1876, CallCode1658:\n\t\treturn []CountryCode{JAM}\n\tcase CallCode20:\n\t\treturn []CountryCode{EGY}\n\tcase CallCode211:\n\t\treturn []CountryCode{SSD}\n\tcase CallCode212:\n\t\treturn []CountryCode{ESH, MAR}\n\tcase CallCode213:\n\t\treturn []CountryCode{DZA}\n\tcase CallCode216:\n\t\treturn []CountryCode{TUN}\n\tcase CallCode218:\n\t\treturn []CountryCode{LBY}\n\tcase CallCode220:\n\t\treturn []CountryCode{GMB}\n\tcase CallCode221:\n\t\treturn []CountryCode{SEN}\n\tcase CallCode222:\n\t\treturn []CountryCode{MRT}\n\tcase CallCode223:\n\t\treturn []CountryCode{MLI}\n\tcase CallCode224:\n\t\treturn []CountryCode{GIN}\n\tcase CallCode225:\n\t\treturn []CountryCode{CIV}\n\tcase CallCode226:\n\t\treturn []CountryCode{BFA}\n\tcase CallCode227:\n\t\treturn []CountryCode{NER}\n\tcase CallCode228:\n\t\treturn []CountryCode{TGO}\n\tcase CallCode229:\n\t\treturn []CountryCode{BEN}\n\tcase CallCode230:\n\t\treturn []CountryCode{MUS}\n\tcase CallCode231:\n\t\treturn []CountryCode{LBR}\n\tcase CallCode232:\n\t\treturn []CountryCode{SLE}\n\tcase CallCode233:\n\t\treturn []CountryCode{GHA}\n\tcase CallCode234:\n\t\treturn []CountryCode{NGA}\n\tcase CallCode235:\n\t\treturn []CountryCode{TCD}\n\tcase CallCode236:\n\t\treturn []CountryCode{CAF}\n\tcase CallCode237:\n\t\treturn []CountryCode{CMR}\n\tcase CallCode238:\n\t\treturn []CountryCode{CPV}\n\tcase CallCode239:\n\t\treturn []CountryCode{STP}\n\tcase CallCode240:\n\t\treturn []CountryCode{GNQ}\n\tcase CallCode241:\n\t\treturn []CountryCode{GAB}\n\tcase CallCode242:\n\t\treturn []CountryCode{COG}\n\tcase CallCode243:\n\t\treturn []CountryCode{COD}\n\tcase CallCode244:\n\t\treturn []CountryCode{AGO}\n\tcase CallCode245:\n\t\treturn []CountryCode{GNB}\n\tcase CallCode246:\n\t\treturn []CountryCode{IOT}\n\tcase CallCode248:\n\t\treturn []CountryCode{SYC}\n\tcase CallCode249:\n\t\treturn []CountryCode{SDN}\n\tcase CallCode250:\n\t\treturn []CountryCode{RWA}\n\tcase CallCode251:\n\t\treturn []CountryCode{ETH}\n\tcase CallCode252:\n\t\treturn []CountryCode{SOM}\n\tcase CallCode253:\n\t\treturn []CountryCode{DJI}\n\tcase CallCode254:\n\t\treturn []CountryCode{KEN}\n\tcase CallCode255:\n\t\treturn []CountryCode{TZA}\n\tcase CallCode256:\n\t\treturn []CountryCode{UGA}\n\tcase CallCode257:\n\t\treturn []CountryCode{BDI}\n\tcase CallCode258:\n\t\treturn []CountryCode{MOZ}\n\tcase CallCode260:\n\t\treturn []CountryCode{ZMB}\n\tcase CallCode261:\n\t\treturn []CountryCode{MDG}\n\tcase CallCode262:\n\t\treturn []CountryCode{MYT, REU}\n\tcase CallCode262269, CallCode262639:\n\t\treturn []CountryCode{MYT}\n\tcase CallCode263:\n\t\treturn []CountryCode{ZWE}\n\tcase CallCode264:\n\t\treturn []CountryCode{NAM}\n\tcase CallCode265:\n\t\treturn []CountryCode{MWI}\n\tcase CallCode266:\n\t\treturn []CountryCode{LSO}\n\tcase CallCode267:\n\t\treturn []CountryCode{BWA}\n\tcase CallCode268:\n\t\treturn []CountryCode{SWZ}\n\tcase CallCode269:\n\t\treturn []CountryCode{COM}\n\tcase CallCode27:\n\t\treturn []CountryCode{ZAF}\n\tcase CallCode290:\n\t\treturn []CountryCode{SHN}\n\tcase CallCode291:\n\t\treturn []CountryCode{ERI}\n\tcase CallCode297, CallCode5998:\n\t\treturn []CountryCode{ABW}\n\tcase CallCode298:\n\t\treturn []CountryCode{FRO}\n\tcase CallCode299:\n\t\treturn []CountryCode{GRL}\n\tcase CallCode30:\n\t\treturn []CountryCode{GRC}\n\tcase CallCode31:\n\t\treturn []CountryCode{NLD}\n\tcase CallCode32:\n\t\treturn []CountryCode{BEL}\n\tcase CallCode33:\n\t\treturn []CountryCode{FRA}\n\tcase CallCode34:\n\t\treturn []CountryCode{ESP}\n\tcase CallCode350:\n\t\treturn []CountryCode{GIB}\n\tcase CallCode351:\n\t\treturn []CountryCode{PRT}\n\tcase CallCode352:\n\t\treturn []CountryCode{LUX}\n\tcase CallCode353:\n\t\treturn []CountryCode{IRL}\n\tcase CallCode354:\n\t\treturn []CountryCode{ISL}\n\tcase CallCode355:\n\t\treturn []CountryCode{ALB}\n\tcase CallCode356:\n\t\treturn []CountryCode{MLT}\n\tcase CallCode357:\n\t\treturn []CountryCode{CYP}\n\tcase CallCode358:\n\t\treturn []CountryCode{ALA, FIN}\n\tcase CallCode359:\n\t\treturn []CountryCode{BGR}\n\tcase CallCode36:\n\t\treturn []CountryCode{HUN}\n\tcase CallCode370:\n\t\treturn []CountryCode{LTU}\n\tcase CallCode371:\n\t\treturn []CountryCode{LVA}\n\tcase CallCode372:\n\t\treturn []CountryCode{EST}\n\tcase CallCode373:\n\t\treturn []CountryCode{MDA}\n\tcase CallCode374:\n\t\treturn []CountryCode{ARM}\n\tcase CallCode375:\n\t\treturn []CountryCode{BLR}\n\tcase CallCode376:\n\t\treturn []CountryCode{AND}\n\tcase CallCode377:\n\t\treturn []CountryCode{MCO}\n\tcase CallCode378:\n\t\treturn []CountryCode{SMR}\n\tcase CallCode38:\n\t\treturn []CountryCode{YUG}\n\tcase CallCode380:\n\t\treturn []CountryCode{UKR}\n\tcase CallCode381:\n\t\treturn []CountryCode{SRB}\n\tcase CallCode382:\n\t\treturn []CountryCode{MNE}\n\tcase CallCode383:\n\t\treturn []CountryCode{XKX}\n\tcase CallCode385:\n\t\treturn []CountryCode{HRV}\n\tcase CallCode386:\n\t\treturn []CountryCode{SVN}\n\tcase CallCode387:\n\t\treturn []CountryCode{BIH}\n\tcase CallCode389:\n\t\treturn []CountryCode{MKD}\n\tcase CallCode39:\n\t\treturn []CountryCode{ITA, VAT}\n\tcase CallCode40:\n\t\treturn []CountryCode{ROU}\n\tcase CallCode41:\n\t\treturn []CountryCode{CHE}\n\tcase CallCode420:\n\t\treturn []CountryCode{CZE}\n\tcase CallCode421:\n\t\treturn []CountryCode{SVK}\n\tcase CallCode423:\n\t\treturn []CountryCode{LIE}\n\tcase CallCode43:\n\t\treturn []CountryCode{AUT}\n\tcase CallCode44:\n\t\treturn []CountryCode{GBR, GGY, IMN, JEY, XSC, XWA}\n\tcase CallCode45:\n\t\treturn []CountryCode{DNK}\n\tcase CallCode46:\n\t\treturn []CountryCode{SWE}\n\tcase CallCode47:\n\t\treturn []CountryCode{BVT, NOR, SJM}\n\tcase CallCode48:\n\t\treturn []CountryCode{POL}\n\tcase CallCode49:\n\t\treturn []CountryCode{DEU}\n\tcase CallCode500:\n\t\treturn []CountryCode{FLK, SGS}\n\tcase CallCode501:\n\t\treturn []CountryCode{BLZ}\n\tcase CallCode502:\n\t\treturn []CountryCode{GTM}\n\tcase CallCode503:\n\t\treturn []CountryCode{SLV}\n\tcase CallCode504:\n\t\treturn []CountryCode{HND}\n\tcase CallCode505:\n\t\treturn []CountryCode{NIC}\n\tcase CallCode506:\n\t\treturn []CountryCode{CRI}\n\tcase CallCode507:\n\t\treturn []CountryCode{PAN}\n\tcase CallCode508:\n\t\treturn []CountryCode{SPM}\n\tcase CallCode509:\n\t\treturn []CountryCode{HTI}\n\tcase CallCode51:\n\t\treturn []CountryCode{PER}\n\tcase CallCode52:\n\t\treturn []CountryCode{MEX}\n\tcase CallCode53:\n\t\treturn []CountryCode{CUB}\n\tcase CallCode54:\n\t\treturn []CountryCode{ARG}\n\tcase CallCode55:\n\t\treturn []CountryCode{BRA}\n\tcase CallCode56:\n\t\treturn []CountryCode{CHL}\n\tcase CallCode57:\n\t\treturn []CountryCode{COL}\n\tcase CallCode58:\n\t\treturn []CountryCode{VEN}\n\tcase CallCode590:\n\t\treturn []CountryCode{BLM, GLP, MAF}\n\tcase CallCode591:\n\t\treturn []CountryCode{BOL}\n\tcase CallCode592:\n\t\treturn []CountryCode{GUY}\n\tcase CallCode593:\n\t\treturn []CountryCode{ECU}\n\tcase CallCode594:\n\t\treturn []CountryCode{GUF}\n\tcase CallCode595:\n\t\treturn []CountryCode{PRY}\n\tcase CallCode596:\n\t\treturn []CountryCode{MTQ}\n\tcase CallCode597:\n\t\treturn []CountryCode{SUR}\n\tcase CallCode598:\n\t\treturn []CountryCode{URY}\n\tcase CallCode599:\n\t\treturn []CountryCode{ANT, BES, CUW}\n\tcase CallCode60:\n\t\treturn []CountryCode{MYS}\n\tcase CallCode61:\n\t\treturn []CountryCode{AUS, CXR, CCK}\n\tcase CallCode62:\n\t\treturn []CountryCode{IDN}\n\tcase CallCode63:\n\t\treturn []CountryCode{PHL}\n\tcase CallCode64:\n\t\treturn []CountryCode{NZL, PCN}\n\tcase CallCode65:\n\t\treturn []CountryCode{SGP}\n\tcase CallCode66:\n\t\treturn []CountryCode{THA}\n\tcase CallCode670:\n\t\treturn []CountryCode{TLS}\n\tcase CallCode672:\n\t\treturn []CountryCode{ATA, CCK, NFK}\n\tcase CallCode673:\n\t\treturn []CountryCode{BRN}\n\tcase CallCode674:\n\t\treturn []CountryCode{NRU}\n\tcase CallCode675:\n\t\treturn []CountryCode{PNG}\n\tcase CallCode676:\n\t\treturn []CountryCode{TON}\n\tcase CallCode677:\n\t\treturn []CountryCode{SLB}\n\tcase CallCode678:\n\t\treturn []CountryCode{VUT}\n\tcase CallCode679:\n\t\treturn []CountryCode{FJI}\n\tcase CallCode680:\n\t\treturn []CountryCode{PLW}\n\tcase CallCode681:\n\t\treturn []CountryCode{WLF}\n\tcase CallCode682:\n\t\treturn []CountryCode{COK}\n\tcase CallCode683:\n\t\treturn []CountryCode{NIU}\n\tcase CallCode685:\n\t\treturn []CountryCode{WSM}\n\tcase CallCode686:\n\t\treturn []CountryCode{KIR}\n\tcase CallCode687:\n\t\treturn []CountryCode{NCL}\n\tcase CallCode688:\n\t\treturn []CountryCode{TUV}\n\tcase CallCode689:\n\t\treturn []CountryCode{PYF}\n\tcase CallCode690:\n\t\treturn []CountryCode{TKL}\n\tcase CallCode691:\n\t\treturn []CountryCode{FSM}\n\tcase CallCode692:\n\t\treturn []CountryCode{MHL}\n\tcase CallCode7:\n\t\treturn []CountryCode{KAZ, RUS}\n\tcase CallCode1721, CallCode5995:\n\t\treturn []CountryCode{SXM}\n\tcase CallCode4779:\n\t\treturn []CountryCode{SJM}\n\tcase CallCode5993, CallCode5994, CallCode5997:\n\t\treturn []CountryCode{BES}\n\tcase CallCode993:\n\t\treturn []CountryCode{TKM}\n\tcase CallCode81:\n\t\treturn []CountryCode{JPN}\n\tcase CallCode82:\n\t\treturn []CountryCode{KOR}\n\tcase CallCode84:\n\t\treturn []CountryCode{VNM}\n\tcase CallCode850:\n\t\treturn []CountryCode{PRK}\n\tcase CallCode852:\n\t\treturn []CountryCode{HKG}\n\tcase CallCode853:\n\t\treturn []CountryCode{MAC}\n\tcase CallCode855:\n\t\treturn []CountryCode{KHM}\n\tcase CallCode856:\n\t\treturn []CountryCode{LAO}\n\tcase CallCode86:\n\t\treturn []CountryCode{CHN}\n\tcase CallCode800:\n\t\treturn []CountryCode{NonCountryInternationalFreephone}\n\tcase CallCode870:\n\t\treturn []CountryCode{NonCountryInmarsat}\n\tcase CallCode875, CallCode876, CallCode877:\n\t\treturn []CountryCode{NonCountryMaritimeMobileService}\n\tcase CallCode878:\n\t\treturn []CountryCode{NonCountryUniversalPersonalTelecommunicationsServices}\n\tcase CallCode879:\n\t\treturn []CountryCode{NonCountryNationalNonCommercialPurposes}\n\tcase CallCode880:\n\t\treturn []CountryCode{BGD}\n\tcase CallCode881:\n\t\treturn []CountryCode{NonCountryGlobalMobileSatelliteSystem}\n\tcase CallCode882, CallCode883:\n\t\treturn []CountryCode{NonCountryInternationalNetworks}\n\tcase CallCode886:\n\t\treturn []CountryCode{TWN}\n\tcase CallCode90:\n\t\treturn []CountryCode{TUR}\n\tcase CallCode91:\n\t\treturn []CountryCode{IND}\n\tcase CallCode92:\n\t\treturn []CountryCode{PAK}\n\tcase CallCode93:\n\t\treturn []CountryCode{AFG}\n\tcase CallCode94:\n\t\treturn []CountryCode{LKA}\n\tcase CallCode95:\n\t\treturn []CountryCode{MMR}\n\tcase CallCode888:\n\t\treturn []CountryCode{NonCountryDisasterRelief}\n\tcase CallCode960:\n\t\treturn []CountryCode{MDV}\n\tcase CallCode961:\n\t\treturn []CountryCode{LBN}\n\tcase CallCode962:\n\t\treturn []CountryCode{JOR}\n\tcase CallCode963:\n\t\treturn []CountryCode{SYR}\n\tcase CallCode964:\n\t\treturn []CountryCode{IRQ}\n\tcase CallCode965:\n\t\treturn []CountryCode{KWT}\n\tcase CallCode966:\n\t\treturn []CountryCode{SAU}\n\tcase CallCode967:\n\t\treturn []CountryCode{YEM}\n\tcase CallCode968:\n\t\treturn []CountryCode{OMN}\n\tcase CallCode970:\n\t\treturn []CountryCode{PSE}\n\tcase CallCode971:\n\t\treturn []CountryCode{ARE}\n\tcase CallCode972:\n\t\treturn []CountryCode{PSE}\n\tcase CallCode973:\n\t\treturn []CountryCode{BHR}\n\tcase CallCode974:\n\t\treturn []CountryCode{QAT}\n\tcase CallCode975:\n\t\treturn []CountryCode{BTN}\n\tcase CallCode976:\n\t\treturn []CountryCode{MNG}\n\tcase CallCode977:\n\t\treturn []CountryCode{NPL}\n\tcase CallCode98:\n\t\treturn []CountryCode{IRN}\n\tcase CallCode979:\n\t\treturn []CountryCode{NonCountryInternationalPremiumRateService}\n\tcase CallCode991:\n\t\treturn []CountryCode{NonCountryInternationalTelecommunicationsCorrespondenceService}\n\tcase CallCode992:\n\t\treturn []CountryCode{TJK}\n\tcase CallCode994:\n\t\treturn []CountryCode{AZE}\n\tcase CallCode995:\n\t\treturn []CountryCode{GEO}\n\tcase CallCode996:\n\t\treturn []CountryCode{KGZ}\n\tcase CallCode998:\n\t\treturn []CountryCode{UZB}\n\tcase CallCode5999:\n\t\treturn []CountryCode{CUW}\n\tcase CallCode35818:\n\t\treturn []CountryCode{ALA}\n\tcase CallCode441481:\n\t\treturn []CountryCode{GGY}\n\tcase CallCode441534:\n\t\treturn []CountryCode{JEY}\n\tcase CallCode441624:\n\t\treturn []CountryCode{IMN}\n\tcase CallCode3906698:\n\t\treturn []CountryCode{VAT}\n\tcase CallCode6189162:\n\t\treturn []CountryCode{CCK}\n\tcase CallCode6189164:\n\t\treturn []CountryCode{CXR}\n\t}\n\treturn []CountryCode{Unknown}\n}",
"func (c CallCode) Countries() []CountryCode { //nolint:gocyclo\n\tswitch c {\n\tcase CallCode1:\n\t\treturn []CountryCode{ATF, CAN, UMI, USA}\n\tcase CallCode1808:\n\t\treturn []CountryCode{USA}\n\tcase CallCode1242:\n\t\treturn []CountryCode{BHS}\n\tcase CallCode1246:\n\t\treturn []CountryCode{BRB}\n\tcase CallCode1264:\n\t\treturn []CountryCode{AIA}\n\tcase CallCode1268:\n\t\treturn []CountryCode{ATG}\n\tcase CallCode1284:\n\t\treturn []CountryCode{VGB}\n\tcase CallCode1340:\n\t\treturn []CountryCode{VIR}\n\tcase CallCode1345:\n\t\treturn []CountryCode{CYM}\n\tcase CallCode1441:\n\t\treturn []CountryCode{BMU}\n\tcase CallCode1473:\n\t\treturn []CountryCode{GRD}\n\tcase CallCode1649:\n\t\treturn []CountryCode{TCA}\n\tcase CallCode1664:\n\t\treturn []CountryCode{MSR}\n\tcase CallCode1670:\n\t\treturn []CountryCode{MNP}\n\tcase CallCode1671:\n\t\treturn []CountryCode{GUM}\n\tcase CallCode1684:\n\t\treturn []CountryCode{ASM}\n\tcase CallCode1758:\n\t\treturn []CountryCode{LCA}\n\tcase CallCode1767:\n\t\treturn []CountryCode{DMA}\n\tcase CallCode1784:\n\t\treturn []CountryCode{VCT}\n\tcase CallCode1787, CallCode1939:\n\t\treturn []CountryCode{PRI}\n\tcase CallCode1809, CallCode1829, CallCode1849:\n\t\treturn []CountryCode{DOM}\n\tcase CallCode1868:\n\t\treturn []CountryCode{TTO}\n\tcase CallCode1869:\n\t\treturn []CountryCode{KNA}\n\tcase CallCode1876, CallCode1658:\n\t\treturn []CountryCode{JAM}\n\tcase CallCode20:\n\t\treturn []CountryCode{EGY}\n\tcase CallCode211:\n\t\treturn []CountryCode{SSD}\n\tcase CallCode212:\n\t\treturn []CountryCode{ESH, MAR}\n\tcase CallCode213:\n\t\treturn []CountryCode{DZA}\n\tcase CallCode216:\n\t\treturn []CountryCode{TUN}\n\tcase CallCode218:\n\t\treturn []CountryCode{LBY}\n\tcase CallCode220:\n\t\treturn []CountryCode{GMB}\n\tcase CallCode221:\n\t\treturn []CountryCode{SEN}\n\tcase CallCode222:\n\t\treturn []CountryCode{MRT}\n\tcase CallCode223:\n\t\treturn []CountryCode{MLI}\n\tcase CallCode224:\n\t\treturn []CountryCode{GIN}\n\tcase CallCode225:\n\t\treturn []CountryCode{CIV}\n\tcase CallCode226:\n\t\treturn []CountryCode{BFA}\n\tcase CallCode227:\n\t\treturn []CountryCode{NER}\n\tcase CallCode228:\n\t\treturn []CountryCode{TGO}\n\tcase CallCode229:\n\t\treturn []CountryCode{BEN}\n\tcase CallCode230:\n\t\treturn []CountryCode{MUS}\n\tcase CallCode231:\n\t\treturn []CountryCode{LBR}\n\tcase CallCode232:\n\t\treturn []CountryCode{SLE}\n\tcase CallCode233:\n\t\treturn []CountryCode{GHA}\n\tcase CallCode234:\n\t\treturn []CountryCode{NGA}\n\tcase CallCode235:\n\t\treturn []CountryCode{TCD}\n\tcase CallCode236:\n\t\treturn []CountryCode{CAF}\n\tcase CallCode237:\n\t\treturn []CountryCode{CMR}\n\tcase CallCode238:\n\t\treturn []CountryCode{CPV}\n\tcase CallCode239:\n\t\treturn []CountryCode{STP}\n\tcase CallCode240:\n\t\treturn []CountryCode{GNQ}\n\tcase CallCode241:\n\t\treturn []CountryCode{GAB}\n\tcase CallCode242:\n\t\treturn []CountryCode{COG}\n\tcase CallCode243:\n\t\treturn []CountryCode{COD}\n\tcase CallCode244:\n\t\treturn []CountryCode{AGO}\n\tcase CallCode245:\n\t\treturn []CountryCode{GNB}\n\tcase CallCode246:\n\t\treturn []CountryCode{IOT}\n\tcase CallCode248:\n\t\treturn []CountryCode{SYC}\n\tcase CallCode249:\n\t\treturn []CountryCode{SDN}\n\tcase CallCode250:\n\t\treturn []CountryCode{RWA}\n\tcase CallCode251:\n\t\treturn []CountryCode{ETH}\n\tcase CallCode252:\n\t\treturn []CountryCode{SOM}\n\tcase CallCode253:\n\t\treturn []CountryCode{DJI}\n\tcase CallCode254:\n\t\treturn []CountryCode{KEN}\n\tcase CallCode255:\n\t\treturn []CountryCode{TZA}\n\tcase CallCode256:\n\t\treturn []CountryCode{UGA}\n\tcase CallCode257:\n\t\treturn []CountryCode{BDI}\n\tcase CallCode258:\n\t\treturn []CountryCode{MOZ}\n\tcase CallCode260:\n\t\treturn []CountryCode{ZMB}\n\tcase CallCode261:\n\t\treturn []CountryCode{MDG}\n\tcase CallCode262:\n\t\treturn []CountryCode{MYT, REU}\n\tcase CallCode262269, CallCode262639:\n\t\treturn []CountryCode{MYT}\n\tcase CallCode263:\n\t\treturn []CountryCode{ZWE}\n\tcase CallCode264:\n\t\treturn []CountryCode{NAM}\n\tcase CallCode265:\n\t\treturn []CountryCode{MWI}\n\tcase CallCode266:\n\t\treturn []CountryCode{LSO}\n\tcase CallCode267:\n\t\treturn []CountryCode{BWA}\n\tcase CallCode268:\n\t\treturn []CountryCode{SWZ}\n\tcase CallCode269:\n\t\treturn []CountryCode{COM}\n\tcase CallCode27:\n\t\treturn []CountryCode{ZAF}\n\tcase CallCode290:\n\t\treturn []CountryCode{SHN}\n\tcase CallCode291:\n\t\treturn []CountryCode{ERI}\n\tcase CallCode297, CallCode5998:\n\t\treturn []CountryCode{ABW}\n\tcase CallCode298:\n\t\treturn []CountryCode{FRO}\n\tcase CallCode299:\n\t\treturn []CountryCode{GRL}\n\tcase CallCode30:\n\t\treturn []CountryCode{GRC}\n\tcase CallCode31:\n\t\treturn []CountryCode{NLD}\n\tcase CallCode32:\n\t\treturn []CountryCode{BEL}\n\tcase CallCode33:\n\t\treturn []CountryCode{FRA}\n\tcase CallCode34:\n\t\treturn []CountryCode{ESP}\n\tcase CallCode350:\n\t\treturn []CountryCode{GIB}\n\tcase CallCode351:\n\t\treturn []CountryCode{PRT}\n\tcase CallCode352:\n\t\treturn []CountryCode{LUX}\n\tcase CallCode353:\n\t\treturn []CountryCode{IRL}\n\tcase CallCode354:\n\t\treturn []CountryCode{ISL}\n\tcase CallCode355:\n\t\treturn []CountryCode{ALB}\n\tcase CallCode356:\n\t\treturn []CountryCode{MLT}\n\tcase CallCode357:\n\t\treturn []CountryCode{CYP}\n\tcase CallCode358:\n\t\treturn []CountryCode{ALA, FIN}\n\tcase CallCode359:\n\t\treturn []CountryCode{BGR}\n\tcase CallCode36:\n\t\treturn []CountryCode{HUN}\n\tcase CallCode370:\n\t\treturn []CountryCode{LTU}\n\tcase CallCode371:\n\t\treturn []CountryCode{LVA}\n\tcase CallCode372:\n\t\treturn []CountryCode{EST}\n\tcase CallCode373:\n\t\treturn []CountryCode{MDA}\n\tcase CallCode374:\n\t\treturn []CountryCode{ARM}\n\tcase CallCode375:\n\t\treturn []CountryCode{BLR}\n\tcase CallCode376:\n\t\treturn []CountryCode{AND}\n\tcase CallCode377:\n\t\treturn []CountryCode{MCO}\n\tcase CallCode378:\n\t\treturn []CountryCode{SMR}\n\tcase CallCode38:\n\t\treturn []CountryCode{YUG}\n\tcase CallCode380:\n\t\treturn []CountryCode{UKR}\n\tcase CallCode381:\n\t\treturn []CountryCode{SRB}\n\tcase CallCode382:\n\t\treturn []CountryCode{MNE}\n\tcase CallCode383:\n\t\treturn []CountryCode{XKX}\n\tcase CallCode385:\n\t\treturn []CountryCode{HRV}\n\tcase CallCode386:\n\t\treturn []CountryCode{SVN}\n\tcase CallCode387:\n\t\treturn []CountryCode{BIH}\n\tcase CallCode389:\n\t\treturn []CountryCode{MKD}\n\tcase CallCode39:\n\t\treturn []CountryCode{ITA, VAT}\n\tcase CallCode40:\n\t\treturn []CountryCode{ROU}\n\tcase CallCode41:\n\t\treturn []CountryCode{CHE}\n\tcase CallCode420:\n\t\treturn []CountryCode{CZE}\n\tcase CallCode421:\n\t\treturn []CountryCode{SVK}\n\tcase CallCode423:\n\t\treturn []CountryCode{LIE}\n\tcase CallCode43:\n\t\treturn []CountryCode{AUT}\n\tcase CallCode44:\n\t\treturn []CountryCode{GBR, GGY, IMN, JEY, XSC, XWA}\n\tcase CallCode45:\n\t\treturn []CountryCode{DNK}\n\tcase CallCode46:\n\t\treturn []CountryCode{SWE}\n\tcase CallCode47:\n\t\treturn []CountryCode{BVT, NOR, SJM}\n\tcase CallCode48:\n\t\treturn []CountryCode{POL}\n\tcase CallCode49:\n\t\treturn []CountryCode{DEU}\n\tcase CallCode500:\n\t\treturn []CountryCode{FLK, SGS}\n\tcase CallCode501:\n\t\treturn []CountryCode{BLZ}\n\tcase CallCode502:\n\t\treturn []CountryCode{GTM}\n\tcase CallCode503:\n\t\treturn []CountryCode{SLV}\n\tcase CallCode504:\n\t\treturn []CountryCode{HND}\n\tcase CallCode505:\n\t\treturn []CountryCode{NIC}\n\tcase CallCode506:\n\t\treturn []CountryCode{CRI}\n\tcase CallCode507:\n\t\treturn []CountryCode{PAN}\n\tcase CallCode508:\n\t\treturn []CountryCode{SPM}\n\tcase CallCode509:\n\t\treturn []CountryCode{HTI}\n\tcase CallCode51:\n\t\treturn []CountryCode{PER}\n\tcase CallCode52:\n\t\treturn []CountryCode{MEX}\n\tcase CallCode53:\n\t\treturn []CountryCode{CUB}\n\tcase CallCode54:\n\t\treturn []CountryCode{ARG}\n\tcase CallCode55:\n\t\treturn []CountryCode{BRA}\n\tcase CallCode56:\n\t\treturn []CountryCode{CHL}\n\tcase CallCode57:\n\t\treturn []CountryCode{COL}\n\tcase CallCode58:\n\t\treturn []CountryCode{VEN}\n\tcase CallCode590:\n\t\treturn []CountryCode{BLM, GLP, MAF}\n\tcase CallCode591:\n\t\treturn []CountryCode{BOL}\n\tcase CallCode592:\n\t\treturn []CountryCode{GUY}\n\tcase CallCode593:\n\t\treturn []CountryCode{ECU}\n\tcase CallCode594:\n\t\treturn []CountryCode{GUF}\n\tcase CallCode595:\n\t\treturn []CountryCode{PRY}\n\tcase CallCode596:\n\t\treturn []CountryCode{MTQ}\n\tcase CallCode597:\n\t\treturn []CountryCode{SUR}\n\tcase CallCode598:\n\t\treturn []CountryCode{URY}\n\tcase CallCode599:\n\t\treturn []CountryCode{ANT, BES, CUW}\n\tcase CallCode60:\n\t\treturn []CountryCode{MYS}\n\tcase CallCode61:\n\t\treturn []CountryCode{AUS, CXR, CCK}\n\tcase CallCode62:\n\t\treturn []CountryCode{IDN}\n\tcase CallCode63:\n\t\treturn []CountryCode{PHL}\n\tcase CallCode64:\n\t\treturn []CountryCode{NZL, PCN}\n\tcase CallCode65:\n\t\treturn []CountryCode{SGP}\n\tcase CallCode66:\n\t\treturn []CountryCode{THA}\n\tcase CallCode670:\n\t\treturn []CountryCode{TLS}\n\tcase CallCode672:\n\t\treturn []CountryCode{ATA, CCK, NFK}\n\tcase CallCode673:\n\t\treturn []CountryCode{BRN}\n\tcase CallCode674:\n\t\treturn []CountryCode{NRU}\n\tcase CallCode675:\n\t\treturn []CountryCode{PNG}\n\tcase CallCode676:\n\t\treturn []CountryCode{TON}\n\tcase CallCode677:\n\t\treturn []CountryCode{SLB}\n\tcase CallCode678:\n\t\treturn []CountryCode{VUT}\n\tcase CallCode679:\n\t\treturn []CountryCode{FJI}\n\tcase CallCode680:\n\t\treturn []CountryCode{PLW}\n\tcase CallCode681:\n\t\treturn []CountryCode{WLF}\n\tcase CallCode682:\n\t\treturn []CountryCode{COK}\n\tcase CallCode683:\n\t\treturn []CountryCode{NIU}\n\tcase CallCode684:\n\t\treturn []CountryCode{WSM}\n\tcase CallCode686:\n\t\treturn []CountryCode{KIR}\n\tcase CallCode687:\n\t\treturn []CountryCode{NCL}\n\tcase CallCode688:\n\t\treturn []CountryCode{TUV}\n\tcase CallCode689:\n\t\treturn []CountryCode{PYF}\n\tcase CallCode690:\n\t\treturn []CountryCode{TKL}\n\tcase CallCode691:\n\t\treturn []CountryCode{FSM}\n\tcase CallCode692:\n\t\treturn []CountryCode{MHL}\n\tcase CallCode7:\n\t\treturn []CountryCode{KAZ, RUS}\n\tcase CallCode1721, CallCode5995:\n\t\treturn []CountryCode{SXM}\n\tcase CallCode4779:\n\t\treturn []CountryCode{SJM}\n\tcase CallCode5993, CallCode5994, CallCode5997:\n\t\treturn []CountryCode{BES}\n\tcase CallCode7370:\n\t\treturn []CountryCode{TKM}\n\tcase CallCode81:\n\t\treturn []CountryCode{JPN}\n\tcase CallCode82:\n\t\treturn []CountryCode{KOR}\n\tcase CallCode84:\n\t\treturn []CountryCode{VNM}\n\tcase CallCode850:\n\t\treturn []CountryCode{PRK}\n\tcase CallCode852:\n\t\treturn []CountryCode{HKG}\n\tcase CallCode853:\n\t\treturn []CountryCode{MAC}\n\tcase CallCode855:\n\t\treturn []CountryCode{KHM}\n\tcase CallCode856:\n\t\treturn []CountryCode{LAO}\n\tcase CallCode86:\n\t\treturn []CountryCode{CHN}\n\tcase CallCode800:\n\t\treturn []CountryCode{NonCountryInternationalFreephone}\n\tcase CallCode870:\n\t\treturn []CountryCode{NonCountryInmarsat}\n\tcase CallCode875, CallCode876, CallCode877:\n\t\treturn []CountryCode{NonCountryMaritimeMobileService}\n\tcase CallCode878:\n\t\treturn []CountryCode{NonCountryUniversalPersonalTelecommunicationsServices}\n\tcase CallCode879:\n\t\treturn []CountryCode{NonCountryNationalNonCommercialPurposes}\n\tcase CallCode880:\n\t\treturn []CountryCode{BGD}\n\tcase CallCode881:\n\t\treturn []CountryCode{NonCountryGlobalMobileSatelliteSystem}\n\tcase CallCode882, CallCode883:\n\t\treturn []CountryCode{NonCountryInternationalNetworks}\n\tcase CallCode886:\n\t\treturn []CountryCode{TWN}\n\tcase CallCode90:\n\t\treturn []CountryCode{TUR}\n\tcase CallCode91:\n\t\treturn []CountryCode{IND}\n\tcase CallCode92:\n\t\treturn []CountryCode{PAK}\n\tcase CallCode93:\n\t\treturn []CountryCode{AFG}\n\tcase CallCode94:\n\t\treturn []CountryCode{LKA}\n\tcase CallCode95:\n\t\treturn []CountryCode{MMR}\n\tcase CallCode888:\n\t\treturn []CountryCode{NonCountryDisasterRelief}\n\tcase CallCode960:\n\t\treturn []CountryCode{MDV}\n\tcase CallCode961:\n\t\treturn []CountryCode{LBN}\n\tcase CallCode962:\n\t\treturn []CountryCode{JOR}\n\tcase CallCode963:\n\t\treturn []CountryCode{SYR}\n\tcase CallCode964:\n\t\treturn []CountryCode{IRQ}\n\tcase CallCode965:\n\t\treturn []CountryCode{KWT}\n\tcase CallCode966:\n\t\treturn []CountryCode{SAU}\n\tcase CallCode967:\n\t\treturn []CountryCode{YEM}\n\tcase CallCode968:\n\t\treturn []CountryCode{OMN}\n\tcase CallCode971:\n\t\treturn []CountryCode{ARE}\n\tcase CallCode972:\n\t\treturn []CountryCode{ISR, PSE}\n\tcase CallCode973:\n\t\treturn []CountryCode{BHR}\n\tcase CallCode974:\n\t\treturn []CountryCode{QAT}\n\tcase CallCode975:\n\t\treturn []CountryCode{BTN}\n\tcase CallCode976:\n\t\treturn []CountryCode{MNG}\n\tcase CallCode977:\n\t\treturn []CountryCode{NPL}\n\tcase CallCode98:\n\t\treturn []CountryCode{IRN}\n\tcase CallCode979:\n\t\treturn []CountryCode{NonCountryInternationalPremiumRateService}\n\tcase CallCode991:\n\t\treturn []CountryCode{NonCountryInternationalTelecommunicationsCorrespondenceService}\n\tcase CallCode992:\n\t\treturn []CountryCode{TJK}\n\tcase CallCode994:\n\t\treturn []CountryCode{AZE}\n\tcase CallCode995:\n\t\treturn []CountryCode{GEO}\n\tcase CallCode996:\n\t\treturn []CountryCode{KGZ}\n\tcase CallCode998:\n\t\treturn []CountryCode{UZB}\n\tcase CallCode5999:\n\t\treturn []CountryCode{CUW}\n\tcase CallCode35818:\n\t\treturn []CountryCode{ALA}\n\tcase CallCode441481:\n\t\treturn []CountryCode{GGY}\n\tcase CallCode441534:\n\t\treturn []CountryCode{JEY}\n\tcase CallCode441624:\n\t\treturn []CountryCode{IMN}\n\tcase CallCode3906698:\n\t\treturn []CountryCode{VAT}\n\tcase CallCode6189162:\n\t\treturn []CountryCode{CCK}\n\tcase CallCode6189164:\n\t\treturn []CountryCode{CXR}\n\t}\n\treturn []CountryCode{Unknown}\n}",
"func (api *LaborStatsAPI) QueryCountry() ([]Country, error) {\n\ta := CountryAPI{\n\t\tDebug: api.Debug,\n\t\tSecretKey: api.SecretKey,\n\t}\n\n\terr := a.sendRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := a.unmarshalData()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}",
"func ByCode(code Code) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code.String()]\n\treturn\n}",
"func ByISO(s string) (Currency, bool) {\n\tc, ok := byISO[strings.ToUpper(s)]\n\tif ok {\n\t\treturn *c, ok\n\t}\n\n\treturn Currency{}, false\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func getGeneralCountryInformation(c *gin.Context) {\n var params gciQueryParams\n _ = c.Bind(¶ms)\n\n if !params.Sort.isValid() {\n params.Sort = confirmed\n }\n\n if !params.Order.isValid() {\n params.Order = descending\n }\n\n columns := []string{\n \"l.id country_id\",\n \"l.country\",\n \"sum(r.confirmed) confirmed\",\n \"sum(r.recovered) recovered\",\n \"sum(r.deaths) deaths\",\n }\n query := databaseManager.\n DB.\n Table(\"location l\").\n Select(columns).\n Joins(\"inner join record r on l.id = r.location_id\").\n Group(\"l.id, l.country\").\n Order(fmt.Sprintf(\"%s %s\", string(params.Sort), string(params.Order)))\n\n var results []gci\n query.Find(&results)\n\n if params.First != 0 {\n OK(c, results[:int(math.Min(float64(params.First), float64(len(results))))])\n } else if params.Last != 0 {\n OK(c, results[len(results)-params.Last:])\n } else {\n OK(c, results)\n }\n}",
"func (s *CountriesService) GetByKey(countryKey string, marketID string, sort string, order string) ([]Country, error) {\n\tvar res []Country\n\turi, err := BuildQuery(\"/v1/countries/\"+countryKey, map[string]interface{}{\n\t\t\"marketId\": marketID,\n\t\t\"sort\": sort,\n\t\t\"order\": order,\n\t})\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\tdata, err := s.client.Get(uri)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\terr = json.Unmarshal(data, &res)\n\n\treturn res, err\n}",
"func (repo *AccountTypeRepository) FindByCurrencyCode(currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"currency_code = ?\", currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func locateIpCountry(ipAddr net.IP) (CountryData, error) {\n var result CountryData\n\n record, err := dataStore.Country(ipAddr)\n\n if err != nil {\n return result, err\n }\n\n if record != nil {\n result.IPAddress = ipAddr\n result.Name = record.Country.Names[\"en\"]\n result.IsoCode = record.Country.IsoCode\n }\n\n return result, nil\n}",
"func GetBillingCurrencyCountryService(sess *session.Session) Billing_Currency_Country {\n\treturn Billing_Currency_Country{Session: sess}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCodeErr lookup for currency type by code
|
func ByCodeErr(code Code) (c currency, err error) {
var ok bool
c, ok = currenciesByCode[code.String()]
if !ok {
return currency{}, fmt.Errorf("'%s' is not valid ISO-4217 code", code)
}
return
}
|
[
"func ByCodeStrErr(code string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func ByCode(code Code) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code.String()]\n\treturn\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func (currencies currencies) CurrencyByCode(code string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.code) == code {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func (repo *AccountTypeRepository) FindByCurrencyCode(currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"currency_code = ?\", currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func ByCurrencyErr(currencyStr Currency) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCodeStr(code string) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func (o *GetRuleTypesNotFound) Code() int {\n\treturn 404\n}",
"func ByNumberErr(number Number) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func (s *Currencies) FindByCode(code string) (*models.Currency, error) {\n\tvar currency models.Currency\n\n\terr := s.db.Where(\"code = ?\", code).FirstOrInit(¤cy).Error\n\n\treturn ¤cy, err\n}",
"func InstitutionTypeByCode(code string) (string, bool) {\n\tt, ok := instType[code]\n\treturn t, ok\n}",
"func (s *Server) providerTypeGetByCode(\n\tsess *pb.Session,\n\tcode string,\n) (*pb.ProviderType, error) {\n\treq := &pb.ProviderTypeGetByCodeRequest{\n\t\tSession: sess,\n\t\tCode: code,\n\t}\n\tmc, err := s.metaClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trec, err := mc.ProviderTypeGetByCode(context.Background(), req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pb.ProviderType{\n\t\tCode: rec.Code,\n\t\tDescription: rec.Description,\n\t}, nil\n}",
"func (o *RefundPaymentNotFound) Code() int {\n\treturn 404\n}",
"func CurrencyCode(id int) string {\n\treturn currencyCode[id]\n}",
"func ByCountryErr(country Country) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country.String()]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func ByCurrencyStrErr(currencyStr string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func (repo *AccountTypeRepository) FindByNameAndCurrencyCode(name, currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"name = ? AND currency_code = ?\", name, currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func Code(err error) codes.Code {\n\tif err == nil {\n\t\treturn codes.OK\n\t}\n\n\tif code, ok := lookupCode(err); ok {\n\t\treturn code\n\t}\n\n\tvar grpcErr GRPCStatuser\n\n\tswitch {\n\tcase errors.As(err, &grpcErr):\n\t\treturn grpcErr.GRPCStatus().Code()\n\tcase errors.Is(err, context.DeadlineExceeded):\n\t\treturn codes.DeadlineExceeded\n\tcase errors.Is(err, context.Canceled):\n\t\treturn codes.Canceled\n\tdefault:\n\t\treturn CodeFromHTTPStatus(merry.HTTPCode(err))\n\t}\n}",
"func GetCurrency(code Code) (c Currency, ok bool) {\n\tok = false\n\tif !code.IsValid() {\n\t\treturn\n\t}\n\n\tc, ok = currenciesByCode[code]\n\treturn\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCurrencyErr lookup for currencies type by code
|
func ByCurrencyErr(currencyStr Currency) (c currency, err error) {
var ok bool
c, ok = currenciesByCurrency[currencyStr.String()]
if !ok {
return currency{}, fmt.Errorf("'%s' is not valid ISO-4217 currency", currencyStr)
}
return
}
|
[
"func ByCodeErr(code Code) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func ByCodeStrErr(code string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func ByCurrencyStrErr(currencyStr string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCountryErr(country Country) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country.String()]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func ByCountryStrErr(country string) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func ByCode(code Code) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code.String()]\n\treturn\n}",
"func CurrencyCode(id int) string {\n\treturn currencyCode[id]\n}",
"func (currencies currencies) CurrencyByCode(code string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.code) == code {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func GetCurrency(code Code) (c Currency, ok bool) {\n\tok = false\n\tif !code.IsValid() {\n\t\treturn\n\t}\n\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func ByNumberErr(number Number) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func (repo *AccountTypeRepository) FindByCurrencyCode(currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"currency_code = ?\", currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func ByNumberStrErr(number string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func ByCodeStr(code string) (c currency, ok bool) {\n\tc, ok = currenciesByCode[code]\n\treturn\n}",
"func convertCardError(t stripe.ErrorCode) pb.CardErrors {\n\tlookup := map[stripe.ErrorCode]pb.CardErrors{\n\t\tstripe.IncorrectNum: pb.CardErrors_IncorrectNumber,\n\t\tstripe.InvalidNum: pb.CardErrors_InvalidNumber,\n\t\tstripe.InvalidExpM: pb.CardErrors_InvalidExpirationMonth,\n\t\tstripe.InvalidExpY: pb.CardErrors_InvalidExpirationYear,\n\t\tstripe.InvalidCvc: pb.CardErrors_InvalidCvc,\n\t\tstripe.ExpiredCard: pb.CardErrors_Expired,\n\t\tstripe.IncorrectCvc: pb.CardErrors_IncorrectCvc,\n\t\tstripe.IncorrectZip: pb.CardErrors_IncorrectZip,\n\t\tstripe.CardDeclined: pb.CardErrors_Declined,\n\t\tstripe.Missing: pb.CardErrors_Missing,\n\t\tstripe.ProcessingErr: pb.CardErrors_ProcessingError,\n\t\tstripe.RateLimit: pb.CardErrors_RateLimited,\n\t}\n\treturn lookup[t]\n}",
"func ByCurrencyStr(currency string) (c currency, ok bool) {\n\tc, ok = currenciesByCurrency[currency]\n\treturn\n}",
"func ERROR_CURRENCY_NOT_FOUND(w http.ResponseWriter) {\n\tbuildForeignError(w, http.StatusNotFound, \"ERROR_CURRENCY_NOT_FOUND\", \"\")\n}",
"func (repo *AccountTypeRepository) FindByNameAndCurrencyCode(name, currencyCode string) (*model.AccountType, error) {\n\tvar accountType model.AccountType\n\tif err := repo.db.Where(\"name = ? AND currency_code = ?\", name, currencyCode).First(&accountType).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accountType, nil\n}",
"func convertErrorType(t stripe.ErrorType) pb.ErrorType {\n\tlookup := map[stripe.ErrorType]pb.ErrorType{\n\t\tstripe.ErrorTypeAPI: pb.ErrorType_API,\n\t\tstripe.ErrorTypeAPIConnection: pb.ErrorType_APIConnection,\n\t\tstripe.ErrorTypeAuthentication: pb.ErrorType_Authentication,\n\t\tstripe.ErrorTypeCard: pb.ErrorType_Card,\n\t\tstripe.ErrorTypeInvalidRequest: pb.ErrorType_InvalidRequest,\n\t\tstripe.ErrorTypePermission: pb.ErrorType_Permission,\n\t\tstripe.ErrorTypeRateLimit: pb.ErrorType_RateLimit,\n\t}\n\treturn lookup[t]\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByNumberErr lookup for currencies type by number
|
func ByNumberErr(number Number) (c currency, err error) {
var ok bool
c, ok = currenciesByNumber[number.String()]
if !ok {
return currency{}, fmt.Errorf("'%s' is not valid ISO-4217 number", number)
}
return
}
|
[
"func ByNumberStrErr(number string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByNumber[number]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 number\", number)\n\t}\n\n\treturn\n}",
"func ByNumber(number Number) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number.String()]\n\treturn\n}",
"func ByNumberStr(number string) (c currency, ok bool) {\n\tc, ok = currenciesByNumber[number]\n\treturn\n}",
"func (currencies currencies) CurrencyByNumber(number string) (currency, bool) {\n\tfor _, c := range currencies {\n\t\tif string(c.number) == number {\n\t\t\treturn c, true\n\t\t}\n\t}\n\n\treturn currency{}, false\n}",
"func ByCurrencyErr(currencyStr Currency) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func ByCodeErr(code Code) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func FindByNumber(num int) *Country {\n\tsearch := fmt.Sprintf(\"%03d\", num)\n\tfor _, c := range countries {\n\t\tif c.ExistsNum(search) {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}",
"func ByCountryErr(country Country) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country.String()]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func ByNumeric(s string) (Currency, bool) {\n\tc, ok := byNumeric[s]\n\tif ok {\n\t\treturn *c, true\n\t}\n\n\treturn Currency{}, false\n}",
"func ByCurrencyStrErr(currencyStr string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func GetCurrency(code string) currency.Type {\n\tc, found := currencies[strings.ToUpper(code)]\n\tif !found {\n\t\treturn -1\n\t}\n\treturn c\n}",
"func ByCodeStrErr(code string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func convertErrorType(t stripe.ErrorType) pb.ErrorType {\n\tlookup := map[stripe.ErrorType]pb.ErrorType{\n\t\tstripe.ErrorTypeAPI: pb.ErrorType_API,\n\t\tstripe.ErrorTypeAPIConnection: pb.ErrorType_APIConnection,\n\t\tstripe.ErrorTypeAuthentication: pb.ErrorType_Authentication,\n\t\tstripe.ErrorTypeCard: pb.ErrorType_Card,\n\t\tstripe.ErrorTypeInvalidRequest: pb.ErrorType_InvalidRequest,\n\t\tstripe.ErrorTypePermission: pb.ErrorType_Permission,\n\t\tstripe.ErrorTypeRateLimit: pb.ErrorType_RateLimit,\n\t}\n\treturn lookup[t]\n}",
"func numberType(f func(...Expression) Expression) func(...Expression) (Expression, error) {\n\n\treturn func(args ...Expression) (Expression, error) {\n\t\tfor _, arg := range args {\n\t\t\tif _, ok := arg.(Number); !ok {\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"Type Error: Recieved %T, Expected Number\", arg))\n\t\t\t}\n\t\t}\n\t\treturn f(args...), nil\n\t}\n}",
"func convertCardError(t stripe.ErrorCode) pb.CardErrors {\n\tlookup := map[stripe.ErrorCode]pb.CardErrors{\n\t\tstripe.IncorrectNum: pb.CardErrors_IncorrectNumber,\n\t\tstripe.InvalidNum: pb.CardErrors_InvalidNumber,\n\t\tstripe.InvalidExpM: pb.CardErrors_InvalidExpirationMonth,\n\t\tstripe.InvalidExpY: pb.CardErrors_InvalidExpirationYear,\n\t\tstripe.InvalidCvc: pb.CardErrors_InvalidCvc,\n\t\tstripe.ExpiredCard: pb.CardErrors_Expired,\n\t\tstripe.IncorrectCvc: pb.CardErrors_IncorrectCvc,\n\t\tstripe.IncorrectZip: pb.CardErrors_IncorrectZip,\n\t\tstripe.CardDeclined: pb.CardErrors_Declined,\n\t\tstripe.Missing: pb.CardErrors_Missing,\n\t\tstripe.ProcessingErr: pb.CardErrors_ProcessingError,\n\t\tstripe.RateLimit: pb.CardErrors_RateLimited,\n\t}\n\treturn lookup[t]\n}",
"func ByCountryStrErr(country string) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func CheckNumberSystem(i interface{}) (n []NumberType, e error) {\n\tswitch i.(type) {\n\tcase int:\n\t\td := int(reflect.ValueOf(i).Int())\n\t\tif IsWholeNumbers(d) {\n\t\t\tn = append(n, WholeNumbers)\n\t\t}\n\n\t\tif IsNaturalNumbers(d) {\n\t\t\tn = append(n, NaturalNumbers)\n\t\t}\n\n\t\tn = append(n, Integers)\n\t\tbreak\n\tcase float64:\n\t\tfmt.Println(\"On working for rational numbers, irrational numbers and real numbers\")\n\t\tbreak\n\tdefault:\n\t\te = errors.New(\"your input is not a type of number\")\n\t\tbreak\n\t}\n\treturn n, e\n}",
"func (s *Scanner) scanNumber(ch rune) TokenType {\n\tif ch == '0' {\n\t\t// check for hexadecimal, octal or float\n\t\tch = s.next()\n\t\tif ch == 'x' || ch == 'X' {\n\t\t\t// hexadecimal\n\t\t\tch = s.next()\n\t\t\tfound := false\n\t\t\tfor isHexadecimal(ch) {\n\t\t\t\tch = s.next()\n\t\t\t\tfound = true\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\ts.errorf(\"illegal hexadecimal number\")\n\t\t\t}\n\n\t\t\tif ch != eof {\n\t\t\t\ts.unread()\n\t\t\t}\n\n\t\t\treturn INT\n\t\t}\n\n\t\t// now it's either something like: 0421(octal) or 0.1231(float)\n\t\tillegalOctal := false\n\t\tfor isDecimal(ch) {\n\t\t\tch = s.next()\n\t\t\tif ch == '8' || ch == '9' {\n\t\t\t\t// this is just a possibility. For example 0159 is illegal, but\n\t\t\t\t// 0159.23 is valid. So we mark a possible illegal octal. If\n\t\t\t\t// the next character is not a period, we'll print the error.\n\t\t\t\tillegalOctal = true\n\t\t\t}\n\t\t}\n\n\t\t// literals of form 01e10 are treates as Numbers in HCL, which differs from Go.\n\t\tif ch == 'e' || ch == 'E' {\n\t\t\tch = s.scanExponent(ch)\n\t\t\treturn INT\n\t\t}\n\n\t\tif ch == '.' {\n\t\t\tch = s.scanFraction(ch)\n\n\t\t\tif ch == 'e' || ch == 'E' {\n\t\t\t\tch = s.next()\n\t\t\t\tch = s.scanExponent(ch)\n\t\t\t}\n\t\t\treturn FLOAT\n\t\t}\n\n\t\tif illegalOctal {\n\t\t\ts.errorf(\"illegal octal number\")\n\t\t}\n\n\t\tif ch != eof {\n\t\t\ts.unread()\n\t\t}\n\t\treturn INT\n\t}\n\n\ts.scanMantissa(ch)\n\tch = s.next() // seek forward\n\t// literals of form 1e10 are treates as Numbers in HCL, which differs from Go.\n\tif ch == 'e' || ch == 'E' {\n\t\tch = s.scanExponent(ch)\n\t\treturn INT\n\t}\n\n\tif ch == '.' {\n\t\tch = s.scanFraction(ch)\n\t\tif ch == 'e' || ch == 'E' {\n\t\t\tch = s.next()\n\t\t\tch = s.scanExponent(ch)\n\t\t}\n\t\treturn FLOAT\n\t}\n\n\tif ch != eof { // goback\n\t\ts.unread()\n\t}\n\treturn INT\n}",
"func (a *API) VatNumberLookup(w http.ResponseWriter, r *http.Request) error {\n\tnumber := chi.URLParam(r, \"vat_number\")\n\n\tresponse, err := vat.CheckVAT(number)\n\tif err != nil {\n\t\treturn internalServerError(\"Failed to lookup VAT Number\").WithInternalError(err)\n\t}\n\n\treturn sendJSON(w, http.StatusOK, map[string]interface{}{\n\t\t\"country\": response.CountryCode,\n\t\t\"valid\": response.Valid,\n\t\t\"company\": response.Name,\n\t\t\"address\": response.Address,\n\t})\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ByCountryErr lookup for currencies type by country
|
func ByCountryErr(country Country) (c currencies, err error) {
var ok bool
c, ok = currenciesByCountry[country.String()]
if !ok {
return nil, fmt.Errorf("'%s' is not valid ISO-4217 country", country)
}
return
}
|
[
"func ByCountryStrErr(country string) (c currencies, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCountry[country]\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"'%s' is not valid ISO-4217 country\", country)\n\t}\n\n\treturn\n}",
"func ByCountry(country Country) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country.String()]\n\treturn\n}",
"func ByCountryStr(country string) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country]\n\treturn\n}",
"func ByCurrencyErr(currencyStr Currency) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func (api *LaborStatsAPI) QueryCountry() ([]Country, error) {\n\ta := CountryAPI{\n\t\tDebug: api.Debug,\n\t\tSecretKey: api.SecretKey,\n\t}\n\n\terr := a.sendRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := a.unmarshalData()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}",
"func ByCodeErr(code Code) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCode[code.String()]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 code\", code)\n\t}\n\n\treturn\n}",
"func lookupCountry(remoteAddr string) string {\n\thost, _, _ := net.SplitHostPort(remoteAddr)\n\ta := net.ParseIP(host)\n\tif a == nil {\n\t\treturn \"id\"\n\t}\n\n\tvar rec struct {\n\t\tCountry struct {\n\t\t\tISOCode string `maxminddb:\"iso_code\"`\n\t\t} `maxminddb:\"country\"`\n\t}\n\n\terr := geoipdb.Lookup(a, &rec)\n\tif err != nil || rec.Country.ISOCode == \"\" {\n\t\treturn \"id\"\n\t}\n\n\treturn strings.ToLower(rec.Country.ISOCode)\n}",
"func ByCurrencyStrErr(currencyStr string) (c currency, err error) {\n\tvar ok bool\n\tc, ok = currenciesByCurrency[currencyStr]\n\n\tif !ok {\n\t\treturn currency{}, fmt.Errorf(\"'%s' is not valid ISO-4217 currency\", currencyStr)\n\t}\n\n\treturn\n}",
"func getGeneralCountryInformation(c *gin.Context) {\n var params gciQueryParams\n _ = c.Bind(¶ms)\n\n if !params.Sort.isValid() {\n params.Sort = confirmed\n }\n\n if !params.Order.isValid() {\n params.Order = descending\n }\n\n columns := []string{\n \"l.id country_id\",\n \"l.country\",\n \"sum(r.confirmed) confirmed\",\n \"sum(r.recovered) recovered\",\n \"sum(r.deaths) deaths\",\n }\n query := databaseManager.\n DB.\n Table(\"location l\").\n Select(columns).\n Joins(\"inner join record r on l.id = r.location_id\").\n Group(\"l.id, l.country\").\n Order(fmt.Sprintf(\"%s %s\", string(params.Sort), string(params.Order)))\n\n var results []gci\n query.Find(&results)\n\n if params.First != 0 {\n OK(c, results[:int(math.Min(float64(params.First), float64(len(results))))])\n } else if params.Last != 0 {\n OK(c, results[len(results)-params.Last:])\n } else {\n OK(c, results)\n }\n}",
"func (instance *XCountryRepo) GetByISO2Code(iso2Code string) (model.XCountry, error) {\n\treturn instance.getByField(\"iso2Code\", iso2Code)\n}",
"func (c CallCode) Countries() []CountryCode { //nolint:gocyclo\n\tswitch c {\n\tcase CallCode1:\n\t\treturn []CountryCode{ATF, CAN, UMI, USA}\n\tcase CallCode1808:\n\t\treturn []CountryCode{USA}\n\tcase CallCode1242:\n\t\treturn []CountryCode{BHS}\n\tcase CallCode1246:\n\t\treturn []CountryCode{BRB}\n\tcase CallCode1264:\n\t\treturn []CountryCode{AIA}\n\tcase CallCode1268:\n\t\treturn []CountryCode{ATG}\n\tcase CallCode1284:\n\t\treturn []CountryCode{VGB}\n\tcase CallCode1340:\n\t\treturn []CountryCode{VIR}\n\tcase CallCode1345:\n\t\treturn []CountryCode{CYM}\n\tcase CallCode1441:\n\t\treturn []CountryCode{BMU}\n\tcase CallCode1473:\n\t\treturn []CountryCode{GRD}\n\tcase CallCode1649:\n\t\treturn []CountryCode{TCA}\n\tcase CallCode1664:\n\t\treturn []CountryCode{MSR}\n\tcase CallCode1670:\n\t\treturn []CountryCode{MNP}\n\tcase CallCode1671:\n\t\treturn []CountryCode{GUM}\n\tcase CallCode1684:\n\t\treturn []CountryCode{ASM}\n\tcase CallCode1758:\n\t\treturn []CountryCode{LCA}\n\tcase CallCode1767:\n\t\treturn []CountryCode{DMA}\n\tcase CallCode1784:\n\t\treturn []CountryCode{VCT}\n\tcase CallCode1787, CallCode1939:\n\t\treturn []CountryCode{PRI}\n\tcase CallCode1809, CallCode1829, CallCode1849:\n\t\treturn []CountryCode{DOM}\n\tcase CallCode1868:\n\t\treturn []CountryCode{TTO}\n\tcase CallCode1869:\n\t\treturn []CountryCode{KNA}\n\tcase CallCode1876, CallCode1658:\n\t\treturn []CountryCode{JAM}\n\tcase CallCode20:\n\t\treturn []CountryCode{EGY}\n\tcase CallCode211:\n\t\treturn []CountryCode{SSD}\n\tcase CallCode212:\n\t\treturn []CountryCode{ESH, MAR}\n\tcase CallCode213:\n\t\treturn []CountryCode{DZA}\n\tcase CallCode216:\n\t\treturn []CountryCode{TUN}\n\tcase CallCode218:\n\t\treturn []CountryCode{LBY}\n\tcase CallCode220:\n\t\treturn []CountryCode{GMB}\n\tcase CallCode221:\n\t\treturn []CountryCode{SEN}\n\tcase CallCode222:\n\t\treturn []CountryCode{MRT}\n\tcase CallCode223:\n\t\treturn []CountryCode{MLI}\n\tcase CallCode224:\n\t\treturn []CountryCode{GIN}\n\tcase CallCode225:\n\t\treturn []CountryCode{CIV}\n\tcase CallCode226:\n\t\treturn []CountryCode{BFA}\n\tcase CallCode227:\n\t\treturn []CountryCode{NER}\n\tcase CallCode228:\n\t\treturn []CountryCode{TGO}\n\tcase CallCode229:\n\t\treturn []CountryCode{BEN}\n\tcase CallCode230:\n\t\treturn []CountryCode{MUS}\n\tcase CallCode231:\n\t\treturn []CountryCode{LBR}\n\tcase CallCode232:\n\t\treturn []CountryCode{SLE}\n\tcase CallCode233:\n\t\treturn []CountryCode{GHA}\n\tcase CallCode234:\n\t\treturn []CountryCode{NGA}\n\tcase CallCode235:\n\t\treturn []CountryCode{TCD}\n\tcase CallCode236:\n\t\treturn []CountryCode{CAF}\n\tcase CallCode237:\n\t\treturn []CountryCode{CMR}\n\tcase CallCode238:\n\t\treturn []CountryCode{CPV}\n\tcase CallCode239:\n\t\treturn []CountryCode{STP}\n\tcase CallCode240:\n\t\treturn []CountryCode{GNQ}\n\tcase CallCode241:\n\t\treturn []CountryCode{GAB}\n\tcase CallCode242:\n\t\treturn []CountryCode{COG}\n\tcase CallCode243:\n\t\treturn []CountryCode{COD}\n\tcase CallCode244:\n\t\treturn []CountryCode{AGO}\n\tcase CallCode245:\n\t\treturn []CountryCode{GNB}\n\tcase CallCode246:\n\t\treturn []CountryCode{IOT}\n\tcase CallCode248:\n\t\treturn []CountryCode{SYC}\n\tcase CallCode249:\n\t\treturn []CountryCode{SDN}\n\tcase CallCode250:\n\t\treturn []CountryCode{RWA}\n\tcase CallCode251:\n\t\treturn []CountryCode{ETH}\n\tcase CallCode252:\n\t\treturn []CountryCode{SOM}\n\tcase CallCode253:\n\t\treturn []CountryCode{DJI}\n\tcase CallCode254:\n\t\treturn []CountryCode{KEN}\n\tcase CallCode255:\n\t\treturn []CountryCode{TZA}\n\tcase CallCode256:\n\t\treturn []CountryCode{UGA}\n\tcase CallCode257:\n\t\treturn []CountryCode{BDI}\n\tcase CallCode258:\n\t\treturn []CountryCode{MOZ}\n\tcase CallCode260:\n\t\treturn []CountryCode{ZMB}\n\tcase CallCode261:\n\t\treturn []CountryCode{MDG}\n\tcase CallCode262:\n\t\treturn []CountryCode{MYT, REU}\n\tcase CallCode262269, CallCode262639:\n\t\treturn []CountryCode{MYT}\n\tcase CallCode263:\n\t\treturn []CountryCode{ZWE}\n\tcase CallCode264:\n\t\treturn []CountryCode{NAM}\n\tcase CallCode265:\n\t\treturn []CountryCode{MWI}\n\tcase CallCode266:\n\t\treturn []CountryCode{LSO}\n\tcase CallCode267:\n\t\treturn []CountryCode{BWA}\n\tcase CallCode268:\n\t\treturn []CountryCode{SWZ}\n\tcase CallCode269:\n\t\treturn []CountryCode{COM}\n\tcase CallCode27:\n\t\treturn []CountryCode{ZAF}\n\tcase CallCode290:\n\t\treturn []CountryCode{SHN}\n\tcase CallCode291:\n\t\treturn []CountryCode{ERI}\n\tcase CallCode297, CallCode5998:\n\t\treturn []CountryCode{ABW}\n\tcase CallCode298:\n\t\treturn []CountryCode{FRO}\n\tcase CallCode299:\n\t\treturn []CountryCode{GRL}\n\tcase CallCode30:\n\t\treturn []CountryCode{GRC}\n\tcase CallCode31:\n\t\treturn []CountryCode{NLD}\n\tcase CallCode32:\n\t\treturn []CountryCode{BEL}\n\tcase CallCode33:\n\t\treturn []CountryCode{FRA}\n\tcase CallCode34:\n\t\treturn []CountryCode{ESP}\n\tcase CallCode350:\n\t\treturn []CountryCode{GIB}\n\tcase CallCode351:\n\t\treturn []CountryCode{PRT}\n\tcase CallCode352:\n\t\treturn []CountryCode{LUX}\n\tcase CallCode353:\n\t\treturn []CountryCode{IRL}\n\tcase CallCode354:\n\t\treturn []CountryCode{ISL}\n\tcase CallCode355:\n\t\treturn []CountryCode{ALB}\n\tcase CallCode356:\n\t\treturn []CountryCode{MLT}\n\tcase CallCode357:\n\t\treturn []CountryCode{CYP}\n\tcase CallCode358:\n\t\treturn []CountryCode{ALA, FIN}\n\tcase CallCode359:\n\t\treturn []CountryCode{BGR}\n\tcase CallCode36:\n\t\treturn []CountryCode{HUN}\n\tcase CallCode370:\n\t\treturn []CountryCode{LTU}\n\tcase CallCode371:\n\t\treturn []CountryCode{LVA}\n\tcase CallCode372:\n\t\treturn []CountryCode{EST}\n\tcase CallCode373:\n\t\treturn []CountryCode{MDA}\n\tcase CallCode374:\n\t\treturn []CountryCode{ARM}\n\tcase CallCode375:\n\t\treturn []CountryCode{BLR}\n\tcase CallCode376:\n\t\treturn []CountryCode{AND}\n\tcase CallCode377:\n\t\treturn []CountryCode{MCO}\n\tcase CallCode378:\n\t\treturn []CountryCode{SMR}\n\tcase CallCode38:\n\t\treturn []CountryCode{YUG}\n\tcase CallCode380:\n\t\treturn []CountryCode{UKR}\n\tcase CallCode381:\n\t\treturn []CountryCode{SRB}\n\tcase CallCode382:\n\t\treturn []CountryCode{MNE}\n\tcase CallCode383:\n\t\treturn []CountryCode{XKX}\n\tcase CallCode385:\n\t\treturn []CountryCode{HRV}\n\tcase CallCode386:\n\t\treturn []CountryCode{SVN}\n\tcase CallCode387:\n\t\treturn []CountryCode{BIH}\n\tcase CallCode389:\n\t\treturn []CountryCode{MKD}\n\tcase CallCode39:\n\t\treturn []CountryCode{ITA, VAT}\n\tcase CallCode40:\n\t\treturn []CountryCode{ROU}\n\tcase CallCode41:\n\t\treturn []CountryCode{CHE}\n\tcase CallCode420:\n\t\treturn []CountryCode{CZE}\n\tcase CallCode421:\n\t\treturn []CountryCode{SVK}\n\tcase CallCode423:\n\t\treturn []CountryCode{LIE}\n\tcase CallCode43:\n\t\treturn []CountryCode{AUT}\n\tcase CallCode44:\n\t\treturn []CountryCode{GBR, GGY, IMN, JEY, XSC, XWA}\n\tcase CallCode45:\n\t\treturn []CountryCode{DNK}\n\tcase CallCode46:\n\t\treturn []CountryCode{SWE}\n\tcase CallCode47:\n\t\treturn []CountryCode{BVT, NOR, SJM}\n\tcase CallCode48:\n\t\treturn []CountryCode{POL}\n\tcase CallCode49:\n\t\treturn []CountryCode{DEU}\n\tcase CallCode500:\n\t\treturn []CountryCode{FLK, SGS}\n\tcase CallCode501:\n\t\treturn []CountryCode{BLZ}\n\tcase CallCode502:\n\t\treturn []CountryCode{GTM}\n\tcase CallCode503:\n\t\treturn []CountryCode{SLV}\n\tcase CallCode504:\n\t\treturn []CountryCode{HND}\n\tcase CallCode505:\n\t\treturn []CountryCode{NIC}\n\tcase CallCode506:\n\t\treturn []CountryCode{CRI}\n\tcase CallCode507:\n\t\treturn []CountryCode{PAN}\n\tcase CallCode508:\n\t\treturn []CountryCode{SPM}\n\tcase CallCode509:\n\t\treturn []CountryCode{HTI}\n\tcase CallCode51:\n\t\treturn []CountryCode{PER}\n\tcase CallCode52:\n\t\treturn []CountryCode{MEX}\n\tcase CallCode53:\n\t\treturn []CountryCode{CUB}\n\tcase CallCode54:\n\t\treturn []CountryCode{ARG}\n\tcase CallCode55:\n\t\treturn []CountryCode{BRA}\n\tcase CallCode56:\n\t\treturn []CountryCode{CHL}\n\tcase CallCode57:\n\t\treturn []CountryCode{COL}\n\tcase CallCode58:\n\t\treturn []CountryCode{VEN}\n\tcase CallCode590:\n\t\treturn []CountryCode{BLM, GLP, MAF}\n\tcase CallCode591:\n\t\treturn []CountryCode{BOL}\n\tcase CallCode592:\n\t\treturn []CountryCode{GUY}\n\tcase CallCode593:\n\t\treturn []CountryCode{ECU}\n\tcase CallCode594:\n\t\treturn []CountryCode{GUF}\n\tcase CallCode595:\n\t\treturn []CountryCode{PRY}\n\tcase CallCode596:\n\t\treturn []CountryCode{MTQ}\n\tcase CallCode597:\n\t\treturn []CountryCode{SUR}\n\tcase CallCode598:\n\t\treturn []CountryCode{URY}\n\tcase CallCode599:\n\t\treturn []CountryCode{ANT, BES, CUW}\n\tcase CallCode60:\n\t\treturn []CountryCode{MYS}\n\tcase CallCode61:\n\t\treturn []CountryCode{AUS, CXR, CCK}\n\tcase CallCode62:\n\t\treturn []CountryCode{IDN}\n\tcase CallCode63:\n\t\treturn []CountryCode{PHL}\n\tcase CallCode64:\n\t\treturn []CountryCode{NZL, PCN}\n\tcase CallCode65:\n\t\treturn []CountryCode{SGP}\n\tcase CallCode66:\n\t\treturn []CountryCode{THA}\n\tcase CallCode670:\n\t\treturn []CountryCode{TLS}\n\tcase CallCode672:\n\t\treturn []CountryCode{ATA, CCK, NFK}\n\tcase CallCode673:\n\t\treturn []CountryCode{BRN}\n\tcase CallCode674:\n\t\treturn []CountryCode{NRU}\n\tcase CallCode675:\n\t\treturn []CountryCode{PNG}\n\tcase CallCode676:\n\t\treturn []CountryCode{TON}\n\tcase CallCode677:\n\t\treturn []CountryCode{SLB}\n\tcase CallCode678:\n\t\treturn []CountryCode{VUT}\n\tcase CallCode679:\n\t\treturn []CountryCode{FJI}\n\tcase CallCode680:\n\t\treturn []CountryCode{PLW}\n\tcase CallCode681:\n\t\treturn []CountryCode{WLF}\n\tcase CallCode682:\n\t\treturn []CountryCode{COK}\n\tcase CallCode683:\n\t\treturn []CountryCode{NIU}\n\tcase CallCode685:\n\t\treturn []CountryCode{WSM}\n\tcase CallCode686:\n\t\treturn []CountryCode{KIR}\n\tcase CallCode687:\n\t\treturn []CountryCode{NCL}\n\tcase CallCode688:\n\t\treturn []CountryCode{TUV}\n\tcase CallCode689:\n\t\treturn []CountryCode{PYF}\n\tcase CallCode690:\n\t\treturn []CountryCode{TKL}\n\tcase CallCode691:\n\t\treturn []CountryCode{FSM}\n\tcase CallCode692:\n\t\treturn []CountryCode{MHL}\n\tcase CallCode7:\n\t\treturn []CountryCode{KAZ, RUS}\n\tcase CallCode1721, CallCode5995:\n\t\treturn []CountryCode{SXM}\n\tcase CallCode4779:\n\t\treturn []CountryCode{SJM}\n\tcase CallCode5993, CallCode5994, CallCode5997:\n\t\treturn []CountryCode{BES}\n\tcase CallCode993:\n\t\treturn []CountryCode{TKM}\n\tcase CallCode81:\n\t\treturn []CountryCode{JPN}\n\tcase CallCode82:\n\t\treturn []CountryCode{KOR}\n\tcase CallCode84:\n\t\treturn []CountryCode{VNM}\n\tcase CallCode850:\n\t\treturn []CountryCode{PRK}\n\tcase CallCode852:\n\t\treturn []CountryCode{HKG}\n\tcase CallCode853:\n\t\treturn []CountryCode{MAC}\n\tcase CallCode855:\n\t\treturn []CountryCode{KHM}\n\tcase CallCode856:\n\t\treturn []CountryCode{LAO}\n\tcase CallCode86:\n\t\treturn []CountryCode{CHN}\n\tcase CallCode800:\n\t\treturn []CountryCode{NonCountryInternationalFreephone}\n\tcase CallCode870:\n\t\treturn []CountryCode{NonCountryInmarsat}\n\tcase CallCode875, CallCode876, CallCode877:\n\t\treturn []CountryCode{NonCountryMaritimeMobileService}\n\tcase CallCode878:\n\t\treturn []CountryCode{NonCountryUniversalPersonalTelecommunicationsServices}\n\tcase CallCode879:\n\t\treturn []CountryCode{NonCountryNationalNonCommercialPurposes}\n\tcase CallCode880:\n\t\treturn []CountryCode{BGD}\n\tcase CallCode881:\n\t\treturn []CountryCode{NonCountryGlobalMobileSatelliteSystem}\n\tcase CallCode882, CallCode883:\n\t\treturn []CountryCode{NonCountryInternationalNetworks}\n\tcase CallCode886:\n\t\treturn []CountryCode{TWN}\n\tcase CallCode90:\n\t\treturn []CountryCode{TUR}\n\tcase CallCode91:\n\t\treturn []CountryCode{IND}\n\tcase CallCode92:\n\t\treturn []CountryCode{PAK}\n\tcase CallCode93:\n\t\treturn []CountryCode{AFG}\n\tcase CallCode94:\n\t\treturn []CountryCode{LKA}\n\tcase CallCode95:\n\t\treturn []CountryCode{MMR}\n\tcase CallCode888:\n\t\treturn []CountryCode{NonCountryDisasterRelief}\n\tcase CallCode960:\n\t\treturn []CountryCode{MDV}\n\tcase CallCode961:\n\t\treturn []CountryCode{LBN}\n\tcase CallCode962:\n\t\treturn []CountryCode{JOR}\n\tcase CallCode963:\n\t\treturn []CountryCode{SYR}\n\tcase CallCode964:\n\t\treturn []CountryCode{IRQ}\n\tcase CallCode965:\n\t\treturn []CountryCode{KWT}\n\tcase CallCode966:\n\t\treturn []CountryCode{SAU}\n\tcase CallCode967:\n\t\treturn []CountryCode{YEM}\n\tcase CallCode968:\n\t\treturn []CountryCode{OMN}\n\tcase CallCode970:\n\t\treturn []CountryCode{PSE}\n\tcase CallCode971:\n\t\treturn []CountryCode{ARE}\n\tcase CallCode972:\n\t\treturn []CountryCode{PSE}\n\tcase CallCode973:\n\t\treturn []CountryCode{BHR}\n\tcase CallCode974:\n\t\treturn []CountryCode{QAT}\n\tcase CallCode975:\n\t\treturn []CountryCode{BTN}\n\tcase CallCode976:\n\t\treturn []CountryCode{MNG}\n\tcase CallCode977:\n\t\treturn []CountryCode{NPL}\n\tcase CallCode98:\n\t\treturn []CountryCode{IRN}\n\tcase CallCode979:\n\t\treturn []CountryCode{NonCountryInternationalPremiumRateService}\n\tcase CallCode991:\n\t\treturn []CountryCode{NonCountryInternationalTelecommunicationsCorrespondenceService}\n\tcase CallCode992:\n\t\treturn []CountryCode{TJK}\n\tcase CallCode994:\n\t\treturn []CountryCode{AZE}\n\tcase CallCode995:\n\t\treturn []CountryCode{GEO}\n\tcase CallCode996:\n\t\treturn []CountryCode{KGZ}\n\tcase CallCode998:\n\t\treturn []CountryCode{UZB}\n\tcase CallCode5999:\n\t\treturn []CountryCode{CUW}\n\tcase CallCode35818:\n\t\treturn []CountryCode{ALA}\n\tcase CallCode441481:\n\t\treturn []CountryCode{GGY}\n\tcase CallCode441534:\n\t\treturn []CountryCode{JEY}\n\tcase CallCode441624:\n\t\treturn []CountryCode{IMN}\n\tcase CallCode3906698:\n\t\treturn []CountryCode{VAT}\n\tcase CallCode6189162:\n\t\treturn []CountryCode{CCK}\n\tcase CallCode6189164:\n\t\treturn []CountryCode{CXR}\n\t}\n\treturn []CountryCode{Unknown}\n}",
"func (c CallCode) Countries() []CountryCode { //nolint:gocyclo\n\tswitch c {\n\tcase CallCode1:\n\t\treturn []CountryCode{ATF, CAN, UMI, USA}\n\tcase CallCode1808:\n\t\treturn []CountryCode{USA}\n\tcase CallCode1242:\n\t\treturn []CountryCode{BHS}\n\tcase CallCode1246:\n\t\treturn []CountryCode{BRB}\n\tcase CallCode1264:\n\t\treturn []CountryCode{AIA}\n\tcase CallCode1268:\n\t\treturn []CountryCode{ATG}\n\tcase CallCode1284:\n\t\treturn []CountryCode{VGB}\n\tcase CallCode1340:\n\t\treturn []CountryCode{VIR}\n\tcase CallCode1345:\n\t\treturn []CountryCode{CYM}\n\tcase CallCode1441:\n\t\treturn []CountryCode{BMU}\n\tcase CallCode1473:\n\t\treturn []CountryCode{GRD}\n\tcase CallCode1649:\n\t\treturn []CountryCode{TCA}\n\tcase CallCode1664:\n\t\treturn []CountryCode{MSR}\n\tcase CallCode1670:\n\t\treturn []CountryCode{MNP}\n\tcase CallCode1671:\n\t\treturn []CountryCode{GUM}\n\tcase CallCode1684:\n\t\treturn []CountryCode{ASM}\n\tcase CallCode1758:\n\t\treturn []CountryCode{LCA}\n\tcase CallCode1767:\n\t\treturn []CountryCode{DMA}\n\tcase CallCode1784:\n\t\treturn []CountryCode{VCT}\n\tcase CallCode1787, CallCode1939:\n\t\treturn []CountryCode{PRI}\n\tcase CallCode1809, CallCode1829, CallCode1849:\n\t\treturn []CountryCode{DOM}\n\tcase CallCode1868:\n\t\treturn []CountryCode{TTO}\n\tcase CallCode1869:\n\t\treturn []CountryCode{KNA}\n\tcase CallCode1876, CallCode1658:\n\t\treturn []CountryCode{JAM}\n\tcase CallCode20:\n\t\treturn []CountryCode{EGY}\n\tcase CallCode211:\n\t\treturn []CountryCode{SSD}\n\tcase CallCode212:\n\t\treturn []CountryCode{ESH, MAR}\n\tcase CallCode213:\n\t\treturn []CountryCode{DZA}\n\tcase CallCode216:\n\t\treturn []CountryCode{TUN}\n\tcase CallCode218:\n\t\treturn []CountryCode{LBY}\n\tcase CallCode220:\n\t\treturn []CountryCode{GMB}\n\tcase CallCode221:\n\t\treturn []CountryCode{SEN}\n\tcase CallCode222:\n\t\treturn []CountryCode{MRT}\n\tcase CallCode223:\n\t\treturn []CountryCode{MLI}\n\tcase CallCode224:\n\t\treturn []CountryCode{GIN}\n\tcase CallCode225:\n\t\treturn []CountryCode{CIV}\n\tcase CallCode226:\n\t\treturn []CountryCode{BFA}\n\tcase CallCode227:\n\t\treturn []CountryCode{NER}\n\tcase CallCode228:\n\t\treturn []CountryCode{TGO}\n\tcase CallCode229:\n\t\treturn []CountryCode{BEN}\n\tcase CallCode230:\n\t\treturn []CountryCode{MUS}\n\tcase CallCode231:\n\t\treturn []CountryCode{LBR}\n\tcase CallCode232:\n\t\treturn []CountryCode{SLE}\n\tcase CallCode233:\n\t\treturn []CountryCode{GHA}\n\tcase CallCode234:\n\t\treturn []CountryCode{NGA}\n\tcase CallCode235:\n\t\treturn []CountryCode{TCD}\n\tcase CallCode236:\n\t\treturn []CountryCode{CAF}\n\tcase CallCode237:\n\t\treturn []CountryCode{CMR}\n\tcase CallCode238:\n\t\treturn []CountryCode{CPV}\n\tcase CallCode239:\n\t\treturn []CountryCode{STP}\n\tcase CallCode240:\n\t\treturn []CountryCode{GNQ}\n\tcase CallCode241:\n\t\treturn []CountryCode{GAB}\n\tcase CallCode242:\n\t\treturn []CountryCode{COG}\n\tcase CallCode243:\n\t\treturn []CountryCode{COD}\n\tcase CallCode244:\n\t\treturn []CountryCode{AGO}\n\tcase CallCode245:\n\t\treturn []CountryCode{GNB}\n\tcase CallCode246:\n\t\treturn []CountryCode{IOT}\n\tcase CallCode248:\n\t\treturn []CountryCode{SYC}\n\tcase CallCode249:\n\t\treturn []CountryCode{SDN}\n\tcase CallCode250:\n\t\treturn []CountryCode{RWA}\n\tcase CallCode251:\n\t\treturn []CountryCode{ETH}\n\tcase CallCode252:\n\t\treturn []CountryCode{SOM}\n\tcase CallCode253:\n\t\treturn []CountryCode{DJI}\n\tcase CallCode254:\n\t\treturn []CountryCode{KEN}\n\tcase CallCode255:\n\t\treturn []CountryCode{TZA}\n\tcase CallCode256:\n\t\treturn []CountryCode{UGA}\n\tcase CallCode257:\n\t\treturn []CountryCode{BDI}\n\tcase CallCode258:\n\t\treturn []CountryCode{MOZ}\n\tcase CallCode260:\n\t\treturn []CountryCode{ZMB}\n\tcase CallCode261:\n\t\treturn []CountryCode{MDG}\n\tcase CallCode262:\n\t\treturn []CountryCode{MYT, REU}\n\tcase CallCode262269, CallCode262639:\n\t\treturn []CountryCode{MYT}\n\tcase CallCode263:\n\t\treturn []CountryCode{ZWE}\n\tcase CallCode264:\n\t\treturn []CountryCode{NAM}\n\tcase CallCode265:\n\t\treturn []CountryCode{MWI}\n\tcase CallCode266:\n\t\treturn []CountryCode{LSO}\n\tcase CallCode267:\n\t\treturn []CountryCode{BWA}\n\tcase CallCode268:\n\t\treturn []CountryCode{SWZ}\n\tcase CallCode269:\n\t\treturn []CountryCode{COM}\n\tcase CallCode27:\n\t\treturn []CountryCode{ZAF}\n\tcase CallCode290:\n\t\treturn []CountryCode{SHN}\n\tcase CallCode291:\n\t\treturn []CountryCode{ERI}\n\tcase CallCode297, CallCode5998:\n\t\treturn []CountryCode{ABW}\n\tcase CallCode298:\n\t\treturn []CountryCode{FRO}\n\tcase CallCode299:\n\t\treturn []CountryCode{GRL}\n\tcase CallCode30:\n\t\treturn []CountryCode{GRC}\n\tcase CallCode31:\n\t\treturn []CountryCode{NLD}\n\tcase CallCode32:\n\t\treturn []CountryCode{BEL}\n\tcase CallCode33:\n\t\treturn []CountryCode{FRA}\n\tcase CallCode34:\n\t\treturn []CountryCode{ESP}\n\tcase CallCode350:\n\t\treturn []CountryCode{GIB}\n\tcase CallCode351:\n\t\treturn []CountryCode{PRT}\n\tcase CallCode352:\n\t\treturn []CountryCode{LUX}\n\tcase CallCode353:\n\t\treturn []CountryCode{IRL}\n\tcase CallCode354:\n\t\treturn []CountryCode{ISL}\n\tcase CallCode355:\n\t\treturn []CountryCode{ALB}\n\tcase CallCode356:\n\t\treturn []CountryCode{MLT}\n\tcase CallCode357:\n\t\treturn []CountryCode{CYP}\n\tcase CallCode358:\n\t\treturn []CountryCode{ALA, FIN}\n\tcase CallCode359:\n\t\treturn []CountryCode{BGR}\n\tcase CallCode36:\n\t\treturn []CountryCode{HUN}\n\tcase CallCode370:\n\t\treturn []CountryCode{LTU}\n\tcase CallCode371:\n\t\treturn []CountryCode{LVA}\n\tcase CallCode372:\n\t\treturn []CountryCode{EST}\n\tcase CallCode373:\n\t\treturn []CountryCode{MDA}\n\tcase CallCode374:\n\t\treturn []CountryCode{ARM}\n\tcase CallCode375:\n\t\treturn []CountryCode{BLR}\n\tcase CallCode376:\n\t\treturn []CountryCode{AND}\n\tcase CallCode377:\n\t\treturn []CountryCode{MCO}\n\tcase CallCode378:\n\t\treturn []CountryCode{SMR}\n\tcase CallCode38:\n\t\treturn []CountryCode{YUG}\n\tcase CallCode380:\n\t\treturn []CountryCode{UKR}\n\tcase CallCode381:\n\t\treturn []CountryCode{SRB}\n\tcase CallCode382:\n\t\treturn []CountryCode{MNE}\n\tcase CallCode383:\n\t\treturn []CountryCode{XKX}\n\tcase CallCode385:\n\t\treturn []CountryCode{HRV}\n\tcase CallCode386:\n\t\treturn []CountryCode{SVN}\n\tcase CallCode387:\n\t\treturn []CountryCode{BIH}\n\tcase CallCode389:\n\t\treturn []CountryCode{MKD}\n\tcase CallCode39:\n\t\treturn []CountryCode{ITA, VAT}\n\tcase CallCode40:\n\t\treturn []CountryCode{ROU}\n\tcase CallCode41:\n\t\treturn []CountryCode{CHE}\n\tcase CallCode420:\n\t\treturn []CountryCode{CZE}\n\tcase CallCode421:\n\t\treturn []CountryCode{SVK}\n\tcase CallCode423:\n\t\treturn []CountryCode{LIE}\n\tcase CallCode43:\n\t\treturn []CountryCode{AUT}\n\tcase CallCode44:\n\t\treturn []CountryCode{GBR, GGY, IMN, JEY, XSC, XWA}\n\tcase CallCode45:\n\t\treturn []CountryCode{DNK}\n\tcase CallCode46:\n\t\treturn []CountryCode{SWE}\n\tcase CallCode47:\n\t\treturn []CountryCode{BVT, NOR, SJM}\n\tcase CallCode48:\n\t\treturn []CountryCode{POL}\n\tcase CallCode49:\n\t\treturn []CountryCode{DEU}\n\tcase CallCode500:\n\t\treturn []CountryCode{FLK, SGS}\n\tcase CallCode501:\n\t\treturn []CountryCode{BLZ}\n\tcase CallCode502:\n\t\treturn []CountryCode{GTM}\n\tcase CallCode503:\n\t\treturn []CountryCode{SLV}\n\tcase CallCode504:\n\t\treturn []CountryCode{HND}\n\tcase CallCode505:\n\t\treturn []CountryCode{NIC}\n\tcase CallCode506:\n\t\treturn []CountryCode{CRI}\n\tcase CallCode507:\n\t\treturn []CountryCode{PAN}\n\tcase CallCode508:\n\t\treturn []CountryCode{SPM}\n\tcase CallCode509:\n\t\treturn []CountryCode{HTI}\n\tcase CallCode51:\n\t\treturn []CountryCode{PER}\n\tcase CallCode52:\n\t\treturn []CountryCode{MEX}\n\tcase CallCode53:\n\t\treturn []CountryCode{CUB}\n\tcase CallCode54:\n\t\treturn []CountryCode{ARG}\n\tcase CallCode55:\n\t\treturn []CountryCode{BRA}\n\tcase CallCode56:\n\t\treturn []CountryCode{CHL}\n\tcase CallCode57:\n\t\treturn []CountryCode{COL}\n\tcase CallCode58:\n\t\treturn []CountryCode{VEN}\n\tcase CallCode590:\n\t\treturn []CountryCode{BLM, GLP, MAF}\n\tcase CallCode591:\n\t\treturn []CountryCode{BOL}\n\tcase CallCode592:\n\t\treturn []CountryCode{GUY}\n\tcase CallCode593:\n\t\treturn []CountryCode{ECU}\n\tcase CallCode594:\n\t\treturn []CountryCode{GUF}\n\tcase CallCode595:\n\t\treturn []CountryCode{PRY}\n\tcase CallCode596:\n\t\treturn []CountryCode{MTQ}\n\tcase CallCode597:\n\t\treturn []CountryCode{SUR}\n\tcase CallCode598:\n\t\treturn []CountryCode{URY}\n\tcase CallCode599:\n\t\treturn []CountryCode{ANT, BES, CUW}\n\tcase CallCode60:\n\t\treturn []CountryCode{MYS}\n\tcase CallCode61:\n\t\treturn []CountryCode{AUS, CXR, CCK}\n\tcase CallCode62:\n\t\treturn []CountryCode{IDN}\n\tcase CallCode63:\n\t\treturn []CountryCode{PHL}\n\tcase CallCode64:\n\t\treturn []CountryCode{NZL, PCN}\n\tcase CallCode65:\n\t\treturn []CountryCode{SGP}\n\tcase CallCode66:\n\t\treturn []CountryCode{THA}\n\tcase CallCode670:\n\t\treturn []CountryCode{TLS}\n\tcase CallCode672:\n\t\treturn []CountryCode{ATA, CCK, NFK}\n\tcase CallCode673:\n\t\treturn []CountryCode{BRN}\n\tcase CallCode674:\n\t\treturn []CountryCode{NRU}\n\tcase CallCode675:\n\t\treturn []CountryCode{PNG}\n\tcase CallCode676:\n\t\treturn []CountryCode{TON}\n\tcase CallCode677:\n\t\treturn []CountryCode{SLB}\n\tcase CallCode678:\n\t\treturn []CountryCode{VUT}\n\tcase CallCode679:\n\t\treturn []CountryCode{FJI}\n\tcase CallCode680:\n\t\treturn []CountryCode{PLW}\n\tcase CallCode681:\n\t\treturn []CountryCode{WLF}\n\tcase CallCode682:\n\t\treturn []CountryCode{COK}\n\tcase CallCode683:\n\t\treturn []CountryCode{NIU}\n\tcase CallCode684:\n\t\treturn []CountryCode{WSM}\n\tcase CallCode686:\n\t\treturn []CountryCode{KIR}\n\tcase CallCode687:\n\t\treturn []CountryCode{NCL}\n\tcase CallCode688:\n\t\treturn []CountryCode{TUV}\n\tcase CallCode689:\n\t\treturn []CountryCode{PYF}\n\tcase CallCode690:\n\t\treturn []CountryCode{TKL}\n\tcase CallCode691:\n\t\treturn []CountryCode{FSM}\n\tcase CallCode692:\n\t\treturn []CountryCode{MHL}\n\tcase CallCode7:\n\t\treturn []CountryCode{KAZ, RUS}\n\tcase CallCode1721, CallCode5995:\n\t\treturn []CountryCode{SXM}\n\tcase CallCode4779:\n\t\treturn []CountryCode{SJM}\n\tcase CallCode5993, CallCode5994, CallCode5997:\n\t\treturn []CountryCode{BES}\n\tcase CallCode7370:\n\t\treturn []CountryCode{TKM}\n\tcase CallCode81:\n\t\treturn []CountryCode{JPN}\n\tcase CallCode82:\n\t\treturn []CountryCode{KOR}\n\tcase CallCode84:\n\t\treturn []CountryCode{VNM}\n\tcase CallCode850:\n\t\treturn []CountryCode{PRK}\n\tcase CallCode852:\n\t\treturn []CountryCode{HKG}\n\tcase CallCode853:\n\t\treturn []CountryCode{MAC}\n\tcase CallCode855:\n\t\treturn []CountryCode{KHM}\n\tcase CallCode856:\n\t\treturn []CountryCode{LAO}\n\tcase CallCode86:\n\t\treturn []CountryCode{CHN}\n\tcase CallCode800:\n\t\treturn []CountryCode{NonCountryInternationalFreephone}\n\tcase CallCode870:\n\t\treturn []CountryCode{NonCountryInmarsat}\n\tcase CallCode875, CallCode876, CallCode877:\n\t\treturn []CountryCode{NonCountryMaritimeMobileService}\n\tcase CallCode878:\n\t\treturn []CountryCode{NonCountryUniversalPersonalTelecommunicationsServices}\n\tcase CallCode879:\n\t\treturn []CountryCode{NonCountryNationalNonCommercialPurposes}\n\tcase CallCode880:\n\t\treturn []CountryCode{BGD}\n\tcase CallCode881:\n\t\treturn []CountryCode{NonCountryGlobalMobileSatelliteSystem}\n\tcase CallCode882, CallCode883:\n\t\treturn []CountryCode{NonCountryInternationalNetworks}\n\tcase CallCode886:\n\t\treturn []CountryCode{TWN}\n\tcase CallCode90:\n\t\treturn []CountryCode{TUR}\n\tcase CallCode91:\n\t\treturn []CountryCode{IND}\n\tcase CallCode92:\n\t\treturn []CountryCode{PAK}\n\tcase CallCode93:\n\t\treturn []CountryCode{AFG}\n\tcase CallCode94:\n\t\treturn []CountryCode{LKA}\n\tcase CallCode95:\n\t\treturn []CountryCode{MMR}\n\tcase CallCode888:\n\t\treturn []CountryCode{NonCountryDisasterRelief}\n\tcase CallCode960:\n\t\treturn []CountryCode{MDV}\n\tcase CallCode961:\n\t\treturn []CountryCode{LBN}\n\tcase CallCode962:\n\t\treturn []CountryCode{JOR}\n\tcase CallCode963:\n\t\treturn []CountryCode{SYR}\n\tcase CallCode964:\n\t\treturn []CountryCode{IRQ}\n\tcase CallCode965:\n\t\treturn []CountryCode{KWT}\n\tcase CallCode966:\n\t\treturn []CountryCode{SAU}\n\tcase CallCode967:\n\t\treturn []CountryCode{YEM}\n\tcase CallCode968:\n\t\treturn []CountryCode{OMN}\n\tcase CallCode971:\n\t\treturn []CountryCode{ARE}\n\tcase CallCode972:\n\t\treturn []CountryCode{ISR, PSE}\n\tcase CallCode973:\n\t\treturn []CountryCode{BHR}\n\tcase CallCode974:\n\t\treturn []CountryCode{QAT}\n\tcase CallCode975:\n\t\treturn []CountryCode{BTN}\n\tcase CallCode976:\n\t\treturn []CountryCode{MNG}\n\tcase CallCode977:\n\t\treturn []CountryCode{NPL}\n\tcase CallCode98:\n\t\treturn []CountryCode{IRN}\n\tcase CallCode979:\n\t\treturn []CountryCode{NonCountryInternationalPremiumRateService}\n\tcase CallCode991:\n\t\treturn []CountryCode{NonCountryInternationalTelecommunicationsCorrespondenceService}\n\tcase CallCode992:\n\t\treturn []CountryCode{TJK}\n\tcase CallCode994:\n\t\treturn []CountryCode{AZE}\n\tcase CallCode995:\n\t\treturn []CountryCode{GEO}\n\tcase CallCode996:\n\t\treturn []CountryCode{KGZ}\n\tcase CallCode998:\n\t\treturn []CountryCode{UZB}\n\tcase CallCode5999:\n\t\treturn []CountryCode{CUW}\n\tcase CallCode35818:\n\t\treturn []CountryCode{ALA}\n\tcase CallCode441481:\n\t\treturn []CountryCode{GGY}\n\tcase CallCode441534:\n\t\treturn []CountryCode{JEY}\n\tcase CallCode441624:\n\t\treturn []CountryCode{IMN}\n\tcase CallCode3906698:\n\t\treturn []CountryCode{VAT}\n\tcase CallCode6189162:\n\t\treturn []CountryCode{CCK}\n\tcase CallCode6189164:\n\t\treturn []CountryCode{CXR}\n\t}\n\treturn []CountryCode{Unknown}\n}",
"func (m *GoIP) Country(ip string) (*ResponseCountry, error) {\n\tinfo, err := m.info(ip)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &info.Country, err\n}",
"func (api *LaborStatsAPI) QueryCountryGoods() ([]CountryGood, error) {\n\ta := CountryGoodsAPI{\n\t\tDebug: api.Debug,\n\t\tSecretKey: api.SecretKey,\n\t}\n\n\terr := a.sendRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := a.unmarshalData()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n\n}",
"func (o GetRegionResultOutput) Country() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRegionResult) string { return v.Country }).(pulumi.StringOutput)\n}",
"func (dstv Dstv) Countries() (*CountriesResponse, error) {\n\tdstv.AddQueryData(paymenex.PActId, \"TFCNT\")\n\tbody, err := dstv.MakeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponse := new(CountriesResponse)\n\tok := dstv.ParseAndVerifyResponse(body, response)\n\tif !ok {\n\t\treturn response, errors.New(errVerifyMsg)\n\t}\n\t// fmt.Printf(\"countries response: %#v\", response) // DEBUG\n\treturn response, nil\n}",
"func (instance *XCountryRepo) GetByISO3Code(iso3Code string) (model.XCountry, error) {\n\treturn instance.getByField(\"iso3Code\", iso3Code)\n}",
"func getCountryCode(name string) (string, error) {\n\tfor _, country := range consts.Countries {\n\t\tif strings.EqualFold(strings.ToUpper(country.Name), strings.ToUpper(name)) {\n\t\t\treturn country.Alpha3Code, nil\n\t\t}\n\t}\n\treturn \"OTH\", fmt.Errorf(\"cannot find country code for country %s\", name)\n}",
"func Country(countryStyle int64) string {\n\tcountry := \"\"\n\tswitch countryStyle {\n\n\tdefault:\n\n\tcase FullCountry:\n\t\tcountry = randomFrom(jsonData.Countries)\n\t\tbreak\n\n\tcase TwoCharCountry:\n\t\tcountry = randomFrom(jsonData.CountriesTwoChars)\n\t\tbreak\n\n\tcase ThreeCharCountry:\n\t\tcountry = randomFrom(jsonData.CountriesThreeChars)\n\t\tbreak\n\t}\n\treturn country\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Name returns a view or table name in SQL database ("actor_info").
|
func (v *actorInfoViewType) Name() string {
return v.s.SQLName
}
|
[
"func (v *pgStatDatabaseViewType) Name() string {\n\treturn v.s.SQLName\n}",
"func (v *pgUserViewType) Name() string {\n\treturn v.s.SQLName\n}",
"func (v *View) ViewName() string { return v.viewName }",
"func (v *paymentP202006ViewType) Name() string {\n\treturn v.s.SQLName\n}",
"func (v *nicerButSlowerFilmListViewType) Name() string {\n\treturn v.s.SQLName\n}",
"func (p *Oracle) ViewNamesQuery() string {\n\treturn `SELECT view_name\n\tFROM\n\t\tall_views\n\tWHERE\n\t\towner IN (SELECT sys_context('userenv', 'current_schema') from dual)`\n}",
"func (v *View) Name() string {\n\treturn v.name\n}",
"func (v *pgStatMonitor09ViewType) Name() string {\n\treturn v.s.SQLName\n}",
"func (v *salesByStoreViewType) Name() string {\n\treturn v.s.SQLName\n}",
"func (v *pgStatStatementsViewType) Name() string {\n\treturn v.s.SQLName\n}",
"func (s *Schema) View(name string) *CreateViewEntity {\n\tif view, ok := s.named[name].(*CreateViewEntity); ok {\n\t\treturn view\n\t}\n\treturn nil\n}",
"func (t *Template) ViewFuncName() string {\n\treturn strings.Join([]string{t.Name(), \"View\"}, \"\")\n}",
"func (t Table) Name() string {\n\treturn t.name\n}",
"func (v *recordingTable) Name() string {\n\treturn v.s.SQLName\n}",
"func (s *ActorInfo) View() reform.View {\n\treturn ActorInfoView\n}",
"func (n *Adaptor) Name() string { return n.name }",
"func (Annotation) Name() string {\n\treturn \"EntSQL\"\n}",
"func TableName(name string) string {\n\tif IsTest {\n\t\treturn fmt.Sprintf(\"%v_test\", name)\n\t}\n\treturn fmt.Sprintf(\"%v_development\", name)\n}",
"func (dt *ColumnDiffTable) Name() string {\n\treturn doltdb.ColumnDiffTableName\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
View returns View object for that struct.
|
func (s *ActorInfo) View() reform.View {
return ActorInfoView
}
|
[
"func (ma *Model) View() *View {\n\treturn ma.view\n}",
"func (db *DB) View(ddoc, view string, result interface{}, opts Options) error {\n\tddoc = strings.Replace(ddoc, \"_design/\", \"\", 1)\n\tpath, err := optpath(opts, viewJsonKeys, db.name, \"_design\", ddoc, \"_view\", view)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := db.request(db.ctx, \"GET\", path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn readBody(resp, &result)\n}",
"func (n *node) View() *View {\n\treturn &n.view\n}",
"func (v VirtualElement) View() interface{} {\n\treturn v.Object\n}",
"func (l *leaf) View() *View {\n\treturn &l.view\n}",
"func (r *root) View() *View {\n\treturn r.rootNode.View()\n}",
"func (s *Schema) View(name string) *CreateViewEntity {\n\tif view, ok := s.named[name].(*CreateViewEntity); ok {\n\t\treturn view\n\t}\n\treturn nil\n}",
"func (f *fileBase) View() source.View {\n\treturn f.view\n}",
"func (r *Resolver) View() generated.ViewResolver {\n\treturn &ViewResolver{r}\n}",
"func (r *Resolver) View() generated.ViewResolver { return &viewResolver{r} }",
"func (b *Buffer) View() *View {\n\treturn b.ViewLimit(b.size)\n}",
"func View(w http.ResponseWriter, r *http.Request, data interface{}, viewName string) {\n\n\ttemplateName := viewName\n\tt, err := Jet.GetTemplate(templateName)\n\tif err != nil {\n\t\tlog.Println(\"Failed to get template \")\n\t}\n\tdataMap := make(map[string]interface{})\n\tif data != nil {\n\t\tdataMap = data.(map[string]interface{})\n\t}\n\tvars := make(jet.VarMap)\n\tdataMap[\"config\"] = Config\n\tdataMap[\"token\"] = csrf.Token(r)\n\tdataMap[\"currentPATH\"] = r.URL.Path\n\tif err = t.Execute(w, vars, dataMap); err != nil {\n\t\tlog.Println(\"Failed to execute view tepmlate \")\n\t}\n}",
"func View(db *bolt.DB, f func(*Root) error) error {\n\treturn db.View(func(tx *bolt.Tx) error {\n\t\treturn f(&Root{tx})\n\t})\n}",
"func (t TxRecord) View() TxView {\n\th, err := t.Transaction.CalculateHash()\n\tif err != nil {\n\t\tlogrus.Panic(err)\n\t}\n\n\tview := TxView{\n\t\tTxMeta: t.TxMeta,\n\t\tType: t.Transaction.Type(),\n\t\tHash: h,\n\t}\n\n\tview.Fee, err = t.Transaction.Fee()\n\tif err != nil {\n\t\tlogrus.WithError(err).Warn(\"failed to decode fee\")\n\t}\n\n\t// switch tx := t.Transaction.(type) {\n\t// case *transactions.BidTransaction:\n\t// \tview.Timelock = tx.ExpirationHeight\n\t// case *transactions.StakeTransaction:\n\t// \tview.Timelock = tx.ExpirationHeight\n\t// case *transactions.Transaction:\n\t// \tview.Data = tx.Data\n\t// }\n\n\treturn view\n}",
"func (r *Resource) View(name string) (*View, error) {\n\treturn r._views.Lookup(name)\n}",
"func (ctrl *Controller) View() *Result {\n\treturn ctrl.ViewFile(ctrl.Controller + \"/\" + ctrl.Action)\n}",
"func New(req *http.Request) *View {\n\tv := &View{}\n\tv.Vars = make(map[string]interface{})\n\tv.Vars[\"AuthLevel\"] = \"anon\"\n\n\tv.BaseURI = viewInfo.BaseURI\n\tv.Extension = viewInfo.Extension\n\tv.Folder = viewInfo.Folder\n\tv.Name = viewInfo.Name\n\n\t// Make sure BaseURI is available in the templates\n\tv.Vars[\"BaseURI\"] = v.BaseURI\n\n\t// This is required for the view to access the request\n\tv.request = req\n\n\t// Get session\n\tsess := session.Instance(v.request)\n\n\t// Set the AuthLevel to auth if the user is logged in\n\tif sess.Values[\"id\"] != nil {\n\t\tv.Vars[\"AuthLevel\"] = \"auth\"\n\t}\n\n\treturn v\n}",
"func (db *CouchDB) View(design, view string, args ViewArgs) (results *ViewResults, err error) {\n\tresults = new(ViewResults)\n\treturn results, db.viewHelper(fmt.Sprintf(\"_design/%s/_view/%s\", design, view), args, results)\n}",
"func NewView(b []byte) *View { return &View{b} }"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetMarginRates gets margin rates
|
func (h *HUOBI) GetMarginRates(ctx context.Context, symbol currency.Pair) (MarginRatesData, error) {
var resp MarginRatesData
vals := url.Values{}
if !symbol.IsEmpty() {
symbolValue, err := h.FormatSymbol(symbol, asset.Spot)
if err != nil {
return resp, err
}
vals.Set("symbol", symbolValue)
}
return resp, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiMarginRates, vals, nil, &resp, false)
}
|
[
"func (f *FTX) GetMarginBorrowRates(ctx context.Context) ([]MarginFundingData, error) {\n\tr := struct {\n\t\tData []MarginFundingData `json:\"result\"`\n\t}{}\n\treturn r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, marginBorrowRates, nil, &r)\n}",
"func (ftx *FTX) GetspotMarginBorrowRates() (*[]SpotMarginBorrowRate, error) {\n\ttype res struct {\n\t\tSuccess bool\n\t\tResult []SpotMarginBorrowRate\n\t}\n\n\tvar resObj res\n\turl := host + spotMarginBorrowRatesAPI\n\theader := ftx.genAuthHeader(\"GET\", spotMarginBorrowRatesAPI, \"\")\n\tftx.restClient.Get(url, header, nil, &resObj)\n\n\tif !resObj.Success {\n\t\tfmt.Println(resObj)\n\t\terrorMsg := fmt.Sprintf(\"Get spot margin borrow rates error\")\n\t\tutil.Error(ftx.tag, errorMsg)\n\t\treturn nil, errors.New(errorMsg)\n\t}\n\n\treturn &resObj.Result, nil\n}",
"func (f *FTX) GetMarginLendingRates(ctx context.Context) ([]MarginFundingData, error) {\n\tr := struct {\n\t\tData []MarginFundingData `json:\"result\"`\n\t}{}\n\treturn r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, marginLendingRates, nil, &r)\n}",
"func (c *TradeData) GetMarginLendingRatio(req requests.GetRatio) (response responses.GetRatio, err error) {\n\tp := \"/api/v5/rubik/stat/margin/loan-ratio\"\n\tm := okex.S2M(req)\n\tres, err := c.client.Do(http.MethodGet, p, false, m)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\td := json.NewDecoder(res.Body)\n\terr = d.Decode(&response)\n\treturn\n}",
"func (s *Sources) Margins(roundID int) (map[string]int, error) {\n\n\tvar err error\n\tvar margins map[string]int\n\tmargins = make(map[string]int)\n\n\t// In each source find fixtures with matching *winners* (for now, assuming only one team can win one fixture per round),\n\t// and calculate weighted margins where applicable\n\tfor idx := range s.Sources {\n\t\tfor f := range s.Sources[idx].Round.Fixtures {\n\t\t\tif _, ok := margins[s.Sources[idx].Round.Fixtures[f].winner]; ok {\n\t\t\t\tif s.Sources[idx].Weight != 0 {\n\t\t\t\t\t// Add new weighted margin to predictions existing aggregate weighted margin\n\t\t\t\t\tmargins[s.Sources[idx].Round.Fixtures[f].winner] = margins[s.Sources[idx].Round.Fixtures[f].winner] + int(float64(s.Sources[idx].Round.Fixtures[f].margin)*s.Sources[idx].Weight)\n\t\t\t\t\thelpers.Logger.Debugf(\"Margin updated from source: %s, winner: %s, weigthed margin now: %d\",\n\t\t\t\t\t\ts.Sources[idx].Name,\n\t\t\t\t\t\ts.Sources[idx].Round.Fixtures[f].winner,\n\t\t\t\t\t\tmargins[s.Sources[idx].Round.Fixtures[f].winner],\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\t// Matched margin prediction without a weighted source, implication being there are 2 sources with the same\n\t\t\t\t\t// tournament that should have margins aggregated using weighted averages but dont have weights\n\t\t\t\t\thelpers.Logger.Errorf(\"Margin matched from new source without a weight, source: %s\", s.Sources[idx].Name)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\terr = fmt.Errorf(\"Margin matched from new source without a weight, source: %s\", s.Sources[idx].Name)\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = fmt.Errorf(\"%w, Margin matched from new source without a weight, source: %s\", err, s.Sources[idx].Name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Add new margin for sources with weight specified (calculating weighted average)\n\t\t\t\tif s.Sources[idx].Weight != 0 {\n\t\t\t\t\tmargins[s.Sources[idx].Round.Fixtures[f].winner] = int(float64(s.Sources[idx].Round.Fixtures[f].margin) * s.Sources[idx].Weight)\n\t\t\t\t\thelpers.Logger.Debugf(\"Margin with weighted prediction added from source: %s, winner: %s, weighted margin: %d\",\n\t\t\t\t\t\ts.Sources[idx].Name,\n\t\t\t\t\t\ts.Sources[idx].Round.Fixtures[f].winner,\n\t\t\t\t\t\tmargins[s.Sources[idx].Round.Fixtures[f].winner],\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\t// Add new margin for sources without weight specified (source margin is our margin)\n\t\t\t\t\tmargins[s.Sources[idx].Round.Fixtures[f].winner] = s.Sources[idx].Round.Fixtures[f].margin\n\t\t\t\t\thelpers.Logger.Debugf(\"Margin without weighted prediction added from source: %s, winner: %s, margin: %d\",\n\t\t\t\t\t\ts.Sources[idx].Name,\n\t\t\t\t\t\ts.Sources[idx].Round.Fixtures[f].winner,\n\t\t\t\t\t\tmargins[s.Sources[idx].Round.Fixtures[f].winner],\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn margins, err\n\n}",
"func (ci converterInfo) Rates() *map[string]map[string]float64 {\n\treturn ci.rates\n}",
"func (f *FTX) MarginDailyBorrowedAmounts(ctx context.Context) ([]MarginDailyBorrowStats, error) {\n\tr := struct {\n\t\tData []MarginDailyBorrowStats `json:\"result\"`\n\t}{}\n\treturn r.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, dailyBorrowedAmounts, &r)\n}",
"func (p Provider) getRatesFromResponse(body []byte) (map[string]float64, map[string]float64, time.Time, error) {\n\tvar (\n\t\terr error\n\t\tapiJson model.SuccessApiResponse\n\t\tdirectRates = make(map[string]float64)\n\t\treverseRates = make(map[string]float64)\n\t\tnormalizedDirectRates = make(map[string]float64)\n\t\tnormalizedReverseRates = make(map[string]float64)\n\t\tproviderGeneratedTime time.Time\n\t)\n\t// Rates\n\tif err = json.Unmarshal(body, &apiJson); err != nil {\n\t\treturn directRates, reverseRates, time.Time{}, err\n\t}\n\n\tfor cur, directRate := range apiJson.Rates {\n\t\tnormalizedDirectRates[cur] = math.Round(directRate*1000000) / 1000000\n\t}\n\n\t// Provider generated time\n\tproviderGeneratedTime = time.Unix(apiJson.Timestamp, 0)\n\treturn normalizedDirectRates, normalizedReverseRates, providerGeneratedTime, nil\n}",
"func (as *apiService) MarginAccount(ar AccountRequest) (*MarginAccount, error) {\n\tparams := make(map[string]string)\n\tparams[\"timestamp\"] = strconv.FormatInt(unixMillis(ar.Timestamp), 10)\n\tif ar.RecvWindow != 0 {\n\t\tparams[\"recvWindow\"] = strconv.FormatInt(recvWindow(ar.RecvWindow), 10)\n\t}\n\n\tres, err := as.request(\"GET\", \"/sapi/v1/margin/account\", params, true, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttextRes, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to read response from account.get\")\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, as.handleError(textRes)\n\t}\n\n\trawAccount := struct {\n\t\tBorrowEnabled \t\tbool \t\t`json:\"borrowEnabled\"`\n\t\tMarginLevel \t\t\t\tstring `json:\"marginLevel\"`\n\t\tTotalAssetOfBtc \t\tstring `json:\"totalAssetOfBtc\"`\n\t\tTotalLiabilityOfBtc string `json:\"totalLiabilityOfBtc\"`\n\t\tTotalNetAssetOfBtc string `json:\"totalNetAssetOfBtc\"`\n\t\tTradeEnabled \tbool \t`json:\"tradeEnabled\"`\n\t\tTransferEnabled bool \t`json:\"transferEnabled\"`\n\t\tUserAssets []struct {\n\t\t\tAsset \t\tstring `json:\"asset\"`\n\t\t\tBorrowed \tstring `json:\"borrowed\"`\n\t\t\tFree \t\tstring `json:\"free\"`\n\t\t\tInterest \tstring `json:\"interest\"`\n\t\t\tLocked \t\tstring `json:\"locked\"`\n\t\t\tNetAsset \tstring `json:\"netAsset\"`\n\t\t}\n\t}{}\n\tif err := json.Unmarshal(textRes, &rawAccount); err != nil {\n\t\treturn nil, errors.Wrap(err, \"rawAccount unmarshal failed\")\n\t}\n\tml, err := floatFromString(rawAccount.MarginLevel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttab, err := floatFromString(rawAccount.TotalAssetOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlb, err := floatFromString(rawAccount.TotalLiabilityOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttnab, err := floatFromString(rawAccount.TotalNetAssetOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tacc := &MarginAccount{\n\t\tBorrowEnabled: \t\t\trawAccount.BorrowEnabled,\n\t\tMarginLevel: \t\t\t\tml,\n\t\tTotalAssetOfBtc: \t\ttab,\n\t\tTotalLiabilityOfBtc: \ttlb,\n\t\tTotalNetAssetOfBtc: tnab,\n\t\tTradeEnabled: \t\trawAccount.TradeEnabled,\n\t\tTransferEnabled: rawAccount.TransferEnabled,\n\t}\n\tfor _, b := range rawAccount.UserAssets {\n\t\tf, err := floatFromString(b.Free)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tl, err := floatFromString(b.Locked)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbo, err := floatFromString(b.Borrowed)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti, err := floatFromString(b.Interest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tn, err := floatFromString(b.NetAsset)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tacc.UserAssets = append(acc.UserAssets, &UserAsset{\n\t\t\tAsset: \tb.Asset,\n\t\t\tBorrowed: bo,\n\t\t\tFree: \tf,\n\t\t\tInterest: i,\n\t\t\tLocked: \tl,\n\t\t\tNetAsset: n,\n\t\t})\n\t}\n\n\treturn acc, nil\n}",
"func (p *swiftPlugin) ScrapeRates(project core.KeystoneProject, prevSerializedState string) (result map[string]*big.Int, serializedState string, err error) {\n\treturn nil, \"\", nil\n}",
"func (f *FTX) GetMarginBorrowHistory(ctx context.Context, startTime, endTime time.Time) ([]MarginTransactionHistoryData, error) {\n\tr := struct {\n\t\tData []MarginTransactionHistoryData `json:\"result\"`\n\t}{}\n\n\tparams := url.Values{}\n\tif !startTime.IsZero() && !endTime.IsZero() {\n\t\tif startTime.After(endTime) {\n\t\t\treturn nil, errStartTimeCannotBeAfterEndTime\n\t\t}\n\t\tparams.Set(\"start_time\", strconv.FormatInt(startTime.Unix(), 10))\n\t\tparams.Set(\"end_time\", strconv.FormatInt(endTime.Unix(), 10))\n\t}\n\tendpoint := common.EncodeURLValues(marginBorrowHistory, params)\n\treturn r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, endpoint, nil, &r)\n}",
"func (blk *Block) GetMargins() (float64, float64, float64, float64) {\n\treturn blk.margins.left, blk.margins.right, blk.margins.top, blk.margins.bottom\n}",
"func (f *Request) GetRates() (ClientResponse, error) {\n\turl := f.GetURL()\n\tresponse, err := f.makeRequest(url)\n\n\tif err != nil {\n\t\treturn ClientResponse{}, err\n\t}\n\n\treturn response, nil\n}",
"func GetDrawMargin(pDraw, beta float64, nPlayers uint) float64 {\n\treturn stats.InverseCDF((pDraw+1)/2) * math.Sqrt(float64(nPlayers)) * beta\n}",
"func (f *FTX) GetMarginMarketInfo(ctx context.Context, market string) ([]MarginMarketInfo, error) {\n\tr := struct {\n\t\tData []MarginMarketInfo `json:\"result\"`\n\t}{}\n\treturn r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, fmt.Sprintf(marginMarketInfo, market), nil, &r)\n}",
"func GetCurrencyRatesTrendController(data Data) (res currency.ArrCurrRatesData, err error) {\n\t// validate parameter, if valid then true\n\tresult, err := isValidParam(data)\n\tif !result {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\t// init pkg\n\tpkg := currency.CurrPkg{}\n\n\t// check if currency exist\n\tresult, err = pkg.IsCurrencyExist(data.From, data.To)\n\tif !result {\n\t\terr = ErrCurrencyNotExist\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\t// if currency does exist, then continue to get rates detail data\n\tres, err = pkg.GetCurrencyTrend(data.From, data.To)\n\tif err != nil {\n\t\tlog.Error(err, \"error when retrieve currency rates data trend\")\n\t\treturn\n\t}\n\n\treturn\n}",
"func (s *Service) Rates(amount, currency string) (*Rates, error) {\n\tif currency == \"\" {\n\t\treturn nil, ErrEmptyCurr\n\t}\n\tam, err := decimal.NewFromString(amount)\n\tif err != nil {\n\t\treturn nil, ErrParseAmount\n\t}\n\n\t// Get from cache or fixer.io.\n\tkey := cacheKey(currency)\n\tfr, err := s.db.Get(key)\n\tif err != nil {\n\t\tfr, err = s.fetchRates(currency, key)\n\t}\n\n\treturn fr.convToRates(am, currency), nil\n}",
"func marginOf(entries []entry) float64 {\n\treturn mbrOf(entries...).Margin()\n}",
"func (rc *RateConverter) Rates() Conversions {\n\tif rc.constantRates != nil {\n\t\t// Converter is not active, returning the constant rates\n\t\treturn rc.constantRates\n\t}\n\tif rates := rc.rates.Load(); rates != nil {\n\t\treturn rates.(*Rates)\n\t}\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetSpotKline returns kline data KlinesRequestParams contains symbol currency.Pair, period and size
|
func (h *HUOBI) GetSpotKline(ctx context.Context, arg KlinesRequestParams) ([]KlineItem, error) {
vals := url.Values{}
symbolValue, err := h.FormatSymbol(arg.Symbol, asset.Spot)
if err != nil {
return nil, err
}
vals.Set("symbol", symbolValue)
vals.Set("period", arg.Period)
if arg.Size != 0 {
vals.Set("size", strconv.Itoa(arg.Size))
}
type response struct {
Response
Data []KlineItem `json:"data"`
}
var result response
err = h.SendHTTPRequest(ctx, exchange.RestSpot, common.EncodeURLValues(huobiMarketHistoryKline, vals), &result)
if result.ErrorMessage != "" {
return nil, errors.New(result.ErrorMessage)
}
return result.Data, err
}
|
[
"func (h *HUOBIHADAX) GetSpotKline(arg KlinesRequestParams) ([]KlineItem, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", arg.Symbol)\n\tvals.Set(\"period\", string(arg.Period))\n\n\tif arg.Size != 0 {\n\t\tvals.Set(\"size\", strconv.Itoa(arg.Size))\n\t}\n\n\ttype response struct {\n\t\tResponse\n\t\tData []KlineItem `json:\"data\"`\n\t}\n\n\tvar result response\n\turlPath := fmt.Sprintf(\"%s/%s\", h.APIUrl, huobihadaxMarketHistoryKline)\n\n\terr := h.SendHTTPRequest(common.EncodeURLValues(urlPath, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Data, err\n}",
"func (this *Spot) GetKlineRecords(pair Pair, period, size, since int) ([]Kline, []byte, error) {\n\tif period != KLINE_PERIOD_1MIN {\n\t\treturn nil, nil, errors.New(\"Can not support the period in bitstamp. \")\n\t}\n\n\turi := fmt.Sprintf(\n\t\t\"/api/v2/transactions/%s/?time=day\",\n\t\tstrings.ToLower(pair.ToSymbol(\"\", false)),\n\t)\n\tresponse := make([]struct {\n\t\tDate int64 `json:\"date,string\"`\n\t\tPrice float64 `json:\"price,string\"`\n\t\tAmount float64 `json:\"amount,string\"`\n\t}, 0)\n\n\tresp, err := this.DoRequest(\"GET\", uri, \"\", &response) //&response)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif len(response) == 0 {\n\t\treturn nil, nil, errors.New(\"Have not receive enough data. \")\n\t}\n\n\tklineRecord := make(map[int64]Kline, 0)\n\tklineTimestamp := make([]int64, 0)\n\tfor _, order := range response {\n\t\tminTimestamp := order.Date / 60 * 60 * 1000\n\t\tkline, exist := klineRecord[minTimestamp]\n\t\tif !exist {\n\t\t\tt := time.Unix(minTimestamp/1000, 0)\n\t\t\tkline = Kline{\n\t\t\t\tTimestamp: minTimestamp,\n\t\t\t\tDate: t.In(this.config.Location).Format(GO_BIRTHDAY),\n\t\t\t\tPair: pair,\n\t\t\t\tExchange: BITSTAMP,\n\t\t\t\tOpen: order.Price,\n\t\t\t\tHigh: order.Price,\n\t\t\t\tLow: order.Price,\n\t\t\t\tClose: order.Price,\n\t\t\t\tVol: order.Amount,\n\t\t\t}\n\t\t\tklineRecord[minTimestamp] = kline\n\t\t\tklineTimestamp = append(klineTimestamp, minTimestamp)\n\t\t\tcontinue\n\t\t}\n\n\t\tkline.Open = order.Price\n\t\tkline.Vol += order.Amount\n\t\tif order.Price > kline.High {\n\t\t\tkline.High = order.Price\n\t\t}\n\t\tif order.Price < kline.Low {\n\t\t\tkline.Low = order.Price\n\t\t}\n\t\tklineRecord[minTimestamp] = kline\n\t}\n\n\tklines := make([]Kline, 0)\n\tfor i := 0; i < len(klineTimestamp)-1; i++ {\n\t\tklines = append(klines, klineRecord[klineTimestamp[i]])\n\t}\n\n\treturn klines, resp, nil\n}",
"func (b *Binance) GetSpotKline(arg KlinesRequestParams) ([]CandleStick, error) {\n\tvar resp interface{}\n\tvar kline []CandleStick\n\n\tparams := url.Values{}\n\tparams.Set(\"symbol\", arg.Symbol)\n\tparams.Set(\"interval\", string(arg.Interval))\n\tif arg.Limit != 0 {\n\t\tparams.Set(\"limit\", strconv.Itoa(arg.Limit))\n\t}\n\tif arg.StartTime != 0 {\n\t\tparams.Set(\"startTime\", strconv.FormatInt(arg.StartTime, 10))\n\t}\n\tif arg.EndTime != 0 {\n\t\tparams.Set(\"endTime\", strconv.FormatInt(arg.EndTime, 10))\n\t}\n\n\tpath := fmt.Sprintf(\"%s%s?%s\", b.APIUrl, candleStick, params.Encode())\n\n\tif err := b.SendHTTPRequest(path, &resp); err != nil {\n\t\treturn kline, err\n\t}\n\n\tfor _, responseData := range resp.([]interface{}) {\n\t\tvar candle CandleStick\n\t\tfor i, individualData := range responseData.([]interface{}) {\n\t\t\tswitch i {\n\t\t\tcase 0:\n\t\t\t\tcandle.OpenTime = individualData.(float64)\n\t\t\tcase 1:\n\t\t\t\tcandle.Open, _ = strconv.ParseFloat(individualData.(string), 64)\n\t\t\tcase 2:\n\t\t\t\tcandle.High, _ = strconv.ParseFloat(individualData.(string), 64)\n\t\t\tcase 3:\n\t\t\t\tcandle.Low, _ = strconv.ParseFloat(individualData.(string), 64)\n\t\t\tcase 4:\n\t\t\t\tcandle.Close, _ = strconv.ParseFloat(individualData.(string), 64)\n\t\t\tcase 5:\n\t\t\t\tcandle.Volume, _ = strconv.ParseFloat(individualData.(string), 64)\n\t\t\tcase 6:\n\t\t\t\tcandle.CloseTime = individualData.(float64)\n\t\t\tcase 7:\n\t\t\t\tcandle.QuoteAssetVolume, _ = strconv.ParseFloat(individualData.(string), 64)\n\t\t\tcase 8:\n\t\t\t\tcandle.TradeCount = individualData.(float64)\n\t\t\tcase 9:\n\t\t\t\tcandle.TakerBuyAssetVolume, _ = strconv.ParseFloat(individualData.(string), 64)\n\t\t\tcase 10:\n\t\t\t\tcandle.TakerBuyQuoteAssetVolume, _ = strconv.ParseFloat(individualData.(string), 64)\n\t\t\t}\n\t\t}\n\t\tkline = append(kline, candle)\n\t}\n\treturn kline, nil\n}",
"func (h *HUOBI) GetSwapKlineData(ctx context.Context, code currency.Pair, period string, size int64, startTime, endTime time.Time) (SwapKlineData, error) {\n\tvar resp SwapKlineData\n\tcodeValue, err := h.FormatSymbol(code, asset.CoinMarginedFutures)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tif !common.StringDataCompareInsensitive(validPeriods, period) {\n\t\treturn resp, fmt.Errorf(\"invalid period value received\")\n\t}\n\tparams := url.Values{}\n\tparams.Set(\"contract_code\", codeValue)\n\tparams.Set(\"period\", period)\n\tif size > 0 {\n\t\tparams.Set(\"size\", strconv.FormatInt(size, 10))\n\t}\n\tif !startTime.IsZero() && !endTime.IsZero() {\n\t\tif startTime.After(endTime) {\n\t\t\treturn resp, errors.New(\"startTime cannot be after endTime\")\n\t\t}\n\t\tparams.Set(\"from\", strconv.FormatInt(startTime.Unix(), 10))\n\t\tparams.Set(\"to\", strconv.FormatInt(endTime.Unix(), 10))\n\t}\n\tpath := common.EncodeURLValues(huobiKLineData, params)\n\treturn resp, h.SendHTTPRequest(ctx, exchange.RestFutures, path, &resp)\n}",
"func (c *Coinbene) GetSwapKlines(symbol string, start, end time.Time, resolution string) (resp CandleResponse, err error) {\n\tv := url.Values{}\n\tv.Set(\"symbol\", symbol)\n\tif !start.IsZero() {\n\t\tv.Add(\"startTime\", strconv.FormatInt(start.Unix(), 10))\n\t}\n\tif !end.IsZero() {\n\t\tv.Add(\"endTime\", strconv.FormatInt(end.Unix(), 10))\n\t}\n\tv.Set(\"resolution\", resolution)\n\n\tpath := common.EncodeURLValues(coinbeneAPIVersion+coinbeneGetKlines, v)\n\tif err = c.SendHTTPRequest(exchange.RestSwap, path, contractKline, &resp); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}",
"func (by *Bybit) GetUSDCMarkPriceKlines(ctx context.Context, symbol currency.Pair, period string, startTime time.Time, limit int64) ([]USDCKlineBase, error) {\n\tresp := struct {\n\t\tData []USDCKlineBase `json:\"result\"`\n\t\tUSDCError\n\t}{}\n\n\tparams := url.Values{}\n\tif symbol.IsEmpty() {\n\t\treturn nil, errSymbolMissing\n\t}\n\tsymbolValue, err := by.FormatSymbol(symbol, asset.USDCMarginedFutures)\n\tif err != nil {\n\t\treturn resp.Data, err\n\t}\n\tparams.Set(\"symbol\", symbolValue)\n\n\tif !common.StringDataCompare(validFuturesIntervals, period) {\n\t\treturn resp.Data, errInvalidPeriod\n\t}\n\tparams.Set(\"period\", period)\n\n\tif startTime.IsZero() {\n\t\treturn nil, errInvalidStartTime\n\t}\n\tparams.Set(\"startTime\", strconv.FormatInt(startTime.Unix(), 10))\n\n\tif limit > 0 && limit <= 200 {\n\t\tparams.Set(\"limit\", strconv.FormatInt(limit, 10))\n\t}\n\treturn resp.Data, by.SendHTTPRequest(ctx, exchange.RestUSDCMargined, common.EncodeURLValues(usdcfuturesGetMarkPriceKlines, params), usdcPublicRate, &resp)\n}",
"func (b *ByBit) GetKLine(symbol string, interval string, from int64, limit int) (result []OHLC, err error) {\n\tvar ret GetKlineResult\n\tparams := map[string]interface{}{}\n\tparams[\"symbol\"] = symbol\n\tparams[\"interval\"] = interval\n\tparams[\"from\"] = from\n\tif limit > 0 {\n\t\tparams[\"limit\"] = limit\n\t}\n\t_, err = b.PublicRequest(http.MethodGet, \"v2/public/kline/list\", params, &ret)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = ret.Result\n\treturn\n}",
"func (nb *Namebase) GetKlines(pair CurrencyPair, interval KlineInterval, limit int) ([]Kline, error) {\n\tparams := make(map[string]interface{})\n\tparams[\"symbol\"] = pair.String()\n\tparams[\"interval\"] = interval\n\n\tif limit != 0 {\n\t\tparams[\"limit\"] = limit\n\t}\n\n\tdata, err := nb.do(http.MethodGet, \"/api/v0/ticker/klines\", params, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar klines []Kline\n\n\tif err := json.Unmarshal(data, &klines); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn klines, nil\n}",
"func (c *Client) Klines(symbol string, interval binance.KlineInterval) (*Klines, error) {\n\tvar b strings.Builder\n\tb.WriteString(baseWS)\n\tb.WriteString(strings.ToLower(symbol))\n\tb.WriteString(\"@kline_\")\n\tb.WriteString(string(interval))\n\tconn, err := fastws.Dial(b.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Klines{wsClient{conn: conn}}, nil\n}",
"func NewAppPricePointsGetInstanceRequest(server string, id string, params *AppPricePointsGetInstanceParams) (*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/appPricePoints/%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\tqueryValues := queryURL.Query()\n\n\tif params.FieldsAppPricePoints != nil {\n\n\t\tif queryFrag, err := runtime.StyleParamWithLocation(\"form\", false, \"fields[appPricePoints]\", runtime.ParamLocationQuery, *params.FieldsAppPricePoints); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif params.Include != nil {\n\n\t\tif queryFrag, err := runtime.StyleParamWithLocation(\"form\", false, \"include\", runtime.ParamLocationQuery, *params.Include); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif params.FieldsTerritories != nil {\n\n\t\tif queryFrag, err := runtime.StyleParamWithLocation(\"form\", false, \"fields[territories]\", runtime.ParamLocationQuery, *params.FieldsTerritories); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tqueryURL.RawQuery = queryValues.Encode()\n\n\treq, err := http.NewRequest(\"GET\", queryURL.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}",
"func getKlines(s model.Stock) ([]*model.Kline, *model.KlineW, *model.KlineM) {\n\tmxw, mxm := getMaxDates(s.Code)\n\tvar klines []*model.Kline\n\t_, err := dbmap.Select(&klines, \"select * from kline_d where code = ? order by date\", s.Code)\n\tcheckErr(err, \"Failed to query kline_d for \"+s.Code)\n\treturn klines, mxw, mxm\n}",
"func (by *Bybit) GetUSDCIndexPriceKlines(ctx context.Context, symbol currency.Pair, period string, startTime time.Time, limit int64) ([]USDCKlineBase, error) {\n\tresp := struct {\n\t\tData []USDCKlineBase `json:\"result\"`\n\t\tUSDCError\n\t}{}\n\n\tparams := url.Values{}\n\tif symbol.IsEmpty() {\n\t\treturn nil, errSymbolMissing\n\t}\n\tsymbolValue, err := by.FormatSymbol(symbol, asset.USDCMarginedFutures)\n\tif err != nil {\n\t\treturn resp.Data, err\n\t}\n\tparams.Set(\"symbol\", symbolValue)\n\n\tif !common.StringDataCompare(validFuturesIntervals, period) {\n\t\treturn resp.Data, errInvalidPeriod\n\t}\n\tparams.Set(\"period\", period)\n\n\tif startTime.IsZero() {\n\t\treturn nil, errInvalidStartTime\n\t}\n\tparams.Set(\"startTime\", strconv.FormatInt(startTime.Unix(), 10))\n\n\tif limit > 0 && limit <= 200 {\n\t\tparams.Set(\"limit\", strconv.FormatInt(limit, 10))\n\t}\n\treturn resp.Data, by.SendHTTPRequest(ctx, exchange.RestUSDCMargined, common.EncodeURLValues(usdcfuturesGetIndexPriceKlines, params), usdcPublicRate, &resp)\n}",
"func (by *Bybit) GetUSDCPremiumIndexKlines(ctx context.Context, symbol currency.Pair, period string, startTime time.Time, limit int64) ([]USDCKlineBase, error) {\n\tresp := struct {\n\t\tData []USDCKlineBase `json:\"result\"`\n\t\tUSDCError\n\t}{}\n\n\tparams := url.Values{}\n\tif symbol.IsEmpty() {\n\t\treturn nil, errSymbolMissing\n\t}\n\tsymbolValue, err := by.FormatSymbol(symbol, asset.USDCMarginedFutures)\n\tif err != nil {\n\t\treturn resp.Data, err\n\t}\n\tparams.Set(\"symbol\", symbolValue)\n\n\tif !common.StringDataCompare(validFuturesIntervals, period) {\n\t\treturn resp.Data, errInvalidPeriod\n\t}\n\tparams.Set(\"period\", period)\n\n\tif startTime.IsZero() {\n\t\treturn nil, errInvalidStartTime\n\t}\n\tparams.Set(\"startTime\", strconv.FormatInt(startTime.Unix(), 10))\n\n\tif limit > 0 && limit <= 200 {\n\t\tparams.Set(\"limit\", strconv.FormatInt(limit, 10))\n\t}\n\treturn resp.Data, by.SendHTTPRequest(ctx, exchange.RestUSDCMargined, common.EncodeURLValues(usdcfuturesGetPremiumIndexKlines, params), usdcPublicRate, &resp)\n}",
"func (f *XqKlineFetcher) fetchKline(stk *model.Stock, fr FetchRequest, incr bool) (\n\ttdmap map[FetchRequest]*model.TradeData, suc, retry bool) {\n\n\ttdmap = make(map[FetchRequest]*model.TradeData)\n\n\tperiod := \"\"\n\txdrType := \"normal\"\n\trtype := fr.Reinstate\n\tcycle := fr.Cycle\n\tswitch cycle {\n\tcase model.DAY:\n\t\tperiod = \"day\"\n\tcase model.WEEK:\n\t\tperiod = \"week\"\n\tcase model.MONTH:\n\t\tperiod = \"month\"\n\tdefault:\n\t\tlog.Panicf(\"unsupported cycle: %+v\", fr.Cycle)\n\t}\n\tswitch rtype {\n\tcase model.Forward:\n\t\txdrType = \"before\"\n\tcase model.Backward:\n\t\txdrType = \"after\"\n\t}\n\n\tcode := stk.Code\n\tsymbol := \"\"\n\tif fr.LocalSource == model.Index {\n\t\tsymbol = strings.ToUpper(code)\n\t} else {\n\t\tmkt := strings.ToUpper(stk.Market.String)\n\t\tsymbol = mkt + code\n\t}\n\n\ttabs := resolveTableNames(fr)\n\tldate := \"\"\n\tif incr {\n\t\tldy := getLatestTradeDataBasic(code, fr.LocalSource, cycle, rtype, 5+1) //plus one offset for pre-close, varate calculation\n\t\tif ldy != nil {\n\t\t\tldate = ldy.Date\n\t\t} else {\n\t\t\tlog.Printf(\"%s latest %+v data not found, will be fully refreshed\", code, tabs)\n\t\t}\n\t} else {\n\t\tlog.Printf(\"%s %+v data will be fully refreshed\", code, tabs)\n\t}\n\n\tstartDateStr := \"1990-12-19\"\n\tstartDate, e := time.Parse(global.DateFormat, startDateStr)\n\tif e != nil {\n\t\tlog.Panicf(\"failed to parse date %s: %+v\", startDateStr, e)\n\t}\n\tcount := -142\n\tmultiGet := false\n\tif ldate == \"\" {\n\t\tcount = int(math.Round(\n\t\t\t-.75*(time.Since(startDate).Hours()/24.) - float64(rand.Intn(1000)),\n\t\t))\n\t\tmultiGet = true\n\t} else {\n\t\tltime, e := time.Parse(global.DateFormat, ldate)\n\t\tif e != nil {\n\t\t\tlog.Warnf(\"%s %+v failed to parse date value '%s': %+v\", stk.Code, tabs, ldate, e)\n\t\t\treturn tdmap, false, false\n\t\t}\n\t\tcount = -1 * (int(time.Since(ltime).Hours()/24) + 2)\n\t}\n\n\txqk, e := tryXQKline(code, symbol, period, xdrType, count, multiGet)\n\tif e != nil {\n\t\treturn tdmap, false, true\n\t}\n\n\tif extd, e := f.fixData(stk, xqk, fr); e != nil {\n\t\treturn tdmap, false, false\n\t} else if len(extd) > 0 {\n\t\tfor k, v := range extd {\n\t\t\ttdmap[k] = v\n\t\t}\n\t} else {\n\t\t//construct empty signal entry\n\t\texfr := f.extraRequest(fr)\n\t\ttdmap[exfr] = nil\n\t}\n\n\t//construct trade data\n\ttdmap[fr] = &model.TradeData{\n\t\tCode: code,\n\t\tSource: fr.LocalSource,\n\t\tCycle: cycle,\n\t\tReinstatement: rtype,\n\t\tBase: xqk.GetData(false),\n\t}\n\n\treturn tdmap, true, false\n}",
"func (s *SinaKlineFetcher) fetchKline(stk *model.Stock, fr FetchRequest, incr bool) (\n\ttdmap map[FetchRequest]*model.TradeData, suc, retry bool) {\n\t//if the fetch request has been completed previously, return immediately\n\tif s.hasCompleted(stk.Code, fr) {\n\t\treturn tdmap, true, false\n\t}\n\n\tswitch fr.Reinstate {\n\tcase model.Backward, model.Forward:\n\t\treturn s.reinstate(stk, fr)\n\t}\n\n\tvar data interface{}\n\tvar e error\n\tif data, e = s.chrome(stk, fr); e != nil {\n\t\tlog.Error(e)\n\t\tif repeat.IsTemporary(e) {\n\t\t\tretry = true\n\t\t}\n\t\treturn\n\t}\n\n\t// extract kline data to tdmap, and all types of Cycle will be populated automatically\n\tif tdmap, e = s.parse(stk.Code, fr, data); e != nil {\n\t\tlog.Error(e)\n\t\tif repeat.IsTemporary(e) {\n\t\t\tretry = true\n\t\t}\n\t\treturn\n\t}\n\n\tsuc = true\n\n\treturn\n}",
"func (h *HUOBI) GetPremiumIndexKlineData(ctx context.Context, code currency.Pair, period string, size int64) (PremiumIndexKlineData, error) {\n\tvar resp PremiumIndexKlineData\n\tcodeValue, err := h.FormatSymbol(code, asset.CoinMarginedFutures)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tif !common.StringDataCompareInsensitive(validPeriods, period) {\n\t\treturn resp, fmt.Errorf(\"invalid period value received\")\n\t}\n\tif size <= 0 || size > 1200 {\n\t\treturn resp, fmt.Errorf(\"invalid size provided, only values between 1-1200 are supported\")\n\t}\n\tparams := url.Values{}\n\tparams.Set(\"contract_code\", codeValue)\n\tparams.Set(\"size\", strconv.FormatInt(size, 10))\n\tparams.Set(\"period\", period)\n\tpath := common.EncodeURLValues(huobiPremiumIndexKlineData, params)\n\treturn resp, h.SendHTTPRequest(ctx, exchange.RestFutures, path, &resp)\n}",
"func (c *Connecter) GetCurrenciesSparkline(csReq CurrenciesSparklineRequest) ([]CurrenciesSparklineResponse, error) {\n\treq, err := c.newRequest(currenciesSparklineURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Formulate query params.\n\tq := req.URL.Query()\n\tq.Add(\"key\", c.apiKey)\n\tif len(csReq.Ids) > 0 {\n\t\tq.Add(\"ids\", strings.Join(csReq.Ids[:], \",\"))\n\t}\n\tif csReq.Start.IsZero() {\n\t\treturn nil, errors.New(\"start is required\")\n\t}\n\tq.Add(\"start\", csReq.Start.Format(time.RFC3339))\n\tif !csReq.End.IsZero() {\n\t\tq.Add(\"end\", csReq.End.Format(time.RFC3339))\n\t}\n\tif csReq.Convert != \"\" {\n\t\tq.Add(\"convert\", csReq.Convert)\n\t}\n\treq.URL.RawQuery = q.Encode()\n\n\t// Do the requset to server.\n\tresp, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Creates formatted response from the server's response.\n\tvar csResp []CurrenciesSparklineResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&csResp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn csResp, nil\n}",
"func (by *Bybit) GetUSDCKlines(ctx context.Context, symbol currency.Pair, period string, startTime time.Time, limit int64) ([]USDCKline, error) {\n\tresp := struct {\n\t\tData []USDCKline `json:\"result\"`\n\t\tUSDCError\n\t}{}\n\n\tparams := url.Values{}\n\tif symbol.IsEmpty() {\n\t\treturn nil, errSymbolMissing\n\t}\n\tsymbolValue, err := by.FormatSymbol(symbol, asset.USDCMarginedFutures)\n\tif err != nil {\n\t\treturn resp.Data, err\n\t}\n\tparams.Set(\"symbol\", symbolValue)\n\n\tif !common.StringDataCompare(validFuturesIntervals, period) {\n\t\treturn resp.Data, errInvalidPeriod\n\t}\n\tparams.Set(\"period\", period)\n\n\tif startTime.IsZero() {\n\t\treturn nil, errInvalidStartTime\n\t}\n\tparams.Set(\"startTime\", strconv.FormatInt(startTime.Unix(), 10))\n\n\tif limit > 0 && limit <= 200 {\n\t\tparams.Set(\"limit\", strconv.FormatInt(limit, 10))\n\t}\n\treturn resp.Data, by.SendHTTPRequest(ctx, exchange.RestUSDCMargined, common.EncodeURLValues(usdcfuturesGetKlines, params), usdcPublicRate, &resp)\n}",
"func SetPriceParams(p interface{}) []string {\n\tparams := p.(map[string]interface{})\n\ts := params[\"symbols\"].([]interface{})\n\tvar symbols []string\n\tfor _, symbol := range s {\n\t\tsymbols = append(symbols, symbol.(string))\n\t}\n\treturn symbols\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get24HrMarketSummary returns 24hr market summary for a given market symbol
|
func (h *HUOBI) Get24HrMarketSummary(ctx context.Context, symbol currency.Pair) (MarketSummary24Hr, error) {
var result MarketSummary24Hr
params := url.Values{}
symbolValue, err := h.FormatSymbol(symbol, asset.Spot)
if err != nil {
return result, err
}
params.Set("symbol", symbolValue)
return result, h.SendHTTPRequest(ctx, exchange.RestSpot, huobi24HrMarketSummary+params.Encode(), &result)
}
|
[
"func (h *HUOBI) GetMarketDetail(ctx context.Context, symbol currency.Pair) (Detail, error) {\n\tvals := url.Values{}\n\tsymbolValue, err := h.FormatSymbol(symbol, asset.Spot)\n\tif err != nil {\n\t\treturn Detail{}, err\n\t}\n\tvals.Set(\"symbol\", symbolValue)\n\n\ttype response struct {\n\t\tResponse\n\t\tTick Detail `json:\"tick\"`\n\t}\n\n\tvar result response\n\n\terr = h.SendHTTPRequest(ctx, exchange.RestSpot, common.EncodeURLValues(huobiMarketDetail, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn result.Tick, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Tick, err\n}",
"func (c *Client) Get24hrStats(symbol string) (Stats24hr, error) {\n\tbody, err := c.GetAPI(c.Address + BNB24hrStats + \"?symbol=\" + symbol)\n\tif err != nil {\n\t\tapiLog.Warn(\"WARN: error submitting get request:\", err)\n\t\treturn Stats24hr{}, err\n\t}\n\n\tstats := Stats24hr{}\n\terr = json.Unmarshal(body, &stats)\n\tif err != nil {\n\t\tapiLog.Warn(\"WARN: error unmarshaling stats:\", err)\n\t\treturn Stats24hr{}, err\n\t}\n\n\treturn stats, nil\n}",
"func (h *HUOBIHADAX) GetMarketDetail(symbol string) (Detail, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\n\ttype response struct {\n\t\tResponse\n\t\tTick Detail `json:\"tick\"`\n\t}\n\n\tvar result response\n\turlPath := fmt.Sprintf(\"%s/%s\", h.APIUrl, huobihadaxMarketDetail)\n\n\terr := h.SendHTTPRequest(common.EncodeURLValues(urlPath, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn result.Tick, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Tick, err\n}",
"func (m *MarketClient) Get24hTickerPriceChange(symbol string) (interface{}, error) {\n\tvar err error\n\tparams := \"\"\n\tif symbol != \"\" {\n\t\tparams = fmt.Sprintf(\"symbol=%s\", symbol)\n\t}\n\treq, err := m.Builder.Build(http.MethodGet, \"/api/v3/ticker/24hr\", params)\n\tif err != nil {\n\t\tlogger.Error(\"Failed to build url: %s\", err.Error())\n\t}\n\tres, err := binance.HttpRequest(req)\n\tvar parser map[string]interface{}\n\terr = json.Unmarshal(res, &parser)\n\tif _, ok := parser[\"code\"]; ok {\n\t\tresult := model.APIErrorResponse{}\n\t\terr = json.Unmarshal(res, &result)\n\t\treturn result, err\n\t}\n\tif params == \"\" {\n\t\tvar result []TickerPriceChangeStatisticsResponse\n\t\terr = json.Unmarshal(res, &result)\n\t\treturn result, err\n\t}\n\tresult := TickerPriceChangeStatisticsResponse{}\n\terr = json.Unmarshal(res, &result)\n\treturn result, err\n}",
"func (h *HUOBI) GetSwapMarketOverview(ctx context.Context, code currency.Pair) (MarketOverviewData, error) {\n\tvar resp MarketOverviewData\n\tcodeValue, err := h.FormatSymbol(code, asset.CoinMarginedFutures)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tparams := url.Values{}\n\tparams.Set(\"contract_code\", codeValue)\n\tpath := common.EncodeURLValues(huobiMarketDataOverview, params)\n\treturn resp, h.SendHTTPRequest(ctx, exchange.RestFutures, path, &resp)\n}",
"func (c *Client) GetDaySummary(coin types.Coin, day, month, year int) (*types.DaySummary, error) {\n\tresp, err := c.Service.GetDaySummary(coin, day, month, year)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting day summary for coin %s: %s\", coin, err)\n\t}\n\tdefer resp.Body.Close()\n\n\t// Example response:\n\t// {\n\t// \t\"date\": \"2020-02-01\",\n\t// \t\"opening\": 40009.09990999,\n\t// \t\"closing\": 39755,\n\t// \t\"lowest\": 39700,\n\t// \t\"highest\": 40139.98,\n\t// \t\"volume\": 1557826.34691214,\n\t// \t\"quantity\": 39.09361166,\n\t// \t\"amount\": 1668,\n\t// \t\"avg_price\": 39848.61671161\n\t// }\n\tvar response *types.DaySummary\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding day summary for coin %s: %s\", coin, err)\n\t}\n\n\tresponse.Date, err = time.Parse(\"2006-01-02\", response.DateStr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding date %s: %s\", response.DateStr, err)\n\t}\n\n\treturn response, nil\n}",
"func (h *HUOBI) GetMarketDetailMerged(ctx context.Context, symbol currency.Pair) (DetailMerged, error) {\n\tvals := url.Values{}\n\tsymbolValue, err := h.FormatSymbol(symbol, asset.Spot)\n\tif err != nil {\n\t\treturn DetailMerged{}, err\n\t}\n\tvals.Set(\"symbol\", symbolValue)\n\n\ttype response struct {\n\t\tResponse\n\t\tTick DetailMerged `json:\"tick\"`\n\t}\n\n\tvar result response\n\n\terr = h.SendHTTPRequest(ctx, exchange.RestSpot, common.EncodeURLValues(huobiMarketDetailMerged, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn result.Tick, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Tick, err\n}",
"func (c *Client) GetTradeMarketData(tickerSymbol string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET TRADE MARKET DATA ==========\")\n\turl := buildURL(path[\"nodes\"], \"trade-market-watch\")\n\n\tts := []string{tickerSymbol}\n\n\treturn c.do(\"GET\", url, \"\", ts)\n}",
"func (h *HUOBIHADAX) GetMarketDetailMerged(symbol string) (DetailMerged, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\n\ttype response struct {\n\t\tResponse\n\t\tTick DetailMerged `json:\"tick\"`\n\t}\n\n\tvar result response\n\turlPath := fmt.Sprintf(\"%s/%s\", h.APIUrl, huobihadaxMarketDetailMerged)\n\n\terr := h.SendHTTPRequest(common.EncodeURLValues(urlPath, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn result.Tick, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Tick, err\n}",
"func (_m *ExtendedTimeStock) FindTimeSeriesByTicker(w http.ResponseWriter, r *http.Request) {\n\t_m.Called(w, r)\n}",
"func (c *Client) GetTicker(symbol string) (Ticker, error) {\n var ticker Ticker\n requestURL := fmt.Sprintf(\"/v1/pubticker/%s\", symbol)\n\n _, err := c.Request(\"GET\", requestURL, nil, &ticker)\n return ticker, err\n}",
"func RenderGlobalMarketDash(color string) error {\n\tprimaryColor := getColor(color)\n\n\tmarketData, err := cmc.GetMarketData()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpar0 := ui.NewPar(fmt.Sprintf(\"$%s\", humanize.Commaf(marketData.TotalMarketCapUsd)))\n\tpar0.Height = 3\n\tpar0.Width = 20\n\tpar0.Y = 1\n\tpar0.TextFgColor = ui.ColorWhite\n\tpar0.BorderLabel = \"Total Market Cap (USD)\"\n\tpar0.BorderLabelFg = primaryColor\n\tpar0.BorderFg = primaryColor\n\n\tpar1 := ui.NewPar(fmt.Sprintf(\"$%s\", humanize.Commaf(marketData.Total24hVolumeUsd)))\n\tpar1.Height = 3\n\tpar1.Width = 20\n\tpar1.Y = 1\n\tpar1.TextFgColor = ui.ColorWhite\n\tpar1.BorderLabel = \"Total Volume (24H)\"\n\tpar1.BorderLabelFg = primaryColor\n\tpar1.BorderFg = primaryColor\n\n\tpar2 := ui.NewPar(fmt.Sprintf(\"%.2f%%\", marketData.BitcoinPercentageOfMarketCap))\n\tpar2.Height = 3\n\tpar2.Width = 20\n\tpar2.Y = 1\n\tpar2.TextFgColor = ui.ColorWhite\n\tpar2.BorderLabel = \"% Bitcoin Dominance\"\n\tpar2.BorderLabelFg = primaryColor\n\tpar2.BorderFg = primaryColor\n\n\tpar3 := ui.NewPar(fmt.Sprintf(\"%s\", humanize.Comma(int64(marketData.ActiveCurrencies))))\n\tpar3.Height = 3\n\tpar3.Width = 20\n\tpar3.Y = 1\n\tpar3.TextFgColor = ui.ColorWhite\n\tpar3.BorderLabel = \"Active Currencies\"\n\tpar3.BorderLabelFg = primaryColor\n\tpar3.BorderFg = primaryColor\n\n\tpar4 := ui.NewPar(fmt.Sprintf(\"%s\", humanize.Comma(int64(marketData.ActiveAssets))))\n\tpar4.Height = 3\n\tpar4.Width = 20\n\tpar4.Y = 1\n\tpar4.TextFgColor = ui.ColorWhite\n\tpar4.BorderLabel = \"Active Assets\"\n\tpar4.BorderLabelFg = primaryColor\n\tpar4.BorderFg = primaryColor\n\n\tpar5 := ui.NewPar(fmt.Sprintf(\"%s\", humanize.Comma(int64(marketData.ActiveMarkets))))\n\tpar5.Height = 3\n\tpar5.Width = 20\n\tpar5.Y = 1\n\tpar5.TextFgColor = ui.ColorWhite\n\tpar5.BorderLabel = \"Active Markets\"\n\tpar5.BorderLabelFg = primaryColor\n\tpar5.BorderFg = primaryColor\n\n\t// reset\n\tui.Body.Rows = ui.Body.Rows[:0]\n\n\t// add grid rows and columns\n\tui.Body.AddRows(\n\t\tui.NewRow(\n\t\t\tui.NewCol(2, 0, par0),\n\t\t\tui.NewCol(2, 0, par1),\n\t\t\tui.NewCol(2, 0, par2),\n\t\t\tui.NewCol(2, 0, par3),\n\t\t\tui.NewCol(2, 0, par4),\n\t\t\tui.NewCol(2, 0, par5),\n\t\t),\n\t)\n\n\t// calculate layout\n\tui.Body.Align()\n\n\t// render to terminal\n\tui.Render(ui.Body)\n\n\treturn nil\n}",
"func (mhq *MarketHoursQuery) QueryMarketInfo() *MarketInfoQuery {\n\tquery := (&MarketInfoClient{config: mhq.config}).Query()\n\tquery.path = func(ctx context.Context) (fromU *sql.Selector, err error) {\n\t\tif err := mhq.prepareQuery(ctx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tselector := mhq.sqlQuery(ctx)\n\t\tif err := selector.Err(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(markethours.Table, markethours.FieldID, selector),\n\t\t\tsqlgraph.To(marketinfo.Table, marketinfo.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, true, markethours.MarketInfoTable, markethours.MarketInfoColumn),\n\t\t)\n\t\tfromU = sqlgraph.SetNeighbors(mhq.driver.Dialect(), step)\n\t\treturn fromU, nil\n\t}\n\treturn query\n}",
"func (f *FTX) GetMarket(ctx context.Context, marketName string) (MarketData, error) {\n\tresp := struct {\n\t\tData MarketData `json:\"result\"`\n\t}{}\n\treturn resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, getMarket+marketName,\n\t\t&resp)\n}",
"func (b Bitstamp) GetTicker(market string) (marketObservables.Ticker, error) {\n\n\tcall := \"ticker/\" + market\n\n\tcontents, err := b.requester(call, nil)\n\n\traw := rawTicker{}\n\n\tif err == nil {\n\t\terr = json.Unmarshal(contents, &raw)\n\t\tif err != nil {\n\t\t\treturn marketObservables.Ticker{}, err\n\t\t}\n\t}\n\n\treturn raw.ticker(), err\n}",
"func mainMarket() *Market {\n\treturn &Market{\"main\", 21}\n}",
"func (p *Base) GetPortfolioSummary(coinFilter string) map[string]float64 {\n\tresult := make(map[string]float64)\n\tfor _, x := range p.Addresses {\n\t\tif coinFilter != \"\" && coinFilter != x.CoinType {\n\t\t\tcontinue\n\t\t}\n\t\tbalance, ok := result[x.CoinType]\n\t\tif !ok {\n\t\t\tresult[x.CoinType] = x.Balance\n\t\t} else {\n\t\t\tresult[x.CoinType] = x.Balance + balance\n\t\t}\n\t}\n\treturn result\n}",
"func (mhq *MarketHoursQuery) WithMarketInfo(opts ...func(*MarketInfoQuery)) *MarketHoursQuery {\n\tquery := (&MarketInfoClient{config: mhq.config}).Query()\n\tfor _, opt := range opts {\n\t\topt(query)\n\t}\n\tmhq.withMarketInfo = query\n\treturn mhq\n}",
"func (sr *scrutinyRepository) GetSummary(ctx context.Context) (map[string]*models.DeviceSummary, error) {\n\tdevices, err := sr.GetDevices(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsummaries := map[string]*models.DeviceSummary{}\n\n\tfor _, device := range devices {\n\t\tsummaries[device.WWN] = &models.DeviceSummary{Device: device}\n\t}\n\n\t// Get parser flux query result\n\t//appConfig.GetString(\"web.influxdb.bucket\")\n\tqueryStr := fmt.Sprintf(`\n \timport \"influxdata/influxdb/schema\"\n \tbucketBaseName = \"%s\"\n\n\tdailyData = from(bucket: bucketBaseName)\n\t|> range(start: -10y, stop: now())\n\t|> filter(fn: (r) => r[\"_measurement\"] == \"smart\" )\n\t|> filter(fn: (r) => r[\"_field\"] == \"temp\" or r[\"_field\"] == \"power_on_hours\" or r[\"_field\"] == \"date\")\n\t|> last()\n\t|> schema.fieldsAsCols()\n\t|> group(columns: [\"device_wwn\"])\n\t\n\tweeklyData = from(bucket: bucketBaseName + \"_weekly\")\n\t|> range(start: -10y, stop: now())\n\t|> filter(fn: (r) => r[\"_measurement\"] == \"smart\" )\n\t|> filter(fn: (r) => r[\"_field\"] == \"temp\" or r[\"_field\"] == \"power_on_hours\" or r[\"_field\"] == \"date\")\n\t|> last()\n\t|> schema.fieldsAsCols()\n\t|> group(columns: [\"device_wwn\"])\n\t\n\tmonthlyData = from(bucket: bucketBaseName + \"_monthly\")\n\t|> range(start: -10y, stop: now())\n\t|> filter(fn: (r) => r[\"_measurement\"] == \"smart\" )\n\t|> filter(fn: (r) => r[\"_field\"] == \"temp\" or r[\"_field\"] == \"power_on_hours\" or r[\"_field\"] == \"date\")\n\t|> last()\n\t|> schema.fieldsAsCols()\n\t|> group(columns: [\"device_wwn\"])\n\t\n\tyearlyData = from(bucket: bucketBaseName + \"_yearly\")\n\t|> range(start: -10y, stop: now())\n\t|> filter(fn: (r) => r[\"_measurement\"] == \"smart\" )\n\t|> filter(fn: (r) => r[\"_field\"] == \"temp\" or r[\"_field\"] == \"power_on_hours\" or r[\"_field\"] == \"date\")\n\t|> last()\n\t|> schema.fieldsAsCols()\n\t|> group(columns: [\"device_wwn\"])\n\t\n\tunion(tables: [dailyData, weeklyData, monthlyData, yearlyData])\n\t|> sort(columns: [\"_time\"], desc: false)\n\t|> group(columns: [\"device_wwn\"])\n\t|> last(column: \"device_wwn\")\n\t|> yield(name: \"last\")\n\t\t`,\n\t\tsr.appConfig.GetString(\"web.influxdb.bucket\"),\n\t)\n\n\tresult, err := sr.influxQueryApi.Query(ctx, queryStr)\n\tif err == nil {\n\t\t// Use Next() to iterate over query result lines\n\t\tfor result.Next() {\n\t\t\t// Observe when there is new grouping key producing new table\n\t\t\tif result.TableChanged() {\n\t\t\t\t//fmt.Printf(\"table: %s\\n\", result.TableMetadata().String())\n\t\t\t}\n\t\t\t// read result\n\n\t\t\t//get summary data from Influxdb.\n\t\t\t//result.Record().Values()\n\t\t\tif deviceWWN, ok := result.Record().Values()[\"device_wwn\"]; ok {\n\n\t\t\t\t//ensure summaries is intialized for this wwn\n\t\t\t\tif _, exists := summaries[deviceWWN.(string)]; !exists {\n\t\t\t\t\tsummaries[deviceWWN.(string)] = &models.DeviceSummary{}\n\t\t\t\t}\n\n\t\t\t\tsummaries[deviceWWN.(string)].SmartResults = &models.SmartSummary{\n\t\t\t\t\tTemp: result.Record().Values()[\"temp\"].(int64),\n\t\t\t\t\tPowerOnHours: result.Record().Values()[\"power_on_hours\"].(int64),\n\t\t\t\t\tCollectorDate: result.Record().Values()[\"_time\"].(time.Time),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif result.Err() != nil {\n\t\t\tfmt.Printf(\"Query error: %s\\n\", result.Err().Error())\n\t\t}\n\t} else {\n\t\treturn nil, err\n\t}\n\n\tdeviceTempHistory, err := sr.GetSmartTemperatureHistory(ctx, DURATION_KEY_FOREVER)\n\tif err != nil {\n\t\tsr.logger.Printf(\"========================>>>>>>>>======================\")\n\t\tsr.logger.Printf(\"========================>>>>>>>>======================\")\n\t\tsr.logger.Printf(\"========================>>>>>>>>======================\")\n\t\tsr.logger.Printf(\"========================>>>>>>>>======================\")\n\t\tsr.logger.Printf(\"========================>>>>>>>>======================\")\n\t\tsr.logger.Printf(\"Error: %v\", err)\n\t}\n\tfor wwn, tempHistory := range deviceTempHistory {\n\t\tsummaries[wwn].TempHistory = tempHistory\n\t}\n\n\treturn summaries, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetMarketDetailMerged returns the ticker for the specified symbol
|
func (h *HUOBI) GetMarketDetailMerged(ctx context.Context, symbol currency.Pair) (DetailMerged, error) {
vals := url.Values{}
symbolValue, err := h.FormatSymbol(symbol, asset.Spot)
if err != nil {
return DetailMerged{}, err
}
vals.Set("symbol", symbolValue)
type response struct {
Response
Tick DetailMerged `json:"tick"`
}
var result response
err = h.SendHTTPRequest(ctx, exchange.RestSpot, common.EncodeURLValues(huobiMarketDetailMerged, vals), &result)
if result.ErrorMessage != "" {
return result.Tick, errors.New(result.ErrorMessage)
}
return result.Tick, err
}
|
[
"func (h *HUOBIHADAX) GetMarketDetailMerged(symbol string) (DetailMerged, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\n\ttype response struct {\n\t\tResponse\n\t\tTick DetailMerged `json:\"tick\"`\n\t}\n\n\tvar result response\n\turlPath := fmt.Sprintf(\"%s/%s\", h.APIUrl, huobihadaxMarketDetailMerged)\n\n\terr := h.SendHTTPRequest(common.EncodeURLValues(urlPath, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn result.Tick, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Tick, err\n}",
"func (h *HUOBIHADAX) GetMarketDetail(symbol string) (Detail, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\n\ttype response struct {\n\t\tResponse\n\t\tTick Detail `json:\"tick\"`\n\t}\n\n\tvar result response\n\turlPath := fmt.Sprintf(\"%s/%s\", h.APIUrl, huobihadaxMarketDetail)\n\n\terr := h.SendHTTPRequest(common.EncodeURLValues(urlPath, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn result.Tick, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Tick, err\n}",
"func (h *HUOBI) GetMarketDetail(ctx context.Context, symbol currency.Pair) (Detail, error) {\n\tvals := url.Values{}\n\tsymbolValue, err := h.FormatSymbol(symbol, asset.Spot)\n\tif err != nil {\n\t\treturn Detail{}, err\n\t}\n\tvals.Set(\"symbol\", symbolValue)\n\n\ttype response struct {\n\t\tResponse\n\t\tTick Detail `json:\"tick\"`\n\t}\n\n\tvar result response\n\n\terr = h.SendHTTPRequest(ctx, exchange.RestSpot, common.EncodeURLValues(huobiMarketDetail, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn result.Tick, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Tick, err\n}",
"func (c *Client) GetTicker(symbol string) (Ticker, error) {\n var ticker Ticker\n requestURL := fmt.Sprintf(\"/v1/pubticker/%s\", symbol)\n\n _, err := c.Request(\"GET\", requestURL, nil, &ticker)\n return ticker, err\n}",
"func (h *HitBTC) GetSymbolsDetailed(ctx context.Context) ([]Symbol, error) {\n\tvar resp []Symbol\n\tpath := fmt.Sprintf(\"/%s\", apiV2Symbol)\n\treturn resp, h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)\n}",
"func GetTickerDetails(baseURL string, symbol string) (*store.Ticker, error) {\r\n\r\n\t// log.Printf(\"url: %s\", url)\r\n\tvar ticker *store.Ticker\r\n\tvar url = baseURL + \"tickers/\" + symbol\r\n\terr := runHTTPGet(url, &ticker)\r\n\treturn ticker, err\r\n}",
"func (m *MarketClient) GetSymbolOrderBookTicker(symbol string) (interface{}, error) {\n\tvar err error\n\tparams := \"\"\n\tif symbol != \"\" {\n\t\tparams = fmt.Sprintf(\"symbol=%s\", symbol)\n\t}\n\treq, err := m.Builder.Build(http.MethodGet, \"/api/v3/ticker/bookTicker\", params)\n\tif err != nil {\n\t\tlogger.Error(\"Failed to build url: %s\", err.Error())\n\t}\n\tres, err := binance.HttpRequest(req)\n\tvar parser map[string]interface{}\n\terr = json.Unmarshal(res, &parser)\n\tif _, ok := parser[\"code\"]; ok {\n\t\tresult := model.APIErrorResponse{}\n\t\terr = json.Unmarshal(res, &result)\n\t\treturn result, err\n\t}\n\tif params == \"\" {\n\t\tvar result []SymbolOrderBookTickerResponse\n\t\terr = json.Unmarshal(res, &result)\n\t\treturn result, err\n\t}\n\tresult := SymbolOrderBookTickerResponse{}\n\terr = json.Unmarshal(res, &result)\n\treturn result, err\n}",
"func (m Market) Symbols() ([]aurora.Symbol, error) {\n\tvar baseAssets []string\n\tvar quoteAssets []string\n\tvar wg sync.WaitGroup\n\tvar err1 error\n\tvar err2 error\n\n\twg.Add(2)\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tvar res, err = http.Get(\"https://api.kucoin.com/v1/open/markets\")\n\t\tif err != nil {\n\t\t\terr1 = err\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\n\t\tvar markets struct {\n\t\t\tAssets []string `json:\"data\"`\n\t\t}\n\t\tif err := json.NewDecoder(res.Body).Decode(&markets); err != nil {\n\t\t\terr1 = err\n\t\t\treturn\n\t\t}\n\t\tbaseAssets = markets.Assets\n\t}()\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tvar res, err = http.Get(\"https://api.kucoin.com/v1/market/open/coins\")\n\t\tif err != nil {\n\t\t\terr2 = err\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\n\t\tvar coins struct {\n\t\t\tData []struct {\n\t\t\t\tAsset string `json:\"coin\"`\n\t\t\t} `json:\"data\"`\n\t\t}\n\t\tif err := json.NewDecoder(res.Body).Decode(&coins); err != nil {\n\t\t\terr2 = err\n\t\t\treturn\n\t\t}\n\t\tquoteAssets = make([]string, 0)\n\t\tfor _, a := range coins.Data {\n\t\t\tquoteAssets = append(quoteAssets, a.Asset)\n\t\t}\n\t}()\n\n\twg.Wait()\n\n\tif err1 != nil {\n\t\treturn nil, err1\n\t}\n\tif err2 != nil {\n\t\treturn nil, err2\n\t}\n\n\tvar symbols = make([]aurora.Symbol, 0)\n\tfor _, ba := range baseAssets {\n\t\tfor _, qa := range quoteAssets {\n\t\t\tsymbols = append(symbols, aurora.Symbol{BaseAsset: ba, QuoteAsset: qa})\n\t\t}\n\t}\n\n\treturn symbols, nil\n}",
"func GetStockData(symbl string, consumerKey string) (Stock, error) {\n\t//Delay to not hit rate limit during larger individual stock pulls\n\ttime.Sleep(500 * time.Millisecond)\n\n\t//Create HTTP Client need for GET call below\n\tclient := &http.Client{}\n\n\t//Create map for Stock struct\n\tvar stockMap map[string]Stock\n\n\t//GET creation request for Quote data, variables used for stock symbl and key\n\trequest, err := http.NewRequest(\"GET\", fmt.Sprintf(\"https://api.tdameritrade.com/v1/marketdata/%s/quotes?apikey=%s\", symbl, consumerKey), nil)\n\n\t//Send HTTP request to server\n\tresp, err := client.Do(request)\n\tif err != nil {\n\t\treturn Stock{}, err\n\t}\n\t//fmt.Println(resp) //#Debugging print line\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn Stock{}, err\n\t}\n\t//fmt.Println(string(body)) //Debugging print line\n\n\t//Confirm Body data\n\tbodyCheck := errorhandlers.ConfirmBody(string(body))\n\n\tif bodyCheck != \"\" {\n\t\treturn Stock{}, errors.New(bodyCheck)\n\t}\n\n\t//Unmarshal response into struct to be used later\n\terr = json.Unmarshal(body, &stockMap)\n\tif err != nil {\n\t\treturn Stock{}, err\n\t}\n\n\t//Convert Map to struct\n\tstockStruct := makeStockStructFromMap(symbl, stockMap)\n\n\t//Return new Stock map\n\treturn stockStruct, nil\n}",
"func (m *Market) Ticker(symbol string) (MarketResponse, error) {\n\ttickerURL := URL(\"/v1/ticker\")\n\tvar result MarketResponse\n\tvalues := url.Values{}\n\n\tif symbol != \"\" {\n\t\tvalues.Add(\"symbol\", symbol)\n\t}\n\n\tresp, err := method.Get(tickerURL, nil, values)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn bodyToMarketResponse(resp.Body, &result)\n}",
"func (repository *Repository) GetBySymbol(symbol string) []models.Coin {\n\tvar coins []models.Coin\n\n\terr := repository.DB.Model(&coins).\n\t\tColumn(\"crr\", \"volume\", \"reserve_balance\", \"name\", \"symbol\").\n\t\tWhere(\"symbol LIKE ?\", fmt.Sprintf(\"%%%s%%\", symbol)).\n\t\tWhere(\"deleted_at IS NULL\").\n\t\tOrder(\"reserve_balance DESC\").\n\t\tSelect()\n\thelpers.CheckErr(err)\n\n\treturn coins\n}",
"func (hc *Client) GetSymbolsPair() ([]Symbol, error) {\n\tvar (\n\t\tsymbolReply SymbolsReply\n\t)\n\tendpoint := fmt.Sprintf(\"%s/v1/common/symbols\", huobiEndpoint)\n\tres, err := hc.sendRequest(\n\t\thttp.MethodGet,\n\t\tendpoint,\n\t\tnil,\n\t\tfalse,\n\t)\n\tif err != nil {\n\t\treturn symbolReply.Data, err\n\t}\n\terr = json.Unmarshal(res, &symbolReply)\n\tif err != nil {\n\t\treturn symbolReply.Data, err\n\t}\n\tif symbolReply.Status != StatusOK.String() {\n\t\treturn symbolReply.Data, fmt.Errorf(\"unexpected reply status %s\", symbolReply.Status)\n\t}\n\treturn symbolReply.Data, nil\n}",
"func GetStock(symbol string) string {\n\tcfg := config.NewConfig()\n\tresponse, err := request(\"GET\", \"https://www.alphavantage.co/query?function=OVERVIEW&symbol=\" + symbol + \"&apikey=\" + cfg.AlphaVantageKey, nil, \"\", nil)\n\n\tif err != nil {\n\t\treturn \"{\\\"error\\\": \\\"Not Found\\\"}\"\n\t}\n\n\treturn response\n}",
"func (p *Bittrex) GetTicker(pair string) *TickerValue {\n\treturn nil\n}",
"func GetMultipleStocks(tickers string, consumerKey string) ([]Stock, error) {\n\t//Delay to not hit rate limit during larger individual stock pulls\n\ttime.Sleep(500 * time.Millisecond)\n\n\tclient := &http.Client{}\n\tvar groupStocks []Stock\n\tvar parsed map[string]Stock\n\tvar newStock Stock\n\n\tv := url.Values{}\n\n\tv.Add(\"symbol\", tickers)\n\t//fmt.Println(v.Encode())\n\n\t//fmt.Println(tickers)\n\trequest, err := http.NewRequest(\"GET\", fmt.Sprintf(\"https://api.tdameritrade.com/v1/marketdata/quotes?apikey=%s&%s\", consumerKey, v.Encode()), nil)\n\n\t//Add this header to enable non delayed quotes\n\t//request.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", configuration.TDKEY))\n\n\tresp, err := client.Do(request)\n\t//fmt.Println(resp) //#Debugging print line\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\t//fmt.Println(string(body)) //Debugging print line\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(body, &parsed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, item := range parsed {\n\t\tnewStock.HighPrice = parsed[item.Symbol].HighPrice\n\t\tnewStock.ClosePrice = parsed[item.Symbol].ClosePrice\n\t\tnewStock.LowPrice = parsed[item.Symbol].LowPrice\n\t\tnewStock.Mark = parsed[item.Symbol].Mark\n\t\tnewStock.OpenPrice = parsed[item.Symbol].OpenPrice\n\t\tnewStock.TotalVolume = parsed[item.Symbol].TotalVolume\n\t\tnewStock.Mark = parsed[item.Symbol].Mark\n\t\tnewStock.Symbol = item.Symbol\n\t\tnewStock.Delayed = parsed[item.Symbol].Delayed\n\n\t\t//stockStruct := makeStockStructFromMap(item.Symbol, item)\n\t\tgroupStocks = append(groupStocks, newStock)\n\t}\n\n\treturn groupStocks, nil\n}",
"func (o *Dividends2) GetSymbol() string {\n\tif o == nil || o.Symbol == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Symbol\n}",
"func (sp *SymbolsProvider) Get() (symbols []schemas.Symbol, err error) {\n\tsmbls, err := sp.getSymbols()\n\tif err != nil {\n\t\treturn\n\t}\n\tcoins, err := sp.getCoins()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, smb := range smbls {\n\t\tvar basePrec, quotePrec int\n\n\t\ts := smb.Map()\n\t\tif p, ok := coins[smb.CoinType]; ok {\n\t\t\tbasePrec = int(p.TradePrecision)\n\t\t}\n\t\tif p, ok := coins[smb.CoinTypePair]; ok {\n\t\t\tquotePrec = int(p.TradePrecision)\n\t\t}\n\n\t\tif basePrec != 0 && quotePrec != 0 {\n\t\t\tif basePrec > quotePrec {\n\t\t\t\ts.PricePrecision = quotePrec\n\t\t\t} else if quotePrec > basePrec {\n\t\t\t\ts.PricePrecision = basePrec\n\t\t\t} else {\n\t\t\t\ts.PricePrecision = basePrec\n\t\t\t}\n\t\t} else {\n\t\t\ts.PricePrecision = defaultPrecision\n\t\t}\n\n\t\tsymbols = append(symbols, s)\n\t}\n\n\treturn\n}",
"func (o *MutualFundSectorExposure) GetSymbol() string {\n\tif o == nil || o.Symbol == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Symbol\n}",
"func (b Bitstamp) GetTicker(market string) (marketObservables.Ticker, error) {\n\n\tcall := \"ticker/\" + market\n\n\tcontents, err := b.requester(call, nil)\n\n\traw := rawTicker{}\n\n\tif err == nil {\n\t\terr = json.Unmarshal(contents, &raw)\n\t\tif err != nil {\n\t\t\treturn marketObservables.Ticker{}, err\n\t\t}\n\t}\n\n\treturn raw.ticker(), err\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetTrades returns the trades for the specified symbol
|
func (h *HUOBI) GetTrades(ctx context.Context, symbol currency.Pair) ([]Trade, error) {
vals := url.Values{}
symbolValue, err := h.FormatSymbol(symbol, asset.Spot)
if err != nil {
return nil, err
}
vals.Set("symbol", symbolValue)
type response struct {
Response
Tick struct {
Data []Trade `json:"data"`
} `json:"tick"`
}
var result response
err = h.SendHTTPRequest(ctx, exchange.RestSpot, common.EncodeURLValues(huobiMarketTrade, vals), &result)
if result.ErrorMessage != "" {
return nil, errors.New(result.ErrorMessage)
}
return result.Tick.Data, err
}
|
[
"func (h *HUOBIHADAX) GetTrades(symbol string) ([]Trade, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\n\ttype response struct {\n\t\tResponse\n\t\tTick struct {\n\t\t\tData []Trade `json:\"data\"`\n\t\t} `json:\"tick\"`\n\t}\n\n\tvar result response\n\turlPath := fmt.Sprintf(\"%s/%s\", h.APIUrl, huobihadaxMarketTrade)\n\n\terr := h.SendHTTPRequest(common.EncodeURLValues(urlPath, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Tick.Data, err\n}",
"func (c *Coinbene) GetTrades(symbol string, limit int64) (Trades, error) {\n\tresp := struct {\n\t\tData [][]string `json:\"data\"`\n\t}{}\n\n\tparams := url.Values{}\n\tparams.Set(\"symbol\", symbol)\n\tparams.Set(\"limit\", strconv.FormatInt(limit, 10))\n\tpath := common.EncodeURLValues(coinbeneAPIVersion+coinbeneGetTrades, params)\n\terr := c.SendHTTPRequest(exchange.RestSpot, path, spotMarketTrades, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar trades Trades\n\tfor x := range resp.Data {\n\t\ttm, err := time.Parse(time.RFC3339, resp.Data[x][4])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tprice, err := strconv.ParseFloat(resp.Data[x][1], 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvolume, err := strconv.ParseFloat(resp.Data[x][2], 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttrades = append(trades, TradeItem{\n\t\t\tCurrencyPair: resp.Data[x][0],\n\t\t\tPrice: price,\n\t\t\tVolume: volume,\n\t\t\tDirection: resp.Data[x][3],\n\t\t\tTradeTime: tm,\n\t\t})\n\t}\n\treturn trades, nil\n}",
"func (tg *TradesGroup) Get() (trades []schemas.Trade, err error) {\n\tif len(tg.symbols) == 0 {\n\t\terr = errors.New(\"[BITFINEX] No symbols provided\")\n\t\treturn\n\t}\n\tfor i := range tg.symbols {\n\t\tvar resp interface{}\n\t\tvar symbol string\n\t\tvar b []byte\n\n\t\tsymbol = tg.symbols[i].OriginalName\n\t\turl := apiTrades + \"/\" + \"t\" + strings.ToUpper(symbol) + \"/hist\"\n\n\t\tif b, err = tg.httpClient.Get(url, httpclient.Params(), false); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif err = json.Unmarshal(b, &resp); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif trds, ok := resp.([]interface{}); ok {\n\t\t\tfor _, tr := range trds {\n\t\t\t\tif t, ok := tr.([]interface{}); ok {\n\t\t\t\t\ttrades = append(trades, tg.mapTrade(symbol, t))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\n\treturn\n}",
"func (h *HitBTC) GetTrades(ctx context.Context, currencyPair, by, sort string, from, till, limit, offset int64) ([]TradeHistory, error) {\n\turlValues := url.Values{}\n\tif from > 0 {\n\t\turlValues.Set(\"from\", strconv.FormatInt(from, 10))\n\t}\n\tif till > 0 {\n\t\turlValues.Set(\"till\", strconv.FormatInt(till, 10))\n\t}\n\tif limit > 0 {\n\t\turlValues.Set(\"limit\", strconv.FormatInt(limit, 10))\n\t}\n\tif offset > 0 {\n\t\turlValues.Set(\"offset\", strconv.FormatInt(offset, 10))\n\t}\n\tif by != \"\" {\n\t\turlValues.Set(\"by\", by)\n\t}\n\tif sort != \"\" {\n\t\turlValues.Set(\"sort\", sort)\n\t}\n\n\tvar resp []TradeHistory\n\tpath := fmt.Sprintf(\"/%s/%s?%s\",\n\t\tapiV2Trades,\n\t\tcurrencyPair,\n\t\turlValues.Encode())\n\treturn resp, h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)\n}",
"func (c *Client) Trades(symbol string) (*Trades, error) {\n\tvar b strings.Builder\n\tb.WriteString(baseWS)\n\tb.WriteString(strings.ToLower(symbol))\n\tb.WriteString(\"@trade\")\n\tconn, err := fastws.Dial(b.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Trades{wsClient{conn: conn}}, nil\n}",
"func (f *FTX) GetTrades(ctx context.Context, marketName string, startTime, endTime, limit int64) ([]TradeData, error) {\n\tif marketName == \"\" {\n\t\treturn nil, errors.New(\"a market pair must be specified\")\n\t}\n\n\tparams := url.Values{}\n\tif limit != 0 {\n\t\tparams.Set(\"limit\", strconv.FormatInt(limit, 10))\n\t}\n\tif startTime > 0 && endTime > 0 {\n\t\tif startTime >= (endTime) {\n\t\t\treturn nil, errStartTimeCannotBeAfterEndTime\n\t\t}\n\t\tparams.Set(\"start_time\", strconv.FormatInt(startTime, 10))\n\t\tparams.Set(\"end_time\", strconv.FormatInt(endTime, 10))\n\t}\n\tresp := struct {\n\t\tData []TradeData `json:\"result\"`\n\t}{}\n\tendpoint := common.EncodeURLValues(fmt.Sprintf(getTrades, marketName), params)\n\treturn resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, endpoint, &resp)\n}",
"func (c *Coinbene) GetSwapTrades(symbol string, limit int) (SwapTrades, error) {\n\tv := url.Values{}\n\tv.Set(\"symbol\", symbol)\n\tif limit != 0 {\n\t\tv.Set(\"limit\", strconv.Itoa(limit))\n\t}\n\ttype resp struct {\n\t\tData [][]string `json:\"data\"`\n\t}\n\tvar r resp\n\tpath := common.EncodeURLValues(coinbeneAPIVersion+coinbeneGetTrades, v)\n\tif err := c.SendHTTPRequest(exchange.RestSwap, path, contractTrades, &r); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar s SwapTrades\n\tfor x := range r.Data {\n\t\ttm, err := time.Parse(time.RFC3339, r.Data[x][3])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tprice, err := strconv.ParseFloat(r.Data[x][0], 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\torderSide := order.Buy\n\t\tif r.Data[x][1] == \"s\" {\n\t\t\torderSide = order.Sell\n\t\t}\n\t\tvolume, err := strconv.ParseFloat(r.Data[x][2], 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts = append(s, SwapTrade{\n\t\t\tPrice: price,\n\t\t\tSide: orderSide,\n\t\t\tVolume: volume,\n\t\t\tTime: tm,\n\t\t})\n\t}\n\treturn s, nil\n}",
"func TestWsGetTrades(t *testing.T) {\n\tsetupWsAuth(t)\n\t_, err := h.wsGetTrades(currency.NewPair(currency.ETH, currency.BTC), 1000, \"ASC\", \"id\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}",
"func (a *api) MyTrades(symbol string, startTime, endTime int64, limit int) (t []model.UserTrade, err error) {\n\tif symbol == \"\" {\n\t\treturn t, NoSymbolProvided\n\t}\n\tq := NewParameters(5)\n\tq.Set(\"symbol\", symbol)\n\tif startTime != 0 {\n\t\tq.Set(\"startTime\", strconv.FormatInt(startTime, 10))\n\t}\n\tif endTime != 0 {\n\t\tq.Set(\"endTime\", strconv.FormatInt(endTime, 10))\n\t}\n\tif limit != 0 {\n\t\tq.Set(\"limit\", strconv.Itoa(limit))\n\t}\n\tq.Set(\"timestamp\", strconv.FormatInt(time.Now().Unix()*1000, 10))\n\n\tbody, err := a.Request(http.MethodGet, myTradesPath, q)\n\tif err != nil {\n\t\treturn t, err\n\t}\n\n\terr = json.Unmarshal(body, &t)\n\tif err != nil {\n\t\treturn t, fmt.Errorf(\"encountered error while unmarshaling '%s' into model.Trade\", body)\n\t}\n\n\treturn t, nil\n}",
"func TestGetTrades(t *testing.T) {\n\tt.Parallel()\n\t_, err := k.GetTrades(\"BCHEUR\")\n\tif err != nil {\n\t\tt.Error(\"Test Failed - GetTrades() error\", err)\n\t}\n}",
"func (s *Server) getTrades(c *gin.Context) {\n\tvar (\n\t\tlogger = s.sugar.With(\"func\", caller.GetCurrentFunctionName())\n\t\tquery getTradesQuery\n\t\thuobiTrades = make(map[string][]huobi.TradeHistory)\n\t\tbinanceTrades = make(map[string][]binance.TradeHistory) // map account with its trades\n\t)\n\n\tif err := c.ShouldBindQuery(&query); err != nil {\n\t\thttputil.ResponseFailure(\n\t\t\tc,\n\t\t\thttp.StatusBadRequest,\n\t\t\terr,\n\t\t)\n\t\treturn\n\t}\n\n\tif len(query.Exchanges) == 0 {\n\t\tquery.Exchanges = []string{\n\t\t\tcommon.Huobi.String(),\n\t\t\tcommon.Binance.String()}\n\t}\n\n\tfromTime, toTime, err := query.Validate(\n\t\thttputil.TimeRangeQueryWithMaxTimeFrame(maxTimeFrame),\n\t\thttputil.TimeRangeQueryWithDefaultTimeFrame(defaultTimeFrame),\n\t)\n\tif err != nil {\n\t\thttputil.ResponseFailure(\n\t\t\tc,\n\t\t\thttp.StatusBadRequest,\n\t\t\terr,\n\t\t)\n\t\treturn\n\t}\n\n\tlogger = logger.With(\"from\", fromTime, \"to\", toTime, \"exchanges\", query.Exchanges)\n\tlogger.Debug(\"querying trades from database\")\n\n\tfor _, cex := range query.Exchanges {\n\t\tswitch cex {\n\t\tcase common.Huobi.String():\n\t\t\thuobiTrades, err = s.hs.GetTradeHistory(fromTime, toTime)\n\t\t\tif err != nil {\n\t\t\t\thttputil.ResponseFailure(\n\t\t\t\t\tc,\n\t\t\t\t\thttp.StatusInternalServerError,\n\t\t\t\t\terr,\n\t\t\t\t)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase common.Binance.String():\n\t\t\tbinanceTrades, err = s.bs.GetTradeHistory(fromTime, toTime)\n\t\t\tif err != nil {\n\t\t\t\thttputil.ResponseFailure(\n\t\t\t\t\tc,\n\t\t\t\t\thttp.StatusInternalServerError,\n\t\t\t\t\terr,\n\t\t\t\t)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tbinanceMarginTrades, err := s.bs.GetMarginTradeHistory(fromTime, toTime)\n\t\t\tif err != nil {\n\t\t\t\thttputil.ResponseFailure(\n\t\t\t\t\tc,\n\t\t\t\t\thttp.StatusInternalServerError,\n\t\t\t\t\terr,\n\t\t\t\t)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor account := range binanceMarginTrades {\n\t\t\t\tbinanceTrades[account] = append(binanceTrades[account], binanceMarginTrades[account]...) // append margin trades into spot trades\n\t\t\t}\n\t\t}\n\t}\n\n\tc.JSON(http.StatusOK, getTradesResponse{\n\t\tHuobi: huobiTrades,\n\t\tBinance: binanceTrades,\n\t})\n}",
"func (trading *TradingProvider) Trades(opts schemas.FilterOptions) (trades []schemas.Trade, p schemas.Paging, err error) {\n\tvar b []byte\n\tparams := httpclient.Params()\n\n\tif len(opts.Symbols) > 0 {\n\t\tvar pairs []string\n\t\tfor _, s := range opts.Symbols {\n\t\t\tpairs = append(pairs, s.Name)\n\t\t}\n\t\tparams.Set(\"symbol\", strings.Join(pairs, \",\"))\n\t}\n\n\tif opts.Limit > 0 {\n\t\tparams.Set(\"limit\", fmt.Sprintf(\"%d\", opts.Limit))\n\t}\n\n\tif opts.Since != 0 {\n\t\tparams.Set(\"since\", fmt.Sprintf(\"%d\", opts.Since))\n\t}\n\tif opts.Before != 0 {\n\t\tparams.Set(\"before\", fmt.Sprintf(\"%d\", opts.Before))\n\t}\n\tif opts.Page != 0 {\n\t\tparams.Set(\"page\", fmt.Sprintf(\"%d\", opts.Page))\n\t}\n\tb, err = trading.httpClient.Get(apiUserTrades, params, true)\n\tif err != nil {\n\t\treturn\n\t}\n\tvar resp UserTradesResponse\n\tif err = json.Unmarshal(b, &resp); err != nil {\n\t\treturn\n\t}\n\tif resp.Success == false {\n\t\tlog.Printf(\"[KUCOIN] resp error: %+v\\n\", resp)\n\t\tif resp.Code == \"UNAUTH\" {\n\t\t\terr = errors.New(resp.Msg)\n\t\t\treturn\n\t\t}\n\t}\n\treturn resp.Map(), schemas.Paging{\n\t\tCount: resp.Data.Total,\n\t\tPages: resp.Data.PageNos,\n\t\tCurrent: resp.Data.CurrPageNo,\n\t\tLimit: resp.Data.Limit,\n\t}, nil\n}",
"func (c *Client) Trades(ctx context.Context, pair string, limit int) (Trades, error) {\n\tif limit == 0 {\n\t\tlimit = 150\n\t}\n\tv := url.Values{}\n\tv.Set(\"limit\", strconv.Itoa(limit))\n\treq, err := c.newRequest(ctx, \"GET\", \"trades/\"+pair, v)\n\tif err != nil {\n\t\treturn Trades{}, err\n\t}\n\n\tvar ret = &Trades{}\n\t_, err = c.do(req, ret)\n\tif err != nil {\n\t\treturn Trades{}, err\n\t}\n\treturn *ret, nil\n}",
"func (c *Client) GetTrades(coin types.Coin, filter *service.GetTradesFilter) ([]*types.Trade, error) {\n\tresp, err := c.Service.GetTrades(coin, filter)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting trades for coin %s: %s\", coin, err)\n\t}\n\tdefer resp.Body.Close()\n\n\t// Example response:\n\t// [\n\t// \t{\n\t// \t\t\"tid\": 10007777, \"date\": 1618979594, \"type\": \"sell\", \"price\": 313100.00031, \"amount\": 0.00011856\n\t// \t},\n\t// ...\n\t// ]\n\n\tvar trades []*types.Trade\n\terr = json.NewDecoder(resp.Body).Decode(&trades)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding trades for coin %s: %s: %s\", coin, err, msg)\n\t}\n\n\tfor i := range trades {\n\t\ttrades[i].Date = time.Unix(int64(trades[i].Timestamp), 0)\n\t}\n\n\treturn trades, nil\n}",
"func (m *DataManager) getTrades(fromNonce *big.Int, toNonce *big.Int, offset uint64) []*Trade {\n\trows, err := m.db.Query(`\n\tSELECT product_id, \n\t\ttaker_order_id, \n\t\tmaker_order_id, \n\t\tprice, \n\t\tamount, \n\t\tside, \n\t\ttaker_fee,\n\t\tmaker_fee \n\tFROM\tt_trade \n\tWHERE\tstatus IN ( \"onchainsettled\", \"onchainconfirmed\" ) \n\t\t\tAND tx_nonce BETWEEN ? AND ? \n\t\t\tAND create_time > ?\n\tORDER BY id\n\tLIMIT ?, ? `, fromNonce.Int64(), toNonce.Int64(), m.dexStartTime, offset, maxRecordsPerQuery)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer rows.Close()\n\n\ttrades := []*Trade{}\n\tfor rows.Next() {\n\t\ttrade := Trade{}\n\t\tif err := rows.Scan(&trade.productID,\n\t\t\t&trade.takerOrderID,\n\t\t\t&trade.makerOrderID,\n\t\t\t&trade.price,\n\t\t\t&trade.amount,\n\t\t\t&trade.side,\n\t\t\t&trade.takerFee,\n\t\t\t&trade.makerFee); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttrades = append(trades, &trade)\n\t}\n\treturn trades\n}",
"func (m *DataManager) GetTrades(fromNonce *big.Int, toNonce *big.Int) []*Trade {\n\toffset := uint64(0)\n\ttrades := []*Trade{}\n\tfor {\n\t\tret := m.getTrades(fromNonce, toNonce, offset)\n\t\ttrades = append(trades, ret...)\n\t\toffset = offset + uint64(len(ret))\n\t\tif len(ret) < maxRecordsPerQuery {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn trades\n}",
"func (b *Bitmex) GetHistoricTrades(ctx context.Context, p currency.Pair, assetType asset.Item, timestampStart, timestampEnd time.Time) ([]trade.Data, error) {\n\tif assetType == asset.Index {\n\t\treturn nil, fmt.Errorf(\"%w %v\", asset.ErrNotSupported, assetType)\n\t}\n\tif err := common.StartEndTimeCheck(timestampStart, timestampEnd); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid time range supplied. Start: %v End %v %w\", timestampStart, timestampEnd, err)\n\t}\n\tvar err error\n\tp, err = b.FormatExchangeCurrency(p, assetType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlimit := 1000\n\treq := &GenericRequestParams{\n\t\tSymbol: p.String(),\n\t\tCount: int32(limit),\n\t\tEndTime: timestampEnd.UTC().Format(\"2006-01-02T15:04:05.000Z\"),\n\t}\n\tts := timestampStart\n\tvar resp []trade.Data\nallTrades:\n\tfor {\n\t\treq.StartTime = ts.UTC().Format(\"2006-01-02T15:04:05.000Z\")\n\t\tvar tradeData []Trade\n\t\ttradeData, err = b.GetTrade(ctx, req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor i := range tradeData {\n\t\t\tif tradeData[i].Timestamp.Before(timestampStart) || tradeData[i].Timestamp.After(timestampEnd) {\n\t\t\t\tbreak allTrades\n\t\t\t}\n\t\t\tvar side order.Side\n\t\t\tside, err = order.StringToOrderSide(tradeData[i].Side)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif tradeData[i].Price == 0 {\n\t\t\t\t// Please note that indices (symbols starting with .) post trades at intervals to the trade feed.\n\t\t\t\t// These have a size of 0 and are used only to indicate a changing price.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresp = append(resp, trade.Data{\n\t\t\t\tExchange: b.Name,\n\t\t\t\tCurrencyPair: p,\n\t\t\t\tAssetType: assetType,\n\t\t\t\tSide: side,\n\t\t\t\tPrice: tradeData[i].Price,\n\t\t\t\tAmount: float64(tradeData[i].Size),\n\t\t\t\tTimestamp: tradeData[i].Timestamp,\n\t\t\t\tTID: tradeData[i].TrdMatchID,\n\t\t\t})\n\t\t\tif i == len(tradeData)-1 {\n\t\t\t\tif ts.Equal(tradeData[i].Timestamp) {\n\t\t\t\t\t// reached end of trades to crawl\n\t\t\t\t\tbreak allTrades\n\t\t\t\t}\n\t\t\t\tts = tradeData[i].Timestamp\n\t\t\t}\n\t\t}\n\t\tif len(tradeData) != limit {\n\t\t\tbreak allTrades\n\t\t}\n\t}\n\terr = b.AddTradesToBuffer(resp...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsort.Sort(trade.ByDate(resp))\n\treturn trade.FilterTradesByTime(resp, timestampStart, timestampEnd), nil\n}",
"func (b *Binance) GetHistoricalTrades(symbol string, limit int, fromID int64) ([]HistoricalTrade, error) {\n\tvar resp []HistoricalTrade\n\n\tif err := b.CheckLimit(limit); err != nil {\n\t\treturn resp, err\n\t}\n\n\tparams := url.Values{}\n\tparams.Set(\"symbol\", common.StringToUpper(symbol))\n\tparams.Set(\"limit\", strconv.Itoa(limit))\n\tparams.Set(\"fromid\", strconv.FormatInt(fromID, 10))\n\n\tpath := fmt.Sprintf(\"%s%s?%s\", b.APIUrl, historicalTrades, params.Encode())\n\n\treturn resp, b.SendHTTPRequest(path, &resp)\n}",
"func (by *Bybit) GetUSDCLatestTrades(ctx context.Context, symbol currency.Pair, category string, limit int64) ([]USDCTrade, error) {\n\tresp := struct {\n\t\tResult struct {\n\t\t\tResultSize int64 `json:\"resultTotalSize\"`\n\t\t\tCursor string `json:\"cursor\"`\n\t\t\tData []USDCTrade `json:\"dataList\"`\n\t\t} `json:\"result\"`\n\t\tUSDCError\n\t}{}\n\n\tparams := url.Values{}\n\tif category == \"\" {\n\t\treturn nil, errInvalidCategory\n\t}\n\tparams.Set(\"category\", category)\n\n\tif !symbol.IsEmpty() {\n\t\tsymbolValue, err := by.FormatSymbol(symbol, asset.USDCMarginedFutures)\n\t\tif err != nil {\n\t\t\treturn resp.Result.Data, err\n\t\t}\n\t\tparams.Set(\"symbol\", symbolValue)\n\t}\n\n\tif limit > 0 && limit <= 500 {\n\t\tparams.Set(\"limit\", strconv.FormatInt(limit, 10))\n\t}\n\treturn resp.Result.Data, by.SendHTTPRequest(ctx, exchange.RestUSDCMargined, common.EncodeURLValues(usdcfuturesGetLatestTrades, params), usdcPublicRate, &resp)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetLatestSpotPrice returns latest spot price of symbol symbol: string of currency pair
|
func (h *HUOBI) GetLatestSpotPrice(ctx context.Context, symbol currency.Pair) (float64, error) {
list, err := h.GetTradeHistory(ctx, symbol, 1)
if err != nil {
return 0, err
}
if len(list) == 0 {
return 0, errors.New("the length of the list is 0")
}
return list[0].Trades[0].Price, nil
}
|
[
"func (b *Binance) GetLatestSpotPrice(symbol string) (SymbolPrice, error) {\n\tresp := SymbolPrice{}\n\n\tif err := b.CheckSymbol(symbol); err != nil {\n\t\treturn resp, err\n\t}\n\n\tparams := url.Values{}\n\tparams.Set(\"symbol\", common.StringToUpper(symbol))\n\n\tpath := fmt.Sprintf(\"%s%s?%s\", b.APIUrl, symbolPrice, params.Encode())\n\n\treturn resp, b.SendHTTPRequest(path, &resp)\n}",
"func (h *HUOBIHADAX) GetLatestSpotPrice(symbol string) (float64, error) {\n\tlist, err := h.GetTradeHistory(symbol, \"1\")\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif len(list) == 0 {\n\t\treturn 0, errors.New(\"the length of the list is 0\")\n\t}\n\n\treturn list[0].Trades[0].Price, nil\n}",
"func getLatestQuote(client *av.Client, symbol string) (float64, error) {\n\tvalues, err := client.StockTimeSeries(av.TimeSeriesDaily, symbol)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\treturn values[len(values)-1].Close, nil\n}",
"func (_Sigmacore *SigmacoreCaller) GetSpotPrice(opts *bind.CallOpts, tokenIn common.Address, tokenOut common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Sigmacore.contract.Call(opts, &out, \"getSpotPrice\", tokenIn, tokenOut)\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 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 (c *Client) GetGlobalQuotesLatestBySymbol(convert string) (result GlobalMetrics, err error) {\n\tvar raw json.RawMessage\n\tq := url.Values{}\n\tq.Set(\"convert\", convert)\n\tif raw, err = c.handleRequest(ltUriGlobalQuotesLatest, &q); err != nil {\n\t\treturn\n\t}\n\terr = json.Unmarshal(raw, &result)\n\treturn\n}",
"func (_Sigmacore *SigmacoreCallerSession) GetSpotPrice(tokenIn common.Address, tokenOut common.Address) (*big.Int, error) {\n\treturn _Sigmacore.Contract.GetSpotPrice(&_Sigmacore.CallOpts, tokenIn, tokenOut)\n}",
"func getCurrentPrice() (float64, error) {\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\treq, err := http.NewRequest(\"GET\", priceAPIURL, nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treq.Close = true\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar data map[string]interface{}\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// extract price data\n\tbpi := data[\"bpi\"]\n\tbpiUSD := bpi.(map[string]interface{})[\"USD\"]\n\tpriceUSD := bpiUSD.(map[string]interface{})[\"rate_float\"].(float64)\n\n\treturn priceUSD, nil\n}",
"func (sa *symbolsArchive) getLatestPriceAs(base SymbolType, as SymbolType) (Price, error) {\n\t// Get symbol\n\tbaseSymbol, err := sa.GetSymbol(base)\n\tif err != nil {\n\t\treturn Price{}, fmt.Errorf(\"No prices for symbol %q\", base)\n\t}\n\n\tprice, err := baseSymbol.GetLatestPriceAs(as)\n\tif err != nil {\n\t\treturn Price{}, fmt.Errorf(\"unable to convert %q to %q as their is no %s/%s prices\", base, as, base, as)\n\t}\n\treturn price, nil\n}",
"func (s *symbol) GetLatestPriceAs(as SymbolType) (Price, error) {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\t// base and as symbol are the same so price == 1\n\tif s.SymbolType == as {\n\t\treturn Price{\n\t\t\tBase: s.SymbolType,\n\t\t\tAs: as,\n\t\t\tPrice: 1.0,\n\t\t\tAt: servertime.Now(),\n\t\t}, nil\n\t}\n\tif prices, ok := s.priceAs[as]; !ok || len(prices) == 0 {\n\t\treturn Price{}, fmt.Errorf(\"Symbol: %s has no price information for: %s\", s.SymbolType, as)\n\t} else {\n\t\t// return last price\n\t\treturn prices[len(prices)-1], nil\n\t}\n}",
"func (m *MarketClient) GetSymbolTickerPrice(symbol string) (interface{}, error) {\n\tvar err error\n\tparams := \"\"\n\tif symbol != \"\" {\n\t\tparams = fmt.Sprintf(\"symbol=%s\", symbol)\n\t}\n\treq, err := m.Builder.Build(http.MethodGet, \"/api/v3/ticker/price\", params)\n\tif err != nil {\n\t\tlogger.Error(\"Failed to build url: %s\", err.Error())\n\t}\n\tres, err := binance.HttpRequest(req)\n\tvar parser map[string]interface{}\n\terr = json.Unmarshal(res, &parser)\n\tif _, ok := parser[\"code\"]; ok {\n\t\tresult := model.APIErrorResponse{}\n\t\terr = json.Unmarshal(res, &result)\n\t\treturn result, err\n\t}\n\tif params == \"\" {\n\t\tvar result []SymbolPriceTickerResponse\n\t\terr = json.Unmarshal(res, &result)\n\t\treturn result, err\n\t}\n\tresult := SymbolPriceTickerResponse{}\n\terr = json.Unmarshal(res, &result)\n\treturn result, err\n}",
"func (b *Binance) GetBestPrice(symbol string) (BestPrice, error) {\n\tresp := BestPrice{}\n\n\tif err := b.CheckSymbol(symbol); err != nil {\n\t\treturn resp, err\n\t}\n\n\tparams := url.Values{}\n\tparams.Set(\"symbol\", common.StringToUpper(symbol))\n\n\tpath := fmt.Sprintf(\"%s%s?%s\", b.APIUrl, bestPrice, params.Encode())\n\n\treturn resp, b.SendHTTPRequest(path, &resp)\n}",
"func GetAWSInstanceSpotHourlyPrice(instance *AWSInstance) (float64, bool, error) {\n\tvar pricePerHour float64\n\tvar priceFound bool\n\n\tsess := session.Must(session.NewSession(&aws.Config{Region: aws.String(instance.Region)}))\n\tsvc := ec2.New(sess)\n\tinput := &ec2.DescribeSpotPriceHistoryInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: aws.String(\"availability-zone\"),\n\t\t\t\tValues: []*string{\n\t\t\t\t\taws.String(instance.AvailabilityZone),\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: aws.String(\"instance-type\"),\n\t\t\t\tValues: []*string{\n\t\t\t\t\taws.String(instance.Type),\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: aws.String(\"product-description\"),\n\t\t\t\tValues: []*string{\n\t\t\t\t\taws.String(\"Linux/UNIX (Amazon VPC)\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := svc.DescribeSpotPriceHistory(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn pricePerHour, priceFound, err\n\t}\n\n\tif len(result.SpotPriceHistory) > 0 {\n\t\tpricePerHour, err = strconv.ParseFloat(*result.SpotPriceHistory[0].SpotPrice, 64)\n\t\tif err != nil {\n\t\t\treturn pricePerHour, priceFound, err\n\t\t}\n\n\t\tpriceFound = true\n\t}\n\n\treturn pricePerHour, priceFound, nil\n}",
"func (g *Gemini) GetTickerPrice(p pair.CurrencyPair, assetType string) (ticker.Price, error) {\n\ttickerNew, err := ticker.GetTicker(g.GetName(), p, assetType)\n\tif err != nil {\n\t\treturn g.UpdateTicker(p, assetType)\n\t}\n\treturn tickerNew, nil\n}",
"func (c CoinTicker) GetFormattedPrice(t time.Time) (string, []error) {\n\n\tres, errors := c.generateResult()\n\n\tif len(errors) != 0 {\n\t\treturn \"\", errors\n\t}\n\tc.Cache.AddEntry(res, t.UTC())\n\tlastEntry := c.Cache.GetLast()\n\n\tkeys := make([]string, len(res.Result))\n\n\ti := 0\n\tfor k := range res.Result {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"\\n\" + t.Format(timeFormat) + \"\\n\")\n\tfor i := 0; i < len(keys); i++ {\n\t\tbuffer.WriteString(fmt.Sprintf(keys[i] + \": %f, \", decorateRatio(res.Result[keys[i]], lastEntry.CoinData.Result[keys[i]], c)(res.Result[keys[i]])))\n\t}\n\n\treturn buffer.String(), nil\n}",
"func getPrice(c int) Stock {\n\tresult, _ := getCurrentPrices(c)\n\treturn result\n}",
"func (b *Bitfinex) GetTickerPrice(p pair.CurrencyPair, assetType string) (ticker.Price, error) {\n\ttick, err := ticker.GetTicker(b.GetName(), p, ticker.Spot)\n\tif err != nil {\n\t\treturn b.UpdateTicker(p, assetType)\n\t}\n\treturn tick, nil\n}",
"func GetPrice(prices []*USDPrice, timestamp time.Time) (*USDPrice, error) {\n\tif len(prices) == 0 {\n\t\treturn nil, errNoPrices\n\t}\n\n\tvar lastPrice *USDPrice\n\n\t// Run through our prices until we find a timestamp that our price\n\t// point lies before. Since we always return the previous price, this\n\t// also works for timestamps that are exactly equal (at the cost of a\n\t// single extra iteration of this loop).\n\tfor _, price := range prices {\n\t\tif timestamp.Before(price.Timestamp) {\n\t\t\tbreak\n\t\t}\n\n\t\tlastPrice = price\n\t}\n\n\t// If we have broken our loop without setting the value of our last\n\t// price, we have a timestamp that is before the first entry in our\n\t// series. We expect our range of price points to start before any\n\t// timestamps we query, so we fail.\n\tif lastPrice == nil {\n\t\treturn nil, errPriceOutOfRange\n\t}\n\n\t// Otherwise, we return the last price that was before (or equal to)\n\t// our timestamp.\n\treturn lastPrice, nil\n}",
"func GetPrice(company string) (StockPrice, error) {\n\tvar stockPrice StockPrice\n\turl, err := getURL(company)\n\tif err != nil {\n\t\treturn stockPrice, err\n\t}\n\tdoc, err := getStockQuote(url)\n\tif err != nil {\n\t\treturn stockPrice, fmt.Errorf(\"Error in reading stock Price\")\n\t}\n\tdoc.Find(\".bsedata_bx\").Each(func(i int, s *goquery.Selection) {\n\t\tstockPrice.BSE.Price, _ = strconv.ParseFloat(s.Find(\".span_price_wrap\").Text(), 64)\n\t\tstockPrice.BSE.PreviousClose, _ = strconv.ParseFloat(s.Find(\".priceprevclose\").Text(), 64)\n\t\tstockPrice.BSE.Open, _ = strconv.ParseFloat(s.Find(\".priceopen\").Text(), 64)\n\t\tstockPrice.BSE.Variation, _ = strconv.ParseFloat(strings.Split(s.Find(\".span_price_change_prcnt\").Text(), \" \")[0], 64)\n\t\tstockPrice.BSE.Percentage, _ = strconv.ParseFloat(strings.Split(strings.Split(s.Find(\".span_price_change_prcnt\").Text(), \"%\")[0], \"(\")[1], 64)\n\t\tstockPrice.BSE.Volume, _ = strconv.ParseInt(strings.ReplaceAll(s.Find(\".volume_data\").Text(), \",\", \"\"), 10, 64)\n\t})\n\tdoc.Find(\".nsedata_bx\").Each(func(i int, s *goquery.Selection) {\n\t\tstockPrice.NSE.Price, _ = strconv.ParseFloat(s.Find(\".span_price_wrap\").Text(), 64)\n\t\tstockPrice.NSE.PreviousClose, _ = strconv.ParseFloat(s.Find(\".priceprevclose\").Text(), 64)\n\t\tstockPrice.NSE.Open, _ = strconv.ParseFloat(s.Find(\".priceopen\").Text(), 64)\n\t\tstockPrice.NSE.Variation, _ = strconv.ParseFloat(strings.Split(s.Find(\".span_price_change_prcnt\").Text(), \" \")[0], 64)\n\t\tstockPrice.NSE.Percentage, _ = strconv.ParseFloat(strings.Split(strings.Split(s.Find(\".span_price_change_prcnt\").Text(), \"%\")[0], \"(\")[1], 64)\n\t\tstockPrice.NSE.Volume, _ = strconv.ParseInt(strings.ReplaceAll(s.Find(\".volume_data\").Text(), \",\", \"\"), 10, 64)\n\t})\n\treturn stockPrice, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetMarketDetail returns the ticker for the specified symbol
|
func (h *HUOBI) GetMarketDetail(ctx context.Context, symbol currency.Pair) (Detail, error) {
vals := url.Values{}
symbolValue, err := h.FormatSymbol(symbol, asset.Spot)
if err != nil {
return Detail{}, err
}
vals.Set("symbol", symbolValue)
type response struct {
Response
Tick Detail `json:"tick"`
}
var result response
err = h.SendHTTPRequest(ctx, exchange.RestSpot, common.EncodeURLValues(huobiMarketDetail, vals), &result)
if result.ErrorMessage != "" {
return result.Tick, errors.New(result.ErrorMessage)
}
return result.Tick, err
}
|
[
"func (h *HUOBIHADAX) GetMarketDetail(symbol string) (Detail, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\n\ttype response struct {\n\t\tResponse\n\t\tTick Detail `json:\"tick\"`\n\t}\n\n\tvar result response\n\turlPath := fmt.Sprintf(\"%s/%s\", h.APIUrl, huobihadaxMarketDetail)\n\n\terr := h.SendHTTPRequest(common.EncodeURLValues(urlPath, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn result.Tick, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Tick, err\n}",
"func (c *Client) GetTicker(symbol string) (Ticker, error) {\n var ticker Ticker\n requestURL := fmt.Sprintf(\"/v1/pubticker/%s\", symbol)\n\n _, err := c.Request(\"GET\", requestURL, nil, &ticker)\n return ticker, err\n}",
"func GetTickerDetails(baseURL string, symbol string) (*store.Ticker, error) {\r\n\r\n\t// log.Printf(\"url: %s\", url)\r\n\tvar ticker *store.Ticker\r\n\tvar url = baseURL + \"tickers/\" + symbol\r\n\terr := runHTTPGet(url, &ticker)\r\n\treturn ticker, err\r\n}",
"func (m *Market) Ticker(symbol string) (MarketResponse, error) {\n\ttickerURL := URL(\"/v1/ticker\")\n\tvar result MarketResponse\n\tvalues := url.Values{}\n\n\tif symbol != \"\" {\n\t\tvalues.Add(\"symbol\", symbol)\n\t}\n\n\tresp, err := method.Get(tickerURL, nil, values)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn bodyToMarketResponse(resp.Body, &result)\n}",
"func GetStock(symbol string) string {\n\tcfg := config.NewConfig()\n\tresponse, err := request(\"GET\", \"https://www.alphavantage.co/query?function=OVERVIEW&symbol=\" + symbol + \"&apikey=\" + cfg.AlphaVantageKey, nil, \"\", nil)\n\n\tif err != nil {\n\t\treturn \"{\\\"error\\\": \\\"Not Found\\\"}\"\n\t}\n\n\treturn response\n}",
"func (h *HUOBIHADAX) GetMarketDetailMerged(symbol string) (DetailMerged, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\n\ttype response struct {\n\t\tResponse\n\t\tTick DetailMerged `json:\"tick\"`\n\t}\n\n\tvar result response\n\turlPath := fmt.Sprintf(\"%s/%s\", h.APIUrl, huobihadaxMarketDetailMerged)\n\n\terr := h.SendHTTPRequest(common.EncodeURLValues(urlPath, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn result.Tick, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Tick, err\n}",
"func (h *HUOBI) GetMarketDetailMerged(ctx context.Context, symbol currency.Pair) (DetailMerged, error) {\n\tvals := url.Values{}\n\tsymbolValue, err := h.FormatSymbol(symbol, asset.Spot)\n\tif err != nil {\n\t\treturn DetailMerged{}, err\n\t}\n\tvals.Set(\"symbol\", symbolValue)\n\n\ttype response struct {\n\t\tResponse\n\t\tTick DetailMerged `json:\"tick\"`\n\t}\n\n\tvar result response\n\n\terr = h.SendHTTPRequest(ctx, exchange.RestSpot, common.EncodeURLValues(huobiMarketDetailMerged, vals), &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn result.Tick, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Tick, err\n}",
"func (model *Trade) Symbol() string {\n\treturn model.Tbk.GetItemInCategory(\"Symbol\")\n}",
"func (m *MarketClient) GetSymbolOrderBookTicker(symbol string) (interface{}, error) {\n\tvar err error\n\tparams := \"\"\n\tif symbol != \"\" {\n\t\tparams = fmt.Sprintf(\"symbol=%s\", symbol)\n\t}\n\treq, err := m.Builder.Build(http.MethodGet, \"/api/v3/ticker/bookTicker\", params)\n\tif err != nil {\n\t\tlogger.Error(\"Failed to build url: %s\", err.Error())\n\t}\n\tres, err := binance.HttpRequest(req)\n\tvar parser map[string]interface{}\n\terr = json.Unmarshal(res, &parser)\n\tif _, ok := parser[\"code\"]; ok {\n\t\tresult := model.APIErrorResponse{}\n\t\terr = json.Unmarshal(res, &result)\n\t\treturn result, err\n\t}\n\tif params == \"\" {\n\t\tvar result []SymbolOrderBookTickerResponse\n\t\terr = json.Unmarshal(res, &result)\n\t\treturn result, err\n\t}\n\tresult := SymbolOrderBookTickerResponse{}\n\terr = json.Unmarshal(res, &result)\n\treturn result, err\n}",
"func (p *Bittrex) GetTicker(pair string) *TickerValue {\n\treturn nil\n}",
"func (b Bitstamp) GetTicker(market string) (marketObservables.Ticker, error) {\n\n\tcall := \"ticker/\" + market\n\n\tcontents, err := b.requester(call, nil)\n\n\traw := rawTicker{}\n\n\tif err == nil {\n\t\terr = json.Unmarshal(contents, &raw)\n\t\tif err != nil {\n\t\t\treturn marketObservables.Ticker{}, err\n\t\t}\n\t}\n\n\treturn raw.ticker(), err\n}",
"func (f *FTX) GetMarket(ctx context.Context, marketName string) (MarketData, error) {\n\tresp := struct {\n\t\tData MarketData `json:\"result\"`\n\t}{}\n\treturn resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, getMarket+marketName,\n\t\t&resp)\n}",
"func (c *Client) GetTradeMarketData(tickerSymbol string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET TRADE MARKET DATA ==========\")\n\turl := buildURL(path[\"nodes\"], \"trade-market-watch\")\n\n\tts := []string{tickerSymbol}\n\n\treturn c.do(\"GET\", url, \"\", ts)\n}",
"func (m *MarketClient) GetSymbolTickerPrice(symbol string) (interface{}, error) {\n\tvar err error\n\tparams := \"\"\n\tif symbol != \"\" {\n\t\tparams = fmt.Sprintf(\"symbol=%s\", symbol)\n\t}\n\treq, err := m.Builder.Build(http.MethodGet, \"/api/v3/ticker/price\", params)\n\tif err != nil {\n\t\tlogger.Error(\"Failed to build url: %s\", err.Error())\n\t}\n\tres, err := binance.HttpRequest(req)\n\tvar parser map[string]interface{}\n\terr = json.Unmarshal(res, &parser)\n\tif _, ok := parser[\"code\"]; ok {\n\t\tresult := model.APIErrorResponse{}\n\t\terr = json.Unmarshal(res, &result)\n\t\treturn result, err\n\t}\n\tif params == \"\" {\n\t\tvar result []SymbolPriceTickerResponse\n\t\terr = json.Unmarshal(res, &result)\n\t\treturn result, err\n\t}\n\tresult := SymbolPriceTickerResponse{}\n\terr = json.Unmarshal(res, &result)\n\treturn result, err\n}",
"func (s *ExchangeInfoService) GetSymbol(symbol string) (info SymbolInfo, err error) {\n\tinfo, ok := s.Symbols[symbol]\n\tif !ok {\n\t\treturn info, fmt.Errorf(\"symbol not found\")\n\t}\n\treturn info, nil\n}",
"func GetStockData(symbl string, consumerKey string) (Stock, error) {\n\t//Delay to not hit rate limit during larger individual stock pulls\n\ttime.Sleep(500 * time.Millisecond)\n\n\t//Create HTTP Client need for GET call below\n\tclient := &http.Client{}\n\n\t//Create map for Stock struct\n\tvar stockMap map[string]Stock\n\n\t//GET creation request for Quote data, variables used for stock symbl and key\n\trequest, err := http.NewRequest(\"GET\", fmt.Sprintf(\"https://api.tdameritrade.com/v1/marketdata/%s/quotes?apikey=%s\", symbl, consumerKey), nil)\n\n\t//Send HTTP request to server\n\tresp, err := client.Do(request)\n\tif err != nil {\n\t\treturn Stock{}, err\n\t}\n\t//fmt.Println(resp) //#Debugging print line\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn Stock{}, err\n\t}\n\t//fmt.Println(string(body)) //Debugging print line\n\n\t//Confirm Body data\n\tbodyCheck := errorhandlers.ConfirmBody(string(body))\n\n\tif bodyCheck != \"\" {\n\t\treturn Stock{}, errors.New(bodyCheck)\n\t}\n\n\t//Unmarshal response into struct to be used later\n\terr = json.Unmarshal(body, &stockMap)\n\tif err != nil {\n\t\treturn Stock{}, err\n\t}\n\n\t//Convert Map to struct\n\tstockStruct := makeStockStructFromMap(symbl, stockMap)\n\n\t//Return new Stock map\n\treturn stockStruct, nil\n}",
"func (h *HitBTC) GetSymbolsDetailed(ctx context.Context) ([]Symbol, error) {\n\tvar resp []Symbol\n\tpath := fmt.Sprintf(\"/%s\", apiV2Symbol)\n\treturn resp, h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)\n}",
"func loadTicker(ctx context.Context, symbol string) (*Ticker, error) {\n\tlogger := log.Ctx(ctx)\n\tredisPool := ctx.Value(\"redisPool\").(*redis.Pool)\n\n\tredisConn := redisPool.Get()\n\tdefer redisConn.Close()\n\n\tvar ticker *Ticker\n\n\tapiKey := ctx.Value(\"yahoofinance_apikey\").(string)\n\tapiHost := ctx.Value(\"yahoofinance_apihost\").(string)\n\n\t// pull recent response from redis (1 day expire), or go get from YF\n\tredisKey := \"yahoofinance/summary/\" + symbol\n\tresponse, err := redis.String(redisConn.Do(\"GET\", redisKey))\n\tif err == nil {\n\t\tlog.Info().Str(\"redis_key\", redisKey).Msg(\"redis cache hit\")\n\t} else {\n\t\tvar err error\n\t\tsummaryParams := map[string]string{\"symbol\": symbol}\n\t\tresponse, err = yahoofinance.GetFromYahooFinance(&apiKey, &apiHost, \"summary\", summaryParams)\n\t\tif err != nil {\n\t\t\tlogger.Warn().Err(err).\n\t\t\t\tStr(\"ticker\", symbol).\n\t\t\t\tMsg(\"Failed to retrieve ticker\")\n\t\t\treturn ticker, err\n\t\t}\n\t\t_, err = redisConn.Do(\"SET\", redisKey, response, \"EX\", 60*60*24)\n\t\tif err != nil {\n\t\t\tlogger.Error().Err(err).\n\t\t\t\tStr(\"ticker\", symbol).\n\t\t\t\tStr(\"redis_key\", redisKey).\n\t\t\t\tMsg(\"Failed to save to redis\")\n\t\t}\n\t}\n\n\tvar summaryResponse yahoofinance.YFSummaryResponse\n\tjson.NewDecoder(strings.NewReader(response)).Decode(&summaryResponse)\n\n\t// can't create exchange - all we get is ExchangeCode and I can't find a\n\t// table to translate those to Exchange MIC or Acronym... so I have to\n\t// link them manually for now\n\texchangeId, err := getExchangeByCode(ctx, summaryResponse.Price.ExchangeCode)\n\tif err != nil {\n\t\tlogger.Error().Err(err).\n\t\t\tStr(\"ticker\", summaryResponse.QuoteType.Symbol).\n\t\t\tStr(\"exchange_code\", summaryResponse.Price.ExchangeCode).\n\t\t\tMsg(\"Failed to find exchange_code matched to exchange mic record\")\n\t\treturn ticker, err\n\t}\n\n\t// create/update ticker\n\tticker = &Ticker{\n\t\t0, // id\n\t\tsummaryResponse.QuoteType.Symbol,\n\t\texchangeId,\n\t\tsummaryResponse.QuoteType.ShortName,\n\t\tsummaryResponse.QuoteType.LongName,\n\t\tsummaryResponse.SummaryProfile.Address1,\n\t\tsummaryResponse.SummaryProfile.City,\n\t\tsummaryResponse.SummaryProfile.State,\n\t\tsummaryResponse.SummaryProfile.Zip,\n\t\tsummaryResponse.SummaryProfile.Country,\n\t\tsummaryResponse.SummaryProfile.Website,\n\t\tsummaryResponse.SummaryProfile.Phone,\n\t\tsummaryResponse.SummaryProfile.Sector,\n\t\tsummaryResponse.SummaryProfile.Industry,\n\t\t\"now()\",\n\t\t\"\", // ms_performance_id\n\t\t\"\", // create_datetime\n\t\t\"\", // update_datetime\n\t}\n\terr = ticker.createOrUpdate(ctx)\n\tif err != nil {\n\t\tlogger.Error().Err(err).\n\t\t\tStr(\"ticker\", summaryResponse.QuoteType.Symbol).\n\t\t\tStr(\"exchange_code\", summaryResponse.QuoteType.ExchangeCode).\n\t\t\tMsg(\"Failed to create or update ticker\")\n\t\treturn ticker, err\n\t}\n\n\ttickerDescription := &TickerDescription{0, ticker.TickerId, summaryResponse.SummaryProfile.LongBusinessSummary, \"\", \"\"}\n\terr = tickerDescription.createIfNew(ctx)\n\tif err != nil {\n\t\tlogger.Error().Err(err).\n\t\t\tStr(\"ticker\", ticker.TickerSymbol).\n\t\t\tMsg(\"Failed to create ticker description\")\n\t}\n\n\t// create upgrade/downgrade recommendations\n\tfor _, updown := range summaryResponse.UpgradeDowngradeHistory.Histories {\n\t\tupdownDate := UnixToDatetimeStr(updown.GradeDate)\n\t\tUpDown := TickerUpDown{0, ticker.TickerId, updown.Action, updown.FromGrade, updown.ToGrade, updownDate, updown.Firm, \"\", \"\", \"\"}\n\t\tUpDown.createIfNew(ctx)\n\t}\n\n\t// create/update ticker_attributes\n\tticker.createOrUpdateAttribute(ctx, \"sector\", summaryResponse.SummaryProfile.Sector)\n\tticker.createOrUpdateAttribute(ctx, \"industry\", summaryResponse.SummaryProfile.Industry)\n\tticker.createOrUpdateAttribute(ctx, \"short_ratio\", summaryResponse.DefaultKeyStatistics.ShortRatio.Fmt)\n\tticker.createOrUpdateAttribute(ctx, \"last_split_date\", summaryResponse.DefaultKeyStatistics.LastSplitDate.Fmt)\n\tticker.createOrUpdateAttribute(ctx, \"last_dividend_date\", summaryResponse.DefaultKeyStatistics.LastDividendDate.Fmt)\n\tticker.createOrUpdateAttribute(ctx, \"shares_short\", summaryResponse.DefaultKeyStatistics.SharesShort.Fmt)\n\tticker.createOrUpdateAttribute(ctx, \"float_shares\", summaryResponse.DefaultKeyStatistics.FloatShares.Fmt)\n\tticker.createOrUpdateAttribute(ctx, \"shares_outstanding\", summaryResponse.DefaultKeyStatistics.SharesOutstanding.Fmt)\n\n\treturn ticker, nil\n}",
"func (o *MutualFundSectorExposure) GetSymbol() string {\n\tif o == nil || o.Symbol == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Symbol\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetSymbols returns an array of symbols supported by Huobi
|
func (h *HUOBI) GetSymbols(ctx context.Context) ([]Symbol, error) {
type response struct {
Response
Symbols []Symbol `json:"data"`
}
var result response
err := h.SendHTTPRequest(ctx, exchange.RestSpot, huobiSymbols, &result)
if result.ErrorMessage != "" {
return nil, errors.New(result.ErrorMessage)
}
return result.Symbols, err
}
|
[
"func (h *HUOBIHADAX) GetSymbols() ([]Symbol, error) {\n\ttype response struct {\n\t\tResponse\n\t\tSymbols []Symbol `json:\"data\"`\n\t}\n\n\tvar result response\n\turlPath := fmt.Sprintf(\"%s/v%s/%s/%s\", h.APIUrl, huobihadaxAPIVersion, huobihadaxAPIName, huobihadaxSymbols)\n\n\terr := h.SendHTTPRequest(urlPath, &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Symbols, err\n}",
"func (sp *SymbolsProvider) getSymbols() (symbols []symbol, err error) {\n\tvar b []byte\n\tvar resp symbolsResponse\n\tif b, err = sp.httpClient.Get(apiSymbols, httpclient.Params(), false); err != nil {\n\t\treturn\n\t}\n\tif err = json.Unmarshal(b, &resp); err != nil {\n\t\treturn\n\t}\n\tif !resp.Success {\n\t\terr = fmt.Errorf(\"[KUCOIN] Error getting symbols: %v\", resp.Message)\n\t\treturn\n\t}\n\tfor _, smb := range resp.Data {\n\t\tsymbols = append(symbols, smb)\n\t}\n\n\treturn\n}",
"func (m Market) Symbols() ([]aurora.Symbol, error) {\n\tvar info, err = binance.GetExchangeInfo()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar res = make([]aurora.Symbol, 0)\n\n\tfor _, s := range info.Symbols {\n\t\tres = append(res, aurora.Symbol{\n\t\t\tBaseAsset: s.BaseAsset,\n\t\t\tQuoteAsset: s.QuoteAsset,\n\t\t})\n\t}\n\n\treturn res, nil\n}",
"func getAllCompanySymbols() ([]string){\r\n return []string{}\r\n}",
"func (m Market) Symbols() ([]aurora.Symbol, error) {\n\tvar baseAssets []string\n\tvar quoteAssets []string\n\tvar wg sync.WaitGroup\n\tvar err1 error\n\tvar err2 error\n\n\twg.Add(2)\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tvar res, err = http.Get(\"https://api.kucoin.com/v1/open/markets\")\n\t\tif err != nil {\n\t\t\terr1 = err\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\n\t\tvar markets struct {\n\t\t\tAssets []string `json:\"data\"`\n\t\t}\n\t\tif err := json.NewDecoder(res.Body).Decode(&markets); err != nil {\n\t\t\terr1 = err\n\t\t\treturn\n\t\t}\n\t\tbaseAssets = markets.Assets\n\t}()\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tvar res, err = http.Get(\"https://api.kucoin.com/v1/market/open/coins\")\n\t\tif err != nil {\n\t\t\terr2 = err\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\n\t\tvar coins struct {\n\t\t\tData []struct {\n\t\t\t\tAsset string `json:\"coin\"`\n\t\t\t} `json:\"data\"`\n\t\t}\n\t\tif err := json.NewDecoder(res.Body).Decode(&coins); err != nil {\n\t\t\terr2 = err\n\t\t\treturn\n\t\t}\n\t\tquoteAssets = make([]string, 0)\n\t\tfor _, a := range coins.Data {\n\t\t\tquoteAssets = append(quoteAssets, a.Asset)\n\t\t}\n\t}()\n\n\twg.Wait()\n\n\tif err1 != nil {\n\t\treturn nil, err1\n\t}\n\tif err2 != nil {\n\t\treturn nil, err2\n\t}\n\n\tvar symbols = make([]aurora.Symbol, 0)\n\tfor _, ba := range baseAssets {\n\t\tfor _, qa := range quoteAssets {\n\t\t\tsymbols = append(symbols, aurora.Symbol{BaseAsset: ba, QuoteAsset: qa})\n\t\t}\n\t}\n\n\treturn symbols, nil\n}",
"func (h *HitBTC) GetSymbols(ctx context.Context, symbol string) ([]string, error) {\n\tvar resp []Symbol\n\tpath := fmt.Sprintf(\"/%s/%s\", apiV2Symbol, symbol)\n\n\tret := make([]string, 0, len(resp))\n\terr := h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tfor _, x := range resp {\n\t\tret = append(ret, x.ID)\n\t}\n\treturn ret, err\n}",
"func (hc *Client) GetSymbolsPair() ([]Symbol, error) {\n\tvar (\n\t\tsymbolReply SymbolsReply\n\t)\n\tendpoint := fmt.Sprintf(\"%s/v1/common/symbols\", huobiEndpoint)\n\tres, err := hc.sendRequest(\n\t\thttp.MethodGet,\n\t\tendpoint,\n\t\tnil,\n\t\tfalse,\n\t)\n\tif err != nil {\n\t\treturn symbolReply.Data, err\n\t}\n\terr = json.Unmarshal(res, &symbolReply)\n\tif err != nil {\n\t\treturn symbolReply.Data, err\n\t}\n\tif symbolReply.Status != StatusOK.String() {\n\t\treturn symbolReply.Data, fmt.Errorf(\"unexpected reply status %s\", symbolReply.Status)\n\t}\n\treturn symbolReply.Data, nil\n}",
"func (a *API) GetStockSymbol(exchange string) []string {\n\treturn []string{}\n}",
"func (s *DeliveryService) GetSymbols() []string {\n\treturn s.symbols\n}",
"func GetSymbols(allSymbols string) []string {\n\tallSymbols = strings.ToUpper(allSymbols)\n\treturn strings.Split(allSymbols, \",\")\n}",
"func (op CosinusOperator) GetSupportedSymbols() map[string]bool {\n\tsupportedSymbols := make(map[string]bool)\n\tsupportedSymbols[\"cos\"] = true\n\treturn supportedSymbols\n}",
"func (m *JSONFileManager) GetAllSymbols() []string {\n\treturn m.symbols\n}",
"func getSymbols(astSymbols []string) []symbols.Symbol {\n\tsymbls := make([]symbols.Symbol, len(astSymbols))\n\tfor i, s := range astSymbols {\n\t\tsymbls[i] = symbols.FromASTString(s)\n\t}\n\treturn symbls\n}",
"func (m *Market) Symbols() (MarketResponse, error) {\n\tsymbolURL := URL(\"/v1/symbols\")\n\n\tvar result MarketResponse\n\tresp, err := method.Get(symbolURL, nil, nil)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn bodyToMarketResponse(resp.Body, &result)\n}",
"func getAllSymbols(quoteAssets []string) []string {\n\tvalidSymbols := make([]string, 0)\n\tvar tradingSymbols []string\n\n\tm := ExchangeInfo{}\n\terr := getJSON(\"https://api.binance.com/api/v1/exchangeInfo\", &m)\n\tif err != nil {\n\t\tlog.Error(\"Binance /exchangeInfo API error: %v\", err)\n\t\ttradingSymbols = []string{\"BTC\", \"ETH\", \"LTC\", \"BNB\"}\n\t} else {\n\t\ttradingSymbols = getTradingSymbols(quoteAssets, m)\n\t}\n\n\tclient := binance.NewClient(\"\", \"\")\n\t// Double check each symbol is working as intended\n\tfor _, s := range tradingSymbols {\n\t\t_, err := client.NewKlinesService().Symbol(s + quoteAssets[0]).Interval(\"1m\").Do(context.Background())\n\t\tif err == nil {\n\t\t\tvalidSymbols = append(validSymbols, s)\n\t\t}\n\t}\n\n\treturn validSymbols\n}",
"func (o *Object) Symbols() []*Symbol {\n\tsymbols := o.self.symbols(false, nil)\n\tret := make([]*Symbol, len(symbols))\n\tfor i, sym := range symbols {\n\t\tret[i], _ = sym.(*Symbol)\n\t}\n\treturn ret\n}",
"func readSymbols(bs index.ByteSlice, version int, off int) ([]string, map[uint32]string, error) {\n\tif off == 0 {\n\t\treturn nil, nil, nil\n\t}\n\td := encoding.NewDecbufAt(bs, off, castagnoliTable)\n\n\tvar (\n\t\torigLen = d.Len()\n\t\tcnt = d.Be32int()\n\t\tbasePos = uint32(off) + 4\n\t\tnextPos = basePos + uint32(origLen-d.Len())\n\t\tsymbolSlice []string\n\t\tsymbols = map[uint32]string{}\n\t)\n\tif version == index.FormatV2 {\n\t\tsymbolSlice = make([]string, 0, cnt)\n\t}\n\n\tfor d.Err() == nil && d.Len() > 0 && cnt > 0 {\n\t\ts := d.UvarintStr()\n\n\t\tif version == index.FormatV2 {\n\t\t\tsymbolSlice = append(symbolSlice, s)\n\t\t} else {\n\t\t\tsymbols[nextPos] = s\n\t\t\tnextPos = basePos + uint32(origLen-d.Len())\n\t\t}\n\t\tcnt--\n\t}\n\treturn symbolSlice, symbols, errors.Wrap(d.Err(), \"read symbols\")\n}",
"func getSymbols(reels [5]uint8) ([5][3]Symbol, uint8) {\n\tresult := [5][3]Symbol{}\n\n\tvar scatters uint8\n\tvar top, bot uint8\n\tfor reel, mid := range reels {\n\t\ttop = mid - 1\n\t\tbot = mid + 1\n\n\t\tif mid == 0 {\n\t\t\ttop = 31\n\t\t} else if mid == 31 {\n\t\t\tbot = 0\n\t\t}\n\n\t\tresult[reel] = [3]Symbol{\n\t\t\tReals[reel][top],\n\t\t\tReals[reel][mid],\n\t\t\tReals[reel][bot],\n\t\t}\n\n\t\tfor _, s := range result[reel] {\n\t\t\tif s == Scatter {\n\t\t\t\tscatters++\n\t\t\t}\n\t\t}\n\t}\n\treturn result, scatters\n}",
"func (m *mockFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {\n\tswitch r.String() {\n\tcase \"line[13]\":\n\t\treturn []*plugin.Sym{\n\t\t\t{\n\t\t\t\tName: []string{\"line1000\"}, File: m.name,\n\t\t\t\tStart: 0x1000, End: 0x1003,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: []string{\"line3000\"}, File: m.name,\n\t\t\t\tStart: 0x3000, End: 0x3004,\n\t\t\t},\n\t\t}, nil\n\t}\n\treturn nil, fmt.Errorf(\"unimplemented\")\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetCurrencies returns a list of currencies supported by Huobi
|
func (h *HUOBI) GetCurrencies(ctx context.Context) ([]string, error) {
type response struct {
Response
Currencies []string `json:"data"`
}
var result response
err := h.SendHTTPRequest(ctx, exchange.RestSpot, huobiCurrencies, &result)
if result.ErrorMessage != "" {
return nil, errors.New(result.ErrorMessage)
}
return result.Currencies, err
}
|
[
"func (h *HUOBIHADAX) GetCurrencies() ([]string, error) {\n\ttype response struct {\n\t\tResponse\n\t\tCurrencies []string `json:\"data\"`\n\t}\n\n\tvar result response\n\turlPath := fmt.Sprintf(\"%s/v%s/%s/%s\", h.APIUrl, huobihadaxAPIVersion, huobihadaxAPIName, huobihadaxCurrencies)\n\n\terr := h.SendHTTPRequest(urlPath, &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Currencies, err\n}",
"func (gw2 *GW2Api) Currencies() (res []int, err error) {\n\tver := \"v2\"\n\ttag := \"currencies\"\n\terr = gw2.fetchEndpoint(ver, tag, nil, &res)\n\treturn\n}",
"func (p *Poloniex) GetCurrencies(ctx context.Context) (map[string]*Currencies, error) {\n\ttype Response struct {\n\t\tData map[string]*Currencies\n\t}\n\tresp := Response{}\n\treturn resp.Data, p.SendHTTPRequest(ctx,\n\t\texchange.RestSpot,\n\t\t\"/public?command=returnCurrencies&includeMultiChainCurrencies=true\",\n\t\t&resp.Data,\n\t)\n}",
"func (s *CurrenciesService) List(ctx context.Context, opt *CurrenciesListOptions) (*CurrenciesResponse, *Response, error) {\n\treq, err := s.client.NewRequest(http.MethodGet, \"/currencies\", opt, nil)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar record *CurrenciesResponse\n\n\tresp, err := s.client.Do(ctx, req, &record)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn record, resp, nil\n}",
"func GetKnownCurrencies(uc *mw.IcopContext, c *gin.Context) {\n\n\t//get the currency\n\tres, err := adminAPIClient.GetKnownCurrencies(c, &pb.Empty{Base: NewBaseRequest(uc)})\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, cerr.LogAndReturnError(uc.Log, err, \"Error getting known currencies\", cerr.GeneralError))\n\t\treturn\n\t}\n\n\tcrs := make([]GetKnownCurrenciesResponse, len(res.Currencies))\n\tfor i, cr := range res.Currencies {\n\t\tcrs[i] = GetKnownCurrenciesResponse{\n\t\t\tID: cr.Id,\n\t\t\tName: cr.Name,\n\t\t\tIssuerPublicKey: cr.IssuerPublicKey,\n\t\t\tAssetCode: cr.AssetCode,\n\t\t\tShortDescription: cr.ShortDescription,\n\t\t\tLongDescription: cr.LongDescription,\n\t\t\tOrderIndex: cr.OrderIndex,\n\t\t}\n\t}\n\n\tc.JSON(http.StatusOK, crs)\n\n}",
"func GetCurrencies(constraints string) (payload Currency) {\n\treturn getCurrencies(constraints, http.DefaultClient.Get)\n}",
"func GetCryptocurrencies() Currencies {\n\treturn storage.GetCryptocurrencies()\n}",
"func getAllCurrencies(w http.ResponseWriter, r *http.Request) {\n\tnumCurrencies := len(currencies)\n\tvar result []currencyInfo\n\tresult = make([]currencyInfo, numCurrencies)\n\tfor i := range currencies {\n\t\tcurrencyInfoLock[i].Lock()\n\t\tresult[i] = currencies[i]\n\t\tcurrencyInfoLock[i].Unlock()\n\t}\n\tvar resp = getAllCurrenciesResponse{\n\t\tCurrencies: result,\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(resp)\n\n}",
"func (p Provider) GetSupportedCurrencies() []string {\n\treturn p.config.SupportedCurrencies\n}",
"func (a *EarnUniApiService) ListUniCurrencies(ctx context.Context) ([]UniCurrency, *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 []UniCurrency\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/earn/uni/currencies\"\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\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tctx = context.WithValue(ctx, ContextPublic, true)\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 + \", \" + string(localVarBody),\n\t\t}\n\t\tvar gateErr GateAPIError\n\t\tif e := a.client.decode(&gateErr, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\")); e == nil && gateErr.Label != \"\" {\n\t\t\tgateErr.APIError = newErr\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, gateErr\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 (c *Connecter) GetCurrenciesTicker(ctReq CurrenciesTickerRequest) ([]CurrenciesTickerResponse, error) {\n\treq, err := c.newRequest(currenciesTickerURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Formulate query params.\n\tq := req.URL.Query()\n\tq.Add(\"key\", c.apiKey)\n\tif len(ctReq.Ids) > 0 {\n\t\tq.Add(\"ids\", strings.Join(ctReq.Ids[:], \",\"))\n\t}\n\tif len(ctReq.Interval) > 0 {\n\t\tq.Add(\"interval\", strings.Join(ctReq.Interval[:], \",\"))\n\t}\n\tif ctReq.Convert != \"\" {\n\t\tq.Add(\"convert\", ctReq.Convert)\n\t}\n\tif ctReq.Status != \"\" {\n\t\tq.Add(\"status\", ctReq.Status)\n\t}\n\tif ctReq.Filter != \"\" {\n\t\tq.Add(\"filter\", ctReq.Filter)\n\t}\n\tif ctReq.Sort != \"\" {\n\t\tq.Add(\"sort\", ctReq.Sort)\n\t}\n\tif ctReq.IncludeTransparency {\n\t\tq.Add(\"include-transparency\", strconv.FormatBool(ctReq.IncludeTransparency))\n\t}\n\tif ctReq.PerPage != 0 {\n\t\tq.Add(\"per-page\", strconv.Itoa(ctReq.PerPage))\n\t}\n\tif ctReq.Page != 0 {\n\t\tq.Add(\"page\", strconv.Itoa(ctReq.Page))\n\t}\n\treq.URL.RawQuery = q.Encode()\n\n\t// Do the requset to server.\n\tresp, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Creates formatted response from the server's response.\n\tvar ctResp []CurrenciesTickerResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&ctResp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ctResp, nil\n}",
"func GetCurrencies(queryRoute string, cdc *codec.Codec) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"currencies\",\n\t\tShort: \"Get all registered currencies\",\n\t\tExample: \"currencies\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcliCtx := context.NewCLIContext().WithCodec(cdc)\n\n\t\t\t// query and parse the result\n\t\t\tres, _, err := cliCtx.QueryWithData(fmt.Sprintf(\"custom/%s/%s\", queryRoute, types.QueryCurrencies), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tvar out ccstorage.Currencies\n\t\t\tcdc.MustUnmarshalJSON(res, &out)\n\n\t\t\treturn cliCtx.PrintOutput(out)\n\t\t},\n\t}\n\n\treturn cmd\n}",
"func TestWsGetCurrencies(t *testing.T) {\n\tsetupWsAuth(t)\n\t_, err := h.wsGetCurrencies(currency.BTC)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}",
"func (s *Currencies) List(params *list_params.ListParams) ([]*models.Currency, error) {\n\tvar currencies []*models.Currency\n\n\tquery := processDbQuery(params, s.db)\n\tif err := query.Find(¤cies).Error; err != nil {\n\t\treturn currencies, err\n\t}\n\treturn currencies, nil\n}",
"func getKnownCurrencies() []Currency {\n\treturn []Currency{\n\t\t{\n\t\t\tName: \"GBP\",\n\t\t\tCountryName: \"United Kingdom\",\n\t\t\tSymbol: \"£\",\n\t\t},\n\t\t{\n\t\t\tName: \"USD\",\n\t\t\tCountryName: \"United States\",\n\t\t\tSymbol: \"$\",\n\t\t},\n\t\t{\n\t\t\tName: \"EUR\",\n\t\t\tCountryName: \"Europe\",\n\t\t\tSymbol: \"€\",\n\t\t},\n\t}\n}",
"func GetFiatCurrencies() Currencies {\n\treturn storage.GetFiatCurrencies()\n}",
"func (r *CompanyCurrenciesCollectionRequest) Get(ctx context.Context) ([]Currency, error) {\n\treturn r.GetN(ctx, 0)\n}",
"func (c *CurrencyService) GetCurrencyList(\n\tctx context.Context,\n\treq *pb.CurrencyRequest,\n) (*pb.CurrencyList, error) {\n\n\tif req.GetNumber() == 0 && req.GetCode() == \"\" {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.InvalidArgument,\n\t\t\t\"must provide currency number or code\",\n\t\t)\n\t}\n\n\tvar items []*pb.Currency\n\tfor _, cur := range c.data {\n\t\tif cur.GetNumber() == req.GetNumber() || cur.GetCode() == req.GetCode() {\n\t\t\titems = append(items, cur)\n\t\t}\n\t}\n\n\treturn &pb.CurrencyList{Items: items}, nil\n}",
"func GetVersusCurrencysList() (*types.SimpleSupportedVSCurrencies, error) {\n\tcg := gecko.NewClient(nil)\n\tcl, err := cg.SimpleSupportedVSCurrencies()\n\n\tif err != nil {\n\t\treturn cl, err\n\t}\n\n\treturn cl, err\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetCurrenciesIncludingChains returns currency and chain data
|
func (h *HUOBI) GetCurrenciesIncludingChains(ctx context.Context, curr currency.Code) ([]CurrenciesChainData, error) {
resp := struct {
Data []CurrenciesChainData `json:"data"`
}{}
vals := url.Values{}
if !curr.IsEmpty() {
vals.Set("currency", curr.Lower().String())
}
path := common.EncodeURLValues(huobiCurrenciesReference, vals)
err := h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)
if err != nil {
return nil, err
}
return resp.Data, nil
}
|
[
"func (p *Poloniex) GetCurrencies(ctx context.Context) (map[string]*Currencies, error) {\n\ttype Response struct {\n\t\tData map[string]*Currencies\n\t}\n\tresp := Response{}\n\treturn resp.Data, p.SendHTTPRequest(ctx,\n\t\texchange.RestSpot,\n\t\t\"/public?command=returnCurrencies&includeMultiChainCurrencies=true\",\n\t\t&resp.Data,\n\t)\n}",
"func (gw2 *GW2Api) Currencies() (res []int, err error) {\n\tver := \"v2\"\n\ttag := \"currencies\"\n\terr = gw2.fetchEndpoint(ver, tag, nil, &res)\n\treturn\n}",
"func (h *HUOBIHADAX) GetCurrencies() ([]string, error) {\n\ttype response struct {\n\t\tResponse\n\t\tCurrencies []string `json:\"data\"`\n\t}\n\n\tvar result response\n\turlPath := fmt.Sprintf(\"%s/v%s/%s/%s\", h.APIUrl, huobihadaxAPIVersion, huobihadaxAPIName, huobihadaxCurrencies)\n\n\terr := h.SendHTTPRequest(urlPath, &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Currencies, err\n}",
"func (h *HUOBI) GetCurrencies(ctx context.Context) ([]string, error) {\n\ttype response struct {\n\t\tResponse\n\t\tCurrencies []string `json:\"data\"`\n\t}\n\n\tvar result response\n\n\terr := h.SendHTTPRequest(ctx, exchange.RestSpot, huobiCurrencies, &result)\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Currencies, err\n}",
"func GetCurrencies(constraints string) (payload Currency) {\n\treturn getCurrencies(constraints, http.DefaultClient.Get)\n}",
"func GetCurrencies(queryRoute string, cdc *codec.Codec) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"currencies\",\n\t\tShort: \"Get all registered currencies\",\n\t\tExample: \"currencies\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcliCtx := context.NewCLIContext().WithCodec(cdc)\n\n\t\t\t// query and parse the result\n\t\t\tres, _, err := cliCtx.QueryWithData(fmt.Sprintf(\"custom/%s/%s\", queryRoute, types.QueryCurrencies), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tvar out ccstorage.Currencies\n\t\t\tcdc.MustUnmarshalJSON(res, &out)\n\n\t\t\treturn cliCtx.PrintOutput(out)\n\t\t},\n\t}\n\n\treturn cmd\n}",
"func (c *Connecter) GetCurrenciesTicker(ctReq CurrenciesTickerRequest) ([]CurrenciesTickerResponse, error) {\n\treq, err := c.newRequest(currenciesTickerURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Formulate query params.\n\tq := req.URL.Query()\n\tq.Add(\"key\", c.apiKey)\n\tif len(ctReq.Ids) > 0 {\n\t\tq.Add(\"ids\", strings.Join(ctReq.Ids[:], \",\"))\n\t}\n\tif len(ctReq.Interval) > 0 {\n\t\tq.Add(\"interval\", strings.Join(ctReq.Interval[:], \",\"))\n\t}\n\tif ctReq.Convert != \"\" {\n\t\tq.Add(\"convert\", ctReq.Convert)\n\t}\n\tif ctReq.Status != \"\" {\n\t\tq.Add(\"status\", ctReq.Status)\n\t}\n\tif ctReq.Filter != \"\" {\n\t\tq.Add(\"filter\", ctReq.Filter)\n\t}\n\tif ctReq.Sort != \"\" {\n\t\tq.Add(\"sort\", ctReq.Sort)\n\t}\n\tif ctReq.IncludeTransparency {\n\t\tq.Add(\"include-transparency\", strconv.FormatBool(ctReq.IncludeTransparency))\n\t}\n\tif ctReq.PerPage != 0 {\n\t\tq.Add(\"per-page\", strconv.Itoa(ctReq.PerPage))\n\t}\n\tif ctReq.Page != 0 {\n\t\tq.Add(\"page\", strconv.Itoa(ctReq.Page))\n\t}\n\treq.URL.RawQuery = q.Encode()\n\n\t// Do the requset to server.\n\tresp, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Creates formatted response from the server's response.\n\tvar ctResp []CurrenciesTickerResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&ctResp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ctResp, nil\n}",
"func GetCryptocurrencies() Currencies {\n\treturn storage.GetCryptocurrencies()\n}",
"func (b *CompanyRequestBuilder) Currencies() *CompanyCurrenciesCollectionRequestBuilder {\n\tbb := &CompanyCurrenciesCollectionRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/currencies\"\n\treturn bb\n}",
"func (v *ChainClient) GetChains(pr, ca, caver, dig, netctrlint string) ([]Chain, error) {\n\t//Construct key and tag to select the entry\n\tkey := ChainKey{\n\t\tProject: pr,\n\t\tCompositeApp: ca,\n\t\tCompositeAppVersion: caver,\n\t\tDigName: dig,\n\t\tNetControlIntent: netctrlint,\n\t\tNetworkChain: \"\",\n\t}\n\n\tvar resp []Chain\n\tvalues, err := db.DBconn.Find(v.db.storeName, key, v.db.tagMeta)\n\tif err != nil {\n\t\treturn []Chain{}, pkgerrors.Wrap(err, \"Get Chains\")\n\t}\n\n\tfor _, value := range values {\n\t\tcp := Chain{}\n\t\terr = db.DBconn.Unmarshal(value, &cp)\n\t\tif err != nil {\n\t\t\treturn []Chain{}, pkgerrors.Wrap(err, \"Unmarshalling Value\")\n\t\t}\n\t\tresp = append(resp, cp)\n\t}\n\n\treturn resp, nil\n}",
"func TestWsGetCurrencies(t *testing.T) {\n\tsetupWsAuth(t)\n\t_, err := h.wsGetCurrencies(currency.BTC)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}",
"func GetRelatableCurrencies(p currency.Pair, incOrig, incUSDT bool) currency.Pairs {\n\tvar pairs currency.Pairs\n\n\taddPair := func(p currency.Pair) {\n\t\tif pairs.Contains(p, true) {\n\t\t\treturn\n\t\t}\n\t\tpairs = append(pairs, p)\n\t}\n\n\tbuildPairs := func(p currency.Pair, incOrig bool) {\n\t\tif incOrig {\n\t\t\taddPair(p)\n\t\t}\n\n\t\tfirst := currency.GetTranslation(p.Base)\n\t\tif !first.Equal(p.Base) {\n\t\t\taddPair(currency.NewPair(first, p.Quote))\n\n\t\t\tsecond := currency.GetTranslation(p.Quote)\n\t\t\tif !second.Equal(p.Quote) {\n\t\t\t\taddPair(currency.NewPair(first, second))\n\t\t\t}\n\t\t}\n\n\t\tsecond := currency.GetTranslation(p.Quote)\n\t\tif !second.Equal(p.Quote) {\n\t\t\taddPair(currency.NewPair(p.Base, second))\n\t\t}\n\t}\n\n\tbuildPairs(p, incOrig)\n\tbuildPairs(p.Swap(), incOrig)\n\n\tif !incUSDT {\n\t\tpairs = pairs.RemovePairsByFilter(currency.USDT)\n\t}\n\n\treturn pairs\n}",
"func ChartCurrencyPairs(uc *mw.IcopContext, c *gin.Context) {\n\n\tdata := []exchangeCurrencyPairs{}\n\tschema := utils.GetSchemaForQuery()\n\n\tcurrencies, _ := models.Currencies().All(utils.DB)\n\tfor _, sourceCurrency := range currencies {\n\n\t\tdestinationCurrencies, err := models.Currencies(\n\t\t\tqm.Select(schema+\"currency.*\"),\n\t\t\tqm.InnerJoin(schema+\"history_chart_data h on h.destination_currency_id = \"+schema+\"currency.id\"),\n\t\t\tqm.Where(\"h.source_currency_id =?\", sourceCurrency.ID),\n\t\t\tqm.GroupBy(schema+\"currency.id\"),\n\t\t).All(utils.DB)\n\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, cerr.LogAndReturnError(uc.Log, err, \"Error getting data from db\", cerr.GeneralError))\n\t\t}\n\n\t\tpair := exchangeCurrencyPairs{}\n\t\tpair.SourceCurrency.AssetCode = sourceCurrency.CurrencyCode\n\t\tpair.SourceCurrency.IssuerPublicKey = sourceCurrency.CurrencyIssuer\n\n\t\tfor _, destinationCurrency := range destinationCurrencies {\n\t\t\tpair.DestinationCurrencies = append(pair.DestinationCurrencies, destinationCurrency.CurrencyCode)\n\t\t}\n\n\t\tif len(pair.DestinationCurrencies) > 0 {\n\t\t\tdata = append(data, pair)\n\t\t}\n\n\t}\n\n\tc.JSON(http.StatusOK, data)\n\n}",
"func (pkg CurrPkg) GetCurrency() (res ArrCurrData, err error) {\n\t// get result\n\trows, err := DBConn.Queryx(queryGetAllCurrency)\n\tif err != nil {\n\t\tlog.Errorf(err, \"error when querying all currency data, with data:[%+v]\", res)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar temp CurrData\n\t\terr = rows.Scan(\n\t\t\t&temp.From,\n\t\t\t&temp.To,\n\t\t\t&temp.Status,\n\t\t)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Error when scan data\")\n\t\t\treturn\n\t\t}\n\n\t\tres.Data = append(res.Data, temp)\n\t}\n\n\treturn\n}",
"func GetTotalMarketCryptocurrencies() ([]Code, error) {\n\treturn storage.GetTotalMarketCryptocurrencies()\n}",
"func GetKnownCurrencies(uc *mw.IcopContext, c *gin.Context) {\n\n\t//get the currency\n\tres, err := adminAPIClient.GetKnownCurrencies(c, &pb.Empty{Base: NewBaseRequest(uc)})\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, cerr.LogAndReturnError(uc.Log, err, \"Error getting known currencies\", cerr.GeneralError))\n\t\treturn\n\t}\n\n\tcrs := make([]GetKnownCurrenciesResponse, len(res.Currencies))\n\tfor i, cr := range res.Currencies {\n\t\tcrs[i] = GetKnownCurrenciesResponse{\n\t\t\tID: cr.Id,\n\t\t\tName: cr.Name,\n\t\t\tIssuerPublicKey: cr.IssuerPublicKey,\n\t\t\tAssetCode: cr.AssetCode,\n\t\t\tShortDescription: cr.ShortDescription,\n\t\t\tLongDescription: cr.LongDescription,\n\t\t\tOrderIndex: cr.OrderIndex,\n\t\t}\n\t}\n\n\tc.JSON(http.StatusOK, crs)\n\n}",
"func getAllCurrencies(w http.ResponseWriter, r *http.Request) {\n\tnumCurrencies := len(currencies)\n\tvar result []currencyInfo\n\tresult = make([]currencyInfo, numCurrencies)\n\tfor i := range currencies {\n\t\tcurrencyInfoLock[i].Lock()\n\t\tresult[i] = currencies[i]\n\t\tcurrencyInfoLock[i].Unlock()\n\t}\n\tvar resp = getAllCurrenciesResponse{\n\t\tCurrencies: result,\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(resp)\n\n}",
"func (m *MockCoinCapAPI) GetRates(currencyID string) (*entity.Cryptocurrency, error) {\n\tcurrency := entity.Cryptocurrency{\n\t\tCurrencyId: currencyID,\n\t\tSymbol: \"CUR\",\n\t\tCurrencySymbol: \"C\",\n\t\tType: \"crypto\",\n\t\tRateUsd: fmt.Sprintf(\"%f\", rand.ExpFloat64()),\n\t}\n\treturn ¤cy, nil\n}",
"func (f *FXHandler) GetCurrencyData(baseCurrency string, currencies []string) (map[string]float64, error) {\n\tvar fullRange = currencies\n\n\tif !common.StringDataCompareInsensitive(currencies, baseCurrency) {\n\t\tfullRange = append(fullRange, baseCurrency)\n\t}\n\n\tf.mtx.Lock()\n\tdefer f.mtx.Unlock()\n\n\tif f.Primary.Provider == nil {\n\t\treturn nil, errors.New(\"primary foreign exchange provider details not set\")\n\t}\n\n\tshunt := f.Primary.CheckCurrencies(fullRange)\n\trates, err := f.Primary.GetNewRate(baseCurrency, currencies)\n\tif err != nil {\n\t\treturn f.backupGetRate(baseCurrency, currencies)\n\t}\n\n\tif len(shunt) != 0 {\n\t\treturn rates, nil\n\t}\n\n\trateNew, err := f.backupGetRate(baseCurrency, shunt)\n\tif err != nil {\n\t\tlog.Warnf(log.Global, \"%s and subsequent providers, failed to update rate map for currencies %v %v\",\n\t\t\tf.Primary.Provider.GetName(),\n\t\t\tshunt,\n\t\t\terr)\n\t}\n\n\tfor key, val := range rateNew {\n\t\trates[key] = val\n\t}\n\treturn rates, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetCurrentServerTime returns the Huobi server time
|
func (h *HUOBI) GetCurrentServerTime(ctx context.Context) (time.Time, error) {
var result struct {
Response
Timestamp int64 `json:"data"`
}
err := h.SendHTTPRequest(ctx, exchange.RestSpot, "/v"+huobiAPIVersion+"/"+huobiTimestamp, &result)
if result.ErrorMessage != "" {
return time.Time{}, errors.New(result.ErrorMessage)
}
return time.UnixMilli(result.Timestamp), err
}
|
[
"func ServerTime(ctx context.Context) (time.Time, error) {\n\tret := new(bybit.BaseResult)\n\terr := PublicRequest(ctx, http.MethodGet, \"/v2/public/time\", nil, ret)\n\tif err != nil {\n\t\treturn time.Time{}, nil\n\t}\n\tt, err := bybit.ParseTime(ret.TimeNow)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\tbybit.UpdateServerTime(ctx, t)\n\treturn t, nil\n}",
"func (b *ByBit) GetServerTime() (timeNow int64, err error) {\n\tparams := map[string]interface{}{}\n\tvar ret BaseResult\n\t_, err = b.PublicRequest(http.MethodGet, \"v2/public/time\", params, &ret)\n\tif err != nil {\n\t\treturn\n\t}\n\tvar t float64\n\tt, err = strconv.ParseFloat(ret.TimeNow, 64)\n\tif err != nil {\n\t\treturn\n\t}\n\ttimeNow = int64(t * 1000)\n\treturn\n}",
"func (y *Yobit) GetServerTime(ctx context.Context, _ asset.Item) (time.Time, error) {\n\tinfo, err := y.GetInfo(ctx)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn time.Unix(info.ServerTime, 0), nil\n}",
"func (c *CoinbasePro) GetServerTime(ctx context.Context, _ asset.Item) (time.Time, error) {\n\tst, err := c.GetCurrentServerTime(ctx)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn st.ISO, nil\n}",
"func (b *OGame) ServerTime() time.Time {\n\treturn b.WithPriority(taskRunner.Normal).ServerTime()\n}",
"func (as *ApiService) ServerTime() (*ApiResponse, error) {\n\treq := NewRequest(http.MethodGet, \"/api/v1/timestamp\", nil)\n\treturn as.Call(req)\n}",
"func GetCurrentTime() time.Time {\n\treturn time.Now().UTC()\n}",
"func GetCurrentTime() uint64 {\n\treturn ComposeTSByTime(time.Now(), 0)\n}",
"func serverSince(db *pgxpool.Pool) (string, error) {\n\tvar dt sql.NullTime\n\terr := db.QueryRow(context.Background(), \"select current_timestamp;\").Scan(&dt)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ts := fmt.Sprintf(\"%s\", dt.Time.Format(time.RFC3339))\n\treturn base64.StdEncoding.EncodeToString([]byte(s)), nil\n}",
"func GetCurrentSysTime(instructionData reflect.Value, finished chan bool) int {\n\tfmt.Println(\"FIBER INFO: Getting sys time...\")\n\n\tvariable.SetVariable(instructionData.FieldByName(\"Output\").Interface().(string), time.Now())\n\tfinished <- true\n\treturn -1\n}",
"func nowTime() time.Time {\n\treturn time.Now().UTC()\n}",
"func GetCurrentTime() int64 {\n\treturn time.Now().UnixNano() * int64(time.Nanosecond) / int64(time.Millisecond)\n}",
"func (client *XenClient) HostGetServerLocaltime(host string) (result time.Time, err error) {\n\tobj, err := client.APICall(\"host.get_server_localtime\", host)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = obj.(time.Time)\n\treturn\n}",
"func (s *Scheduler) TimeFromServerTime(t time.Time) (ConcentratorTime, bool) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tif !s.clock.IsSynced() {\n\t\treturn 0, false\n\t}\n\treturn s.clock.FromServerTime(t)\n}",
"func GetCurrentTime() typeutil.Timestamp {\n\treturn ComposeTSByTime(time.Now(), 0)\n}",
"func TestGetServerTime(t *testing.T) {\n\tt.Parallel()\n\t_, err := k.GetServerTime()\n\tif err != nil {\n\t\tt.Error(\"Test Failed - GetServerTime() error\", err)\n\t}\n}",
"func (t *timeServer) getTimeStamp() uint64 {\n\tstamp := t.getCurrentNano() - t.startTime\n\treturn stamp\n}",
"func GetCurrentDateTimeInTime() time.Time {\n\treturn time.Now()\n}",
"func TimeNow() time.Time {\n\treturn time.Now().UTC()\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetAccounts returns the Huobi user accounts
|
func (h *HUOBI) GetAccounts(ctx context.Context) ([]Account, error) {
result := struct {
Accounts []Account `json:"data"`
}{}
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiAccounts, url.Values{}, nil, &result, false)
return result.Accounts, err
}
|
[
"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 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 GetAccounts(c *gin.Context) {\n\tvar account []models.Account\n\terr := models.GetAllAccounts(&account)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t c.JSON(http.StatusOK, account)\n\t}\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 (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 GetAccountsHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\n\tvar query *string\n\tvar limit int\n\tvar offset int\n\tvar err error\n\n\tif q := r.URL.Query().Get(\"query\"); q != \"\" {\n\t\tquery = &q\n\t}\n\tif l := r.URL.Query().Get(\"limit\"); l != \"\" {\n\t\tlimit, err = strconv.Atoi(l)\n\t\tif err != nil {\n\t\t\twriteResult(http.StatusBadRequest,\n\t\t\t\t\"Cannot parse limit parameter: \"+err.Error(), nil, w)\n\t\t\treturn\n\t\t}\n\t}\n\tif o := r.URL.Query().Get(\"offset\"); o != \"\" {\n\t\toffset, err = strconv.Atoi(o)\n\t\tif err != nil {\n\t\t\twriteResult(http.StatusBadRequest,\n\t\t\t\t\"Cannot parse offset parameter: \"+err.Error(), nil, w)\n\t\t\treturn\n\t\t}\n\t}\n\tif limit > 500 || limit <= 0 {\n\t\tlimit = 500\n\t}\n\tif offset < 0 {\n\t\toffset = 0\n\t}\n\tapi := client.NewAPI(endpoint, \"\", nil, \"\")\n\tsearchReq := mongoQuery{\n\t\tQuery: query,\n\t\tLimit: limit,\n\t\tOffset: offset,\n\t}\n\tsearchReqStr, _ := json.Marshal(searchReq)\n\tacc, err := api.SearchAccounts(searchReqStr)\n\tif err != nil {\n\t\twriteResult(http.StatusBadRequest, err.Error(), nil, w)\n\t\treturn\n\t}\n\n\twriteResult(http.StatusOK, \"OK\", acc, w)\n\treturn\n}",
"func GetAllAccounts(w http.ResponseWriter, r *http.Request) {\n\taccounts, err := database.ReadAccounts()\n\n\tif err != nil {\n\t\trender.Status(r, http.StatusInternalServerError)\n\t\trender.JSON(w, r, http.StatusText(http.StatusInternalServerError))\n\t\treturn\n\t}\n\n\trender.JSON(w, r, accounts)\n}",
"func GetAccountsHandler(c *gin.Context) {\n\taccounts := FindAccounts()\n\n\tc.JSON(http.StatusOK, gin.H{\"accounts\": accounts})\n}",
"func GetAllAccounts(ctx context.Context, session *asmodel.Session) response.RPC {\n\tcommonResponse := response.Response{\n\t\tOdataType: \"#ManagerAccountCollection.ManagerAccountCollection\",\n\t\tOdataID: \"/redfish/v1/AccountService/Accounts\",\n\t\tOdataContext: \"/redfish/v1/$metadata#ManagerAccountCollection.ManagerAccountCollection\",\n\t\tName: \"Account Service\",\n\t}\n\n\tvar resp response.RPC\n\n\terrLogPrefix := \"failed to fetch accounts : \"\n\tif !session.Privileges[common.PrivilegeConfigureUsers] {\n\t\terrorMessage := errLogPrefix + \"User \" + session.UserName + \" does not have the privilege to view all users\"\n\t\tresp.StatusCode = http.StatusForbidden\n\t\tresp.StatusMessage = response.InsufficientPrivilege\n\t\targs := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{})\n\t\tresp.Body = args.CreateGenericErrorResponse()\n\t\tauth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode)\n\t\treturn resp\n\t}\n\n\tl.LogWithFields(ctx).Info(\"Retrieving all users from the database\")\n\t//Get all user keys\n\tusers, err := asmodel.GetAllUsers()\n\tif err != nil {\n\t\terrorMessage := errLogPrefix + err.Error()\n\t\tresp.CreateInternalErrorResponse(errorMessage)\n\t\tl.LogWithFields(ctx).Error(errorMessage)\n\t\treturn resp\n\t}\n\t//Build response body and headers\n\tvar accountLinks []asresponse.ListMember\n\tfor _, key := range users {\n\t\taccountLink := asresponse.ListMember{\n\t\t\tOdataID: \"/redfish/v1/AccountService/Accounts/\" + key.UserName,\n\t\t}\n\t\taccountLinks = append(accountLinks, accountLink)\n\t}\n\n\tresp.StatusCode = http.StatusOK\n\tresp.StatusMessage = response.Success\n\n\tresp.Header = map[string]string{\n\t\t\"Link\": \"</redfish/v1/SchemaStore/en/ManagerAccountCollection.json/>; rel=describedby\",\n\t}\n\n\tcommonResponse.CreateGenericResponse(resp.StatusMessage)\n\tcommonResponse.ID = \"\"\n\tcommonResponse = mapEmptyValuesResponseFields(commonResponse)\n\tresp.Body = asresponse.List{\n\t\tResponse: commonResponse,\n\t\tMembersCount: len(users),\n\t\tMembers: accountLinks,\n\t}\n\n\treturn resp\n\n}",
"func ListAccounts(w http.ResponseWriter, r *http.Request) {\n\tisAdmin := false\n\tif oauth, ok := OAuthToken(r); ok {\n\t\tisAdmin = oauth.Match.Contains(\"account-admin\")\n\t}\n\n\tvar accounts []data.Account\n\tsearch := r.URL.Query().Get(\"q\")\n\tif search != \"\" {\n\t\taccounts = data.SearchAccounts(search)\n\t} else {\n\t\taccounts = data.ListAccounts()\n\t}\n\n\tmarshal := make([]data.AccountMarshaler, 0, len(accounts))\n\tfor i := 0; i < len(accounts); i++ {\n\t\tacc := &accounts[i]\n\t\tmarshal = append(marshal, data.AccountMarshaler{\n\t\t\tWithMail: isAdmin || acc.IsEmailPublic,\n\t\t\tWithAffiliation: isAdmin || acc.IsAffiliationPublic,\n\t\t\tAccount: acc,\n\t\t})\n\t}\n\n\tw.Header().Add(\"Cache-Control\", \"no-cache\")\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tenc := json.NewEncoder(w)\n\terr := enc.Encode(marshal)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}",
"func (w *wallet) Accounts() []accounts.Account {\n var err error\n\t// Return whatever account list we ended up with\n w.log.Debug(\"wallet.Accounts\")\n \n\tw.stateLock.RLock()\n\tdefer w.stateLock.RUnlock()\n\n w.accounts, err = w.driver.ReadAccounts()\n if err != nil {\n w.log.Debug(\"wallet.Accounts\", \"err\", err)\n return []accounts.Account{}\n }\n\tcpy := make([]accounts.Account, len(w.accounts))\n\tcopy(cpy, w.accounts)\n\treturn cpy\n}",
"func ListAccounts(uid string) ([]*model.GitAccount, error) {\n\tapiClient, err := util.GetRancherClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfilters := make(map[string]interface{})\n\tfilters[\"kind\"] = GIT_ACCOUNT_TYPE\n\tgoCollection, err := apiClient.GenericObject.List(&client.ListOpts{\n\t\tFilters: filters,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error %v filtering genericObjects by key\", err)\n\t}\n\tvar accounts []*model.GitAccount\n\tfor _, gobj := range goCollection.Data {\n\t\tb := []byte(gobj.ResourceData[\"data\"].(string))\n\t\ta := &model.GitAccount{}\n\t\tjson.Unmarshal(b, a)\n\t\tif uid == a.RancherUserID || !a.Private {\n\t\t\taccounts = append(accounts, a)\n\t\t}\n\t}\n\n\treturn accounts, nil\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 (c *client) Accounts(options ...option) (string, []Account, error) {\n\n\turlStr := fmt.Sprintf(\"%s/accounts/\", c.url)\n\turl, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tfor _, op := range options {\n\t\tif err := op(url); err != nil {\n\t\t\treturn \"\", nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\treq.SetBasicAuth(c.user, c.pass)\n\treq.Header.Set(\"Accept\", \"application/json\")\n\tnext, payload, err := c.do(req)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\taccs, err := accountsFromPayload(payload)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\treturn next, accs, err\n}",
"func (c *MockClient) Accounts(\n\tctx context.Context) (result []string, err error) {\n\tfor k := range c.Acc {\n\t\tresult = append(result, k)\n\t}\n\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 (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 accountsGet(c *gin.Context) {\n\tres := c.Query(\"result\")\n\n\tidStr := c.Query(\"id\")\n\n\tvar id int\n\tvar err error\n\tid, err = strconv.Atoi(idStr)\n\tif err != nil {\n\t\tid = noId\n\t}\n\n\t// if there is an id in the request (getting only one balance)\n\tif id != noId {\n\t\tbalance, err := manager.Get(id)\n\t\tif err != nil {\n\t\t\tlogger.Zap().Error(\"failed to get balance\", zap.Error(err))\n\t\t\t// TODO: return more explicit error code\n\t\t\tc.String(http.StatusInternalServerError, \"failed to get balance\")\n\t\t\treturn\n\t\t}\n\t\tc.String(http.StatusOK, \"%d\", balance)\n\t\treturn\n\t}\n\n\t// getting all balances\n\tswitch res {\n\t// to return sum of all balances\n\tcase \"aggregate\":\n\t\tbalance, err := manager.GetAll()\n\t\tif err != nil {\n\t\t\tlogger.Zap().Error(\"failed to get all balances\", zap.Error(err))\n\t\t\t// TODO: return more explicit error code\n\t\t\tc.String(http.StatusInternalServerError, \"failed to get all balances\")\n\t\t\treturn\n\t\t}\n\t\tc.String(http.StatusOK, \"%d\", balance)\n\t// to return the list all balances\n\tcase \"list\":\n\t\t// TODO: declare business api to support returning a list all the accounts (ids and values)\n\t\t// Its difference in concurrent mode would be the way we protect the global slice in the memory (which all go routines will add an account to)\n\t\t// We need to use locking (mutex) around the piece of code that inserts into the slice in that case\n\t\tc.String(http.StatusNotImplemented, \"not implemented\")\n\tdefault:\n\t\tc.String(http.StatusUnprocessableEntity, \"please specify the result mod (aggregate,...)\")\n\t}\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}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetAggregatedBalance returns the balances of all the subaccount aggregated.
|
func (h *HUOBI) GetAggregatedBalance(ctx context.Context) ([]AggregatedBalance, error) {
result := struct {
AggregatedBalances []AggregatedBalance `json:"data"`
}{}
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot,
http.MethodGet,
huobiAggregatedBalance,
nil,
nil,
&result,
false,
)
return result.AggregatedBalances, err
}
|
[
"func (h *HUOBIHADAX) GetAggregatedBalance() ([]AggregatedBalance, error) {\n\ttype response struct {\n\t\tResponse\n\t\tAggregatedBalances []AggregatedBalance `json:\"data\"`\n\t}\n\n\tvar result response\n\n\terr := h.SendAuthenticatedHTTPRequest(\n\t\thttp.MethodGet,\n\t\thuobihadaxAggregatedBalance,\n\t\turl.Values{},\n\t\t&result,\n\t)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.AggregatedBalances, err\n}",
"func (a SubAccountClient) GetSubAccountBalance(req *rest3.RequestForSubAccountBalance) (rest3.ResponseForSubAccountBalance, error) {\n\tpanic(\"implement me\")\n}",
"func (a *Application) GetTotalBalance() float64 {\n\tvar totalBalance float64\n\tfor _, balance := range a.BalanceHistory {\n\t\ttotalBalance += balance\n\t}\n\n\treturn totalBalance\n}",
"func (_Sigmacore *SigmacoreCaller) GetBalance(opts *bind.CallOpts, token common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Sigmacore.contract.Call(opts, &out, \"getBalance\", token)\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 GetBalances() (balances []Balance, error error) {\n\tvar b []Balance\n\tvar w struct {\n\t\tWallets []Balance `json:\"wallets\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/listbalances\", nil)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tif err := json.Unmarshal(jsonData, &w); err != nil {\n\t\treturn b, err\n\t}\n\treturn w.Wallets, nil\n}",
"func (a Account) GetBalance() int {\n\treturn a.balance\n}",
"func (account *Account) GetBalance(asset *Asset) string {\n\tif asset.IsNative() {\n\t\treturn account.GetNativeBalance()\n\t}\n\n\tfor _, b := range account.Balances {\n\t\tif asset.Equals(*b.Asset) {\n\t\t\treturn b.Amount\n\t\t}\n\t}\n\n\treturn \"\"\n}",
"func (c *Client) GetBalance(ctx context.Context) (Balances, error) {\n\treq, err := c.newAuthenticatedRequest(ctx, \"GetBalance\", nil)\n\tif err != nil {\n\t\treturn Balances{}, errors.Wrap(err, \"Faild to new authenticated request\")\n\t}\n\n\tvar ret = &Balances{}\n\t_, err = c.do(req, ret)\n\tif err != nil {\n\t\treturn *ret, errors.Wrap(err, \"Faild to do request\")\n\t}\n\treturn *ret, nil\n}",
"func (_DevUtils *DevUtilsSession) GetBalance(ownerAddress common.Address, assetData []byte) (*types.Transaction, error) {\n\treturn _DevUtils.Contract.GetBalance(&_DevUtils.TransactOpts, ownerAddress, assetData)\n}",
"func (_DevUtils *DevUtilsTransactorSession) GetBalance(ownerAddress common.Address, assetData []byte) (*types.Transaction, error) {\n\treturn _DevUtils.Contract.GetBalance(&_DevUtils.TransactOpts, ownerAddress, assetData)\n}",
"func (_Sigmacore *SigmacoreSession) GetBalance(token common.Address) (*big.Int, error) {\n\treturn _Sigmacore.Contract.GetBalance(&_Sigmacore.CallOpts, token)\n}",
"func GetBalance(tx *gorm.DB, requestCreated *models.TransactionRequests) (responses.TransactionResponse, error) {\n\t//first get Balance of the DebitAccount\n\tresponse := responses.TransactionResponse{}\n\tcbalance := models.Accounts{}\n\n\terr := tx.Debug().Model(&models.Accounts{}).Where(\"account_no = ?\", requestCreated.DebitAccount).Take(&cbalance).Error\n\tif err != nil {\n\t\treturn responses.TransactionResponse{}, err\n\t}\n\tresponse.Procode = requestCreated.Procode\n\tresponse.ResponseCode = Successful\n\tresponse.Remarks = \"Balance Enquiry Successful\"\n\tresponse.Reference = requestCreated.TxnRef\n\tamt, _ := strconv.ParseFloat(\"0.00\", 64)\n\tresponse.Amount = amt\n\tresponse.Account = cbalance.AccountNo\n\tbal, _ := strconv.ParseFloat(cbalance.AvailableBal, 64)\n\tresponse.AvailableBalance = bal\n\n\treturn response, nil\n}",
"func (a *Account) Balance() int {\n\treturn a.balance\n}",
"func (p *Bittrex) GetBalance() map[string]interface{} {\n\tif err, response := p.marketRequest(\"/account/getbalances\", map[string]string{\n\t\t\"apikey\": p.config.API,\n\t}, true); err != nil {\n\t\tlogger.Errorf(\"Fail to get balance:%v\", err)\n\t\treturn nil\n\t} else {\n\n\t\tif response == nil || response[\"success\"] != true {\n\t\t\tlogger.Errorf(\"Fail to get the balances:%v\", response[\"message\"])\n\t\t\treturn nil\n\t\t}\n\n\t\tbalances := make(map[string]interface{})\n\t\tresult := response[\"result\"].([]interface{})\n\t\tif result != nil {\n\t\t\tfor _, item := range result {\n\t\t\t\tbalance := item.(map[string]interface{})\n\t\t\t\tbalances[balance[\"Currency\"].(string)] = balance[\"Available\"].(float64)\n\t\t\t}\n\n\t\t\treturn balances\n\t\t}\n\n\t}\n\n\treturn nil\n}",
"func (f *FTX) SubaccountBalances(ctx context.Context, name string) ([]SubaccountBalance, error) {\n\tif name == \"\" {\n\t\treturn nil, errSubaccountNameMustBeSpecified\n\t}\n\tresp := struct {\n\t\tData []SubaccountBalance `json:\"result\"`\n\t}{}\n\tif err := f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, fmt.Sprintf(subaccountsBalance, name), nil, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.Data, nil\n}",
"func (_ArbOwner *ArbOwnerCaller) GetTotalOfEthBalances(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ArbOwner.contract.Call(opts, &out, \"getTotalOfEthBalances\")\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 GetAccountBalance(ctx context.Context, bid, lid int64, dt *time.Time) (float64, error) {\n\treturn GetRAAccountBalance(ctx, bid, lid, 0, dt)\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 GetAccountBal(cfg *config.Config, c client.Client) string {\n\tvar balanceMsg string\n\n\tbalance := GetAccountBalWithDenomFromdb(cfg, c) // get heimdall account balance\n\tbalanceMsg = fmt.Sprintf(\"Heimdall Node : \\n- Current balance of your account(%s) is %s \\n\", cfg.ValDetails.SignerAddress, balance)\n\n\tborBalance := GetBorBalanceFromDB(cfg, c) + \"ETH\" // get bor account balance\n\tbalanceMsg = balanceMsg + fmt.Sprintf(\"\\nBor Node : \\n- Current balance of your account(%s) is %s \\n\", cfg.ValDetails.SignerAddress, borBalance)\n\n\treturn balanceMsg\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SpotNewOrder submits an order to Huobi
|
func (h *HUOBI) SpotNewOrder(ctx context.Context, arg *SpotNewOrderRequestParams) (int64, error) {
symbolValue, err := h.FormatSymbol(arg.Symbol, asset.Spot)
if err != nil {
return 0, err
}
data := struct {
AccountID int `json:"account-id,string"`
Amount string `json:"amount"`
Price string `json:"price"`
Source string `json:"source"`
Symbol string `json:"symbol"`
Type string `json:"type"`
}{
AccountID: arg.AccountID,
Amount: strconv.FormatFloat(arg.Amount, 'f', -1, 64),
Symbol: symbolValue,
Type: string(arg.Type),
}
// Only set price if order type is not equal to buy-market or sell-market
if arg.Type != SpotNewOrderRequestTypeBuyMarket && arg.Type != SpotNewOrderRequestTypeSellMarket {
data.Price = strconv.FormatFloat(arg.Price, 'f', -1, 64)
}
if arg.Source != "" {
data.Source = arg.Source
}
result := struct {
OrderID int64 `json:"data,string"`
}{}
err = h.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
huobiOrderPlace,
nil,
data,
&result,
false,
)
return result.OrderID, err
}
|
[
"func (h *HUOBIHADAX) SpotNewOrder(arg SpotNewOrderRequestParams) (int64, error) {\n\tvals := make(map[string]string)\n\tvals[\"account-id\"] = fmt.Sprintf(\"%d\", arg.AccountID)\n\tvals[\"amount\"] = strconv.FormatFloat(arg.Amount, 'f', -1, 64)\n\n\t// Only set price if order type is not equal to buy-market or sell-market\n\tif arg.Type != SpotNewOrderRequestTypeBuyMarket && arg.Type != SpotNewOrderRequestTypeSellMarket {\n\t\tvals[\"price\"] = strconv.FormatFloat(arg.Price, 'f', -1, 64)\n\t}\n\n\tif arg.Source != \"\" {\n\t\tvals[\"source\"] = arg.Source\n\t}\n\n\tvals[\"symbol\"] = arg.Symbol\n\tvals[\"type\"] = string(arg.Type)\n\n\ttype response struct {\n\t\tResponse\n\t\tOrderID int64 `json:\"data,string\"`\n\t}\n\n\t// The API indicates that for the POST request, the parameters of each method are not signed and authenticated. That is, only the AccessKeyId, SignatureMethod, SignatureVersion, and Timestamp parameters are required for the POST request. The other parameters are placed in the body.\n\t// So re-encode the Post parameter\n\tbytesParams, _ := json.Marshal(vals)\n\tpostBodyParams := string(bytesParams)\n\tif h.Verbose {\n\t\tfmt.Println(\"Post params:\", postBodyParams)\n\t}\n\n\tvar result response\n\tendpoint := fmt.Sprintf(\"%s/%s\", huobihadaxAPIName, huobihadaxOrderPlace)\n\terr := h.SendAuthenticatedHTTPPostRequest(http.MethodPost, endpoint, postBodyParams, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.OrderID, err\n}",
"func (b *Bitmex) SubmitOrder(ctx context.Context, s *order.Submit) (*order.SubmitResponse, error) {\n\tif err := s.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif math.Trunc(s.Amount) != s.Amount {\n\t\treturn nil,\n\t\t\terrors.New(\"order contract amount can not have decimals\")\n\t}\n\n\tfPair, err := b.FormatExchangeCurrency(s.Pair, s.AssetType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar orderNewParams = OrderNewParams{\n\t\tOrderType: s.Type.Title(),\n\t\tSymbol: fPair.String(),\n\t\tOrderQuantity: s.Amount,\n\t\tSide: s.Side.Title(),\n\t}\n\n\tif s.Type == order.Limit {\n\t\torderNewParams.Price = s.Price\n\t}\n\n\tresponse, err := b.CreateOrder(ctx, &orderNewParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.DeriveSubmitResponse(response.OrderID)\n}",
"func (c *Client) SubmitOrder(order *Order) error {\n\treturn c.submitOrder(\"/api/v3/order\", order)\n}",
"func (s *Service) PlaceOrder(w http.ResponseWriter, r *http.Request) {\n\tvar entry order.Order\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&entry); err != nil {\n\t\tlog.Errorf(\"PlaceOrder: %v\", err)\n\t\tutils.ResponseWithError(w, http.StatusBadRequest, \"Invalid request payload JSON format\")\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\t// Create the order in the storage\n\tvar err error\n\tentry.ID, err = usecases.PlaceOrder(s.storage, &entry)\n\tif err != nil {\n\t\tlog.Errorf(\"PlaceOrder usecase: %v\", err)\n\t\tutils.ResponseWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tutils.ResponseWithJSON(w, http.StatusCreated, entry)\n}",
"func (b *Binance) NewOrder(o *NewOrderRequest) (NewOrderResponse, error) {\n\tvar resp NewOrderResponse\n\n\tpath := fmt.Sprintf(\"%s%s\", b.APIUrl, newOrder)\n\n\tparams := url.Values{}\n\tparams.Set(\"symbol\", o.Symbol)\n\tparams.Set(\"side\", string(o.Side))\n\tparams.Set(\"type\", string(o.TradeType))\n\tparams.Set(\"quantity\", strconv.FormatFloat(o.Quantity, 'f', -1, 64))\n\tif o.TradeType == \"LIMIT\" {\n\t\tparams.Set(\"price\", strconv.FormatFloat(o.Price, 'f', -1, 64))\n\t}\n\tif o.TimeInForce != \"\" {\n\t\tparams.Set(\"timeInForce\", string(o.TimeInForce))\n\t}\n\n\tif o.NewClientOrderID != \"\" {\n\t\tparams.Set(\"newClientOrderID\", o.NewClientOrderID)\n\t}\n\n\tif o.StopPrice != 0 {\n\t\tparams.Set(\"stopPrice\", strconv.FormatFloat(o.StopPrice, 'f', -1, 64))\n\t}\n\n\tif o.IcebergQty != 0 {\n\t\tparams.Set(\"icebergQty\", strconv.FormatFloat(o.IcebergQty, 'f', -1, 64))\n\t}\n\n\tif o.NewOrderRespType != \"\" {\n\t\tparams.Set(\"newOrderRespType\", o.NewOrderRespType)\n\t}\n\n\tif err := b.SendAuthHTTPRequest(http.MethodPost, path, params, &resp); err != nil {\n\t\treturn resp, err\n\t}\n\n\tif resp.Code != 0 {\n\t\treturn resp, errors.New(resp.Msg)\n\t}\n\treturn resp, nil\n}",
"func CreateNewOrder(res http.ResponseWriter, req *http.Request) {\n\tdefer func() { //to handle potential panic situation\n\t\tif err := recover(); err != nil {\n\t\t\tlog.Panic(\"Panic occured at create order:\", err)\n\t\t}\n\t}()\n\tmyUser := ses.GetUser(res, req)\n\tif !ses.AlreadyLoggedIn(req) {\n\t\thttp.Redirect(res, req, \"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\t//fmt.Println(Items)\n\tsortItems(ds.Items)\n\n\tvar newShoppingCart = []ds.Order{}\n\n\tif req.Method == http.MethodPost {\n\t\tnameRegExp := regexp.MustCompile(`^[\\w'\\-,.][^0-9_!¡?÷?¿/\\\\+=@#$%ˆ&*(){}|~<>;:[\\]]{2,30}$`) //name regexp to check for name pattern match\n\t\tname := strings.TrimSpace(req.FormValue(\"name\"))\n\t\tif !nameRegExp.MatchString(name) {\n\t\t\thttp.Error(res, \"You have entered an invalid name field.\", http.StatusBadRequest)\n\t\t\tlog.Warning(\"Invalid user input for name field\")\n\t\t\treturn\n\t\t}\n\t\tname = pol.Sanitize(name) //pol.Sanitize is used to sanitize inputs\n\n\t\taddRegExp := regexp.MustCompile(`^[\\w'\\-,.][^_!¡?÷?¿/\\\\+=$%ˆ&*(){}|~<>;:[\\]]{2,100}$`) ////address regexp to check for address pattern match\n\t\tadd := strings.TrimSpace(req.FormValue(\"address\"))\n\t\tif !addRegExp.MatchString(add) {\n\t\t\thttp.Error(res, \"You have entered an invalid address.\", http.StatusBadRequest)\n\t\t\tlog.Warning(\"Invalid user input for address field\")\n\t\t\treturn\n\t\t}\n\t\tadd = pol.Sanitize(add) //pol.Sanitize is used to sanitize inputs\n\n\t\tsday := req.FormValue(\"dday\") //sday is string day\n\t\tdayRegExp := regexp.MustCompile(`^[1-7]$`)\n\t\tif !dayRegExp.MatchString(sday) {\n\t\t\thttp.Error(res, \"You have entered an invalid delivery day.\", http.StatusBadRequest)\n\t\t\tlog.Warning(\"Invalid user input for delivery day\")\n\t\t\treturn\n\t\t}\n\n\t\tdday, _ := strconv.Atoi(sday)\n\n\t\tavailableDay := ds.IsDayAvailable(dday)\n\t\tif availableDay == false { //this checks if the order was placed on an unavailable day\n\t\t\terrorString := \"Sorry! There are no more available delivery slots for \" + ds.IntToDay(dday)\n\t\t\thttp.Error(res, errorString, http.StatusBadRequest)\n\t\t\tlog.Warning(\"There are no more available delivery slots for \" + ds.IntToDay(dday))\n\t\t\treturn\n\t\t}\n\n\t\torderQtyRegExp := regexp.MustCompile(`^[0-9]{1,2}$`) //order quantity reg exp to check for quantity pattern match\n\n\t\tfor i := 0; i < len(ds.Items); i++ {\n\t\t\tif !orderQtyRegExp.MatchString(req.FormValue(ds.Items[i].Name)) {\n\t\t\t\terrorString := \"You have entered an invalid order quantity for \" + ds.Items[i].Name + \".\"\n\t\t\t\thttp.Error(res, errorString, http.StatusBadRequest)\n\t\t\t\tlog.Warning(\"Invalid user input for order quantity\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tquantity, _ := strconv.Atoi(req.FormValue(ds.Items[i].Name)) //label for the form input is the item name, but returns a quantity of that item\n\t\t\tquantity64 := float64(quantity)\n\n\t\t\tif quantity64 > 0 {\n\t\t\t\titemAvailable := availableItem(ds.Items[i].Name)\n\t\t\t\tif itemAvailable == false { // this checks if the current item is in stock\n\t\t\t\t\terrorString := \"Oops, \" + ds.Items[i].Name + \" is no longer available for ordering.\"\n\t\t\t\t\thttp.Error(res, errorString, http.StatusBadRequest)\n\t\t\t\t\tlog.Warning(\"User overordered on item:\", ds.Items[i].Name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tavailableBalance := isBalanceEnough(ds.Items[i].Name, quantity64)\n\t\t\t\tif availableBalance == false { //this checks if the user over ordered on the item\n\t\t\t\t\terrorString := \"Oops, there is no sufficient balance of\" + ds.Items[i].Name + \" for ordering..\"\n\t\t\t\t\thttp.Error(res, errorString, http.StatusBadRequest)\n\t\t\t\t\tlog.Warning(\"User overordered on item:\", ds.Items[i].Name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tsingleCart := ds.Order{\n\t\t\t\t\tOrderItem: ds.Items[i].Name,\n\t\t\t\t\tQty: quantity64,\n\t\t\t\t}\n\t\t\t\tnewShoppingCart = append(newShoppingCart, singleCart)\n\t\t\t}\n\t\t}\n\n\t\tif len(newShoppingCart) == 0 {\n\t\t\thttp.Error(res, \"Error: You cannot submit an empty shopping cart.\", http.StatusBadRequest)\n\t\t\tlog.Warning(\"User entered empty shopping cart.\")\n\t\t\treturn\n\t\t}\n\n\t\ton := atomic.AddInt64(&OrderNumber, 1) // use of atomic function to prevent multiple clients from possibly creating identical order number\n\t\tamt := ds.CalculateAmount(newShoppingCart)\n\t\tnewOrder := ds.OrderInfo{\n\t\t\tUsername: myUser.Username,\n\t\t\tName: name,\n\t\t\tAddress: add,\n\t\t\tDeliveryDay: dday,\n\t\t\tOrderNum: on,\n\t\t\tShoppingCart: newShoppingCart,\n\t\t\tAmount: amt,\n\t\t}\n\n\t\tds.OrderList.AddOrder(newOrder)\n\t\terr := UpdateWeeklySchedule(ds.OrderList)\n\t\tif err != nil {\n\t\t\thttp.Error(res, err.Error(), http.StatusBadRequest)\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\n\t\terr = UpdateWeeklyOrder(ds.OrderList)\n\t\tif err != nil {\n\t\t\thttp.Error(res, err.Error(), http.StatusBadRequest)\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\n\t\t//fmt.Println(weeklySchedule)\n\t\t//fmt.Println(items)\n\t\t//orderList.printAllOrderNodes()\n\n\t\thttp.Redirect(res, req, \"/menu\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\ttype balanceStruct struct {\n\t\tItem string\n\t\tQuantity float64\n\t}\n\n\tvar itemData []balanceStruct\n\n\tfor i := 0; i < len(ds.Items); i++ {\n\t\tremainingQuantity := ds.Items[i].WeeklyCapacity - ds.Items[i].WeeklyOrder\n\t\td := balanceStruct{\n\t\t\tItem: ds.Items[i].Name,\n\t\t\tQuantity: remainingQuantity}\n\t\titemData = append(itemData, d)\n\t}\n\n\terr := tpl.ExecuteTemplate(res, \"createOrder.gohtml\", itemData)\n\tif err != nil {\n\t\thttp.Error(res, err.Error(), http.StatusBadRequest)\n\t\tlog.Fatalln(err)\n\t}\n\n\tViewAvailableDays(res, req)\n\tshowRemainingBalance(res, req)\n}",
"func PlaceOrder(w http.ResponseWriter, r *http.Request) {\n\t// send order to waiting sandwich\n\tctx := r.Context()\n\tres := Resolver{}\n\torder := OrderFromContext(ctx)\n\tuser := UserFromContext(ctx)\n\n\tlimit := 1\n\ts, serr := res.Query().Sandwiches(ctx, *order.Order.Runtime, &limit)\n\tif serr != nil {\n\t\tpanic(serr)\n\t}\n\n\thost := s[0].Host\n\tif s[0].Port != nil {\n\t\thost = host + \":\" + strconv.Itoa(*s[0].Port)\n\t}\n\n\turlParts := []string{host, order.TenantID, *order.Order.Path}\n\tenvVariables, _ := json.Marshal(order.Order.Env)\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{\n\t\t\"auth\": order.Order.Auth,\n\t\t\"auth_header\": order.Order.AuthHeader,\n\t\t\"authorized\": user.Authorized,\n\t\t\"env\": string(envVariables),\n\t\t\"name\": order.Order.Name,\n\t\t\"path\": order.Order.Path,\n\t\t\"runtime\": order.Order.Runtime,\n\t\t\"tenant\": order.TenantID,\n\t\t\"exp\": time.Now().Add(time.Minute * 1).Unix(),\n\t})\n\n\ttokenString, err := token.SignedString([]byte(os.Getenv(\"JWT_SECRET\")))\n\tif err != nil {\n\t\tjwterr := fmt.Errorf(\"something went wrong validating the request: %s\", err.Error())\n\t\tlog.Println(jwterr)\n\t\treturn\n\t}\n\n\tclient := &http.Client{}\n\treq, _ := http.NewRequest(\"POST\", strings.Join(urlParts, \"/\"), r.Body)\n\treq.Header.Set(\"Token\", tokenString)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif authHeader := order.Order.AuthHeader; authHeader != nil && *authHeader != \"\" {\n\t\theaderVal := r.Header.Get(*authHeader)\n\t\treq.Header.Set(*authHeader, headerVal)\n\t} else {\n\t\theaderVal := r.Header.Get(\"Authorization\")\n\t\treq.Header.Set(\"Authorization\", headerVal)\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tjwterr := fmt.Errorf(\"something went wrong sending client request: %s\", err.Error())\n\t\tlog.Println(jwterr)\n\t\tw.Write([]byte(`{ \"error\": \"The shop seems to be down.\" }`))\n\t\treturn\n\t}\n\n\tif body, _ := ioutil.ReadAll(resp.Body); len(body) > 0 {\n\t\tif resp.StatusCode != 200 {\n\t\t\thttp.Error(w, http.StatusText(resp.StatusCode), resp.StatusCode)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Add(\"Content-Type\", \"application/json\")\n\t\tw.Write(body)\n\t\treturn\n\t}\n\n\tw.Write([]byte(\"{}\"))\n}",
"func (wfe *WebFrontEndImpl) NewOrder(\n\tctx context.Context,\n\tresponse http.ResponseWriter,\n\trequest *http.Request) {\n\n\tpostData, prob := wfe.verifyPOST(request, wfe.lookupJWK)\n\tif prob != nil {\n\t\twfe.sendError(prob, response)\n\t\treturn\n\t}\n\n\texistingReg, prob := wfe.getAcctByKey(postData.jwk)\n\tif prob != nil {\n\t\twfe.sendError(prob, response)\n\t\treturn\n\t}\n\n\t// Unpack the order request body\n\tvar newOrder acme.Order\n\terr := json.Unmarshal(postData.body, &newOrder)\n\tif err != nil {\n\t\twfe.sendError(\n\t\t\tacme.MalformedProblem(\"Error unmarshaling body JSON: \"+err.Error()), response)\n\t\treturn\n\t}\n\n\tvar orderDNSs []string\n\tvar orderIPs []net.IP\n\tfor _, ident := range newOrder.Identifiers {\n\t\tswitch ident.Type {\n\t\tcase acme.IdentifierDNS:\n\t\t\torderDNSs = append(orderDNSs, ident.Value)\n\t\tcase acme.IdentifierIP:\n\t\t\torderIPs = append(orderIPs, net.ParseIP(ident.Value))\n\t\tdefault:\n\t\t\twfe.sendError(acme.MalformedProblem(\n\t\t\t\tfmt.Sprintf(\"Order includes unknown identifier type %s\", ident.Type)), response)\n\t\t\treturn\n\t\t}\n\t}\n\torderDNSs = uniqueLowerNames(orderDNSs)\n\torderIPs = uniqueIPs(orderIPs)\n\tvar uniquenames []acme.Identifier\n\tfor _, name := range orderDNSs {\n\t\tuniquenames = append(uniquenames, acme.Identifier{Value: name, Type: acme.IdentifierDNS})\n\t}\n\tfor _, ip := range orderIPs {\n\t\tuniquenames = append(uniquenames, acme.Identifier{Value: ip.String(), Type: acme.IdentifierIP})\n\t}\n\texpires := time.Now().AddDate(0, 0, 1)\n\torder := &core.Order{\n\t\tID: newToken(),\n\t\tAccountID: existingReg.ID,\n\t\tOrder: acme.Order{\n\t\t\tStatus: acme.StatusPending,\n\t\t\tExpires: expires.UTC().Format(time.RFC3339),\n\t\t\t// Only the Identifiers, NotBefore and NotAfter from the submitted order\n\t\t\t// are carried forward\n\t\t\tIdentifiers: uniquenames,\n\t\t\tNotBefore: newOrder.NotBefore,\n\t\t\tNotAfter: newOrder.NotAfter,\n\t\t},\n\t\tExpiresDate: expires,\n\t}\n\n\t// Verify the details of the order before creating authorizations\n\tif err := wfe.verifyOrder(order); err != nil {\n\t\twfe.sendError(err, response)\n\t\treturn\n\t}\n\n\t// Create the authorizations for the order\n\terr = wfe.makeAuthorizations(order, request)\n\tif err != nil {\n\t\twfe.sendError(\n\t\t\tacme.InternalErrorProblem(\"Error creating authorizations for order\"), response)\n\t\treturn\n\t}\n\n\t// Add the order to the in-memory DB\n\tcount, err := wfe.db.AddOrder(order)\n\tif err != nil {\n\t\twfe.sendError(\n\t\t\tacme.InternalErrorProblem(\"Error saving order\"), response)\n\t\treturn\n\t}\n\twfe.log.Printf(\"Added order %q to the db\\n\", order.ID)\n\twfe.log.Printf(\"There are now %d orders in the db\\n\", count)\n\n\t// Get the stored order back from the DB. The memorystore will set the order's\n\t// status for us.\n\tstoredOrder := wfe.db.GetOrderByID(order.ID)\n\n\torderURL := wfe.relativeEndpoint(request, fmt.Sprintf(\"%s%s\", orderPath, storedOrder.ID))\n\tresponse.Header().Add(\"Location\", orderURL)\n\n\torderResp := wfe.orderForDisplay(storedOrder, request)\n\terr = wfe.writeJSONResponse(response, http.StatusCreated, orderResp)\n\tif err != nil {\n\t\twfe.sendError(acme.InternalErrorProblem(\"Error marshaling order\"), response)\n\t\treturn\n\t}\n}",
"func (n *Nicehash) CreateNewOrder(location, algo int64, amount, price, limit float64, pool_host, pool_port, pool_user, pool_pass string, code int64) (order OrderCallBack, err error) {\n\n\treqUrl := fmt.Sprintf(\"?method=orders.create&location=%d&algo=%d&amount=%f&price=%f&limit=%f&pool_host=%s&pool_port=%s&pool_user=%s&pool_pass=%s\", location, algo, amount, price, limit, pool_host, pool_port, pool_user, pool_pass)\n\tif code != 0 {\n\t\treqUrl += fmt.Sprintf(\"code=%d\", code)\n\t}\n\t_, err = n.client.do(\"POST\", reqUrl, \"private\", &order)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}",
"func (e Exchange) SubmitOrder(exch string, submit *order.Submit) (*order.SubmitResponse, error) {\n\tr, err := engine.Bot.OrderManager.Submit(exch, submit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &r.SubmitResponse, nil\n}",
"func (h Handler) create(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tvar co CreateOrder\n\n\tdefer r.Body.Close()\n\tif err := json.NewDecoder(r.Body).Decode(&co); err != nil {\n\t\tdhttputil.ErrorHandler(err, w, r)\n\t\treturn\n\t}\n\n\tif err := h.service.CreateOrder(ctx, co); err != nil {\n\t\tdhttputil.ErrorHandler(err, w, r)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}",
"func (y *Yobit) SubmitOrder(ctx context.Context, s *order.Submit) (*order.SubmitResponse, error) {\n\tif err := s.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif s.Type != order.Limit {\n\t\treturn nil, errors.New(\"only limit orders are allowed\")\n\t}\n\n\tfPair, err := y.FormatExchangeCurrency(s.Pair, s.AssetType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := y.Trade(ctx,\n\t\tfPair.String(),\n\t\ts.Side.String(),\n\t\ts.Amount,\n\t\ts.Price)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.DeriveSubmitResponse(strconv.FormatInt(response, 10))\n}",
"func (_HashDice *HashDiceTransactor) SubmitBetOrder(opts *bind.TransactOpts, roomId *big.Int, startBlock *big.Int, betType uint8, betValue []uint32) (*types.Transaction, error) {\n\treturn _HashDice.contract.Transact(opts, \"SubmitBetOrder\", roomId, startBlock, betType, betValue)\n}",
"func (sC StoreController) PlaceOrder(context *gin.Context) {\n\tvar order models.Order\n\tif err := context.ShouldBindJSON(&order); err != nil {\n\t\tcontext.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\torder, err := sC.StoreService.Create(order)\n\tif err != nil {\n\t\tcontext.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\tcontext.JSON(http.StatusCreated, gin.H{\"data\": order})\n}",
"func (s *Server) SubmitOrder(ctx context.Context, in *orderPb.SubmitOrderRequest) (*orderPb.Null, error) {\n\tt := time.Now()\n\trpcRequestCount.With(prometheus.Labels{\"method\": \"SubmitOrderTotal\"}).Inc()\n\n\t// Check input params.\n\torderId := in.GetOrderId()\n\tfileHash := in.GetFileHash()\n\tresult := \"error\"\n\tif orderId <= 0 {\n\t\trpcRequestCount.With(prometheus.Labels{\"method\": \"SubmitOrderFailed\"}).Inc()\n\t\treturn nil, errorm.RequestParamEmpty\n\t}\n\n\tdefer func(t time.Time) {\n\t\tdefer rpcRequestDuration.With(prometheus.Labels{\"method\": \"SubmitOrder\"}).Observe(float64(time.Since(t).Microseconds()) / 1000)\n\t}(t)\n\n\t// Submit order by orderId.\n\terr := s.SubmitOrderController(fileHash, result, orderId)\n\tif err != nil {\n\t\trpcRequestCount.With(prometheus.Labels{\"method\": \"SubmitOrderError\"}).Inc()\n\t\treturn nil, err\n\t}\n\n\trpcRequestCount.With(prometheus.Labels{\"method\": \"SubmitOrderSuccess\"}).Inc()\n\treturn &orderPb.Null{}, nil\n}",
"func (h *orderRouteHandler) CreateOrder(ctx *fasthttp.RequestCtx) {\n\tuserID := ctx.UserValue(\"user_id\").(string)\n\th.orderStore.Create(ctx, userID)\n}",
"func (ctrl OrderController) Create(w http.ResponseWriter, r *http.Request) {\n\tlogStartInfo(ctrl.Name, funcName(), time.Now())\n\n\tsession, err := Authenticate(r)\n\tif err != nil {\n\t\tresponseError(w, http.StatusInternalServerError, fmt.Sprintf(\"Error while creating order: %v\", err))\n\t\treturn\n\t}\n\torder := &model.Order{}\n\tif err := utility.ReadRequestData(r, order); err != nil {\n\t\tresponseError(w, http.StatusInternalServerError, fmt.Sprintf(\"Error while creating order: %v\", err))\n\t\treturn\n\t}\n\tif err := order.Insert(session.TenantID); err != nil {\n\t\tresponseError(w, http.StatusInternalServerError, fmt.Sprintf(\"Error while creating order: %v\", err))\n\t\treturn\n\t}\n\tfmt.Fprintf(w, \"%s\", utility.ToJSON(order))\n}",
"func (c *Client) Create(ctx context.Context, params *razorpay.OrderParams) (*razorpay.Order, error) {\n\torder := &razorpay.Order{}\n\terr := c.Call(ctx, http.MethodPost, \"/orders\", params, order)\n\treturn order, err\n}",
"func (client *Client) PlaceOrder(market string, side string, price float64,\n\t_type string, size float64, reduceOnly bool, ioc bool, postOnly bool) (NewOrderResponse, error) {\n\tvar newOrderResponse NewOrderResponse\n\trequestBody, err := json.Marshal(NewOrder{\n\t\tMarket: market,\n\t\tSide: side,\n\t\tPrice: price,\n\t\tType: _type,\n\t\tSize: size,\n\t\tReduceOnly: reduceOnly,\n\t\tIoc: ioc,\n\t\tPostOnly: postOnly})\n\tif err != nil {\n\t\tlog.Println(\"Error PlaceOrder\", err)\n\t\treturn newOrderResponse, err\n\t}\n\tresp, err := client._post(\"orders\", requestBody)\n\tif err != nil {\n\t\tlog.Println(\"Error PlaceOrder\", err)\n\t\treturn newOrderResponse, err\n\t}\n\terr = _processResponse(resp, &newOrderResponse)\n\treturn newOrderResponse, err\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
CancelExistingOrder cancels an order on Huobi
|
func (h *HUOBI) CancelExistingOrder(ctx context.Context, orderID int64) (int64, error) {
resp := struct {
OrderID int64 `json:"data,string"`
}{}
endpoint := fmt.Sprintf(huobiOrderCancel, strconv.FormatInt(orderID, 10))
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, endpoint, url.Values{}, nil, &resp, false)
return resp.OrderID, err
}
|
[
"func (h *HUOBIHADAX) CancelExistingOrder(orderID int64) (int64, error) {\n\ttype response struct {\n\t\tResponse\n\t\tOrderID int64 `json:\"data,string\"`\n\t}\n\n\tvar result response\n\tendpoint := fmt.Sprintf(huobihadaxOrderCancel, strconv.FormatInt(orderID, 10))\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodPost, endpoint, url.Values{}, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.OrderID, err\n}",
"func (b *Binance) CancelExistingOrder(symbol string, orderID int64, origClientOrderID string) (CancelOrderResponse, error) {\n\tvar resp CancelOrderResponse\n\n\tpath := fmt.Sprintf(\"%s%s\", b.APIUrl, cancelOrder)\n\n\tparams := url.Values{}\n\tparams.Set(\"symbol\", symbol)\n\n\tif orderID != 0 {\n\t\tparams.Set(\"orderId\", strconv.FormatInt(orderID, 10))\n\t}\n\n\tif origClientOrderID != \"\" {\n\t\tparams.Set(\"origClientOrderId\", origClientOrderID)\n\t}\n\n\treturn resp, b.SendAuthHTTPRequest(http.MethodDelete, path, params, &resp)\n}",
"func CancelOrder(context echo.Context) error {\n\tid := context.Param(\"id\")\n\n\tDeletedID, err := DeleteOrder(id)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not bind request to struct: %+v\", err)\n\t\treturn util.SendError(context, \"\", \"\", \"\")\n\t}\n\n\treturn util.SendSuccess(context, DeletedID)\n\n}",
"func TestCancelExistingOrder(t *testing.T) {\n\tt.Parallel()\n\t_, err := k.CancelExistingOrder(\"OAVY7T-MV5VK-KHDF5X\")\n\tif err == nil {\n\t\tt.Error(\"Test Failed - CancelExistingOrder() error\", err)\n\t}\n}",
"func TestCancelExistingOrder(t *testing.T) {\n\tt.Parallel()\n\t_, err := k.CancelExistingOrder(context.Background(), \"OAVY7T-MV5VK-KHDF5X\")\n\tif err == nil {\n\t\tt.Error(\"CancelExistingOrder() Expected error\")\n\t}\n}",
"func (cl *ocxClient) CancelOrder(args []string) (err error) {\n\tif err = cl.UnlockKey(); err != nil {\n\t\tlogging.Fatalf(\"Could not unlock key! Fatal!\")\n\t}\n\torderID := args[0]\n\n\t// remove this and _ when cancel order has returns\n\t// var cancelOrderReply *cxrpc.CancelOrderReply\n\tif _, err = cl.RPCClient.CancelOrder(orderID); err != nil {\n\t\treturn\n\t}\n\n\tlogging.Infof(\"Cancelled order successfully\")\n\treturn\n}",
"func (_WyvernExchange *WyvernExchangeSession) CancelOrder(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _WyvernExchange.Contract.CancelOrder(&_WyvernExchange.TransactOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata, v, r, s)\n}",
"func (_WyvernExchange *WyvernExchangeTransactorSession) CancelOrder(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _WyvernExchange.Contract.CancelOrder(&_WyvernExchange.TransactOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata, v, r, s)\n}",
"func (w Wrapper) CancelOrder(_ context.Context, exch, orderid string, cp currency.Pair, a asset.Item) (bool, error) {\n\tif exch == exchError.String() {\n\t\treturn false, errTestFailed\n\t}\n\tif orderid == \"\" {\n\t\treturn false, errTestFailed\n\t}\n\tif !cp.IsEmpty() && cp.IsInvalid() {\n\t\treturn false, errTestFailed\n\t}\n\tif a != asset.Empty && !a.IsValid() {\n\t\treturn false, errTestFailed\n\t}\n\treturn true, nil\n}",
"func (o *Order) Cancel() {\n\to.status = OrderCancelPending\n}",
"func (_EtherDelta *EtherDeltaSession) CancelOrder(tokenGet common.Address, amountGet *big.Int, tokenGive common.Address, amountGive *big.Int, expires *big.Int, nonce *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _EtherDelta.Contract.CancelOrder(&_EtherDelta.TransactOpts, tokenGet, amountGet, tokenGive, amountGive, expires, nonce, v, r, s)\n}",
"func (g *Gemini) CancelExchangeOrder(p pair.CurrencyPair, orderID int64) (int64, error) {\n\treturn 0, errors.New(\"not yet implemented\")\n}",
"func (b *Bitfinex) CancelExchangeOrder(p pair.CurrencyPair, orderID int64) (int64, error) {\n\treturn 0, errors.New(\"not yet implemented\")\n}",
"func (m *Marketplace) CancelOrder(ctx context.Context, req *pb.Order) (*pb.Empty, error) {\n\n\tlogger := ctx_zap.Extract(ctx)\n\tlogger.Sugar().Infof(\"Canceling order %s\", req.GetId())\n\n\t// used by CheckPermissions bellow\n\torder, err := m.getOrderByID(req.GetId())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.OrderType = pb.OrderType(order.OrderType)\n\treq.ByuerID = order.BuyerID\n\treq.SupplierID = order.SupplierID\n\n\tif err := CheckPermissions(ctx, req); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.commandBus.Handle(command.CancelOrder{ID: req.Id}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Sugar().Infof(\"Order %s successfully canceled\", req.GetId())\n\n\treturn &pb.Empty{}, nil\n}",
"func (_EtherDelta *EtherDeltaTransactorSession) CancelOrder(tokenGet common.Address, amountGet *big.Int, tokenGive common.Address, amountGive *big.Int, expires *big.Int, nonce *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _EtherDelta.Contract.CancelOrder(&_EtherDelta.TransactOpts, tokenGet, amountGet, tokenGive, amountGive, expires, nonce, v, r, s)\n}",
"func (o *Order) Cancel() error {\n\tif o.Status == OrderStatusCANCELED {\n\t\treturn errors.Wrap(ErrInvalidTransition, \"Cancel\")\n\t}\n\n\to.Status = OrderStatusCANCELED\n\treturn nil\n}",
"func (client *Client) CancelTriggerOrder(orderID int64) (Response, error) {\n\tvar deleteResponse Response\n\tid := strconv.FormatInt(orderID, 10)\n\tresp, err := client._delete(\"conditional_orders/\"+id, []byte(\"\"))\n\tif err != nil {\n\t\tlog.Println(\"Error CancelTriggerOrder\", err)\n\t\treturn deleteResponse, err\n\t}\n\terr = _processResponse(resp, &deleteResponse)\n\treturn deleteResponse, err\n}",
"func (s *Socket) cancelOrder(p Payload) {\n\tocp := NewOrderCancelPayload()\n\n\tif err := ocp.DecodeOrderCancelPayload(p); err != nil {\n\t\tlog.Printf(\"Error: %v\", err)\n\t}\n\n\toc := ocp.OrderCancel\n\n\tif err := s.server.engine.CancelOrder(oc); err != nil {\n\t\tlog.Printf(\"Error: %v\", err)\n\t}\n}",
"func (c *Client) CancelOrder(serverAssignedOrderID string) error {\n\tfullURL := fmt.Sprintf(\"%s/%s\", ordersURL, serverAssignedOrderID)\n\treq, err := http.NewRequest(\"DELETE\", fullURL, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, _, err = c.doAuthAndReq(req)\n\treturn err\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
CancelOrderBatch cancels a batch of orders
|
func (h *HUOBI) CancelOrderBatch(ctx context.Context, orderIDs, clientOrderIDs []string) (*CancelOrderBatch, error) {
resp := struct {
Response
Data *CancelOrderBatch `json:"data"`
}{}
data := struct {
ClientOrderIDs []string `json:"client-order-ids"`
OrderIDs []string `json:"order-ids"`
}{
ClientOrderIDs: clientOrderIDs,
OrderIDs: orderIDs,
}
return resp.Data, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, huobiOrderCancelBatch, nil, data, &resp, false)
}
|
[
"func (h *HUOBIHADAX) CancelOrderBatch(orderIDs []int64) (CancelOrderBatch, error) {\n\ttype response struct {\n\t\tStatus string `json:\"status\"`\n\t\tData CancelOrderBatch `json:\"data\"`\n\t}\n\n\t// Used to send param formatting\n\ttype postBody struct {\n\t\tList []int64 `json:\"order-ids\"`\n\t}\n\n\t// Format to JSON\n\tbytesParams, _ := common.JSONEncode(&postBody{List: orderIDs})\n\tpostBodyParams := string(bytesParams)\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPPostRequest(http.MethodPost, huobihadaxOrderCancelBatch, postBodyParams, &result)\n\n\tif len(result.Data.Failed) != 0 {\n\t\terrJSON, _ := common.JSONEncode(result.Data.Failed)\n\t\treturn CancelOrderBatch{}, errors.New(string(errJSON))\n\t}\n\treturn result.Data, err\n}",
"func (b *BTCMarkets) CancelBatchOrders(ctx context.Context, o []order.Cancel) (*order.CancelBatchResponse, error) {\n\tif len(o) == 0 {\n\t\treturn nil, order.ErrCancelOrderIsNil\n\t}\n\tids := make([]string, len(o))\n\tfor i := range o {\n\t\tswitch {\n\t\tcase o[i].ClientOrderID != \"\":\n\t\t\treturn nil, order.ErrClientOrderIDNotSupported\n\t\tcase o[i].OrderID != \"\":\n\t\t\tids[i] = o[i].OrderID\n\t\tdefault:\n\t\t\treturn nil, order.ErrOrderIDNotSet\n\t\t}\n\t}\n\tbatchResp, err := b.CancelBatch(ctx, ids)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp := &order.CancelBatchResponse{\n\t\tStatus: make(map[string]string),\n\t}\n\tfor i := range batchResp.CancelOrders {\n\t\tresp.Status[batchResp.CancelOrders[i].OrderID] = \"success\"\n\t}\n\tfor i := range batchResp.UnprocessedRequests {\n\t\tresp.Status[batchResp.UnprocessedRequests[i].RequestID] = batchResp.UnprocessedRequests[i].Code + \" - \" + batchResp.UnprocessedRequests[i].Message\n\t}\n\n\treturn resp, nil\n}",
"func (h *HUOBI) CancelOpenOrdersBatch(ctx context.Context, accountID string, symbol currency.Pair) (CancelOpenOrdersBatch, error) {\n\tparams := url.Values{}\n\tsymbolValue, err := h.FormatSymbol(symbol, asset.Spot)\n\tif err != nil {\n\t\treturn CancelOpenOrdersBatch{}, err\n\t}\n\tparams.Set(\"account-id\", accountID)\n\tvar result CancelOpenOrdersBatch\n\n\tdata := struct {\n\t\tAccountID string `json:\"account-id\"`\n\t\tSymbol string `json:\"symbol\"`\n\t}{\n\t\tAccountID: accountID,\n\t\tSymbol: symbolValue,\n\t}\n\n\terr = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, huobiBatchCancelOpenOrders, url.Values{}, data, &result, false)\n\tif result.Data.FailedCount > 0 {\n\t\treturn result, fmt.Errorf(\"there were %v failed order cancellations\", result.Data.FailedCount)\n\t}\n\n\treturn result, err\n}",
"func (h *HUOBIHADAX) CancelOpenOrdersBatch(accountID, symbol string) (CancelOpenOrdersBatch, error) {\n\tparams := url.Values{}\n\n\tparams.Set(\"account-id\", accountID)\n\tvar result CancelOpenOrdersBatch\n\n\tdata := struct {\n\t\tAccountID string `json:\"account-id\"`\n\t\tSymbol string `json:\"symbol\"`\n\t}{\n\t\tAccountID: accountID,\n\t\tSymbol: symbol,\n\t}\n\n\tbytesParams, _ := common.JSONEncode(data)\n\tpostBodyParams := string(bytesParams)\n\n\terr := h.SendAuthenticatedHTTPPostRequest(http.MethodPost, huobiHadaxBatchCancelOpenOrders, postBodyParams, &result)\n\n\tif result.Data.FailedCount > 0 {\n\t\treturn result, fmt.Errorf(\"there were %v failed order cancellations\", result.Data.FailedCount)\n\t}\n\n\treturn result, err\n}",
"func (ok *Okx) WsCancelMultipleOrder(args []CancelOrderRequestParam) ([]OrderData, error) {\n\tfor x := range args {\n\t\targ := args[x]\n\t\tif arg.InstrumentID == \"\" {\n\t\t\treturn nil, errMissingInstrumentID\n\t\t}\n\t\tif arg.OrderID == \"\" && arg.ClientSupplierOrderID == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"either order id or client supplier id is required\")\n\t\t}\n\t}\n\trandomID, err := common.GenerateRandomString(4, common.NumberCharacters)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinput := WsCancelOrderInput{\n\t\tID: randomID,\n\t\tArguments: args,\n\t\tOperation: okxOpBatchCancelOrders,\n\t}\n\terr = ok.Websocket.AuthConn.SendJSONMessage(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttimer := time.NewTimer(ok.WebsocketResponseMaxLimit)\n\twsResponse := make(chan *wsIncomingData)\n\tok.WsResponseMultiplexer.Register <- &wsRequestInfo{\n\t\tID: randomID,\n\t\tChan: wsResponse,\n\t}\n\tdefer func() { ok.WsResponseMultiplexer.Unregister <- randomID }()\n\tfor {\n\t\tselect {\n\t\tcase data := <-wsResponse:\n\t\t\tif data.Operation == okxOpBatchCancelOrders && data.ID == input.ID {\n\t\t\t\tif data.Code == \"0\" || data.Code == \"2\" {\n\t\t\t\t\tvar resp *WSOrderResponse\n\t\t\t\t\tresp, err = data.copyToPlaceOrderResponse()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\treturn resp.Data, nil\n\t\t\t\t}\n\t\t\t\tif len(data.Data) == 0 {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error code:%s message: %v\", data.Code, ErrorCodes[data.Code])\n\t\t\t\t}\n\t\t\t\tvar resp WsOrderActionResponse\n\t\t\t\terr = resp.populateFromIncomingData(data)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\terr = json.Unmarshal(data.Data, &(resp.Data))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tvar errs error\n\t\t\t\tfor x := range resp.Data {\n\t\t\t\t\tif resp.Data[x].SCode != \"0\" {\n\t\t\t\t\t\terrs = common.AppendError(errs, fmt.Errorf(\"error code:%s message: %v\", resp.Data[x].SCode, resp.Data[x].SMessage))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil, errs\n\t\t\t}\n\t\t\tcontinue\n\t\tcase <-timer.C:\n\t\t\ttimer.Stop()\n\t\t\treturn nil, fmt.Errorf(\"%s websocket connection: timeout waiting for response with an operation: %v\",\n\t\t\t\tok.Name,\n\t\t\t\tinput.Operation)\n\t\t}\n\t}\n}",
"func (c *Coinbene) CancelSwapOrders(orderIDs []string) ([]OrderCancellationResponse, error) {\n\tif len(orderIDs) > 10 {\n\t\treturn nil, errors.New(\"only 10 orderIDs are allowed at a time\")\n\t}\n\treq := make(map[string]interface{})\n\treq[\"orderIds\"] = orderIDs\n\ttype resp struct {\n\t\tData []OrderCancellationResponse `json:\"data\"`\n\t}\n\n\tvar r resp\n\tpath := coinbeneAPIVersion + coinbeneBatchCancel\n\terr := c.SendAuthHTTPRequest(exchange.RestSwap, http.MethodPost,\n\t\tpath,\n\t\tcoinbeneBatchCancel,\n\t\ttrue,\n\t\treq,\n\t\t&r,\n\t\tcontractCancelMultipleOrders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Data, nil\n}",
"func CancelOrder(context echo.Context) error {\n\tid := context.Param(\"id\")\n\n\tDeletedID, err := DeleteOrder(id)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not bind request to struct: %+v\", err)\n\t\treturn util.SendError(context, \"\", \"\", \"\")\n\t}\n\n\treturn util.SendSuccess(context, DeletedID)\n\n}",
"func (c *Coinbene) CancelSpotOrders(orderIDs []string) ([]OrderCancellationResponse, error) {\n\treq := make(map[string]interface{})\n\treq[\"orderIds\"] = orderIDs\n\ttype resp struct {\n\t\tData []OrderCancellationResponse `json:\"data\"`\n\t}\n\n\tvar r resp\n\tpath := coinbeneAPIVersion + coinbeneBatchCancel\n\terr := c.SendAuthHTTPRequest(exchange.RestSpot, http.MethodPost,\n\t\tpath,\n\t\tcoinbeneBatchCancel,\n\t\tfalse,\n\t\treq,\n\t\t&r,\n\t\tspotCancelOrdersBatch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Data, nil\n}",
"func (cl *ocxClient) CancelOrder(args []string) (err error) {\n\tif err = cl.UnlockKey(); err != nil {\n\t\tlogging.Fatalf(\"Could not unlock key! Fatal!\")\n\t}\n\torderID := args[0]\n\n\t// remove this and _ when cancel order has returns\n\t// var cancelOrderReply *cxrpc.CancelOrderReply\n\tif _, err = cl.RPCClient.CancelOrder(orderID); err != nil {\n\t\treturn\n\t}\n\n\tlogging.Infof(\"Cancelled order successfully\")\n\treturn\n}",
"func (_EtherDelta *EtherDeltaSession) CancelOrder(tokenGet common.Address, amountGet *big.Int, tokenGive common.Address, amountGive *big.Int, expires *big.Int, nonce *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _EtherDelta.Contract.CancelOrder(&_EtherDelta.TransactOpts, tokenGet, amountGet, tokenGive, amountGive, expires, nonce, v, r, s)\n}",
"func (_EtherDelta *EtherDeltaTransactorSession) CancelOrder(tokenGet common.Address, amountGet *big.Int, tokenGive common.Address, amountGive *big.Int, expires *big.Int, nonce *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _EtherDelta.Contract.CancelOrder(&_EtherDelta.TransactOpts, tokenGet, amountGet, tokenGive, amountGive, expires, nonce, v, r, s)\n}",
"func (_WyvernExchange *WyvernExchangeSession) CancelOrder(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _WyvernExchange.Contract.CancelOrder(&_WyvernExchange.TransactOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata, v, r, s)\n}",
"func (_WyvernExchange *WyvernExchangeTransactorSession) CancelOrder(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _WyvernExchange.Contract.CancelOrder(&_WyvernExchange.TransactOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata, v, r, s)\n}",
"func (e *PlaceOrderServiceAdapter) CancelCustomerOrder(ctx context.Context, orderInfos placeorder.PlacedOrderInfos, auth auth.Identity) error {\n\torderNumbers := []string{}\n\tfor _, poi := range orderInfos {\n\t\torderNumbers = append(orderNumbers, poi.OrderNumber)\n\t}\n\treturn e.sendMail(e.emailAddress, &Mail{Subject: fmt.Sprintf(\"Customer Order(s) %v canceled\", strings.Join(orderNumbers, \";\"))})\n\n}",
"func (w Wrapper) CancelOrder(_ context.Context, exch, orderid string, cp currency.Pair, a asset.Item) (bool, error) {\n\tif exch == exchError.String() {\n\t\treturn false, errTestFailed\n\t}\n\tif orderid == \"\" {\n\t\treturn false, errTestFailed\n\t}\n\tif !cp.IsEmpty() && cp.IsInvalid() {\n\t\treturn false, errTestFailed\n\t}\n\tif a != asset.Empty && !a.IsValid() {\n\t\treturn false, errTestFailed\n\t}\n\treturn true, nil\n}",
"func (o *Okcoin) WsCancelMultipleOrders(args []CancelTradeOrderRequest) ([]TradeOrderResponse, error) {\n\tvar err error\n\tif len(args) == 0 {\n\t\treturn nil, fmt.Errorf(\"%w, 0 length place order requests\", errNilArgument)\n\t}\n\tfor x := range args {\n\t\terr = args[x].validate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar resp []TradeOrderResponse\n\treturn resp, o.SendWebsocketRequest(\"batch-cancel-orders\", args, &resp, true)\n}",
"func (s *Socket) cancelOrder(p Payload) {\n\tocp := NewOrderCancelPayload()\n\n\tif err := ocp.DecodeOrderCancelPayload(p); err != nil {\n\t\tlog.Printf(\"Error: %v\", err)\n\t}\n\n\toc := ocp.OrderCancel\n\n\tif err := s.server.engine.CancelOrder(oc); err != nil {\n\t\tlog.Printf(\"Error: %v\", err)\n\t}\n}",
"func (e *PlaceOrderServiceAdapter) CancelGuestOrder(ctx context.Context, orderInfos placeorder.PlacedOrderInfos) error {\n\torderNumbers := []string{}\n\tfor _, poi := range orderInfos {\n\t\torderNumbers = append(orderNumbers, poi.OrderNumber)\n\t}\n\treturn e.sendMail(e.emailAddress, &Mail{Subject: fmt.Sprintf(\"Guest Order(s) %v canceled\", strings.Join(orderNumbers, \";\"))})\n}",
"func (a adminAPIHandlers) CancelBatchJob(w http.ResponseWriter, r *http.Request) {\n\tctx := newContext(r, w, \"CancelBatchJob\")\n\n\tdefer logger.AuditLog(ctx, w, r, mustGetClaimsFromToken(r))\n\n\tobjectAPI, _ := validateAdminReq(ctx, w, r, iampolicy.CancelBatchJobAction)\n\tif objectAPI == nil {\n\t\treturn\n\t}\n\tjobID := r.Form.Get(\"id\")\n\tif jobID == \"\" {\n\t\twriteErrorResponseJSON(ctx, w, toAPIError(ctx, errInvalidArgument), r.URL)\n\t\treturn\n\t}\n\tif err := globalBatchJobPool.canceler(jobID, true); err != nil {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErrWithErr(ErrInvalidRequest, err), r.URL)\n\t\treturn\n\t}\n\tj := BatchJobRequest{\n\t\tID: jobID,\n\t\tLocation: pathJoin(batchJobPrefix, jobID),\n\t}\n\tj.delete(ctx, objectAPI)\n\n\twriteSuccessNoContent(w)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
CancelOpenOrdersBatch cancels a batch of orders todo
|
func (h *HUOBI) CancelOpenOrdersBatch(ctx context.Context, accountID string, symbol currency.Pair) (CancelOpenOrdersBatch, error) {
params := url.Values{}
symbolValue, err := h.FormatSymbol(symbol, asset.Spot)
if err != nil {
return CancelOpenOrdersBatch{}, err
}
params.Set("account-id", accountID)
var result CancelOpenOrdersBatch
data := struct {
AccountID string `json:"account-id"`
Symbol string `json:"symbol"`
}{
AccountID: accountID,
Symbol: symbolValue,
}
err = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, huobiBatchCancelOpenOrders, url.Values{}, data, &result, false)
if result.Data.FailedCount > 0 {
return result, fmt.Errorf("there were %v failed order cancellations", result.Data.FailedCount)
}
return result, err
}
|
[
"func (h *HUOBIHADAX) CancelOpenOrdersBatch(accountID, symbol string) (CancelOpenOrdersBatch, error) {\n\tparams := url.Values{}\n\n\tparams.Set(\"account-id\", accountID)\n\tvar result CancelOpenOrdersBatch\n\n\tdata := struct {\n\t\tAccountID string `json:\"account-id\"`\n\t\tSymbol string `json:\"symbol\"`\n\t}{\n\t\tAccountID: accountID,\n\t\tSymbol: symbol,\n\t}\n\n\tbytesParams, _ := common.JSONEncode(data)\n\tpostBodyParams := string(bytesParams)\n\n\terr := h.SendAuthenticatedHTTPPostRequest(http.MethodPost, huobiHadaxBatchCancelOpenOrders, postBodyParams, &result)\n\n\tif result.Data.FailedCount > 0 {\n\t\treturn result, fmt.Errorf(\"there were %v failed order cancellations\", result.Data.FailedCount)\n\t}\n\n\treturn result, err\n}",
"func (h *HUOBI) CancelOrderBatch(ctx context.Context, orderIDs, clientOrderIDs []string) (*CancelOrderBatch, error) {\n\tresp := struct {\n\t\tResponse\n\t\tData *CancelOrderBatch `json:\"data\"`\n\t}{}\n\tdata := struct {\n\t\tClientOrderIDs []string `json:\"client-order-ids\"`\n\t\tOrderIDs []string `json:\"order-ids\"`\n\t}{\n\t\tClientOrderIDs: clientOrderIDs,\n\t\tOrderIDs: orderIDs,\n\t}\n\treturn resp.Data, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, huobiOrderCancelBatch, nil, data, &resp, false)\n}",
"func (b *BTCMarkets) CancelBatchOrders(ctx context.Context, o []order.Cancel) (*order.CancelBatchResponse, error) {\n\tif len(o) == 0 {\n\t\treturn nil, order.ErrCancelOrderIsNil\n\t}\n\tids := make([]string, len(o))\n\tfor i := range o {\n\t\tswitch {\n\t\tcase o[i].ClientOrderID != \"\":\n\t\t\treturn nil, order.ErrClientOrderIDNotSupported\n\t\tcase o[i].OrderID != \"\":\n\t\t\tids[i] = o[i].OrderID\n\t\tdefault:\n\t\t\treturn nil, order.ErrOrderIDNotSet\n\t\t}\n\t}\n\tbatchResp, err := b.CancelBatch(ctx, ids)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp := &order.CancelBatchResponse{\n\t\tStatus: make(map[string]string),\n\t}\n\tfor i := range batchResp.CancelOrders {\n\t\tresp.Status[batchResp.CancelOrders[i].OrderID] = \"success\"\n\t}\n\tfor i := range batchResp.UnprocessedRequests {\n\t\tresp.Status[batchResp.UnprocessedRequests[i].RequestID] = batchResp.UnprocessedRequests[i].Code + \" - \" + batchResp.UnprocessedRequests[i].Message\n\t}\n\n\treturn resp, nil\n}",
"func (h *HUOBIHADAX) CancelOrderBatch(orderIDs []int64) (CancelOrderBatch, error) {\n\ttype response struct {\n\t\tStatus string `json:\"status\"`\n\t\tData CancelOrderBatch `json:\"data\"`\n\t}\n\n\t// Used to send param formatting\n\ttype postBody struct {\n\t\tList []int64 `json:\"order-ids\"`\n\t}\n\n\t// Format to JSON\n\tbytesParams, _ := common.JSONEncode(&postBody{List: orderIDs})\n\tpostBodyParams := string(bytesParams)\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPPostRequest(http.MethodPost, huobihadaxOrderCancelBatch, postBodyParams, &result)\n\n\tif len(result.Data.Failed) != 0 {\n\t\terrJSON, _ := common.JSONEncode(result.Data.Failed)\n\t\treturn CancelOrderBatch{}, errors.New(string(errJSON))\n\t}\n\treturn result.Data, err\n}",
"func (c *Coinbene) CancelSpotOrders(orderIDs []string) ([]OrderCancellationResponse, error) {\n\treq := make(map[string]interface{})\n\treq[\"orderIds\"] = orderIDs\n\ttype resp struct {\n\t\tData []OrderCancellationResponse `json:\"data\"`\n\t}\n\n\tvar r resp\n\tpath := coinbeneAPIVersion + coinbeneBatchCancel\n\terr := c.SendAuthHTTPRequest(exchange.RestSpot, http.MethodPost,\n\t\tpath,\n\t\tcoinbeneBatchCancel,\n\t\tfalse,\n\t\treq,\n\t\t&r,\n\t\tspotCancelOrdersBatch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Data, nil\n}",
"func (ok *Okx) WsCancelMultipleOrder(args []CancelOrderRequestParam) ([]OrderData, error) {\n\tfor x := range args {\n\t\targ := args[x]\n\t\tif arg.InstrumentID == \"\" {\n\t\t\treturn nil, errMissingInstrumentID\n\t\t}\n\t\tif arg.OrderID == \"\" && arg.ClientSupplierOrderID == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"either order id or client supplier id is required\")\n\t\t}\n\t}\n\trandomID, err := common.GenerateRandomString(4, common.NumberCharacters)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinput := WsCancelOrderInput{\n\t\tID: randomID,\n\t\tArguments: args,\n\t\tOperation: okxOpBatchCancelOrders,\n\t}\n\terr = ok.Websocket.AuthConn.SendJSONMessage(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttimer := time.NewTimer(ok.WebsocketResponseMaxLimit)\n\twsResponse := make(chan *wsIncomingData)\n\tok.WsResponseMultiplexer.Register <- &wsRequestInfo{\n\t\tID: randomID,\n\t\tChan: wsResponse,\n\t}\n\tdefer func() { ok.WsResponseMultiplexer.Unregister <- randomID }()\n\tfor {\n\t\tselect {\n\t\tcase data := <-wsResponse:\n\t\t\tif data.Operation == okxOpBatchCancelOrders && data.ID == input.ID {\n\t\t\t\tif data.Code == \"0\" || data.Code == \"2\" {\n\t\t\t\t\tvar resp *WSOrderResponse\n\t\t\t\t\tresp, err = data.copyToPlaceOrderResponse()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\treturn resp.Data, nil\n\t\t\t\t}\n\t\t\t\tif len(data.Data) == 0 {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error code:%s message: %v\", data.Code, ErrorCodes[data.Code])\n\t\t\t\t}\n\t\t\t\tvar resp WsOrderActionResponse\n\t\t\t\terr = resp.populateFromIncomingData(data)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\terr = json.Unmarshal(data.Data, &(resp.Data))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tvar errs error\n\t\t\t\tfor x := range resp.Data {\n\t\t\t\t\tif resp.Data[x].SCode != \"0\" {\n\t\t\t\t\t\terrs = common.AppendError(errs, fmt.Errorf(\"error code:%s message: %v\", resp.Data[x].SCode, resp.Data[x].SMessage))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil, errs\n\t\t\t}\n\t\t\tcontinue\n\t\tcase <-timer.C:\n\t\t\ttimer.Stop()\n\t\t\treturn nil, fmt.Errorf(\"%s websocket connection: timeout waiting for response with an operation: %v\",\n\t\t\t\tok.Name,\n\t\t\t\tinput.Operation)\n\t\t}\n\t}\n}",
"func (c *Coinbene) CancelSwapOrders(orderIDs []string) ([]OrderCancellationResponse, error) {\n\tif len(orderIDs) > 10 {\n\t\treturn nil, errors.New(\"only 10 orderIDs are allowed at a time\")\n\t}\n\treq := make(map[string]interface{})\n\treq[\"orderIds\"] = orderIDs\n\ttype resp struct {\n\t\tData []OrderCancellationResponse `json:\"data\"`\n\t}\n\n\tvar r resp\n\tpath := coinbeneAPIVersion + coinbeneBatchCancel\n\terr := c.SendAuthHTTPRequest(exchange.RestSwap, http.MethodPost,\n\t\tpath,\n\t\tcoinbeneBatchCancel,\n\t\ttrue,\n\t\treq,\n\t\t&r,\n\t\tcontractCancelMultipleOrders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Data, nil\n}",
"func (o *Okcoin) WsCancelMultipleOrders(args []CancelTradeOrderRequest) ([]TradeOrderResponse, error) {\n\tvar err error\n\tif len(args) == 0 {\n\t\treturn nil, fmt.Errorf(\"%w, 0 length place order requests\", errNilArgument)\n\t}\n\tfor x := range args {\n\t\terr = args[x].validate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar resp []TradeOrderResponse\n\treturn resp, o.SendWebsocketRequest(\"batch-cancel-orders\", args, &resp, true)\n}",
"func (h *HitBTC) CancelAllExistingOrders(ctx context.Context) ([]Order, error) {\n\tvar result []Order\n\tvalues := url.Values{}\n\treturn result, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodDelete,\n\t\tapiOrder,\n\t\tvalues,\n\t\ttradingRequests,\n\t\t&result)\n}",
"func (e *PlaceOrderServiceAdapter) CancelCustomerOrder(ctx context.Context, orderInfos placeorder.PlacedOrderInfos, auth auth.Identity) error {\n\torderNumbers := []string{}\n\tfor _, poi := range orderInfos {\n\t\torderNumbers = append(orderNumbers, poi.OrderNumber)\n\t}\n\treturn e.sendMail(e.emailAddress, &Mail{Subject: fmt.Sprintf(\"Customer Order(s) %v canceled\", strings.Join(orderNumbers, \";\"))})\n\n}",
"func TestWsCancelMultiOrders(t *testing.T) {\n\tif !b.Websocket.IsEnabled() && !b.API.AuthenticatedWebsocketSupport {\n\t\tsharedtestvalues.SkipTestIfCredentialsUnset(t, b)\n\t}\n\tif !wsAuthExecuted {\n\t\trunAuth(t)\n\t}\n\terr := b.WsCancelMultiOrders([]int64{1, 2, 3, 4})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}",
"func (h *Hbdm) CancelAllOrders(symbol string) (resp *CancelAllOrdersResponse, err error) {\n\tpayload := make(map[string]interface{}, 1)\n\tpayload[\"symbol\"] = symbol\n\n\tr, err := h.client.do(\"POST\", \"contract_cancelall\", payload, true)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar response interface{}\n\tif err = json.Unmarshal(r, &response); err != nil {\n\t\treturn\n\t}\n\n\tif err = handleErr(response); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r, &resp)\n\treturn\n\n}",
"func CancelOrder(context echo.Context) error {\n\tid := context.Param(\"id\")\n\n\tDeletedID, err := DeleteOrder(id)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not bind request to struct: %+v\", err)\n\t\treturn util.SendError(context, \"\", \"\", \"\")\n\t}\n\n\treturn util.SendSuccess(context, DeletedID)\n\n}",
"func (p *Poloniex) CancelMultipleOrdersByIDs(ctx context.Context, orderIDs, clientOrderIDs []string) ([]CancelOrdersResponse, error) {\n\tvalues := url.Values{}\n\tif len(orderIDs) > 0 {\n\t\tvalues.Set(\"orderIds\", strings.Join(orderIDs, \",\"))\n\t}\n\tif len(clientOrderIDs) > 0 {\n\t\tvalues.Set(\"clientOrderIds\", strings.Join(clientOrderIDs, \",\"))\n\t}\n\tvar result []CancelOrdersResponse\n\treturn result, p.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodDelete,\n\t\tpoloniexCancelByIDs,\n\t\tvalues,\n\t\t&result)\n}",
"func (_WyvernExchange *WyvernExchangeSession) CancelOrder(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _WyvernExchange.Contract.CancelOrder(&_WyvernExchange.TransactOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata, v, r, s)\n}",
"func (cl *ocxClient) CancelOrder(args []string) (err error) {\n\tif err = cl.UnlockKey(); err != nil {\n\t\tlogging.Fatalf(\"Could not unlock key! Fatal!\")\n\t}\n\torderID := args[0]\n\n\t// remove this and _ when cancel order has returns\n\t// var cancelOrderReply *cxrpc.CancelOrderReply\n\tif _, err = cl.RPCClient.CancelOrder(orderID); err != nil {\n\t\treturn\n\t}\n\n\tlogging.Infof(\"Cancelled order successfully\")\n\treturn\n}",
"func (_WyvernExchange *WyvernExchangeTransactorSession) CancelOrder(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _WyvernExchange.Contract.CancelOrder(&_WyvernExchange.TransactOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata, v, r, s)\n}",
"func (b *Bitfinex) CancelAllExchangeOrders(p pair.CurrencyPair) error {\n\treturn errors.New(\"not yet implemented\")\n}",
"func (_EtherDelta *EtherDeltaSession) CancelOrder(tokenGet common.Address, amountGet *big.Int, tokenGive common.Address, amountGive *big.Int, expires *big.Int, nonce *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _EtherDelta.Contract.CancelOrder(&_EtherDelta.TransactOpts, tokenGet, amountGet, tokenGive, amountGive, expires, nonce, v, r, s)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetOrderMatchResults returns matched order info for the specified order
|
func (h *HUOBI) GetOrderMatchResults(ctx context.Context, orderID int64) ([]OrderMatchInfo, error) {
resp := struct {
Orders []OrderMatchInfo `json:"data"`
}{}
endpoint := fmt.Sprintf(huobiGetOrderMatch, strconv.FormatInt(orderID, 10))
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, endpoint, url.Values{}, nil, &resp, false)
return resp.Orders, err
}
|
[
"func (h *HUOBIHADAX) GetOrderMatchResults(orderID int64) ([]OrderMatchInfo, error) {\n\ttype response struct {\n\t\tResponse\n\t\tOrders []OrderMatchInfo `json:\"data\"`\n\t}\n\n\tvar result response\n\tendpoint := fmt.Sprintf(huobihadaxGetOrderMatch, strconv.FormatInt(orderID, 10))\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodGet, endpoint, url.Values{}, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Orders, err\n}",
"func (h *HUOBI) GetOrdersMatch(ctx context.Context, symbol currency.Pair, types, start, end, from, direct, size string) ([]OrderMatchInfo, error) {\n\tresp := struct {\n\t\tOrders []OrderMatchInfo `json:\"data\"`\n\t}{}\n\n\tvals := url.Values{}\n\tsymbolValue, err := h.FormatSymbol(symbol, asset.Spot)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvals.Set(\"symbol\", symbolValue)\n\n\tif types != \"\" {\n\t\tvals.Set(\"types\", types)\n\t}\n\n\tif start != \"\" {\n\t\tvals.Set(\"start-date\", start)\n\t}\n\n\tif end != \"\" {\n\t\tvals.Set(\"end-date\", end)\n\t}\n\n\tif from != \"\" {\n\t\tvals.Set(\"from\", from)\n\t}\n\n\tif direct != \"\" {\n\t\tvals.Set(\"direct\", direct)\n\t}\n\n\tif size != \"\" {\n\t\tvals.Set(\"size\", size)\n\t}\n\n\terr = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiGetOrdersMatch, vals, nil, &resp, false)\n\treturn resp.Orders, err\n}",
"func (h *HUOBIHADAX) GetOrdersMatch(symbol, types, start, end, from, direct, size string) ([]OrderMatchInfo, error) {\n\ttype response struct {\n\t\tResponse\n\t\tOrders []OrderMatchInfo `json:\"data\"`\n\t}\n\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\n\tif types != \"\" {\n\t\tvals.Set(\"types\", types)\n\t}\n\n\tif start != \"\" {\n\t\tvals.Set(\"start-date\", start)\n\t}\n\n\tif end != \"\" {\n\t\tvals.Set(\"end-date\", end)\n\t}\n\n\tif from != \"\" {\n\t\tvals.Set(\"from\", from)\n\t}\n\n\tif direct != \"\" {\n\t\tvals.Set(\"direct\", direct)\n\t}\n\n\tif size != \"\" {\n\t\tvals.Set(\"size\", size)\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodGet, huobihadaxGetOrdersMatch, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Orders, err\n}",
"func (m *Market) Match() (matched []Order) {\n\t// loop till there is no match in either Bid or Offer side\n\tfor m.Bids.Len() > 0 && m.Offers.Len() > 0 {\n\t\tbestBid := m.Bids.orders[0]\n\t\tbestOffer := m.Offers.orders[0]\n\n\t\tprice := bestOffer.Price\n\t\tquantity := bestBid.OpenQuantity()\n\t\tif offerQuant := bestOffer.OpenQuantity(); offerQuant.Cmp(quantity) == -1 {\n\t\t\tquantity = offerQuant\n\t\t}\n\n\t\tbestBid.Execute(price, quantity)\n\t\tbestOffer.Execute(price, quantity)\n\n\t\tmatched = append(matched, *bestBid, *bestOffer)\n\n\t\tif bestBid.IsClosed() {\n\t\t\tm.Bids.orders = m.Bids.orders[1:]\n\t\t}\n\n\t\tif bestOffer.IsClosed() {\n\t\t\tm.Offers.orders = m.Offers.orders[1:]\n\t\t}\n\t}\n\n\treturn\n}",
"func findMatchingOrder(cmClient cmclient.Interface, ctx context.Context, req *cmapi.CertificateRequest) (*cmacme.Order, error) {\n\torders, err := cmClient.AcmeV1().Orders(req.Namespace).List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpossibleMatches := []*cmacme.Order{}\n\tfor _, order := range orders.Items {\n\t\tif predicate.ResourceOwnedBy(req)(&order) {\n\t\t\tpossibleMatches = append(possibleMatches, order.DeepCopy())\n\t\t}\n\t}\n\n\tif len(possibleMatches) < 1 {\n\t\treturn nil, nil\n\t} else if len(possibleMatches) == 1 {\n\t\treturn possibleMatches[0], nil\n\t} else {\n\t\treturn nil, fmt.Errorf(\"found multiple orders owned by CertificateRequest %s\", req.Name)\n\t}\n}",
"func (m *Matcher) Match(book Booker, queue []order.Order) (matches []*order.MatchSet, passed, failed, doneOK, partial, booked, unbooked []order.Order) {\n\t// Apply the deterministic pseudorandom shuffling.\n\tshuffleQueue(queue)\n\n\t// For each order in the queue, find the best match in the book.\n\tfor _, q := range queue {\n\t\tif !orderLotSizeOK(q, book.LotSize()) {\n\t\t\tlog.Warnf(\"Order with bad lot size in the queue: %v!\", q.ID())\n\t\t\tfailed = append(failed, q)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch o := q.(type) {\n\t\tcase *order.CancelOrder:\n\t\t\tremoved, ok := book.Remove(o.TargetOrderID)\n\t\t\tif !ok {\n\t\t\t\t// The targeted order might be down queue or non-existent.\n\t\t\t\tlog.Debugf(\"Failed to remove order %v set by a cancel order %v\",\n\t\t\t\t\to.ID(), o.TargetOrderID)\n\t\t\t\tfailed = append(failed, q)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpassed = append(passed, q)\n\t\t\tdoneOK = append(doneOK, q)\n\t\t\t// CancelOrder Match has zero values for Amounts, Rates, and Total.\n\t\t\tmatches = append(matches, &order.MatchSet{\n\t\t\t\tTaker: q,\n\t\t\t\tMakers: []*order.LimitOrder{removed},\n\t\t\t\tAmounts: []uint64{removed.Remaining()},\n\t\t\t\tRates: []uint64{removed.Rate},\n\t\t\t})\n\t\t\tunbooked = append(unbooked, removed)\n\n\t\tcase *order.LimitOrder:\n\t\t\t// limit-limit order matching\n\t\t\tvar makers []*order.LimitOrder\n\t\t\tmatchSet := matchLimitOrder(book, o)\n\t\t\tif matchSet != nil {\n\t\t\t\tmatches = append(matches, matchSet)\n\t\t\t\tmakers = matchSet.Makers\n\t\t\t} else if o.Force == order.ImmediateTiF {\n\t\t\t\t// There was no match and TiF is Immediate. Fail.\n\t\t\t\tfailed = append(failed, q)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Either matched or standing unmatched => passed.\n\t\t\tpassed = append(passed, q)\n\n\t\t\t// Unbook matched makers with no remaining amount.\n\t\t\tfor _, maker := range makers {\n\t\t\t\tif maker.Remaining() == 0 {\n\t\t\t\t\tunbooked = append(unbooked, maker)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar wasBooked bool\n\t\t\tif o.Remaining() > 0 {\n\t\t\t\tif matchSet != nil {\n\t\t\t\t\tpartial = append(partial, q)\n\t\t\t\t}\n\t\t\t\tif o.Force == order.StandingTiF {\n\t\t\t\t\t// Standing TiF orders go on the book.\n\t\t\t\t\tbook.Insert(o)\n\t\t\t\t\tbooked = append(booked, q)\n\t\t\t\t\twasBooked = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !wasBooked {\n\t\t\t\tdoneOK = append(doneOK, q)\n\t\t\t}\n\n\t\tcase *order.MarketOrder:\n\t\t\t// market-limit order matching\n\t\t\tvar matchSet *order.MatchSet\n\t\t\tif o.Sell {\n\t\t\t\tmatchSet = matchMarketSellOrder(book, o)\n\t\t\t} else {\n\t\t\t\t// Market buy order Quantity is denominated in the quote asset,\n\t\t\t\t// and lot size multiples are not applicable.\n\t\t\t\tmatchSet = matchMarketBuyOrder(book, o)\n\t\t\t}\n\t\t\tif matchSet != nil {\n\t\t\t\tmatches = append(matches, matchSet)\n\t\t\t\tpassed = append(passed, q)\n\t\t\t\tdoneOK = append(doneOK, q)\n\t\t\t} else {\n\t\t\t\t// There was no match and this is a market order. Fail.\n\t\t\t\tfailed = append(failed, q)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tfor _, maker := range matchSet.Makers {\n\t\t\t\tif maker.Remaining() == 0 {\n\t\t\t\t\tunbooked = append(unbooked, maker)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Regardless of remaining amount, market orders never go on the book.\n\t\t}\n\n\t}\n\n\treturn\n}",
"func orderMatchCompare(l, r *Order) (matched bool, msg string) {\n\t// Market order at any side is tradable\n\tif l.Type == pb.OrderType_MARKET || r.Type == pb.OrderType_MARKET {\n\t\treturn true, \"a market match\"\n\t}\n\tvar bid, ask *Order\n\tif l.Side == pb.OrderSide_BID {\n\t\tbid, ask = l, r\n\t} else {\n\t\tbid, ask = r, l\n\t}\n\tmatched = (bid.Price.Cmp(ask.Price) >= 0)\n\tif !matched {\n\t\tmsg = fmt.Sprintf(\"not match because bid price %v, ask price %v\", bid, ask)\n\t}\n\tmsg = fmt.Sprintf(\"matched because bid price %v, ask price %v\", bid, ask)\n\treturn\n}",
"func (_WyvernExchange *WyvernExchangeFilterer) FilterOrdersMatched(opts *bind.FilterOpts, maker []common.Address, taker []common.Address, metadata [][32]byte) (*WyvernExchangeOrdersMatchedIterator, error) {\n\n\tvar makerRule []interface{}\n\tfor _, makerItem := range maker {\n\t\tmakerRule = append(makerRule, makerItem)\n\t}\n\tvar takerRule []interface{}\n\tfor _, takerItem := range taker {\n\t\ttakerRule = append(takerRule, takerItem)\n\t}\n\n\tvar metadataRule []interface{}\n\tfor _, metadataItem := range metadata {\n\t\tmetadataRule = append(metadataRule, metadataItem)\n\t}\n\n\tlogs, sub, err := _WyvernExchange.contract.FilterLogs(opts, \"OrdersMatched\", makerRule, takerRule, metadataRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &WyvernExchangeOrdersMatchedIterator{contract: _WyvernExchange.contract, event: \"OrdersMatched\", logs: logs, sub: sub}, nil\n}",
"func ParseRPCMatchedOrders(orders *auctioneerrpc.MatchedOrder) ([]*MatchedOrder,\n\terror) {\n\n\tvar result []*MatchedOrder\n\t// The only thing we can check in this step is that not both matched\n\t// bids and matched asks are set at the same time as that wouldn't make\n\t// sense. Everything else is checked at a later stage when we know more\n\t// about our order that was matched against.\n\tswitch {\n\tcase len(orders.MatchedAsks) > 0 && len(orders.MatchedBids) > 0:\n\t\treturn nil, fmt.Errorf(\"order cannot match both asks and bids\")\n\n\tcase len(orders.MatchedAsks) > 0:\n\t\tfor _, ask := range orders.MatchedAsks {\n\t\t\tmatchedAsk, err := ParseRPCServerAsk(ask.Ask)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error parsing server \"+\n\t\t\t\t\t\"ask: %v\", err)\n\t\t\t}\n\t\t\tmatchedAsk.UnitsFilled = SupplyUnit(ask.UnitsFilled)\n\n\t\t\tresult = append(result, matchedAsk)\n\t\t}\n\n\tcase len(orders.MatchedBids) > 0:\n\t\tfor _, bid := range orders.MatchedBids {\n\t\t\tmatchedBid, err := ParseRPCServerBid(bid.Bid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error parsing server \"+\n\t\t\t\t\t\"bid: %v\", err)\n\t\t\t}\n\t\t\tmatchedBid.UnitsFilled = SupplyUnit(bid.UnitsFilled)\n\n\t\t\tresult = append(result, matchedBid)\n\t\t}\n\t}\n\n\treturn result, nil\n}",
"func OrdersMatch(a, b order.Order) bool {\n\t// Get order data needed for comparison.\n\taType, aSell, _, aRate := orderData(a)\n\tbType, bSell, _, bRate := orderData(b)\n\n\t// Orders must be on opposite sides of the market.\n\tif aSell == bSell {\n\t\treturn false\n\t}\n\n\t// Screen order types.\n\tswitch aType {\n\tcase order.MarketOrderType:\n\t\tswitch bType {\n\t\tcase order.LimitOrderType:\n\t\t\treturn true // market-limit\n\t\tcase order.MarketOrderType:\n\t\t\tfallthrough // no two market orders\n\t\tdefault:\n\t\t\treturn false // cancel or unknown\n\t\t}\n\tcase order.LimitOrderType:\n\t\tswitch bType {\n\t\tcase order.LimitOrderType:\n\t\t\t// limit-limit: must check rates\n\t\tcase order.MarketOrderType:\n\t\t\treturn true // limit-market\n\t\tdefault:\n\t\t\treturn false // cancel or unknown\n\t\t}\n\tdefault: // cancel or unknown\n\t\treturn false\n\t}\n\n\t// For limit-limit orders, check that the rates overlap.\n\tcmp := func(buyRate, sellRate uint64) bool { return sellRate <= buyRate }\n\tif bSell {\n\t\t// a is buy, b is sell\n\t\treturn cmp(aRate, bRate)\n\t}\n\t// a is sell, b is buy\n\treturn cmp(bRate, aRate)\n}",
"func (s *orderMgtServer) SearchOrders(searchQuery *wrappers.StringValue, stream pb.OrderManagement_SearchOrdersServer) error {\n\tfor key, order := range orderMap {\n\t\tlog.Print(key, order)\n\t\tfor _, itemStr := range order.Items {\n\t\t\tlog.Print(itemStr)\n\t\t\tif strings.Contains(itemStr, searchQuery.Value) {\n\t\t\t\t// Send the matching orders in a stream\n\t\t\t\terr := stream.Send(&order)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error sending message to stream : %v\", err)\n\t\t\t\t}\n\t\t\t\tlog.Print(\"Matching Order Found : \" + key)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (k Keeper) OnOrderMatched(ctx sdk.Context, order types.Order) {\n\t// TODO: assert state transition\n\torder.State = types.OrderMatched\n\tk.updateOrder(ctx, order)\n}",
"func (mgr OrderManager) Search(qry *OrderInfoQuery, pg *Pagination) ([]OrderInfo, error) {\n\tsqlFmt := `\n\t\tselect O.id, O.order_name, O.created_at, O.customer_id, \n\t\t\tsum(OI.quantity * price_per_unit) as total_amount, \n\t\t\tsum(delivered_quantity * price_per_unit) as delivered_amount\n\t\tfrom orders as O\n\t\t\tjoin order_items as OI on O.id = OI.order_id\n\t\t\tjoin deliveries as D on D.order_item_id = OI.id\n\t\t%s\n\t\tgroup by O.id\n\t\t%s`\n\n\twhereClause, values, err := mgr.generateWhereClause(qry)\n\tif (err != nil) {\n\t\treturn nil, err\n\t}\n\tlimitOffset, values := mgr.generateLimitOffset(pg, values)\n\n\tsql := fmt.Sprintf(sqlFmt, whereClause, limitOffset)\n\n\tstmt, err := mgr.db.Prepare(sql)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Preparing sql statement failed. %w\", err)\n\t}\n\tdefer stmt.Close()\n\n\trows, err := stmt.Query(values...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Querying database failed. %w\", err)\n\t}\n\n\torderInfos := []OrderInfo{}\n\n\tfor rows.Next() {\n\t\tvar oi OrderInfo\n\t\terr := rows.Scan(&oi.OrderID, &oi.OrderName, &oi.CreatedAt, &oi.CustomerID, &oi.TotalAmount, &oi.DeliveredAmount)\n\t\tif (err != nil) {\n\t\t\tlog.Printf(\"Structuring returned data failed.\", err.Error())\n\t\t}\n\t\torderInfos = append(orderInfos, oi)\n\t}\n\treturn orderInfos, nil\n}",
"func (_WyvernExchange *WyvernExchangeFilterer) WatchOrdersMatched(opts *bind.WatchOpts, sink chan<- *WyvernExchangeOrdersMatched, maker []common.Address, taker []common.Address, metadata [][32]byte) (event.Subscription, error) {\n\n\tvar makerRule []interface{}\n\tfor _, makerItem := range maker {\n\t\tmakerRule = append(makerRule, makerItem)\n\t}\n\tvar takerRule []interface{}\n\tfor _, takerItem := range taker {\n\t\ttakerRule = append(takerRule, takerItem)\n\t}\n\n\tvar metadataRule []interface{}\n\tfor _, metadataItem := range metadata {\n\t\tmetadataRule = append(metadataRule, metadataItem)\n\t}\n\n\tlogs, sub, err := _WyvernExchange.contract.WatchLogs(opts, \"OrdersMatched\", makerRule, takerRule, metadataRule)\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(WyvernExchangeOrdersMatched)\n\t\t\t\tif err := _WyvernExchange.contract.UnpackLog(event, \"OrdersMatched\", 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 (_DevUtils *DevUtilsTransactor) GetSimulatedOrderTransferResults(opts *bind.TransactOpts, order LibOrderOrder, takerAddress common.Address, takerAssetFillAmount *big.Int) (*types.Transaction, error) {\n\treturn _DevUtils.contract.Transact(opts, \"getSimulatedOrderTransferResults\", order, takerAddress, takerAssetFillAmount)\n}",
"func match(aggressive, resting *order) (bool, int) {\n\tif aggressive.IsMarket() {\n\t\t// a market order matches any resting order regardless of price\n\t\treturn true, resting.Price\n\t} else {\n\t\tif aggressive.IsBuy() {\n\t\t\tif aggressive.Price >= resting.Price {\n\t\t\t\treturn true, resting.Price\n\t\t\t}\n\t\t} else {\n\t\t\tif aggressive.Price <= resting.Price {\n\t\t\t\treturn true, resting.Price\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false, -1\n}",
"func (e *exmo) GetOrders(ctx context.Context, pairs ...model.Pair) (pairOrders model.PairOrders, err error) {\n\n\tif len(pairs) == 0 {\n\t\terr = errors.New(\"`pairs` must not be empty\")\n\t\treturn\n\t}\n\n\tpairParam := \"\"\n\tfor _, pair := range pairs {\n\t\tpairParam += string(pair) + \",\"\n\t}\n\tpairParam = strings.TrimRight(pairParam, \",\")\n\n\tresp, err := e.doRequest(ctx, http.MethodGet, e.baseUrl+\"/order_book/?limit=1&pair=\"+pairParam, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tvar bodyStruct map[model.Pair]struct {\n\t\tAsk [][]string\n\t\tBid [][]string\n\t}\n\terr = json.NewDecoder(resp.Body).Decode(&bodyStruct)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpairOrders = model.PairOrders{}\n\n\tfor bodyPair, bodyOrder := range bodyStruct {\n\n\t\tif len(bodyOrder.Ask) == 0 || len(bodyOrder.Bid) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(bodyOrder.Ask[0]) != 3 || len(bodyOrder.Bid[0]) != 3 {\n\t\t\tcontinue\n\t\t}\n\n\t\taskPrice, errParse := strconv.ParseFloat(bodyOrder.Ask[0][0], 64)\n\t\tif errParse != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tbidPrice, errParse := strconv.ParseFloat(bodyOrder.Bid[0][0], 64)\n\t\tif errParse != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tpairOrders[bodyPair] = model.Order{\n\t\t\tAsk: model.Offer{\n\t\t\t\tPrice: askPrice,\n\t\t\t},\n\t\t\tBid: model.Offer{\n\t\t\t\tPrice: bidPrice,\n\t\t\t},\n\t\t}\n\n\t}\n\n\treturn\n\n}",
"func (a *Client) SearchOrders(params *SearchOrdersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*SearchOrdersOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewSearchOrdersParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"SearchOrders\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/v2/orders/search\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &SearchOrdersReader{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.(*SearchOrdersOK)\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 SearchOrders: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}",
"func (a *Client) OrderOrderGroupSearch(params *OrderOrderGroupSearchParams, authInfo runtime.ClientAuthInfoWriter) (*OrderOrderGroupSearchOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewOrderOrderGroupSearchParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"OrderOrderGroup_search\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/order/orderGroup\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &OrderOrderGroupSearchReader{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.(*OrderOrderGroupSearchOK)\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 OrderOrderGroup_search: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetOrdersMatch returns a list of matched orders
|
func (h *HUOBI) GetOrdersMatch(ctx context.Context, symbol currency.Pair, types, start, end, from, direct, size string) ([]OrderMatchInfo, error) {
resp := struct {
Orders []OrderMatchInfo `json:"data"`
}{}
vals := url.Values{}
symbolValue, err := h.FormatSymbol(symbol, asset.Spot)
if err != nil {
return nil, err
}
vals.Set("symbol", symbolValue)
if types != "" {
vals.Set("types", types)
}
if start != "" {
vals.Set("start-date", start)
}
if end != "" {
vals.Set("end-date", end)
}
if from != "" {
vals.Set("from", from)
}
if direct != "" {
vals.Set("direct", direct)
}
if size != "" {
vals.Set("size", size)
}
err = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiGetOrdersMatch, vals, nil, &resp, false)
return resp.Orders, err
}
|
[
"func (h *HUOBIHADAX) GetOrdersMatch(symbol, types, start, end, from, direct, size string) ([]OrderMatchInfo, error) {\n\ttype response struct {\n\t\tResponse\n\t\tOrders []OrderMatchInfo `json:\"data\"`\n\t}\n\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\n\tif types != \"\" {\n\t\tvals.Set(\"types\", types)\n\t}\n\n\tif start != \"\" {\n\t\tvals.Set(\"start-date\", start)\n\t}\n\n\tif end != \"\" {\n\t\tvals.Set(\"end-date\", end)\n\t}\n\n\tif from != \"\" {\n\t\tvals.Set(\"from\", from)\n\t}\n\n\tif direct != \"\" {\n\t\tvals.Set(\"direct\", direct)\n\t}\n\n\tif size != \"\" {\n\t\tvals.Set(\"size\", size)\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodGet, huobihadaxGetOrdersMatch, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Orders, err\n}",
"func (h *HUOBI) GetOrderMatchResults(ctx context.Context, orderID int64) ([]OrderMatchInfo, error) {\n\tresp := struct {\n\t\tOrders []OrderMatchInfo `json:\"data\"`\n\t}{}\n\tendpoint := fmt.Sprintf(huobiGetOrderMatch, strconv.FormatInt(orderID, 10))\n\terr := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, endpoint, url.Values{}, nil, &resp, false)\n\treturn resp.Orders, err\n}",
"func (h *HUOBIHADAX) GetOrderMatchResults(orderID int64) ([]OrderMatchInfo, error) {\n\ttype response struct {\n\t\tResponse\n\t\tOrders []OrderMatchInfo `json:\"data\"`\n\t}\n\n\tvar result response\n\tendpoint := fmt.Sprintf(huobihadaxGetOrderMatch, strconv.FormatInt(orderID, 10))\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodGet, endpoint, url.Values{}, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Orders, err\n}",
"func (m *Market) Match() (matched []Order) {\n\t// loop till there is no match in either Bid or Offer side\n\tfor m.Bids.Len() > 0 && m.Offers.Len() > 0 {\n\t\tbestBid := m.Bids.orders[0]\n\t\tbestOffer := m.Offers.orders[0]\n\n\t\tprice := bestOffer.Price\n\t\tquantity := bestBid.OpenQuantity()\n\t\tif offerQuant := bestOffer.OpenQuantity(); offerQuant.Cmp(quantity) == -1 {\n\t\t\tquantity = offerQuant\n\t\t}\n\n\t\tbestBid.Execute(price, quantity)\n\t\tbestOffer.Execute(price, quantity)\n\n\t\tmatched = append(matched, *bestBid, *bestOffer)\n\n\t\tif bestBid.IsClosed() {\n\t\t\tm.Bids.orders = m.Bids.orders[1:]\n\t\t}\n\n\t\tif bestOffer.IsClosed() {\n\t\t\tm.Offers.orders = m.Offers.orders[1:]\n\t\t}\n\t}\n\n\treturn\n}",
"func (_WyvernExchange *WyvernExchangeFilterer) FilterOrdersMatched(opts *bind.FilterOpts, maker []common.Address, taker []common.Address, metadata [][32]byte) (*WyvernExchangeOrdersMatchedIterator, error) {\n\n\tvar makerRule []interface{}\n\tfor _, makerItem := range maker {\n\t\tmakerRule = append(makerRule, makerItem)\n\t}\n\tvar takerRule []interface{}\n\tfor _, takerItem := range taker {\n\t\ttakerRule = append(takerRule, takerItem)\n\t}\n\n\tvar metadataRule []interface{}\n\tfor _, metadataItem := range metadata {\n\t\tmetadataRule = append(metadataRule, metadataItem)\n\t}\n\n\tlogs, sub, err := _WyvernExchange.contract.FilterLogs(opts, \"OrdersMatched\", makerRule, takerRule, metadataRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &WyvernExchangeOrdersMatchedIterator{contract: _WyvernExchange.contract, event: \"OrdersMatched\", logs: logs, sub: sub}, nil\n}",
"func findMatchingOrder(cmClient cmclient.Interface, ctx context.Context, req *cmapi.CertificateRequest) (*cmacme.Order, error) {\n\torders, err := cmClient.AcmeV1().Orders(req.Namespace).List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpossibleMatches := []*cmacme.Order{}\n\tfor _, order := range orders.Items {\n\t\tif predicate.ResourceOwnedBy(req)(&order) {\n\t\t\tpossibleMatches = append(possibleMatches, order.DeepCopy())\n\t\t}\n\t}\n\n\tif len(possibleMatches) < 1 {\n\t\treturn nil, nil\n\t} else if len(possibleMatches) == 1 {\n\t\treturn possibleMatches[0], nil\n\t} else {\n\t\treturn nil, fmt.Errorf(\"found multiple orders owned by CertificateRequest %s\", req.Name)\n\t}\n}",
"func OrdersMatch(a, b order.Order) bool {\n\t// Get order data needed for comparison.\n\taType, aSell, _, aRate := orderData(a)\n\tbType, bSell, _, bRate := orderData(b)\n\n\t// Orders must be on opposite sides of the market.\n\tif aSell == bSell {\n\t\treturn false\n\t}\n\n\t// Screen order types.\n\tswitch aType {\n\tcase order.MarketOrderType:\n\t\tswitch bType {\n\t\tcase order.LimitOrderType:\n\t\t\treturn true // market-limit\n\t\tcase order.MarketOrderType:\n\t\t\tfallthrough // no two market orders\n\t\tdefault:\n\t\t\treturn false // cancel or unknown\n\t\t}\n\tcase order.LimitOrderType:\n\t\tswitch bType {\n\t\tcase order.LimitOrderType:\n\t\t\t// limit-limit: must check rates\n\t\tcase order.MarketOrderType:\n\t\t\treturn true // limit-market\n\t\tdefault:\n\t\t\treturn false // cancel or unknown\n\t\t}\n\tdefault: // cancel or unknown\n\t\treturn false\n\t}\n\n\t// For limit-limit orders, check that the rates overlap.\n\tcmp := func(buyRate, sellRate uint64) bool { return sellRate <= buyRate }\n\tif bSell {\n\t\t// a is buy, b is sell\n\t\treturn cmp(aRate, bRate)\n\t}\n\t// a is sell, b is buy\n\treturn cmp(bRate, aRate)\n}",
"func (m *Matcher) Match(book Booker, queue []order.Order) (matches []*order.MatchSet, passed, failed, doneOK, partial, booked, unbooked []order.Order) {\n\t// Apply the deterministic pseudorandom shuffling.\n\tshuffleQueue(queue)\n\n\t// For each order in the queue, find the best match in the book.\n\tfor _, q := range queue {\n\t\tif !orderLotSizeOK(q, book.LotSize()) {\n\t\t\tlog.Warnf(\"Order with bad lot size in the queue: %v!\", q.ID())\n\t\t\tfailed = append(failed, q)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch o := q.(type) {\n\t\tcase *order.CancelOrder:\n\t\t\tremoved, ok := book.Remove(o.TargetOrderID)\n\t\t\tif !ok {\n\t\t\t\t// The targeted order might be down queue or non-existent.\n\t\t\t\tlog.Debugf(\"Failed to remove order %v set by a cancel order %v\",\n\t\t\t\t\to.ID(), o.TargetOrderID)\n\t\t\t\tfailed = append(failed, q)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpassed = append(passed, q)\n\t\t\tdoneOK = append(doneOK, q)\n\t\t\t// CancelOrder Match has zero values for Amounts, Rates, and Total.\n\t\t\tmatches = append(matches, &order.MatchSet{\n\t\t\t\tTaker: q,\n\t\t\t\tMakers: []*order.LimitOrder{removed},\n\t\t\t\tAmounts: []uint64{removed.Remaining()},\n\t\t\t\tRates: []uint64{removed.Rate},\n\t\t\t})\n\t\t\tunbooked = append(unbooked, removed)\n\n\t\tcase *order.LimitOrder:\n\t\t\t// limit-limit order matching\n\t\t\tvar makers []*order.LimitOrder\n\t\t\tmatchSet := matchLimitOrder(book, o)\n\t\t\tif matchSet != nil {\n\t\t\t\tmatches = append(matches, matchSet)\n\t\t\t\tmakers = matchSet.Makers\n\t\t\t} else if o.Force == order.ImmediateTiF {\n\t\t\t\t// There was no match and TiF is Immediate. Fail.\n\t\t\t\tfailed = append(failed, q)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Either matched or standing unmatched => passed.\n\t\t\tpassed = append(passed, q)\n\n\t\t\t// Unbook matched makers with no remaining amount.\n\t\t\tfor _, maker := range makers {\n\t\t\t\tif maker.Remaining() == 0 {\n\t\t\t\t\tunbooked = append(unbooked, maker)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar wasBooked bool\n\t\t\tif o.Remaining() > 0 {\n\t\t\t\tif matchSet != nil {\n\t\t\t\t\tpartial = append(partial, q)\n\t\t\t\t}\n\t\t\t\tif o.Force == order.StandingTiF {\n\t\t\t\t\t// Standing TiF orders go on the book.\n\t\t\t\t\tbook.Insert(o)\n\t\t\t\t\tbooked = append(booked, q)\n\t\t\t\t\twasBooked = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !wasBooked {\n\t\t\t\tdoneOK = append(doneOK, q)\n\t\t\t}\n\n\t\tcase *order.MarketOrder:\n\t\t\t// market-limit order matching\n\t\t\tvar matchSet *order.MatchSet\n\t\t\tif o.Sell {\n\t\t\t\tmatchSet = matchMarketSellOrder(book, o)\n\t\t\t} else {\n\t\t\t\t// Market buy order Quantity is denominated in the quote asset,\n\t\t\t\t// and lot size multiples are not applicable.\n\t\t\t\tmatchSet = matchMarketBuyOrder(book, o)\n\t\t\t}\n\t\t\tif matchSet != nil {\n\t\t\t\tmatches = append(matches, matchSet)\n\t\t\t\tpassed = append(passed, q)\n\t\t\t\tdoneOK = append(doneOK, q)\n\t\t\t} else {\n\t\t\t\t// There was no match and this is a market order. Fail.\n\t\t\t\tfailed = append(failed, q)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tfor _, maker := range matchSet.Makers {\n\t\t\t\tif maker.Remaining() == 0 {\n\t\t\t\t\tunbooked = append(unbooked, maker)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Regardless of remaining amount, market orders never go on the book.\n\t\t}\n\n\t}\n\n\treturn\n}",
"func ParseRPCMatchedOrders(orders *auctioneerrpc.MatchedOrder) ([]*MatchedOrder,\n\terror) {\n\n\tvar result []*MatchedOrder\n\t// The only thing we can check in this step is that not both matched\n\t// bids and matched asks are set at the same time as that wouldn't make\n\t// sense. Everything else is checked at a later stage when we know more\n\t// about our order that was matched against.\n\tswitch {\n\tcase len(orders.MatchedAsks) > 0 && len(orders.MatchedBids) > 0:\n\t\treturn nil, fmt.Errorf(\"order cannot match both asks and bids\")\n\n\tcase len(orders.MatchedAsks) > 0:\n\t\tfor _, ask := range orders.MatchedAsks {\n\t\t\tmatchedAsk, err := ParseRPCServerAsk(ask.Ask)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error parsing server \"+\n\t\t\t\t\t\"ask: %v\", err)\n\t\t\t}\n\t\t\tmatchedAsk.UnitsFilled = SupplyUnit(ask.UnitsFilled)\n\n\t\t\tresult = append(result, matchedAsk)\n\t\t}\n\n\tcase len(orders.MatchedBids) > 0:\n\t\tfor _, bid := range orders.MatchedBids {\n\t\t\tmatchedBid, err := ParseRPCServerBid(bid.Bid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error parsing server \"+\n\t\t\t\t\t\"bid: %v\", err)\n\t\t\t}\n\t\t\tmatchedBid.UnitsFilled = SupplyUnit(bid.UnitsFilled)\n\n\t\t\tresult = append(result, matchedBid)\n\t\t}\n\t}\n\n\treturn result, nil\n}",
"func (e *exmo) GetOrders(ctx context.Context, pairs ...model.Pair) (pairOrders model.PairOrders, err error) {\n\n\tif len(pairs) == 0 {\n\t\terr = errors.New(\"`pairs` must not be empty\")\n\t\treturn\n\t}\n\n\tpairParam := \"\"\n\tfor _, pair := range pairs {\n\t\tpairParam += string(pair) + \",\"\n\t}\n\tpairParam = strings.TrimRight(pairParam, \",\")\n\n\tresp, err := e.doRequest(ctx, http.MethodGet, e.baseUrl+\"/order_book/?limit=1&pair=\"+pairParam, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tvar bodyStruct map[model.Pair]struct {\n\t\tAsk [][]string\n\t\tBid [][]string\n\t}\n\terr = json.NewDecoder(resp.Body).Decode(&bodyStruct)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpairOrders = model.PairOrders{}\n\n\tfor bodyPair, bodyOrder := range bodyStruct {\n\n\t\tif len(bodyOrder.Ask) == 0 || len(bodyOrder.Bid) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(bodyOrder.Ask[0]) != 3 || len(bodyOrder.Bid[0]) != 3 {\n\t\t\tcontinue\n\t\t}\n\n\t\taskPrice, errParse := strconv.ParseFloat(bodyOrder.Ask[0][0], 64)\n\t\tif errParse != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tbidPrice, errParse := strconv.ParseFloat(bodyOrder.Bid[0][0], 64)\n\t\tif errParse != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tpairOrders[bodyPair] = model.Order{\n\t\t\tAsk: model.Offer{\n\t\t\t\tPrice: askPrice,\n\t\t\t},\n\t\t\tBid: model.Offer{\n\t\t\t\tPrice: bidPrice,\n\t\t\t},\n\t\t}\n\n\t}\n\n\treturn\n\n}",
"func (keeper *PersistentOrderKeeper) GetMatchingCandidates(ctx sdk.Context) []*types.Order {\n\tstore := ctx.KVStore(keeper.marketKey)\n\t// mark this order book as not-newly-added\n\tstore.Delete(append(NewlyAddedKeyPrefix, []byte(keeper.symbol)...))\n\n\tpriceStartPos := len(keeper.symbol) + 2\n\tpriceEndPos := priceStartPos + types.DecByteCount\n\tbidListStart := myposchain.ConcatKeys(BidListKeyPrefix, []byte(keeper.symbol), []byte{0x0})\n\tbidListEnd := myposchain.ConcatKeys(BidListKeyPrefix, []byte(keeper.symbol), []byte{0x1})\n\taskListStart := myposchain.ConcatKeys(AskListKeyPrefix, []byte(keeper.symbol), []byte{0x0})\n\taskListEnd := myposchain.ConcatKeys(AskListKeyPrefix, []byte(keeper.symbol), []byte{0x1})\n\tbidIter := store.ReverseIterator(bidListStart, bidListEnd)\n\taskIter := store.Iterator(askListStart, askListEnd)\n\tdefer func() {\n\t\tbidIter.Close()\n\t\taskIter.Close()\n\t}()\n\tif !bidIter.Valid() || !askIter.Valid() {\n\t\treturn nil\n\t}\n\tfirstBidKey := bidIter.Key()\n\tfirstAskKey := askIter.Key()\n\tfirstBidPrice := firstBidKey[priceStartPos:priceEndPos]\n\tfirstAskPrice := firstAskKey[priceStartPos:priceEndPos]\n\tif bytes.Compare(firstAskPrice, firstBidPrice) > 0 {\n\t\treturn nil\n\t}\n\torderIDList := []string{string(firstBidKey[priceEndPos:]), string(firstAskKey[priceEndPos:])}\n\tfor askIter.Next(); askIter.Valid(); askIter.Next() {\n\t\taskKey := askIter.Key()\n\t\taskPrice := askKey[priceStartPos:priceEndPos]\n\t\tif bytes.Compare(askPrice, firstBidPrice) > 0 {\n\t\t\tbreak\n\t\t} else {\n\t\t\torderIDList = append(orderIDList, string(askKey[priceEndPos:]))\n\t\t}\n\t}\n\tfor bidIter.Next(); bidIter.Valid(); bidIter.Next() {\n\t\tbidKey := bidIter.Key()\n\t\tbidPrice := bidKey[priceStartPos:priceEndPos]\n\t\tif bytes.Compare(firstAskPrice, bidPrice) > 0 {\n\t\t\tbreak\n\t\t} else {\n\t\t\torderIDList = append(orderIDList, string(bidKey[priceEndPos:]))\n\t\t}\n\t}\n\tresult := make([]*types.Order, 0, len(orderIDList))\n\tfor _, orderID := range orderIDList {\n\t\torder := keeper.getOrder(ctx, orderID)\n\t\tif order != nil {\n\t\t\tresult = append(result, order)\n\t\t}\n\n\t}\n\treturn result\n}",
"func (_WyvernExchange *WyvernExchangeFilterer) WatchOrdersMatched(opts *bind.WatchOpts, sink chan<- *WyvernExchangeOrdersMatched, maker []common.Address, taker []common.Address, metadata [][32]byte) (event.Subscription, error) {\n\n\tvar makerRule []interface{}\n\tfor _, makerItem := range maker {\n\t\tmakerRule = append(makerRule, makerItem)\n\t}\n\tvar takerRule []interface{}\n\tfor _, takerItem := range taker {\n\t\ttakerRule = append(takerRule, takerItem)\n\t}\n\n\tvar metadataRule []interface{}\n\tfor _, metadataItem := range metadata {\n\t\tmetadataRule = append(metadataRule, metadataItem)\n\t}\n\n\tlogs, sub, err := _WyvernExchange.contract.WatchLogs(opts, \"OrdersMatched\", makerRule, takerRule, metadataRule)\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(WyvernExchangeOrdersMatched)\n\t\t\t\tif err := _WyvernExchange.contract.UnpackLog(event, \"OrdersMatched\", 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 (m manager) AllOrders() (acmeserverless.Orders, error) {\n\t// Create a map of DynamoDB Attribute Values containing the table keys\n\t// for the access pattern PK = ORDER\n\tkm := make(map[string]*dynamodb.AttributeValue)\n\tkm[\":type\"] = &dynamodb.AttributeValue{\n\t\tS: aws.String(\"ORDER\"),\n\t}\n\n\t// Create the QueryInput\n\tqi := &dynamodb.QueryInput{\n\t\tTableName: aws.String(os.Getenv(\"TABLE\")),\n\t\tKeyConditionExpression: aws.String(\"PK = :type\"),\n\t\tExpressionAttributeValues: km,\n\t}\n\n\tqo, err := dbs.Query(qi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\torders := make(acmeserverless.Orders, len(qo.Items))\n\n\tfor idx, ord := range qo.Items {\n\t\tstr := ord[\"OrderString\"].S\n\t\to, err := acmeserverless.UnmarshalOrder(*str)\n\t\tif err != nil {\n\t\t\tlog.Println(fmt.Sprintf(\"error unmarshalling order data: %s\", err.Error()))\n\t\t\tcontinue\n\t\t}\n\t\torders[idx] = o\n\t}\n\n\treturn orders, nil\n}",
"func GetOrders() (orders []Orders, err error) {\r\n\tvar rows *sql.Rows\r\n\tif rows, err = Get(`select * from orders where deleted_at is null order by created_at desc;`); err != nil {\r\n\t\tCheckError(\"Error getting Orders.\", err, false)\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tdefer rows.Close()\r\n\tfor rows.Next() {\r\n\t\torder := Orders{}\r\n\t\tif err = rows.Scan(&order.ID, &order.DocEntry, &order.DocNum, &order.Canceled, &order.CardCode, &order.CardName, &order.VatSum, &order.DocTotal, &order.Synced, &order.CreatedBy, &order.CreatedAt, &order.UpdatedAt, &order.DeletedAt, &order.Comment, &order.Returned, &order.DiscountApprovedBy); err != nil {\r\n\t\t\tCheckError(\"Error Scanning Orders.\", err, false)\r\n\t\t} else {\r\n\t\t\torders = append(orders, order)\r\n\t\t}\r\n\t}\r\n\r\n\treturn\r\n}",
"func (app *App) GetOrders(page, perPage int, snapshotID string) (*rpc.GetOrdersResponse, error) {\n\tordersInfos := []*zeroex.AcceptedOrderInfo{}\n\tif perPage <= 0 {\n\t\treturn &rpc.GetOrdersResponse{\n\t\t\tOrdersInfos: ordersInfos,\n\t\t\tSnapshotID: snapshotID,\n\t\t}, nil\n\t}\n\n\tvar snapshot *db.Snapshot\n\tif snapshotID == \"\" {\n\t\t// Create a new snapshot\n\t\tsnapshotID = uuid.New().String()\n\t\tvar err error\n\t\tsnapshot, err = app.db.Orders.GetSnapshot()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texpirationTimestamp := time.Now().Add(1 * time.Minute)\n\t\tapp.snapshotExpirationWatcher.Add(expirationTimestamp, snapshotID)\n\t\tapp.muIdToSnapshotInfo.Lock()\n\t\tapp.idToSnapshotInfo[snapshotID] = snapshotInfo{\n\t\t\tSnapshot: snapshot,\n\t\t\tExpirationTimestamp: expirationTimestamp,\n\t\t}\n\t\tapp.muIdToSnapshotInfo.Unlock()\n\t} else {\n\t\t// Try and find an existing snapshot\n\t\tapp.muIdToSnapshotInfo.Lock()\n\t\tinfo, ok := app.idToSnapshotInfo[snapshotID]\n\t\tif !ok {\n\t\t\tapp.muIdToSnapshotInfo.Unlock()\n\t\t\treturn nil, ErrSnapshotNotFound{id: snapshotID}\n\t\t}\n\t\tsnapshot = info.Snapshot\n\t\t// Reset the snapshot's expiry\n\t\tapp.snapshotExpirationWatcher.Remove(info.ExpirationTimestamp, snapshotID)\n\t\texpirationTimestamp := time.Now().Add(1 * time.Minute)\n\t\tapp.snapshotExpirationWatcher.Add(expirationTimestamp, snapshotID)\n\t\tapp.idToSnapshotInfo[snapshotID] = snapshotInfo{\n\t\t\tSnapshot: snapshot,\n\t\t\tExpirationTimestamp: expirationTimestamp,\n\t\t}\n\t\tapp.muIdToSnapshotInfo.Unlock()\n\t}\n\n\tnotRemovedFilter := app.db.Orders.IsRemovedIndex.ValueFilter([]byte{0})\n\tvar selectedOrders []*meshdb.Order\n\terr := snapshot.NewQuery(notRemovedFilter).Offset(page * perPage).Max(perPage).Run(&selectedOrders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, order := range selectedOrders {\n\t\tordersInfos = append(ordersInfos, &zeroex.AcceptedOrderInfo{\n\t\t\tOrderHash: order.Hash,\n\t\t\tSignedOrder: order.SignedOrder,\n\t\t\tFillableTakerAssetAmount: order.FillableTakerAssetAmount,\n\t\t})\n\t}\n\n\tgetOrdersResponse := &rpc.GetOrdersResponse{\n\t\tSnapshotID: snapshotID,\n\t\tOrdersInfos: ordersInfos,\n\t}\n\n\treturn getOrdersResponse, nil\n}",
"func (_WyvernExchange *WyvernExchangeCaller) OrdersCanMatch(opts *bind.CallOpts, addrs [14]common.Address, uints [18]*big.Int, feeMethodsSidesKindsHowToCalls [8]uint8, calldataBuy []byte, calldataSell []byte, replacementPatternBuy []byte, replacementPatternSell []byte, staticExtradataBuy []byte, staticExtradataSell []byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _WyvernExchange.contract.Call(opts, out, \"ordersCanMatch_\", addrs, uints, feeMethodsSidesKindsHowToCalls, calldataBuy, calldataSell, replacementPatternBuy, replacementPatternSell, staticExtradataBuy, staticExtradataSell)\n\treturn *ret0, err\n}",
"func (s *orderMgtServer) SearchOrders(searchQuery *wrappers.StringValue, stream pb.OrderManagement_SearchOrdersServer) error {\n\tfor key, order := range orderMap {\n\t\tlog.Print(key, order)\n\t\tfor _, itemStr := range order.Items {\n\t\t\tlog.Print(itemStr)\n\t\t\tif strings.Contains(itemStr, searchQuery.Value) {\n\t\t\t\t// Send the matching orders in a stream\n\t\t\t\terr := stream.Send(&order)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error sending message to stream : %v\", err)\n\t\t\t\t}\n\t\t\t\tlog.Print(\"Matching Order Found : \" + key)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (b *Bitmex) GetActiveOrders(ctx context.Context, req *order.MultiOrderRequest) (order.FilteredOrders, error) {\n\terr := req.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams := OrdersRequest{\n\t\tFilter: \"{\\\"open\\\":true}\",\n\t}\n\tresp, err := b.GetOrders(ctx, ¶ms)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tformat, err := b.GetPairFormat(asset.PerpetualContract, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\torders := make([]order.Detail, len(resp))\n\tfor i := range resp {\n\t\tvar orderStatus order.Status\n\t\torderStatus, err = order.StringToOrderStatus(resp[i].OrdStatus)\n\t\tif err != nil {\n\t\t\tlog.Errorf(log.ExchangeSys, \"%s %v\", b.Name, err)\n\t\t}\n\t\tvar oType order.Type\n\t\toType, err = b.getOrderType(resp[i].OrdType)\n\t\tif err != nil {\n\t\t\tlog.Errorf(log.ExchangeSys, \"%s %v\", b.Name, err)\n\t\t}\n\t\torderDetail := order.Detail{\n\t\t\tDate: resp[i].Timestamp,\n\t\t\tPrice: resp[i].Price,\n\t\t\tAmount: resp[i].OrderQty,\n\t\t\tExecutedAmount: resp[i].CumQty,\n\t\t\tRemainingAmount: resp[i].LeavesQty,\n\t\t\tExchange: b.Name,\n\t\t\tOrderID: resp[i].OrderID,\n\t\t\tSide: orderSideMap[resp[i].Side],\n\t\t\tStatus: orderStatus,\n\t\t\tType: oType,\n\t\t\tPair: currency.NewPairWithDelimiter(resp[i].Symbol,\n\t\t\t\tresp[i].SettlCurrency,\n\t\t\t\tformat.Delimiter),\n\t\t}\n\n\t\torders[i] = orderDetail\n\t}\n\treturn req.Filter(b.Name, orders), nil\n}",
"func (r Restorer) GetOrders(isBuy bool) (openedOrders []models.Order, err error) {\n\tcollection := r.Accesser.client.Database(r.Accesser.Database).Collection(r.Accesser.Table)\n\n\tfilter := bson.M{\"$and\": bson.A{\n\t\tbson.M{\"is_closed\": bson.M{\"$eq\": false}},\n\t\tbson.M{\"is_purchase\": bson.M{\"$eq\": isBuy}},\n\t}}\n\n\tcursor, err := collection.Find(context.Background(), filter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar dbOrders []models.DatabaseOrder\n\tif err = cursor.All(context.Background(), &dbOrders); err != nil {\n\t\treturn nil, err\n\t}\n\n\topenedOrders = make([]models.Order, len(dbOrders))\n\tfor i, o := range dbOrders {\n\t\topenedOrders[i] = *o.Convert()\n\t}\n\n\treturn\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
MarginTransfer transfers assets into or out of the margin account
|
func (h *HUOBI) MarginTransfer(ctx context.Context, symbol currency.Pair, currency string, amount float64, in bool) (int64, error) {
symbolValue, err := h.FormatSymbol(symbol, asset.Spot)
if err != nil {
return 0, err
}
data := struct {
Symbol string `json:"symbol"`
Currency string `json:"currency"`
Amount string `json:"amount"`
}{
Symbol: symbolValue,
Currency: currency,
Amount: strconv.FormatFloat(amount, 'f', -1, 64),
}
path := huobiMarginTransferIn
if !in {
path = huobiMarginTransferOut
}
resp := struct {
TransferID int64 `json:"data"`
}{}
err = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, path, nil, data, &resp, false)
return resp.TransferID, err
}
|
[
"func (h *HUOBIHADAX) MarginTransfer(symbol, currency string, amount float64, in bool) (int64, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\tvals.Set(\"currency\", currency)\n\tvals.Set(\"amount\", strconv.FormatFloat(amount, 'f', -1, 64))\n\n\tpath := huobihadaxMarginTransferIn\n\tif !in {\n\t\tpath = huobihadaxMarginTransferOut\n\t}\n\n\ttype response struct {\n\t\tResponse\n\t\tTransferID int64 `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodPost, path, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.TransferID, err\n}",
"func (as *apiService) MarginAccount(ar AccountRequest) (*MarginAccount, error) {\n\tparams := make(map[string]string)\n\tparams[\"timestamp\"] = strconv.FormatInt(unixMillis(ar.Timestamp), 10)\n\tif ar.RecvWindow != 0 {\n\t\tparams[\"recvWindow\"] = strconv.FormatInt(recvWindow(ar.RecvWindow), 10)\n\t}\n\n\tres, err := as.request(\"GET\", \"/sapi/v1/margin/account\", params, true, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttextRes, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to read response from account.get\")\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, as.handleError(textRes)\n\t}\n\n\trawAccount := struct {\n\t\tBorrowEnabled \t\tbool \t\t`json:\"borrowEnabled\"`\n\t\tMarginLevel \t\t\t\tstring `json:\"marginLevel\"`\n\t\tTotalAssetOfBtc \t\tstring `json:\"totalAssetOfBtc\"`\n\t\tTotalLiabilityOfBtc string `json:\"totalLiabilityOfBtc\"`\n\t\tTotalNetAssetOfBtc string `json:\"totalNetAssetOfBtc\"`\n\t\tTradeEnabled \tbool \t`json:\"tradeEnabled\"`\n\t\tTransferEnabled bool \t`json:\"transferEnabled\"`\n\t\tUserAssets []struct {\n\t\t\tAsset \t\tstring `json:\"asset\"`\n\t\t\tBorrowed \tstring `json:\"borrowed\"`\n\t\t\tFree \t\tstring `json:\"free\"`\n\t\t\tInterest \tstring `json:\"interest\"`\n\t\t\tLocked \t\tstring `json:\"locked\"`\n\t\t\tNetAsset \tstring `json:\"netAsset\"`\n\t\t}\n\t}{}\n\tif err := json.Unmarshal(textRes, &rawAccount); err != nil {\n\t\treturn nil, errors.Wrap(err, \"rawAccount unmarshal failed\")\n\t}\n\tml, err := floatFromString(rawAccount.MarginLevel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttab, err := floatFromString(rawAccount.TotalAssetOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlb, err := floatFromString(rawAccount.TotalLiabilityOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttnab, err := floatFromString(rawAccount.TotalNetAssetOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tacc := &MarginAccount{\n\t\tBorrowEnabled: \t\t\trawAccount.BorrowEnabled,\n\t\tMarginLevel: \t\t\t\tml,\n\t\tTotalAssetOfBtc: \t\ttab,\n\t\tTotalLiabilityOfBtc: \ttlb,\n\t\tTotalNetAssetOfBtc: tnab,\n\t\tTradeEnabled: \t\trawAccount.TradeEnabled,\n\t\tTransferEnabled: rawAccount.TransferEnabled,\n\t}\n\tfor _, b := range rawAccount.UserAssets {\n\t\tf, err := floatFromString(b.Free)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tl, err := floatFromString(b.Locked)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbo, err := floatFromString(b.Borrowed)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti, err := floatFromString(b.Interest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tn, err := floatFromString(b.NetAsset)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tacc.UserAssets = append(acc.UserAssets, &UserAsset{\n\t\t\tAsset: \tb.Asset,\n\t\t\tBorrowed: bo,\n\t\t\tFree: \tf,\n\t\t\tInterest: i,\n\t\t\tLocked: \tl,\n\t\t\tNetAsset: n,\n\t\t})\n\t}\n\n\treturn acc, nil\n}",
"func (s *StorageInMemory) Transfer(accountFrom, accountTo storage.AccountID, amountToTransfer storage.AccountBalance) error {\n\tbalanceFrom, err := s.getBalance(accountFrom)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbalanceTo, err := s.getBalance(accountTo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbalanceFrom.mu.Lock()\n\tbalanceTo.mu.Lock()\n\tdefer balanceFrom.mu.Unlock()\n\tdefer balanceTo.mu.Unlock()\n\n\tif balanceFrom.amount < amountToTransfer {\n\t\treturn ErrNotEnoughBalance\n\t}\n\t// todo del (для отладки)\n\t// fmt.Println(\"операция: \", balanceFrom.amount, balanceTo.amount, balanceFrom.amount+balanceTo.amount)\n\tbalanceFrom.amount -= amountToTransfer\n\tbalanceTo.amount += amountToTransfer\n\treturn nil\n}",
"func (_Sigmacore *SigmacoreTransactor) Transfer(opts *bind.TransactOpts, dst common.Address, amt *big.Int) (*types.Transaction, error) {\n\treturn _Sigmacore.contract.Transact(opts, \"transfer\", dst, amt)\n}",
"func Transfer(fromAcct Account, toAcct Account, amount Money) error {\n\tif err := fromAcct.Withdraw(amount); err == nil {\n\t\tif depErr := toAcct.Deposit(amount); depErr == nil {\n\t\t\tfmt.Printf(\"Transfered %f from %s to %+v\", amount, fromAcct, toAcct)\n\t\t} else {\n\t\t\t//return the root cause\n\t\t\treturn depErr\n\t\t}\n\t} else {\n\t\t//return the root cause\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (_Sigmacore *SigmacoreTransactorSession) Transfer(dst common.Address, amt *big.Int) (*types.Transaction, error) {\n\treturn _Sigmacore.Contract.Transfer(&_Sigmacore.TransactOpts, dst, amt)\n}",
"func Transfer(from, to string, amount int64) error {\n\tif amount <= 0 {\n\t\treturn fmt.Errorf(\"invalid amount; %d\", amount)\n\t}\n\n\tvar accs []*share.Account\n\terr := client.GetByNames(ctx, share.KindAccount, []string{from, to}, &accs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get accounts error; %v\", err)\n\t}\n\n\tif accs[0].Balance < amount {\n\t\treturn fmt.Errorf(\"balance of account %s is %d, not enough for withdraw %d\", from, accs[0].Balance, amount)\n\t}\n\n\taccs[0].Balance -= amount\n\taccs[1].Balance += amount\n\ttrans := []*share.Transaction{\n\t\t{Type: share.TransactionTypeWithdraw, AccountID: from, Amount: -amount},\n\t\t{Type: share.TransactionTypeDeposit, AccountID: to, Amount: amount},\n\t}\n\tfor _, tran := range trans {\n\t\ttran.NewKey(share.KindTransaction)\n\t}\n\terr = client.SaveModels(ctx, \"\", []interface{}{accs[0], accs[1], trans[0], trans[1]})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"save models error; %v\", err)\n\t}\n\treturn nil\n}",
"func (b *Bank) Transfer(req *structs.Request) *structs.Request {\n\tvar account string\n\tif req.DestBank != b.Bankid {\n\t\taccount = req.Account\n\t} else {\n\t\taccount = req.DestAccount\n\t}\n\tb.CheckId(account)\n\ta := b.amap[account]\n\tnewTrans := MakeTransaction(req)\n\tresp := b.T.checkTransaction(newTrans)\n\tif resp == \"new\" {\n\t\tresp = \"processed\"\n\t\tb.T.RecordTransaction(newTrans)\n\t\tif req.DestBank != b.Bankid {\n\t\t\tif (a.Balance - req.Amount) < 0 {\n\t\t\t\treturn structs.Makereply(req.Requestid, req.Account, \"insufficientfunds\",\n\t\t\t\t\t\"transfer\", req.DestAccount, req.DestBank, req.Amount, a.getbalance())\n\t\t\t}\n\t\t\ta.Balance = a.Balance - req.Amount\n\t\t} else {\n\t\t\ta.Balance = a.Balance + req.Amount\n\t\t}\n\n\t}\n\treturn structs.Makereply(req.Requestid, req.Account, resp, \"transfer\",\n\t\treq.DestAccount, req.DestBank, req.Amount, a.getbalance())\n}",
"func (reqctx *requestContext) creditAssetsToChain() {\n\treq := reqctx.req\n\tif req.IsOffLedger() {\n\t\t// off ledger request does not bring any deposit\n\t\treturn\n\t}\n\t// Consume the output. Adjustment in L2 is needed because of storage deposit in the internal UTXOs\n\tstorageDepositNeeded := reqctx.vm.txbuilder.Consume(req.(isc.OnLedgerRequest))\n\n\t// if sender is specified, all assets goes to sender's sender\n\t// Otherwise it all goes to the common sender and panics is logged in the SC call\n\tsender := req.SenderAccount()\n\tif sender == nil {\n\t\tif req.IsOffLedger() {\n\t\t\tpanic(\"nil sender on offledger requests should never happen\")\n\t\t}\n\t\t// onleger request with no sender, send all assets to the payoutAddress\n\t\tpayoutAgentID := reqctx.vm.payoutAgentID()\n\t\tcreditNFTToAccount(reqctx.uncommittedState, payoutAgentID, req.NFT())\n\t\tcreditToAccount(reqctx.uncommittedState, payoutAgentID, req.Assets())\n\n\t\t// debit any SD required for accounting UTXOs\n\t\tif storageDepositNeeded > 0 {\n\t\t\tdebitFromAccount(reqctx.uncommittedState, payoutAgentID, isc.NewAssetsBaseTokens(storageDepositNeeded))\n\t\t}\n\t\treturn\n\t}\n\n\tsenderBaseTokens := req.Assets().BaseTokens + reqctx.GetBaseTokensBalance(sender)\n\n\tif senderBaseTokens < storageDepositNeeded {\n\t\t// user doesn't have enough funds to pay for the SD needs of this request\n\t\tpanic(vmexceptions.ErrNotEnoughFundsForSD)\n\t}\n\n\tcreditToAccount(reqctx.uncommittedState, sender, req.Assets())\n\tcreditNFTToAccount(reqctx.uncommittedState, sender, req.NFT())\n\tif storageDepositNeeded > 0 {\n\t\treqctx.sdCharged = storageDepositNeeded\n\t\tdebitFromAccount(reqctx.uncommittedState, sender, isc.NewAssetsBaseTokens(storageDepositNeeded))\n\t}\n}",
"func TransferAsset(c router.Context) (interface{}, error) {\n\t// get the data from the request and parse it as structure\n\tdata := c.Param(`data`).(GetTransaction)\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\n\t// check receiver data\n\tqueryRecevierString := fmt.Sprintf(\"{\\\"selector\\\": {\\\"user_addresses\\\": {\\\"$elemMatch\\\": {\\\"value\\\": \\\"%s\\\"}},\\\"doc_type\\\":\\\"%s\\\"}}\", data.To, utils.DocTypeUser)\n\treceiverData, receiverID, err5 := utils.Get(c, queryRecevierString, fmt.Sprintf(\"Receiver %s does not exist!\", data.To))\n\tif err5 != nil {\n\t\treturn nil, err5\n\t}\n\n\treceiver := User{}\n\terr = json.Unmarshal(receiverData, &receiver)\n\tif err != nil {\n\t\treturn nil, status.ErrInternal.WithError(err)\n\t}\n\n\tvar receiverOwnLabel string\n\tfor i := range receiver.UserAddresses {\n\t\tif receiver.UserAddresses[i].Value == data.To {\n\t\t\treceiverOwnLabel = receiver.UserAddresses[i].Label\n\t\t}\n\t}\n\n\t// check sender data\n\tquerySenderString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"_id\\\":\\\"%s\\\",\\\"doc_type\\\":\\\"%s\\\"}}\", data.From, utils.DocTypeUser)\n\tsenderData, _, err6 := utils.Get(c, querySenderString, fmt.Sprintf(\"You account %s does not exist!\", data.From))\n\tif err6 != nil {\n\t\treturn nil, err6\n\t}\n\tsender := User{}\n\terr = json.Unmarshal(senderData, &sender)\n\tif err != nil {\n\t\treturn nil, status.ErrInternal.WithError(err)\n\t}\n\n\tif sender.WalletBalance < utils.TransferAssetFee {\n\t\treturn nil, status.ErrInternal.WithMessage(fmt.Sprintf(\"You don't have enough coins to transfer the asset.\"))\n\t}\n\n\tfor i := range sender.UserAddresses {\n\t\tif sender.UserAddresses[i].Value == data.To {\n\t\t\treturn nil, status.ErrInternal.WithMessage(fmt.Sprintf(\"You can't transfer asset to yourself!\"))\n\t\t}\n\t}\n\n\t// check sender asset data\n\tqueryString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"code\\\":\\\"%s\\\",\\\"user_id\\\":\\\"%s\\\",\\\"doc_type\\\":\\\"%s\\\"}}\", data.Code, data.From, utils.DocTypeAsset)\n\tsenderAssetData, senderAssetKey, err2 := utils.Get(c, queryString, fmt.Sprintf(\"Symbol %s does not exist!\", data.Code))\n\tif senderAssetData == nil {\n\t\treturn nil, err2\n\t}\n\tsenderAsset := Asset{}\n\terr = json.Unmarshal(senderAssetData, &senderAsset)\n\tif err != nil {\n\t\treturn nil, status.ErrInternal.WithError(err)\n\t}\n\tif data.Quantity > senderAsset.Quantity {\n\t\treturn nil, status.ErrInternal.WithMessage(fmt.Sprintf(\"Quantity should be less or equal to %d\", senderAsset.Quantity))\n\t}\n\n\tstub := c.Stub()\n\ttxID := stub.GetTxID()\n\tdata.CreatedAt = time.Now().Format(time.RFC3339)\n\n\tvar receiverLabel, senderLabel string\n\t// check label of receiver in sender's address book\n\treceiverLabelString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"user_id\\\":\\\"%s\\\",\\\"address\\\":\\\"%s\\\",\\\"label\\\":\\\"%s\\\",\\\"doc_type\\\":\\\"%s\\\"}}\", data.From, data.To, data.Label, utils.DocTypeAddressBook)\n\treceiverLabelData, _, err6 := utils.Get(c, receiverLabelString, fmt.Sprintf(\"Label of receiver does not exist!\"))\n\n\t//If label does not exist in address book then save it into db\n\tif receiverLabelData == nil {\n\t\t// check if label is unique\n\t\tcheckUniqueString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"user_id\\\":\\\"%s\\\",\\\"label\\\":\\\"%s\\\",\\\"doc_type\\\":\\\"%s\\\"}}\", data.From, data.Label, utils.DocTypeAddressBook)\n\t\tuniqueLabelData, _, err := utils.Get(c, checkUniqueString, fmt.Sprintf(\"This label already exists!\"))\n\t\tif uniqueLabelData != nil {\n\t\t\treturn nil, status.ErrInternal.WithMessage(fmt.Sprintf(\"This label already exists!\"))\n\t\t}\n\n\t\tlabelTxn := AddressBook{UserID: data.From, Address: data.To, Label: data.Label, DocType: utils.DocTypeAddressBook}\n\t\treceiverLabel = data.Label\n\t\t// Save the data\n\t\terr = c.State().Put(txID, labelTxn)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\n\t\taddressLabel := AddressBook{}\n\t\terr = json.Unmarshal(receiverLabelData, &addressLabel)\n\t\tif err != nil {\n\t\t\treturn nil, status.ErrInternal.WithError(err)\n\t\t}\n\t\treceiverLabel = addressLabel.Label\n\t}\n\n\t// check label of sender in receiver's address book\n\tsenderLabelString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"user_id\\\":\\\"%s\\\",\\\"address\\\":\\\"%s\\\",\\\"doc_type\\\":\\\"%s\\\"}}\", receiver.UserAddresses[0].UserID, sender.Address, utils.DocTypeAddressBook)\n\tsenderLabelData, _, err6 := utils.Get(c, senderLabelString, fmt.Sprintf(\"Label of sender does not exist!\"))\n\n\t//If label does not exist in address book\n\tif senderLabelData == nil {\n\t\tsenderLabel = \"N/A\"\n\t} else {\n\n\t\taddressLabel1 := AddressBook{}\n\t\terr = json.Unmarshal(senderLabelData, &addressLabel1)\n\t\tif err != nil {\n\t\t\treturn nil, status.ErrInternal.WithError(err)\n\t\t}\n\t\tsenderLabel = addressLabel1.Label\n\t}\n\n\t// sender transactions\n\tvar senderTransaction = Transaction{UserID: data.From, Type: utils.Send, Code: data.Code, AssetLabel: senderAsset.Label, Quantity: data.Quantity, DocType: utils.DocTypeTransaction, CreatedAt: data.CreatedAt, AddressValue: data.To, LabelValue: receiverOwnLabel, AddressBookLabel: receiverLabel, TxnType: utils.AssetTxnType}\n\terr = c.State().Put(txID+strconv.Itoa(1), senderTransaction)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// receiver transactions\n\tvar receiveTransaction = Transaction{UserID: receiverID, Type: utils.Receive, Code: data.Code, AssetLabel: senderAsset.Label, Quantity: data.Quantity, DocType: utils.DocTypeTransaction, CreatedAt: data.CreatedAt, AddressValue: sender.Address, LabelValue: \"Original\", AddressBookLabel: senderLabel, TxnType: utils.AssetTxnType}\n\terr = c.State().Put(txID+strconv.Itoa(2), receiveTransaction)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsenderAsset.Quantity = senderAsset.Quantity - data.Quantity\n\n\t// update sender asset data\n\terr = c.State().Put(senderAssetKey, senderAsset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// check receiver asset data\n\tqueryReceiverDataString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"code\\\":\\\"%s\\\",\\\"user_id\\\":\\\"%s\\\",\\\"doc_type\\\":\\\"%s\\\"}}\", data.Code, receiverID, utils.DocTypeAsset)\n\treceiverAssetData, receiveAssetKey, _ := utils.Get(c, queryReceiverDataString, \"\")\n\tif receiverAssetData == nil {\n\t\t// add to receiver asset\n\t\tvar receiveAsset = Asset{UserID: receiverID, Code: data.Code, Label: senderAsset.Label, Quantity: data.Quantity, DocType: utils.DocTypeAsset}\n\t\terr = c.State().Put(txID+strconv.Itoa(3), receiveAsset)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\treceiverAsset := Asset{}\n\t\terr = json.Unmarshal(receiverAssetData, &receiverAsset)\n\t\tif err != nil {\n\t\t\treturn nil, status.ErrInternal.WithError(err)\n\t\t}\n\t\t// update receiver asset\n\t\treceiverAsset.Quantity = receiverAsset.Quantity + data.Quantity\n\t\terr = c.State().Put(receiveAssetKey, receiverAsset)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tsender.WalletBalance = sender.WalletBalance - utils.TransferAssetFee\n\n\t// Transfer asset transaction\n\tvar transferAssetTransaction = Transaction{UserID: data.From, Type: utils.Send, Code: utils.WalletCoinSymbol, AssetLabel: senderAsset.Label, Quantity: utils.TransferAssetFee, DocType: utils.DocTypeTransaction, CreatedAt: data.CreatedAt, AddressValue: data.To, LabelValue: receiverOwnLabel, AddressBookLabel: receiverLabel, TxnType: utils.AssetTransferredTxn}\n\terr = c.State().Put(txID+strconv.Itoa(4), transferAssetTransaction)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponseBody := ResponseAddAsset{ID: txID, Balance: sender.WalletBalance, Symbol: sender.Symbol}\n\n\t// Save the data and return the response\n\treturn responseBody, c.State().Put(data.From, sender)\n}",
"func (_ProjectWallet *ProjectWalletTransactorSession) Transfer(_receiver common.Address, _amt *big.Int) (*types.Transaction, error) {\n\treturn _ProjectWallet.Contract.Transfer(&_ProjectWallet.TransactOpts, _receiver, _amt)\n}",
"func (_ProjectWallet *ProjectWalletSession) Transfer(_receiver common.Address, _amt *big.Int) (*types.Transaction, error) {\n\treturn _ProjectWallet.Contract.Transfer(&_ProjectWallet.TransactOpts, _receiver, _amt)\n}",
"func (_Wmatic *WmaticTransactor) Transfer(opts *bind.TransactOpts, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.contract.Transact(opts, \"transfer\", dst, wad)\n}",
"func (reqctx *requestContext) transferAllowedFunds(target isc.AgentID, transfer ...*isc.Assets) *isc.Assets {\n\tif reqctx.vm.isCoreAccount(target) {\n\t\t// if the target is one of core contracts, assume target is the common account\n\t\ttarget = accounts.CommonAccount()\n\t}\n\n\tvar toMove *isc.Assets\n\tif len(transfer) == 0 {\n\t\ttoMove = reqctx.allowanceAvailable()\n\t} else {\n\t\ttoMove = transfer[0]\n\t}\n\n\treqctx.spendAllowedBudget(toMove) // panics if not enough\n\n\tcaller := reqctx.Caller() // have to take it here because callCore changes that\n\n\t// if the caller is a core contract, funds should be taken from the common account\n\tif reqctx.vm.isCoreAccount(caller) {\n\t\tcaller = accounts.CommonAccount()\n\t}\n\treqctx.callCore(accounts.Contract, func(s kv.KVStore) {\n\t\tif err := accounts.MoveBetweenAccounts(s, caller, target, toMove); err != nil {\n\t\t\tpanic(vm.ErrNotEnoughFundsForAllowance)\n\t\t}\n\t})\n\treturn reqctx.allowanceAvailable()\n}",
"func (s *SmartContract) TransferAsset(ctx contractapi.TransactionContextInterface) error {\n\t// get transient input\n\ttype AssetTransferInput struct {\n\t\tNo string `json:\"no\"`\n\t\tBuyer string `json:\"buyer\"`\n\t\tSeller string `json:\"seller\"`\n\t}\n\tstub := ctx.GetStub()\n\ttransMap, err := stub.GetTransient()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read transient %s\", err.Error())\n\t}\n\n\ttransferJSON, ok := transMap[TRANSIENT_KEY_TRANS]\n\tif !ok {\n\t\treturn errors.New(\"key in the transient map is not correct\")\n\t}\n\tif len(transferJSON) == 0 {\n\t\treturn errors.New(\"transfer request in the transient map must be a non-empty JSON string\")\n\t}\n\tfmt.Printf(\"transfer, input: %s\", transferJSON)\n\tfmt.Println()\n\n\ttransferInput := new(AssetTransferInput)\n\terr = json.Unmarshal(transferJSON, transferInput)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to decode JSON of transient: %s\", transferJSON)\n\t}\n\n\tassetResult, err := s.QueryAsset(ctx, transferInput.No)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// change owner\n\tif assetResult.Detail != nil {\n\t\tif assetResult.Detail.Owner != transferInput.Seller {\n\t\t\tfmt.Printf(\"%s !+ %s\", assetResult.Detail.Owner, transferInput.Seller)\n\t\t\tfmt.Println()\n\t\t\treturn errors.New(\"failed to transfer asset: wrong ownership\")\n\t\t}\n\n\t\tassetResult.Detail.Owner = transferInput.Buyer\n\t\tassetDetailBytes, err := json.Marshal(assetResult.Detail)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = stub.PutState(assetResult.No, assetDetailBytes)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"no permission to access the private collection. err: %s\", err)\n\t\t\tfmt.Println()\n\t\t}\n\t\tfmt.Printf(\"asset detail added to %s\", transferInput.Buyer)\n\t\tfmt.Println()\n\t\tfmt.Printf(string(assetDetailBytes))\n\t\tfmt.Println()\n\t}\n\t// payment\n\terr = s.payment(ctx, transferInput.Buyer, transferInput.Seller, assetResult.Asset.Price)\n\tif err != nil {\n\t\treturn err\n\t}\n\tassetBytes, _ := json.Marshal(assetResult.Asset)\n\n\treturn ctx.GetStub().PutState(assetResult.No, assetBytes)\n}",
"func (c *Counter) Transfer(src *Counter) {\n\tif src.Count == 0 {\n\t\treturn // nothing to do\n\t}\n\tif c.Count == 0 {\n\t\t*c = *src // copy everything at once\n\t\tsrc.Reset()\n\t\treturn\n\t}\n\tc.Count += src.Count\n\tif src.Min < c.Min {\n\t\tc.Min = src.Min\n\t}\n\tif src.Max > c.Max {\n\t\tc.Max = src.Max\n\t}\n\tc.Sum += src.Sum\n\tc.sumOfSquares += src.sumOfSquares\n\tsrc.Reset()\n}",
"func ProceFundsTransfer(tx *gorm.DB, requestCreated *models.TransactionRequests) (responses.TransactionResponse, error) {\n\t//first get Balance of the DebitAccount\n\tresponse := responses.TransactionResponse{}\n\tcbalance1 := models.Accounts{}\n\terr := tx.Debug().Model(&models.Accounts{}).Where(\"account_no = ?\", requestCreated.DebitAccount).Take(&cbalance1).Error\n\tif err != nil {\n\t\treturn responses.TransactionResponse{}, err\n\t}\n\t//check if available balnce is enough for cash Withdrawal - should be more than the Amount and the Charge\n\tcustomerBal, _ := strconv.ParseFloat(cbalance1.AvailableBal, 64)\n\twithdrawalAmt, _ := strconv.ParseFloat(requestCreated.Amount, 64)\n\tif withdrawalAmt > customerBal {\n\t\tresponse.Procode = requestCreated.Procode\n\t\tresponse.ResponseCode = InsufficientBalance\n\t\tresponse.Remarks = InsufficientBalRemark\n\t\tresponse.Reference = requestCreated.TxnRef\n\t\tresponse.Amount = withdrawalAmt\n\t\tresponse.Account = cbalance1.AccountNo\n\t\tresponse.AvailableBalance = customerBal\n\t\treturn response, nil\n\t}\n\t//do the withdrawal Debit entry - DR\n\tnewBal := customerBal - withdrawalAmt\n\t//insert Debit entry\n\tt := models.Transactions{} //Transactions object\n\tt.MsgType = requestCreated.MsgType\n\tt.Procode = requestCreated.Procode\n\tt.Channel = requestCreated.Channel\n\tt.TxnRef = requestCreated.TxnRef\n\tt.AccountNo = requestCreated.DebitAccount\n\tt.Amount = requestCreated.Amount\n\tt.DrCr = \"DR\"\n\tt.Narration = requestCreated.Narration\n\tt.AvailableBal = fmt.Sprintf(\"%.2f\", newBal)\n\n\tt.Prepare()\n\tt.Validate()\n\t_, err = t.SaveTransactions(tx)\n\tif err != nil {\n\t\treturn responses.TransactionResponse{}, err\n\t}\n\n\t//do credit entry\n\tcbalance2 := models.Accounts{}\n\t//get Balance for the credit account_no\n\terr = tx.Debug().Model(&models.Accounts{}).Where(\"account_no = ?\", requestCreated.CreditAccount).Take(&cbalance2).Error\n\tif err != nil {\n\t\treturn responses.TransactionResponse{}, err\n\t}\n\t//Insert Credit entry\n\treceiverBal, _ := strconv.ParseFloat(cbalance2.AvailableBal, 64)\n\treceiverNewBal := receiverBal + withdrawalAmt\n\n\tt2 := models.Transactions{} //Transactions object\n\tt2.MsgType = requestCreated.MsgType\n\tt2.Procode = requestCreated.Procode\n\tt2.Channel = requestCreated.Channel\n\tt2.TxnRef = requestCreated.TxnRef\n\tt2.AccountNo = requestCreated.CreditAccount\n\tt2.Amount = requestCreated.Amount\n\tt2.DrCr = \"CR\"\n\tt2.Narration = requestCreated.Narration\n\tt2.AvailableBal = fmt.Sprintf(\"%.2f\", receiverNewBal)\n\n\tt2.Prepare()\n\tt2.Validate()\n\t_, err = t2.SaveTransactions(tx)\n\tif err != nil {\n\t\treturn responses.TransactionResponse{}, err\n\t}\n\t//Update balances on both credit and debit Accounts\n\t//1. debit account.\n\tupdatedAcc1, err := UpdateBalance(tx, requestCreated.DebitAccount, newBal)\n\tif err != nil {\n\t\treturn responses.TransactionResponse{}, err\n\t}\n\t//2.Credit Account\n\tupdatedAcc2, err := UpdateBalance(tx, requestCreated.CreditAccount, receiverNewBal)\n\tif err != nil {\n\t\treturn responses.TransactionResponse{}, err\n\t}\n\n\tresponse.Procode = requestCreated.Procode\n\tresponse.ResponseCode = Successful\n\n\tresponse.Reference = requestCreated.TxnRef\n\tresponse.Amount = withdrawalAmt\n\n\tif requestCreated.Procode == \"210000\" {\n\t\tresponse.AvailableBalance = receiverNewBal\n\t\tresponse.Account = updatedAcc2.AccountNo\n\t\tresponse.Remarks = \"Cash Deposit Successful\"\n\t} else {\n\t\tresponse.Remarks = \"Cash Withdrawal Successful\"\n\t\tresponse.AvailableBalance = newBal\n\t\tresponse.Account = updatedAcc1.AccountNo\n\t}\n\n\treturn response, nil\n\n}",
"func getRemainingDiskSpace(ctxPtr *volumemgrContext) (uint64, error) {\n\n\tvar totalDiskSize uint64\n\n\tpubContentTree := ctxPtr.pubContentTreeStatus\n\titemsContentTree := pubContentTree.GetAll()\n\tfor _, iterContentTreeStatusJSON := range itemsContentTree {\n\t\titerContentTreeStatus := iterContentTreeStatusJSON.(types.ContentTreeStatus)\n\t\tif iterContentTreeStatus.State < types.LOADED {\n\t\t\tlog.Tracef(\"Content tree %s State %d < LOADED\",\n\t\t\t\titerContentTreeStatus.Key(), iterContentTreeStatus.State)\n\t\t\tcontinue\n\t\t}\n\t\ttotalDiskSize += uint64(iterContentTreeStatus.CurrentSize)\n\t}\n\n\tpubVolume := ctxPtr.pubVolumeStatus\n\titemsVolume := pubVolume.GetAll()\n\tfor _, iterVolumeStatusJSON := range itemsVolume {\n\t\titerVolumeStatus := iterVolumeStatusJSON.(types.VolumeStatus)\n\t\t// we start consume space when moving into CREATING_VOLUME state\n\t\tif iterVolumeStatus.State < types.CREATING_VOLUME {\n\t\t\tlog.Tracef(\"Volume %s State %d < CREATING_VOLUME\",\n\t\t\t\titerVolumeStatus.Key(), iterVolumeStatus.State)\n\t\t\tcontinue\n\t\t}\n\t\ttotalDiskSize += volumehandlers.GetVolumeHandler(log, ctxPtr, &iterVolumeStatus).UsageFromStatus()\n\t}\n\tdeviceDiskUsage, err := diskmetrics.PersistUsageStat(log)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Failed to get diskUsage for /persist. err: %s\", err)\n\t\tlog.Error(err)\n\t\treturn 0, err\n\t}\n\tdeviceDiskSize := deviceDiskUsage.Total\n\tdiskReservedForDom0 := diskmetrics.Dom0DiskReservedSize(log, ctxPtr.globalConfig, deviceDiskSize)\n\tvar allowedDeviceDiskSize uint64\n\tif deviceDiskSize < diskReservedForDom0 {\n\t\terr = fmt.Errorf(\"Total Disk Size(%d) <= diskReservedForDom0(%d)\",\n\t\t\tdeviceDiskSize, diskReservedForDom0)\n\t\tlog.Errorf(\"***getRemainingDiskSpace: err: %s\", err)\n\t\treturn uint64(0), err\n\t}\n\tallowedDeviceDiskSize = deviceDiskSize - diskReservedForDom0\n\tif allowedDeviceDiskSize < totalDiskSize {\n\t\treturn 0, nil\n\t} else {\n\t\treturn allowedDeviceDiskSize - totalDiskSize, nil\n\t}\n}",
"func (_TokenContractFunctions *TokenContractFunctionsTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _TokenContractFunctions.contract.Transact(opts, \"transfer\", _to, _value)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
MarginOrder submits a margin order application
|
func (h *HUOBI) MarginOrder(ctx context.Context, symbol currency.Pair, currency string, amount float64) (int64, error) {
symbolValue, err := h.FormatSymbol(symbol, asset.Spot)
if err != nil {
return 0, err
}
data := struct {
Symbol string `json:"symbol"`
Currency string `json:"currency"`
Amount string `json:"amount"`
}{
Symbol: symbolValue,
Currency: currency,
Amount: strconv.FormatFloat(amount, 'f', -1, 64),
}
resp := struct {
MarginOrderID int64 `json:"data"`
}{}
err = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, huobiMarginOrders, nil, data, &resp, false)
return resp.MarginOrderID, err
}
|
[
"func (h *HUOBIHADAX) MarginOrder(symbol, currency string, amount float64) (int64, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\tvals.Set(\"currency\", currency)\n\tvals.Set(\"amount\", strconv.FormatFloat(amount, 'f', -1, 64))\n\n\ttype response struct {\n\t\tResponse\n\t\tMarginOrderID int64 `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodPost, huobihadaxMarginOrders, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.MarginOrderID, err\n}",
"func PreOrdMarginCalculation(w http.ResponseWriter, r *http.Request) {\r\n\r\n\tClientCode := r.URL.Query().Get(\"ClientCode\")\r\n\r\n\tconfig := CheckConfig()\r\n\r\n\turl := config.ServiceURL + \"PreOrdMarginCalculation\"\r\n\r\n\tmethod := \"POST\"\r\n\r\n\theader := Header{AppName: config.AppName, AppVer: config.AppVer, Key: config.Key, OsName: config.OsName, RequestCode: config.RequestCodePreOrdMarCal, UserID: config.UserID, Password: config.Password}\r\n\r\n\tbody := PreOrdMarginCalculationBody{OrderRequestorCode: ClientCode, Exch: \"N\", ExchType: \"D\", ClientCode: ClientCode, ScripCode: \"45609\", PlaceModifyCancel: \"M\",\r\n\t\tTransactionType: \"B\", AtMarket: \"false\", LimitRate: 650, WithSL: \"N\", SLTriggerRate: 0, IsSLTriggered: \"N\", Volume: 250, OldTradedQty: 0, ProductType: \"D\",\r\n\t\tExchOrderID: \"0\", ClientIP: \"21.1.2\", AppSource: 54}\r\n\r\n\tPreOrdMarginCalculationData := PreOrdMarginCalculationReq{Head: header, Body: body}\r\n\r\n\tdata, _ := json.Marshal(PreOrdMarginCalculationData)\r\n\r\n\tpayload := strings.NewReader(string(data))\r\n\r\n\tbodyString := HTTPClient(method, url, payload)\r\n\tjson.NewEncoder(w).Encode(bodyString)\r\n\r\n\tvar PreOrdMarginCalculationRes PreOrdMarginCalculationResponse\r\n\r\n\t// json to golang struct\r\n\tjson.Unmarshal([]byte(bodyString), &PreOrdMarginCalculationRes)\r\n\tfmt.Printf(\"Message: %s, StatusDescription: %s\", PreOrdMarginCalculationRes.Body.Message, PreOrdMarginCalculationRes.Head.StatusDescription)\r\n\r\n}",
"func (p *Poloniex) PlaceMarginOrder(ctx context.Context, currency string, rate, amount, lendingRate float64, buy bool) (OrderResponse, error) {\n\tresult := OrderResponse{}\n\tvalues := url.Values{}\n\n\tvar orderType string\n\tif buy {\n\t\torderType = poloniexMarginBuy\n\t} else {\n\t\torderType = poloniexMarginSell\n\t}\n\n\tvalues.Set(\"currencyPair\", currency)\n\tvalues.Set(\"rate\", strconv.FormatFloat(rate, 'f', -1, 64))\n\tvalues.Set(\"amount\", strconv.FormatFloat(amount, 'f', -1, 64))\n\n\tif lendingRate != 0 {\n\t\tvalues.Set(\"lendingRate\", strconv.FormatFloat(lendingRate, 'f', -1, 64))\n\t}\n\n\treturn result, p.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, orderType, values, &result)\n}",
"func (s *Service) Submit(c context.Context, ap *archive.ArcParam) (err error) {\n\tvar (\n\t\ttx *sql.Tx\n\t\ta *archive.Archive\n\t\taddit *archive.Addit\n\t\toperConts, flowConts []string\n\t\toldMissionID, missionID, descFormatID int64\n\t\tmUser *manager.User\n\t\tporderConts []string\n\t\tporder = &archive.Porder{}\n\t\trel = &oversea.ArchiveRelation{}\n\t)\n\tif a, err = s.arc.Archive(c, ap.Aid); err != nil || a == nil {\n\t\tlog.Error(\"s.arc.Archive(%d) error(%v) or a==nil\", ap.Aid, err)\n\t\treturn\n\t}\n\tif addit, _ = s.arc.Addit(c, ap.Aid); addit != nil {\n\t\tmissionID = addit.MissionID\n\t\tdescFormatID = addit.DescFormatID\n\t}\n\tforbid, _ := s.arc.Forbid(c, ap.Aid)\n\tif tx, err = s.arc.BeginTran(c); err != nil {\n\t\tlog.Error(\"s.arc.BeginTran() error(%v)\", err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\ttx.Rollback()\n\t\t\tlog.Error(\"wocao jingran recover le error(%v)\", r)\n\t\t}\n\t}()\n\t//私单稿件 审核后台允许 私单只填写 流量TAG\n\tif ap.GroupID > 0 {\n\t\tporderConts, porder = s.diffPorder(c, a.Aid, ap)\n\t\toperConts = append(operConts, porderConts...)\n\t\tif err = s.TxUpPorder(tx, ap); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn\n\t\t}\n\t\t//自动匹配流量tag\n\t\tap.OnFlowID = ap.GroupID\n\t\tif err = s.txUpFlowID(tx, ap); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn\n\t\t}\n\t}\n\ts.sendPorderLog(c, ap, porderConts, porder, a)\n\t//流量属性控制,比如:频道禁止\n\tif flowConts, err = s.txBatchUpFlowsState(c, tx, a.Aid, ap.UID, ap.FlowAttribute); err != nil {\n\t\tlog.Error(\"s.txBatchUpFlowsState error(%v)\", err)\n\t\ttx.Rollback()\n\t\treturn\n\t}\n\tif len(flowConts) > 0 {\n\t\toperConts = append(operConts, flowConts...)\n\t}\n\n\t//审核更换流量TAG 或者新增私单 私单二期 flow_design.pool=2 聚合到 archive_forbid + archive.attr 由前端merge\n\tvar delayCont string\n\tif ap.State, delayCont, err = s.txUpArcDelay(c, tx, ap.Aid, ap.Mid, ap.State, ap.Delay, ap.DTime); err != nil {\n\t\ttx.Rollback()\n\t\tlog.Error(\"s.arc.txUpArcDelay(%d,%d,%d,%d,%v,%d) error(%v)\", ap.Aid, ap.Mid, ap.TypeID, ap.State, ap.Delay, ap.DTime, err)\n\t\treturn\n\t}\n\tif delayCont != \"\" {\n\t\toperConts = append(operConts, delayCont)\n\t}\n\tap.Round = s.archiveRound(c, a, ap.Aid, a.Mid, a.TypeID, a.Round, ap.State, ap.CanCelMission)\n\tif ap.Access, err = s.txUpArcMainState(c, tx, ap.Aid, ap.Forward, ap.TypeID, ap.Access, ap.State, ap.Round, ap.RejectReason); err != nil {\n\t\ttx.Rollback()\n\t\tlog.Error(\"s.arc.txUpArcMainState(%d,%d,%d,%d,%d,%d,%s) error(%v)\", ap.Aid, ap.Forward, ap.TypeID, ap.Access, ap.State, ap.Round, ap.RejectReason, err)\n\t\treturn\n\t}\n\tap.PTime = s.archivePtime(c, ap.Aid, ap.State, ap.PTime)\n\t// access、cancel_mission、cover、reject_reason、attr、source、redirecturl、forward、state、pubtime、copyright、mtime、round、title、typeid、content、delay\n\tif _, err = s.arc.TxUpArchive(tx, ap.Aid, ap.Title, ap.Content, ap.Cover, ap.Note, ap.Copyright, ap.PTime); err != nil {\n\t\ttx.Rollback()\n\t\tlog.Error(\"s.arc.TxUpArchive(%d,%s,%s,%s,%s,%d,%d) error(%v)\", ap.Aid, ap.Title, ap.Content, ap.Cover, ap.Note, ap.Copyright, ap.PTime, err)\n\t\treturn\n\t}\n\tlog.Info(\"aid(%d) update archive title(%s) content(%s) cover(%s) copyright(%d) ,ptime(%d), round(%d), state(%d)\", ap.Aid, ap.Title, ap.Content, ap.Cover, ap.Copyright, ap.PTime, ap.Round, ap.State)\n\t// cancel activity\n\tif ap.CanCelMission {\n\t\toldMissionID = missionID\n\t\tmissionID = 0\n\t}\n\tdesc := \"\"\n\tif descFormatID > 0 {\n\t\tdesc = ap.Content\n\t}\n\tif _, err = s.arc.TxUpAddit(tx, ap.Aid, missionID, ap.Source, desc, ap.Dynamic); err != nil {\n\t\ttx.Rollback()\n\t\tlog.Error(\"s.arc.TxUpAddit(%d,%d,%s,%s,%s) error(%v)\", ap.Aid, missionID, ap.Source, desc, ap.Dynamic, err)\n\t\treturn\n\t}\n\tif ap.PolicyID > 1 {\n\t\tap.Attrs.LimitArea = 1\n\t} else {\n\t\tap.Attrs.LimitArea = 0\n\t}\n\tattrs, forbidAttrs := s.archiveAttr(c, ap, true)\n\tvar attrConts []string\n\tif attrConts, err = s.TxUpArchiveAttr(c, tx, a, ap.Aid, ap.UID, attrs, forbidAttrs, ap.URL); err != nil {\n\t\ttx.Rollback()\n\t\tlog.Error(\"s.TxUpArchiveAttr(%d) error(%v)\", ap.Aid, err)\n\t\treturn\n\t}\n\toperConts = append(operConts, attrConts...)\n\tlog.Info(\"aid(%d) update archive attribute(%+v)\", ap.Aid, attrs)\n\tif err = tx.Commit(); err != nil {\n\t\tlog.Error(\"tx.Commit() error(%v)\", err)\n\t\treturn\n\t}\n\tif ap.PolicyID != 0 {\n\t\tif rel, err = s.oversea.PolicyRelation(c, ap.Aid); err != nil {\n\t\t\tlog.Error(\"s.oversea.PolicyRelation(%d) error(%v)\", ap.Aid, err)\n\t\t\treturn\n\t\t}\n\t\tif rel == nil || rel.GroupID != ap.PolicyID {\n\t\t\tif _, err = s.oversea.UpPolicyRelation(c, ap.Aid, ap.PolicyID); err != nil {\n\t\t\t\tlog.Error(\"s.oversea.UpPolicyRelation(%d,%d) error(%v)\", ap.Aid, ap.PolicyID, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\toperConts = append(operConts, fmt.Sprintf(\"[地区展示]应用策略组ID[%d]\", ap.PolicyID))\n\t\t}\n\t}\n\tlog.Info(\"aid(%d) end second_round submit pro\", ap.Aid)\n\t// is send email\n\tvar isChanged = true\n\tif (((ap.State == archive.StateOpen && ap.Access == archive.AccessDefault) || ap.State == archive.StateForbidUserDelay) && !ap.AdminChange) ||\n\t\t(ap.State == archive.StateForbidWait) {\n\t\tisChanged = false\n\t}\n\tarchiveOperConts, changeTypeID, changeCopyright, changeTitle, changeCover := s.diffArchiveOper(ap, a, addit, forbid)\n\n\toperConts = append(operConts, archiveOperConts...)\n\toper := &archive.ArcOper{Aid: ap.Aid, UID: ap.UID, TypeID: ap.TypeID, State: archive.AccessState(ap.State, ap.Access), Round: ap.Round, Attribute: a.Attribute, Remark: ap.Note}\n\toper.Content = strings.Join(operConts, \",\")\n\tif ap.ApplyUID != 0 {\n\t\tmUser, _ = s.mng.User(c, ap.ApplyUID)\n\t\toper.Content = \"[通过\" + mUser.NickName + \"(\" + strconv.FormatInt(ap.ApplyUID, 10) + \")申请的工单]\" + oper.Content\n\t}\n\ts.addArchiveOper(c, oper)\n\t// databus\n\ts.busSecondRound(ap.Aid, oldMissionID, ap.Notify, isChanged, changeTypeID, changeCopyright, changeTitle, changeCover, ap.FromList, ap)\n\tgo s.busSecondRoundUpCredit(ap.Aid, 0, ap.Mid, ap.UID, ap.State, ap.Round, ap.ReasonID, ap.RejectReason)\n\t// log\n\ts.sendArchiveLog(c, ap, operConts, a)\n\treturn\n}",
"func userSubmit(w http.ResponseWriter, r *http.Request) {\n\tlogger.Debug(\"User submit a payssion payment\")\n\t//ip := GetIP(r)\n\t//try to get user post information about the payment\n\n\tpayload := new(data.UserSubmitOrderRequest)\n\tif err := json.NewDecoder(r.Body).Decode(payload); err != nil {\n\t\t//RespondError(w, err, http.StatusBadRequest, GetReqID(r))\n\t\tlogger.Errorf(\"user submit error\", err)\n\t\tdata.RenderJSON(w, r, map[string]interface{}{\n\t\t\t\"retCode\": -1,\n\t\t\t\"msg\": data.PaymentErrInputData,\n\t\t})\n\t\treturn\n\t}\n\t//reqJSON := getJSONFromBody(r)\n\tpayload.IPAddr = data.GetIP(r)\n\tif err := validateRequest(payload); err != nil {\n\t\tdata.RenderJSON(w, r, map[string]interface{}{\n\t\t\t\"retCode\": -1,\n\t\t\t\"msg\": err,\n\t\t})\n\t\treturn\n\t}\n\tpayload.OrderID = data.GetShortOrderID()\n\tpayload.OrderDate = time.Now().Unix()\n\trespond, err := createOrder(payload) //create payssion call\n\t//payload.Respond = fmt.Sprint(respond)\n\tif err != nil {\n\t\tdata.RenderJSON(w, r, map[string]interface{}{\n\t\t\t\"retCode\": -1,\n\t\t\t\"msg\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\trettxt, _ := json.MarshalIndent(respond, \"\", \" \")\n\tpayload.Respond = string(rettxt)\n\n\terr = data.SaveOrderRequest(payload) //finished save request,\n\n\tgo prometheus.OrderCounter.WithLabelValues(\"payssion\").Add(1) //metric order creation\n\n\tif err != nil {\n\t\tdata.RenderJSON(w, r, map[string]interface{}{\n\t\t\t\"retCode\": -1,\n\t\t\t\"msg\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tdata.RenderJSON(w, r, map[string]interface{}{\n\t\t\"retCode\": 0,\n\t\t\"msg\": \"ok\",\n\t\t\"data\": payload,\n\t})\n}",
"func (h *HUOBI) MarginRepayment(ctx context.Context, orderID int64, amount float64) (int64, error) {\n\tdata := struct {\n\t\tAmount string `json:\"amount\"`\n\t}{\n\t\tAmount: strconv.FormatFloat(amount, 'f', -1, 64),\n\t}\n\n\tresp := struct {\n\t\tMarginOrderID int64 `json:\"data\"`\n\t}{}\n\n\tendpoint := fmt.Sprintf(huobiMarginRepay, strconv.FormatInt(orderID, 10))\n\terr := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, endpoint, nil, data, &resp, false)\n\treturn resp.MarginOrderID, err\n}",
"func (h *HUOBIHADAX) MarginRepayment(orderID int64, amount float64) (int64, error) {\n\tvals := url.Values{}\n\tvals.Set(\"order-id\", strconv.FormatInt(orderID, 10))\n\tvals.Set(\"amount\", strconv.FormatFloat(amount, 'f', -1, 64))\n\n\ttype response struct {\n\t\tResponse\n\t\tMarginOrderID int64 `json:\"data\"`\n\t}\n\n\tvar result response\n\tendpoint := fmt.Sprintf(huobihadaxMarginRepay, strconv.FormatInt(orderID, 10))\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodPost, endpoint, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.MarginOrderID, err\n}",
"func makeOrderDirect(db *sql.DB, w http.ResponseWriter, r *http.Request, p string) bool {\n var details OrderSent\n \n recipe_id, err := strconv.Atoi(p)\n if err != nil {\n return false \n }\n\n tmpl, _ := template.ParseFiles(\"admin_header.html\", \"admin_make.html\", \"admin_footer.html\")\n\n // Generate command list. This will fail if not all the ingrediants are present\n fmt.Printf(\"makeOrder: preparing command list for receipe [%d]\\n\", recipe_id)\n cmdList, ret, _ := getCommandList(-1, recipe_id)\n\n if ret != 0 {\n fmt.Printf(\"makeOrder: failed to generate command list!\\n\")\n details.Success = false\n details.FailReason = \"Missing ingrediant(s)\"\n t, _ := template.ParseFiles(\"order_make.html\")\n t.Execute(w, details)\n return true\n }\n details.Success = true\n\n BarbotSerialChan <- cmdList\n \n var adminHead AdminHeader\n adminHead.AllowMaint = AllowMaint\n tmpl.ExecuteTemplate(w, \"admin_header\", adminHead)\n tmpl.ExecuteTemplate(w, \"admin_make\", details)\n tmpl.ExecuteTemplate(w, \"admin_footer\", nil)\n tmpl.Execute(w, details)\n\n return true\n}",
"func (c *Client) SubmitOrder(order *Order) error {\n\treturn c.submitOrder(\"/api/v3/order\", order)\n}",
"func (h *HUOBI) MarginTransfer(ctx context.Context, symbol currency.Pair, currency string, amount float64, in bool) (int64, error) {\n\tsymbolValue, err := h.FormatSymbol(symbol, asset.Spot)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdata := struct {\n\t\tSymbol string `json:\"symbol\"`\n\t\tCurrency string `json:\"currency\"`\n\t\tAmount string `json:\"amount\"`\n\t}{\n\t\tSymbol: symbolValue,\n\t\tCurrency: currency,\n\t\tAmount: strconv.FormatFloat(amount, 'f', -1, 64),\n\t}\n\n\tpath := huobiMarginTransferIn\n\tif !in {\n\t\tpath = huobiMarginTransferOut\n\t}\n\n\tresp := struct {\n\t\tTransferID int64 `json:\"data\"`\n\t}{}\n\terr = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, path, nil, data, &resp, false)\n\treturn resp.TransferID, err\n}",
"func orderFlight(writer http.ResponseWriter, request *http.Request) {\n\terr := request.ParseForm()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ti, err := strconv.ParseInt(request.PostFormValue(\"offerID\"), 10, 32)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tofferID := uint(i)\n\tmanufacturer := request.PostFormValue(\"manufacturer\")\n\taircraftType := request.PostFormValue(\"type\")\n\n\torder := storage.Order{\n\t\tStartTime: time.Now().Local(),\n\t\tName: request.PostFormValue(\"name\"),\n\t\tEmail: request.PostFormValue(\"email\"),\n\t\tPhone: request.PostFormValue(\"phone\"),\n\t\tOfferID: offerID,\n\t\tReturnCode: generateID(),\n\t}\n\tstorage.Db.Create(&order)\n\tsendOrderMail(order.Email, order.ID, order.StartTime, order.ReturnCode, manufacturer+\" - \"+aircraftType)\n\tmsg := `Dear %s, <br><br>\n\tselected aircraft was successfully reserved.\n\t<br>\n\tPlease wait for confirmation e-mail with your return code.\n\t<br><br>\n\tThank you,\n\t<br>\n\tFlyIT team`\n\n\tgenerateHTML(writer, fmt.Sprintf(msg, order.Name), \"base\", \"navbar\", \"return\", \"return_confirm\")\n\t// http.Redirect(writer, request, \"/\", 302)\n}",
"func (a *FuturesApiService) UpdateDualModePositionMargin(ctx context.Context, settle string, contract string, change string, dualSide string) ([]Position, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []Position\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/futures/{settle}/dual_comp/positions/{contract}/margin\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"settle\"+\"}\", url.QueryEscape(parameterToString(settle, \"\")), -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"contract\"+\"}\", url.QueryEscape(parameterToString(contract, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\tlocalVarQueryParams.Add(\"change\", parameterToString(change, \"\"))\n\tlocalVarQueryParams.Add(\"dual_side\", parameterToString(dualSide, \"\"))\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\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tif ctx.Value(ContextGateAPIV4) == nil {\n\t\t// for compatibility, set configuration key and secret to context if ContextGateAPIV4 value is not present\n\t\tctx = context.WithValue(ctx, ContextGateAPIV4, GateAPIV4{\n\t\t\tKey: a.client.cfg.Key,\n\t\t\tSecret: a.client.cfg.Secret,\n\t\t})\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status + \", \" + string(localVarBody),\n\t\t}\n\t\tvar gateErr GateAPIError\n\t\tif e := a.client.decode(&gateErr, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\")); e == nil && gateErr.Label != \"\" {\n\t\t\tgateErr.APIError = newErr\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, gateErr\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 (b *Bitmex) SubmitOrder(ctx context.Context, s *order.Submit) (*order.SubmitResponse, error) {\n\tif err := s.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif math.Trunc(s.Amount) != s.Amount {\n\t\treturn nil,\n\t\t\terrors.New(\"order contract amount can not have decimals\")\n\t}\n\n\tfPair, err := b.FormatExchangeCurrency(s.Pair, s.AssetType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar orderNewParams = OrderNewParams{\n\t\tOrderType: s.Type.Title(),\n\t\tSymbol: fPair.String(),\n\t\tOrderQuantity: s.Amount,\n\t\tSide: s.Side.Title(),\n\t}\n\n\tif s.Type == order.Limit {\n\t\torderNewParams.Price = s.Price\n\t}\n\n\tresponse, err := b.CreateOrder(ctx, &orderNewParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.DeriveSubmitResponse(response.OrderID)\n}",
"func (m *AddFooter) SetMargin(value *int32)() {\n err := m.GetBackingStore().Set(\"margin\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (h *HUOBIHADAX) MarginTransfer(symbol, currency string, amount float64, in bool) (int64, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\tvals.Set(\"currency\", currency)\n\tvals.Set(\"amount\", strconv.FormatFloat(amount, 'f', -1, 64))\n\n\tpath := huobihadaxMarginTransferIn\n\tif !in {\n\t\tpath = huobihadaxMarginTransferOut\n\t}\n\n\ttype response struct {\n\t\tResponse\n\t\tTransferID int64 `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodPost, path, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.TransferID, err\n}",
"func (y *Yobit) SubmitOrder(ctx context.Context, s *order.Submit) (*order.SubmitResponse, error) {\n\tif err := s.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif s.Type != order.Limit {\n\t\treturn nil, errors.New(\"only limit orders are allowed\")\n\t}\n\n\tfPair, err := y.FormatExchangeCurrency(s.Pair, s.AssetType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := y.Trade(ctx,\n\t\tfPair.String(),\n\t\ts.Side.String(),\n\t\ts.Amount,\n\t\ts.Price)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.DeriveSubmitResponse(strconv.FormatInt(response, 10))\n}",
"func (as *apiService) MarginAccount(ar AccountRequest) (*MarginAccount, error) {\n\tparams := make(map[string]string)\n\tparams[\"timestamp\"] = strconv.FormatInt(unixMillis(ar.Timestamp), 10)\n\tif ar.RecvWindow != 0 {\n\t\tparams[\"recvWindow\"] = strconv.FormatInt(recvWindow(ar.RecvWindow), 10)\n\t}\n\n\tres, err := as.request(\"GET\", \"/sapi/v1/margin/account\", params, true, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttextRes, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to read response from account.get\")\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, as.handleError(textRes)\n\t}\n\n\trawAccount := struct {\n\t\tBorrowEnabled \t\tbool \t\t`json:\"borrowEnabled\"`\n\t\tMarginLevel \t\t\t\tstring `json:\"marginLevel\"`\n\t\tTotalAssetOfBtc \t\tstring `json:\"totalAssetOfBtc\"`\n\t\tTotalLiabilityOfBtc string `json:\"totalLiabilityOfBtc\"`\n\t\tTotalNetAssetOfBtc string `json:\"totalNetAssetOfBtc\"`\n\t\tTradeEnabled \tbool \t`json:\"tradeEnabled\"`\n\t\tTransferEnabled bool \t`json:\"transferEnabled\"`\n\t\tUserAssets []struct {\n\t\t\tAsset \t\tstring `json:\"asset\"`\n\t\t\tBorrowed \tstring `json:\"borrowed\"`\n\t\t\tFree \t\tstring `json:\"free\"`\n\t\t\tInterest \tstring `json:\"interest\"`\n\t\t\tLocked \t\tstring `json:\"locked\"`\n\t\t\tNetAsset \tstring `json:\"netAsset\"`\n\t\t}\n\t}{}\n\tif err := json.Unmarshal(textRes, &rawAccount); err != nil {\n\t\treturn nil, errors.Wrap(err, \"rawAccount unmarshal failed\")\n\t}\n\tml, err := floatFromString(rawAccount.MarginLevel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttab, err := floatFromString(rawAccount.TotalAssetOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlb, err := floatFromString(rawAccount.TotalLiabilityOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttnab, err := floatFromString(rawAccount.TotalNetAssetOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tacc := &MarginAccount{\n\t\tBorrowEnabled: \t\t\trawAccount.BorrowEnabled,\n\t\tMarginLevel: \t\t\t\tml,\n\t\tTotalAssetOfBtc: \t\ttab,\n\t\tTotalLiabilityOfBtc: \ttlb,\n\t\tTotalNetAssetOfBtc: tnab,\n\t\tTradeEnabled: \t\trawAccount.TradeEnabled,\n\t\tTransferEnabled: rawAccount.TransferEnabled,\n\t}\n\tfor _, b := range rawAccount.UserAssets {\n\t\tf, err := floatFromString(b.Free)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tl, err := floatFromString(b.Locked)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbo, err := floatFromString(b.Borrowed)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti, err := floatFromString(b.Interest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tn, err := floatFromString(b.NetAsset)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tacc.UserAssets = append(acc.UserAssets, &UserAsset{\n\t\t\tAsset: \tb.Asset,\n\t\t\tBorrowed: bo,\n\t\t\tFree: \tf,\n\t\t\tInterest: i,\n\t\t\tLocked: \tl,\n\t\t\tNetAsset: n,\n\t\t})\n\t}\n\n\treturn acc, nil\n}",
"func (g *Gemini) SubmitExchangeOrder(p pair.CurrencyPair, side string, orderType int, amount, price float64) (int64, error) {\n\treturn 0, errors.New(\"not yet implemented\")\n}",
"func addorder(res http.ResponseWriter, req *http.Request) {\r\n\tmyUser := getUser(res, req)\r\n\tif !alreadyLoggedIn(req) {\r\n\t\thttp.Redirect(res, req, \"/\", http.StatusSeeOther)\r\n\t\treturn\r\n\t}\r\n\r\n\tclientMsg := \"\" // To display message to the user on the client\r\n\tbValidOrder := true // Use to determine if an order entry is valid\r\n\r\n\tviewOrderItemSlice := make([]viewOrderItem, 0) // To use for display in the template\r\n\torderItemSlice := make([]order.OrderItem, 0) // To add new OrderItem into the slice from user selected pizzas\r\n\r\n\tpizzaSlice, err := pizzaList.GetAllPizza() // Get all pizzas from the LinkedList data structure\r\n\r\n\tif err != nil {\r\n\t\tclientMsg = \"No pizza in the menu today\"\r\n\t\tlog.WithFields(logrus.Fields{\r\n\t\t\t\"userName\": myUser.UserName,\r\n\t\t}).Error(\"no pizza in the menu\")\r\n\t} else {\r\n\t\t// Loop through pizzaSlice, create a viewOrderItem struct and append it to viewOrderItemSlice\r\n\t\t// viewOrderItemSlice will be used to display the template form\r\n\t\tfor idx1, val1 := range pizzaSlice {\r\n\t\t\tpizzaOrder := viewOrderItem{idx1 + 1, val1.PizzaNo, val1.PizzaName, fmt.Sprintf(\"%.2f\", val1.PizzaPrice), 0, \"\", \"\"}\r\n\t\t\tviewOrderItemSlice = append(viewOrderItemSlice, pizzaOrder)\r\n\t\t}\r\n\t}\r\n\r\n\t// Process the form submission\r\n\tif req.Method == http.MethodPost {\r\n\t\tfor _, val1 := range viewOrderItemSlice {\r\n\t\t\terrMsg := \"\"\r\n\r\n\t\t\t// Get selectedPizza from form checkbox using viewOrderItem.PizzaNo as its value\r\n\t\t\t// Since viewOrderItem.PizzaNo is an int, use strconv.Itoa to convert it to a string\r\n\t\t\tselectedPizza := req.FormValue(strconv.Itoa(val1.PizzaNo))\r\n\r\n\t\t\t// If selectedPizza is not an empty string, the pizza is selected i.e. checkbox is checked in the form\r\n\t\t\t// Otherwise, no action required since the pizza is not selected\r\n\t\t\tif selectedPizza != \"\" {\r\n\t\t\t\t// Get associated quantity value from form textbox that is in line with the selected pizza\r\n\t\t\t\tselectedQty := req.FormValue(\"orderqty\" + strconv.Itoa(val1.ItemNo))\r\n\r\n\t\t\t\t// Convert selectedPizza and selectedQty to int values\r\n\t\t\t\tpizzaNo, _ := strconv.Atoi(selectedPizza) // blank identifier is used for error as pizzaNo value is assured\r\n\r\n\t\t\t\torderQty, err := validateQuantity(selectedQty)\r\n\r\n\t\t\t\tif err != nil || orderQty == 0 {\r\n\t\t\t\t\terrMsg = \"Enter a valid quantity\" // Error message to display next to quantity checkbox in the tempplate\r\n\r\n\t\t\t\t\tbValidOrder = false // Order entry is invalid\r\n\t\t\t\t} else {\r\n\t\t\t\t\t// Add user selected pizza and valid quantity into orderItemSlice\r\n\t\t\t\t\torderItemSlice = addOrder(orderItemSlice, pizzaNo, orderQty)\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Update values for display in the template form\r\n\t\t\t\tviewOrderItemSlice[val1.ItemNo-1].OrderQty = orderQty\r\n\t\t\t\tviewOrderItemSlice[val1.ItemNo-1].Checked = \"checked\"\r\n\t\t\t\tviewOrderItemSlice[val1.ItemNo-1].ErrorMsg = errMsg\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Continue processing only if there are OrderItem in the orderItemSlice and the order entry is valid\r\n\t\tif len(orderItemSlice) > 0 && bValidOrder {\r\n\t\t\t// Set generateOrderNo as a go routine and add it into a wait group\r\n\t\t\t// This is to prevent multiple clients creating an order at the same time and the same order no being used\r\n\t\t\twg.Add(1)\r\n\t\t\tgo generateOrderNo(orderItemSlice)\r\n\t\t\twg.Wait()\r\n\r\n\t\t\torderNo := newOrderNo\r\n\r\n\t\t\t// Get the total cost of the order from order.CalOrderTotal func\r\n\t\t\ttotalCost := calOrderTotal(orderItemSlice)\r\n\r\n\t\t\t// Enqueue the order\r\n\t\t\torderQueue.Enqueue(orderNo, orderItemSlice, totalCost, myUser.UserName)\r\n\r\n\t\t\t// Print an order receipt on the server\r\n\t\t\tprintOrderReceipt(orderNo, orderItemSlice, totalCost)\r\n\r\n\t\t\tclientMsg = \"Order \" + strconv.Itoa(orderNo) + \" added successfully. Total payment is $\" + fmt.Sprintf(\"%.2f\", totalCost)\r\n\r\n\t\t\tlog.WithFields(logrus.Fields{\r\n\t\t\t\t\"userName\": myUser.UserName,\r\n\t\t\t\t\"orderNo\": orderNo,\r\n\t\t\t\t\"orderItemSlice\": orderItemSlice,\r\n\t\t\t\t\"totalCost\": totalCost,\r\n\t\t\t}).Info(\"new order added successfully\")\r\n\r\n\t\t} else {\r\n\t\t\tclientMsg = \"No orders made\"\r\n\r\n\t\t\tlog.WithFields(logrus.Fields{\r\n\t\t\t\t\"userName\": myUser.UserName,\r\n\t\t\t}).Info(\"no orders made\")\r\n\r\n\t\t}\r\n\t}\r\n\r\n\tdata := struct {\r\n\t\tUser user\r\n\t\tOrderSlice []viewOrderItem\r\n\t\tCntCurrentItems int\r\n\t\tMaxOrder int\r\n\t\tClientMsg string\r\n\t}{\r\n\t\tmyUser,\r\n\t\tviewOrderItemSlice,\r\n\t\tlen(viewOrderItemSlice),\r\n\t\tmaxOrderQty,\r\n\t\tclientMsg,\r\n\t}\r\n\r\n\ttpl.ExecuteTemplate(res, \"addorder.gohtml\", data)\r\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
MarginRepayment repays a margin amount for a margin ID
|
func (h *HUOBI) MarginRepayment(ctx context.Context, orderID int64, amount float64) (int64, error) {
data := struct {
Amount string `json:"amount"`
}{
Amount: strconv.FormatFloat(amount, 'f', -1, 64),
}
resp := struct {
MarginOrderID int64 `json:"data"`
}{}
endpoint := fmt.Sprintf(huobiMarginRepay, strconv.FormatInt(orderID, 10))
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, endpoint, nil, data, &resp, false)
return resp.MarginOrderID, err
}
|
[
"func (h *HUOBIHADAX) MarginRepayment(orderID int64, amount float64) (int64, error) {\n\tvals := url.Values{}\n\tvals.Set(\"order-id\", strconv.FormatInt(orderID, 10))\n\tvals.Set(\"amount\", strconv.FormatFloat(amount, 'f', -1, 64))\n\n\ttype response struct {\n\t\tResponse\n\t\tMarginOrderID int64 `json:\"data\"`\n\t}\n\n\tvar result response\n\tendpoint := fmt.Sprintf(huobihadaxMarginRepay, strconv.FormatInt(orderID, 10))\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodPost, endpoint, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.MarginOrderID, err\n}",
"func (as *apiService) Repay(bor BorrowRequest){\n\tparams := make(map[string]string)\n\tparams[\"asset\"] = bor.Asset\n\tparams[\"amount\"] = strconv.FormatFloat(bor.Amount, 'f', -1, 64)\n\tif bor.RecvWindow != 0 {\n\t\tparams[\"recvWindow\"] = strconv.FormatInt(recvWindow(bor.RecvWindow), 10)\n\t}\n\tparams[\"timestamp\"] = strconv.FormatInt(unixMillis(bor.Timestamp), 10)\n\n\tres, err := as.request(\"POST\", \"sapi/v1/margin/repay\", params, true, true)\n\tif err != nil {\n\t\treturn\n\t}\n\ttextRes, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 200 {\n\t\treturn\n\t}\n\n\trawResponse := rawTransaction{}\n\tif err := json.Unmarshal(textRes, &rawResponse); err != nil {\n\t\treturn\n\t}\n\treturn\n}",
"func PreOrdMarginCalculation(w http.ResponseWriter, r *http.Request) {\r\n\r\n\tClientCode := r.URL.Query().Get(\"ClientCode\")\r\n\r\n\tconfig := CheckConfig()\r\n\r\n\turl := config.ServiceURL + \"PreOrdMarginCalculation\"\r\n\r\n\tmethod := \"POST\"\r\n\r\n\theader := Header{AppName: config.AppName, AppVer: config.AppVer, Key: config.Key, OsName: config.OsName, RequestCode: config.RequestCodePreOrdMarCal, UserID: config.UserID, Password: config.Password}\r\n\r\n\tbody := PreOrdMarginCalculationBody{OrderRequestorCode: ClientCode, Exch: \"N\", ExchType: \"D\", ClientCode: ClientCode, ScripCode: \"45609\", PlaceModifyCancel: \"M\",\r\n\t\tTransactionType: \"B\", AtMarket: \"false\", LimitRate: 650, WithSL: \"N\", SLTriggerRate: 0, IsSLTriggered: \"N\", Volume: 250, OldTradedQty: 0, ProductType: \"D\",\r\n\t\tExchOrderID: \"0\", ClientIP: \"21.1.2\", AppSource: 54}\r\n\r\n\tPreOrdMarginCalculationData := PreOrdMarginCalculationReq{Head: header, Body: body}\r\n\r\n\tdata, _ := json.Marshal(PreOrdMarginCalculationData)\r\n\r\n\tpayload := strings.NewReader(string(data))\r\n\r\n\tbodyString := HTTPClient(method, url, payload)\r\n\tjson.NewEncoder(w).Encode(bodyString)\r\n\r\n\tvar PreOrdMarginCalculationRes PreOrdMarginCalculationResponse\r\n\r\n\t// json to golang struct\r\n\tjson.Unmarshal([]byte(bodyString), &PreOrdMarginCalculationRes)\r\n\tfmt.Printf(\"Message: %s, StatusDescription: %s\", PreOrdMarginCalculationRes.Body.Message, PreOrdMarginCalculationRes.Head.StatusDescription)\r\n\r\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 (as *apiService) MarginAccount(ar AccountRequest) (*MarginAccount, error) {\n\tparams := make(map[string]string)\n\tparams[\"timestamp\"] = strconv.FormatInt(unixMillis(ar.Timestamp), 10)\n\tif ar.RecvWindow != 0 {\n\t\tparams[\"recvWindow\"] = strconv.FormatInt(recvWindow(ar.RecvWindow), 10)\n\t}\n\n\tres, err := as.request(\"GET\", \"/sapi/v1/margin/account\", params, true, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttextRes, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to read response from account.get\")\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, as.handleError(textRes)\n\t}\n\n\trawAccount := struct {\n\t\tBorrowEnabled \t\tbool \t\t`json:\"borrowEnabled\"`\n\t\tMarginLevel \t\t\t\tstring `json:\"marginLevel\"`\n\t\tTotalAssetOfBtc \t\tstring `json:\"totalAssetOfBtc\"`\n\t\tTotalLiabilityOfBtc string `json:\"totalLiabilityOfBtc\"`\n\t\tTotalNetAssetOfBtc string `json:\"totalNetAssetOfBtc\"`\n\t\tTradeEnabled \tbool \t`json:\"tradeEnabled\"`\n\t\tTransferEnabled bool \t`json:\"transferEnabled\"`\n\t\tUserAssets []struct {\n\t\t\tAsset \t\tstring `json:\"asset\"`\n\t\t\tBorrowed \tstring `json:\"borrowed\"`\n\t\t\tFree \t\tstring `json:\"free\"`\n\t\t\tInterest \tstring `json:\"interest\"`\n\t\t\tLocked \t\tstring `json:\"locked\"`\n\t\t\tNetAsset \tstring `json:\"netAsset\"`\n\t\t}\n\t}{}\n\tif err := json.Unmarshal(textRes, &rawAccount); err != nil {\n\t\treturn nil, errors.Wrap(err, \"rawAccount unmarshal failed\")\n\t}\n\tml, err := floatFromString(rawAccount.MarginLevel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttab, err := floatFromString(rawAccount.TotalAssetOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlb, err := floatFromString(rawAccount.TotalLiabilityOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttnab, err := floatFromString(rawAccount.TotalNetAssetOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tacc := &MarginAccount{\n\t\tBorrowEnabled: \t\t\trawAccount.BorrowEnabled,\n\t\tMarginLevel: \t\t\t\tml,\n\t\tTotalAssetOfBtc: \t\ttab,\n\t\tTotalLiabilityOfBtc: \ttlb,\n\t\tTotalNetAssetOfBtc: tnab,\n\t\tTradeEnabled: \t\trawAccount.TradeEnabled,\n\t\tTransferEnabled: rawAccount.TransferEnabled,\n\t}\n\tfor _, b := range rawAccount.UserAssets {\n\t\tf, err := floatFromString(b.Free)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tl, err := floatFromString(b.Locked)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbo, err := floatFromString(b.Borrowed)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti, err := floatFromString(b.Interest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tn, err := floatFromString(b.NetAsset)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tacc.UserAssets = append(acc.UserAssets, &UserAsset{\n\t\t\tAsset: \tb.Asset,\n\t\t\tBorrowed: bo,\n\t\t\tFree: \tf,\n\t\t\tInterest: i,\n\t\t\tLocked: \tl,\n\t\t\tNetAsset: n,\n\t\t})\n\t}\n\n\treturn acc, nil\n}",
"func (h *HUOBIHADAX) MarginTransfer(symbol, currency string, amount float64, in bool) (int64, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\tvals.Set(\"currency\", currency)\n\tvals.Set(\"amount\", strconv.FormatFloat(amount, 'f', -1, 64))\n\n\tpath := huobihadaxMarginTransferIn\n\tif !in {\n\t\tpath = huobihadaxMarginTransferOut\n\t}\n\n\ttype response struct {\n\t\tResponse\n\t\tTransferID int64 `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodPost, path, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.TransferID, err\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 (h *HUOBI) MarginTransfer(ctx context.Context, symbol currency.Pair, currency string, amount float64, in bool) (int64, error) {\n\tsymbolValue, err := h.FormatSymbol(symbol, asset.Spot)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdata := struct {\n\t\tSymbol string `json:\"symbol\"`\n\t\tCurrency string `json:\"currency\"`\n\t\tAmount string `json:\"amount\"`\n\t}{\n\t\tSymbol: symbolValue,\n\t\tCurrency: currency,\n\t\tAmount: strconv.FormatFloat(amount, 'f', -1, 64),\n\t}\n\n\tpath := huobiMarginTransferIn\n\tif !in {\n\t\tpath = huobiMarginTransferOut\n\t}\n\n\tresp := struct {\n\t\tTransferID int64 `json:\"data\"`\n\t}{}\n\terr = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, path, nil, data, &resp, false)\n\treturn resp.TransferID, err\n}",
"func (h *HUOBIHADAX) MarginOrder(symbol, currency string, amount float64) (int64, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\tvals.Set(\"currency\", currency)\n\tvals.Set(\"amount\", strconv.FormatFloat(amount, 'f', -1, 64))\n\n\ttype response struct {\n\t\tResponse\n\t\tMarginOrderID int64 `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodPost, huobihadaxMarginOrders, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.MarginOrderID, err\n}",
"func InvoicePayed(ID string) sql.Result {\n\tinvoiceID, err := GetDB().Exec(\"UPDATE parking_invoice SET ispayed = true WHERE id = $1\", ID)\n\n\tif err != nil {\n\t\tlog.Println(\"Error invoice paying!\", err)\n\t}\n\n\treturn invoiceID\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 Pay(id string, params *stripe.InvoiceParams) (*stripe.Invoice, error) {\n\treturn getC().Pay(id, params)\n}",
"func (h *HUOBI) MarginOrder(ctx context.Context, symbol currency.Pair, currency string, amount float64) (int64, error) {\n\tsymbolValue, err := h.FormatSymbol(symbol, asset.Spot)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdata := struct {\n\t\tSymbol string `json:\"symbol\"`\n\t\tCurrency string `json:\"currency\"`\n\t\tAmount string `json:\"amount\"`\n\t}{\n\t\tSymbol: symbolValue,\n\t\tCurrency: currency,\n\t\tAmount: strconv.FormatFloat(amount, 'f', -1, 64),\n\t}\n\n\tresp := struct {\n\t\tMarginOrderID int64 `json:\"data\"`\n\t}{}\n\terr = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, huobiMarginOrders, nil, data, &resp, false)\n\treturn resp.MarginOrderID, err\n}",
"func (w *Wx) PayPrepayId(c Context) {\n\t// TODO\n\tc.String(http.StatusOK, \"get pay prepay id\")\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 (m *AddFooter) SetMargin(value *int32)() {\n err := m.GetBackingStore().Set(\"margin\", value)\n if err != nil {\n panic(err)\n }\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 (_Harberger *HarbergerCaller) TaxDue(opts *bind.CallOpts, _tokenId *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Harberger.contract.Call(opts, out, \"taxDue\", _tokenId)\n\treturn *ret0, err\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}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetMarginLoanOrders returns the margin loan orders
|
func (h *HUOBI) GetMarginLoanOrders(ctx context.Context, symbol currency.Pair, currency, start, end, states, from, direct, size string) ([]MarginOrder, error) {
vals := url.Values{}
symbolValue, err := h.FormatSymbol(symbol, asset.Spot)
if err != nil {
return nil, err
}
vals.Set("symbol", symbolValue)
vals.Set("currency", currency)
if start != "" {
vals.Set("start-date", start)
}
if end != "" {
vals.Set("end-date", end)
}
if states != "" {
vals.Set("states", states)
}
if from != "" {
vals.Set("from", from)
}
if direct != "" {
vals.Set("direct", direct)
}
if size != "" {
vals.Set("size", size)
}
resp := struct {
MarginLoanOrders []MarginOrder `json:"data"`
}{}
err = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiMarginLoanOrders, vals, nil, &resp, false)
return resp.MarginLoanOrders, err
}
|
[
"func (h *HUOBIHADAX) GetMarginLoanOrders(symbol, currency, start, end, states, from, direct, size string) ([]MarginOrder, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\tvals.Set(\"currency\", currency)\n\n\tif start != \"\" {\n\t\tvals.Set(\"start-date\", start)\n\t}\n\n\tif end != \"\" {\n\t\tvals.Set(\"end-date\", end)\n\t}\n\n\tif states != \"\" {\n\t\tvals.Set(\"states\", states)\n\t}\n\n\tif from != \"\" {\n\t\tvals.Set(\"from\", from)\n\t}\n\n\tif direct != \"\" {\n\t\tvals.Set(\"direct\", direct)\n\t}\n\n\tif size != \"\" {\n\t\tvals.Set(\"size\", size)\n\t}\n\n\ttype response struct {\n\t\tResponse\n\t\tMarginLoanOrders []MarginOrder `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodGet, huobihadaxMarginLoanOrders, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.MarginLoanOrders, err\n}",
"func (p *Poloniex) GetLoanOrders(ctx context.Context, currency string) (LoanOrders, error) {\n\tresp := LoanOrders{}\n\tpath := fmt.Sprintf(\"/public?command=returnLoanOrders¤cy=%s\", currency)\n\n\treturn resp, p.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)\n}",
"func (p *Poloniex) LoanOrders(currency string) (loanOrders LoanOrders, err error) {\r\n\tparams := url.Values{}\r\n\tparams.Add(\"currency\", currency)\r\n\terr = p.public(\"returnLoanOrders\", params, &loanOrders)\r\n\treturn\r\n}",
"func (f *FTX) GetMarginLendingOffers(ctx context.Context) ([]LendingOffersData, error) {\n\tr := struct {\n\t\tData []LendingOffersData `json:\"result\"`\n\t}{}\n\treturn r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, marginLendingOffers, nil, &r)\n}",
"func (h *HUOBIHADAX) MarginOrder(symbol, currency string, amount float64) (int64, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\tvals.Set(\"currency\", currency)\n\tvals.Set(\"amount\", strconv.FormatFloat(amount, 'f', -1, 64))\n\n\ttype response struct {\n\t\tResponse\n\t\tMarginOrderID int64 `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodPost, huobihadaxMarginOrders, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.MarginOrderID, err\n}",
"func LoanPaymentGetList(lp models.LoanPayment, m *models.Message) {\n\tm.Code = http.StatusBadRequest\n\tif lp.CodLoan <= 0 {\n\t\tm.Message = \"falta prestamo\"\n\t\treturn\n\t}\n\tlps := []models.LoanPayment{lp}\n\tdb := configuration.GetConnection()\n\tdefer db.Close()\n\terr := getLoanPaymentList(&lps, db)\n\tif err != nil {\n\t\tm.Code = http.StatusBadRequest\n\t\tm.Message = \"no se encontro litado de pago a prestamos\"\n\t\treturn\n\t}\n\tm.Code = http.StatusOK\n\tm.Message = \"lista de pago a prestamos\"\n\tm.Data = lps\n}",
"func getLoanPaymentList(lps *[]models.LoanPayment, db *gorm.DB) error {\n\tvar lp models.LoanPayment\n\tif len(*lps) == 1 {\n\t\tlp = (*lps)[0]\n\t}\n\twhere := fmt.Sprintf(\"cod_collection = %v\", lp.CodCollection)\n\tif lp.CodLoan != 0 {\n\t\twhere = fmt.Sprintf(\"cod_loan = %v\", lp.CodLoan)\n\t}\n\tif lp.CodUser != 0 {\n\t\twhere += fmt.Sprintf(\" and cod_user = %v\", lp.CodUser)\n\t}\n\terr := db.Where(where).Select(\"id,updated_at,cod_loan,cash,cod_user\").Find(lps).GetErrors()\n\tif len(err) != 0 {\n\t\treturn errors.New(\"no se encuentra\")\n\t}\n\treturn nil\n}",
"func (h *HUOBI) MarginOrder(ctx context.Context, symbol currency.Pair, currency string, amount float64) (int64, error) {\n\tsymbolValue, err := h.FormatSymbol(symbol, asset.Spot)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdata := struct {\n\t\tSymbol string `json:\"symbol\"`\n\t\tCurrency string `json:\"currency\"`\n\t\tAmount string `json:\"amount\"`\n\t}{\n\t\tSymbol: symbolValue,\n\t\tCurrency: currency,\n\t\tAmount: strconv.FormatFloat(amount, 'f', -1, 64),\n\t}\n\n\tresp := struct {\n\t\tMarginOrderID int64 `json:\"data\"`\n\t}{}\n\terr = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, huobiMarginOrders, nil, data, &resp, false)\n\treturn resp.MarginOrderID, err\n}",
"func getCurrentOrders(userName string, isAdmin bool) ([]viewOrder, error) {\r\n\r\n\tviewOrderSlice := make([]viewOrder, 0)\r\n\tpizzaSlice, _ := pizzaList.GetAllPizza()\r\n\torderQSlice, err := orderQueue.GetAllOrders(userName, isAdmin)\r\n\r\n\tif err != nil {\r\n\t\treturn viewOrderSlice, err\r\n\t} else {\r\n\t\tfor idx1, val1 := range orderQSlice {\r\n\t\t\torderSlice := val1.OrderSlice\r\n\t\t\tviewOrderItemSlice := make([]viewOrderItem, 0)\r\n\r\n\t\t\tfor idx2, val2 := range orderSlice {\r\n\t\t\t\tfor _, val3 := range pizzaSlice {\r\n\t\t\t\t\tif val2.PizzaNo == val3.PizzaNo {\r\n\t\t\t\t\t\tpizzaOrder := viewOrderItem{idx2 + 1, val2.PizzaNo, val3.PizzaName, fmt.Sprintf(\"%.2f\", val3.PizzaPrice), val2.OrderQty, \"\", \"\"}\r\n\t\t\t\t\t\tviewOrderItemSlice = append(viewOrderItemSlice, pizzaOrder)\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tviewOrder := viewOrder{idx1 + 1, val1.OrderNo, viewOrderItemSlice, fmt.Sprintf(\"%.2f\", val1.TotalCost), val1.UserName}\r\n\t\t\tviewOrderSlice = append(viewOrderSlice, viewOrder)\r\n\t\t}\r\n\t}\r\n\r\n\treturn viewOrderSlice, nil\r\n}",
"func (env Env) ListOrders(filter checkout.OrderFilter, page gorest.Pagination) (checkout.CMSOrderList, error) {\n\tdefer env.logger.Sync()\n\tsugar := env.logger.Sugar()\n\n\twhere := filter.SQLWhere()\n\tcountCh := make(chan int64)\n\tlistCh := make(chan checkout.CMSOrderList)\n\n\tgo func() {\n\t\tdefer close(countCh)\n\t\tn, err := env.countOrder(where)\n\t\tif err != nil {\n\t\t\tsugar.Error(err)\n\t\t}\n\n\t\tcountCh <- n\n\t}()\n\n\tgo func() {\n\t\tdefer close(listCh)\n\n\t\torders, err := env.listOrders(where, page)\n\n\t\tlistCh <- checkout.CMSOrderList{\n\t\t\tPagedList: pkg.PagedList{\n\t\t\t\tTotal: 0,\n\t\t\t\tPagination: gorest.Pagination{},\n\t\t\t\tErr: err,\n\t\t\t},\n\t\t\tData: orders,\n\t\t}\n\t}()\n\n\tcount, listResult := <-countCh, <-listCh\n\tif listResult.Err != nil {\n\t\treturn checkout.CMSOrderList{}, listResult.Err\n\t}\n\n\treturn checkout.CMSOrderList{\n\t\tPagedList: pkg.PagedList{\n\t\t\tTotal: count,\n\t\t\tPagination: page,\n\t\t\tErr: nil,\n\t\t},\n\t\tData: listResult.Data,\n\t}, nil\n}",
"func GetAllLotteryOrder(offset int64, limit int64) (ml []LotteryOrder, err error) {\n\to := orm.NewOrm()\n\tqs := o.QueryTable(new(LotteryOrder))\n\tif _, err := qs.Limit(limit, offset).All(&ml); err == nil {\n\t\treturn ml, nil\n\t}\n\treturn nil, err\n}",
"func getLoanList(ls *[]models.Loan, db *gorm.DB) error {\n\tvar l models.Loan\n\tif len(*ls) == 1 {\n\t\tl = (*ls)[0]\n\t}\n\twhere := \"\"\n\tif l.CodCollection != 0 {\n\t\twhere = fmt.Sprintf(\"cod_collection = %v\", l.CodCollection)\n\t}\n\tif l.CodClient != 0 {\n\t\twhere = fmt.Sprintf(\"cod_client = %v\", l.CodClient)\n\t}\n\tif where != \"\" && l.CodLoanState != 0 {\n\t\twhere += fmt.Sprintf(\" and cod_loan_state = %v\", l.CodLoanState)\n\t}\n\terr := db.Where(where).Select(\"id,created_at,updated_at,initial_value,interest,quota,balance,cod_loan_state,cod_client\").Find(ls).GetErrors()\n\tif len(err) != 0 {\n\t\treturn errors.New(\"no se encuentra\")\n\t}\n\treturn nil\n}",
"func LoanPaymentGet(lp models.LoanPayment, m *models.Message) {\n\tm.Code = http.StatusBadRequest\n\tif lp.ID <= 0 {\n\t\tm.Message = \"falta identificador de pago de prestamo\"\n\t\treturn\n\t}\n\tdb := configuration.GetConnection()\n\tdefer db.Close()\n\terr := getLoanPayment(&lp, db)\n\tif err != nil {\n\t\tm.Code = http.StatusBadRequest\n\t\tm.Message = \"no se encotro pago a prestamo\"\n\t\treturn\n\t}\n\tm.Code = http.StatusOK\n\tm.Message = \"pago a prestamo creado\"\n\tm.Data = lp\n}",
"func GetLoanResponses(txHashes [][]byte, bcr BlockchainRetriever) []ResponseData {\n\tdata := []ResponseData{}\n\tfor _, txHash := range txHashes {\n\t\thash, err := (&common.Hash{}).NewHash(txHash)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"NewHash err: %x\\n\", txHash)\n\t\t\tcontinue\n\t\t}\n\t\t_, _, _, txOld, err := bcr.GetTransactionByHash(hash)\n\t\tif txOld == nil || err != nil {\n\t\t\tfmt.Printf(\"GetTxByHash err: %x\\n\", hash)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"Type: %d\\n\", txOld.GetMetadataType())\n\t\tif txOld.GetMetadataType() == LoanResponseMeta {\n\t\t\tmeta := txOld.GetMetadata().(*LoanResponse)\n\t\t\trespData := ResponseData{\n\t\t\t\tPublicKey: txOld.GetSigPubKey(),\n\t\t\t\tResponse: meta.Response,\n\t\t\t}\n\t\t\tdata = append(data, respData)\n\t\t}\n\t}\n\treturn data\n}",
"func (company *Company) Orders() []*Order {\n\tif company == nil {\n\t\treturn nil\n\t}\n\n\treturn company.orders\n}",
"func GetGLAccountChildAccts(ctx context.Context, bid, lid int64) ([]int64, error) {\n\tvar m []int64\n\tfor _, v := range RRdb.BizTypes[bid].GLAccounts {\n\t\tif v.PLID == lid {\n\t\t\tm = append(m, v.LID)\n\t\t}\n\t}\n\n\t// TODO(): returning things from the memory cache,\n\t// need authorization of user on top of this call/here.\n\treturn m, nil\n}",
"func getLoanPayment(lp *models.LoanPayment, db *gorm.DB) error {\n\terr := db.Select(\"id,created_at,updated_at,cod_loan,cash,cod_user,cod_collection\").First(lp).GetErrors()\n\tif len(err) != 0 {\n\t\treturn errors.New(\"no se encuentra\")\n\t}\n\treturn nil\n}",
"func (c *TradeData) GetMarginLendingRatio(req requests.GetRatio) (response responses.GetRatio, err error) {\n\tp := \"/api/v5/rubik/stat/margin/loan-ratio\"\n\tm := okex.S2M(req)\n\tres, err := c.client.Do(http.MethodGet, p, false, m)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\td := json.NewDecoder(res.Body)\n\terr = d.Decode(&response)\n\treturn\n}",
"func (p *Poloniex) GetOpenLoanOffers(ctx context.Context) (map[string][]LoanOffer, error) {\n\ttype Response struct {\n\t\tData map[string][]LoanOffer\n\t}\n\tresult := Response{}\n\n\terr := p.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, poloniexOpenLoanOffers, url.Values{}, &result.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif result.Data == nil {\n\t\treturn nil, errors.New(\"there are no open loan offers\")\n\t}\n\n\treturn result.Data, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetMarginAccountBalance returns the margin account balances
|
func (h *HUOBI) GetMarginAccountBalance(ctx context.Context, symbol currency.Pair) ([]MarginAccountBalance, error) {
resp := struct {
Balances []MarginAccountBalance `json:"data"`
}{}
vals := url.Values{}
if !symbol.IsEmpty() {
symbolValue, err := h.FormatSymbol(symbol, asset.Spot)
if err != nil {
return resp.Balances, err
}
vals.Set("symbol", symbolValue)
}
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiMarginAccountBalance, vals, nil, &resp, false)
return resp.Balances, err
}
|
[
"func (h *HUOBIHADAX) GetMarginAccountBalance(symbol string) ([]MarginAccountBalance, error) {\n\ttype response struct {\n\t\tResponse\n\t\tBalances []MarginAccountBalance `json:\"data\"`\n\t}\n\n\tvals := url.Values{}\n\tif symbol != \"\" {\n\t\tvals.Set(\"symbol\", symbol)\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodGet, huobihadaxMarginAccountBalance, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.Balances, err\n}",
"func (as *apiService) MarginAccount(ar AccountRequest) (*MarginAccount, error) {\n\tparams := make(map[string]string)\n\tparams[\"timestamp\"] = strconv.FormatInt(unixMillis(ar.Timestamp), 10)\n\tif ar.RecvWindow != 0 {\n\t\tparams[\"recvWindow\"] = strconv.FormatInt(recvWindow(ar.RecvWindow), 10)\n\t}\n\n\tres, err := as.request(\"GET\", \"/sapi/v1/margin/account\", params, true, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttextRes, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to read response from account.get\")\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, as.handleError(textRes)\n\t}\n\n\trawAccount := struct {\n\t\tBorrowEnabled \t\tbool \t\t`json:\"borrowEnabled\"`\n\t\tMarginLevel \t\t\t\tstring `json:\"marginLevel\"`\n\t\tTotalAssetOfBtc \t\tstring `json:\"totalAssetOfBtc\"`\n\t\tTotalLiabilityOfBtc string `json:\"totalLiabilityOfBtc\"`\n\t\tTotalNetAssetOfBtc string `json:\"totalNetAssetOfBtc\"`\n\t\tTradeEnabled \tbool \t`json:\"tradeEnabled\"`\n\t\tTransferEnabled bool \t`json:\"transferEnabled\"`\n\t\tUserAssets []struct {\n\t\t\tAsset \t\tstring `json:\"asset\"`\n\t\t\tBorrowed \tstring `json:\"borrowed\"`\n\t\t\tFree \t\tstring `json:\"free\"`\n\t\t\tInterest \tstring `json:\"interest\"`\n\t\t\tLocked \t\tstring `json:\"locked\"`\n\t\t\tNetAsset \tstring `json:\"netAsset\"`\n\t\t}\n\t}{}\n\tif err := json.Unmarshal(textRes, &rawAccount); err != nil {\n\t\treturn nil, errors.Wrap(err, \"rawAccount unmarshal failed\")\n\t}\n\tml, err := floatFromString(rawAccount.MarginLevel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttab, err := floatFromString(rawAccount.TotalAssetOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlb, err := floatFromString(rawAccount.TotalLiabilityOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttnab, err := floatFromString(rawAccount.TotalNetAssetOfBtc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tacc := &MarginAccount{\n\t\tBorrowEnabled: \t\t\trawAccount.BorrowEnabled,\n\t\tMarginLevel: \t\t\t\tml,\n\t\tTotalAssetOfBtc: \t\ttab,\n\t\tTotalLiabilityOfBtc: \ttlb,\n\t\tTotalNetAssetOfBtc: tnab,\n\t\tTradeEnabled: \t\trawAccount.TradeEnabled,\n\t\tTransferEnabled: rawAccount.TransferEnabled,\n\t}\n\tfor _, b := range rawAccount.UserAssets {\n\t\tf, err := floatFromString(b.Free)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tl, err := floatFromString(b.Locked)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbo, err := floatFromString(b.Borrowed)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti, err := floatFromString(b.Interest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tn, err := floatFromString(b.NetAsset)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tacc.UserAssets = append(acc.UserAssets, &UserAsset{\n\t\t\tAsset: \tb.Asset,\n\t\t\tBorrowed: bo,\n\t\t\tFree: \tf,\n\t\t\tInterest: i,\n\t\t\tLocked: \tl,\n\t\t\tNetAsset: n,\n\t\t})\n\t}\n\n\treturn acc, nil\n}",
"func GetAccountBalance(bid, lid int64, dt *time.Time) (float64, rlib.LedgerMarker) {\n\tlm := rlib.GetRALedgerMarkerOnOrBeforeDeprecated(bid, lid, 0, dt) // find nearest ledgermarker, use it as a starting point\n\tbal, _ := rlib.GetAccountActivity(bid, lid, &lm.Dt, dt)\n\treturn bal, lm\n}",
"func GetAccountBalance(ctx context.Context, bid, lid int64, dt *time.Time) (float64, error) {\n\treturn GetRAAccountBalance(ctx, bid, lid, 0, dt)\n}",
"func (a Account) GetBalance() int {\n\treturn a.balance\n}",
"func (_Token *TokenCallerSession) GetBalance() (struct {\n\tTokenList [][32]byte\n\tBalances []*big.Int\n}, error) {\n\treturn _Token.Contract.GetBalance(&_Token.CallOpts)\n}",
"func (a *Account) Balance() int {\n\treturn a.balance\n}",
"func (_Sigmacore *SigmacoreSession) GetBalance(token common.Address) (*big.Int, error) {\n\treturn _Sigmacore.Contract.GetBalance(&_Sigmacore.CallOpts, token)\n}",
"func GetBalance(tx *gorm.DB, requestCreated *models.TransactionRequests) (responses.TransactionResponse, error) {\n\t//first get Balance of the DebitAccount\n\tresponse := responses.TransactionResponse{}\n\tcbalance := models.Accounts{}\n\n\terr := tx.Debug().Model(&models.Accounts{}).Where(\"account_no = ?\", requestCreated.DebitAccount).Take(&cbalance).Error\n\tif err != nil {\n\t\treturn responses.TransactionResponse{}, err\n\t}\n\tresponse.Procode = requestCreated.Procode\n\tresponse.ResponseCode = Successful\n\tresponse.Remarks = \"Balance Enquiry Successful\"\n\tresponse.Reference = requestCreated.TxnRef\n\tamt, _ := strconv.ParseFloat(\"0.00\", 64)\n\tresponse.Amount = amt\n\tresponse.Account = cbalance.AccountNo\n\tbal, _ := strconv.ParseFloat(cbalance.AvailableBal, 64)\n\tresponse.AvailableBalance = bal\n\n\treturn response, nil\n}",
"func (_Sigmacore *SigmacoreCaller) GetBalance(opts *bind.CallOpts, token common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Sigmacore.contract.Call(opts, &out, \"getBalance\", token)\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 (_Withdrawable *WithdrawableSession) GetDepositedBalance(arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\treturn _Withdrawable.Contract.GetDepositedBalance(&_Withdrawable.CallOpts, arg0, arg1)\n}",
"func (me *XsdGoPkgHasElems_GetAccountBalance) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_GetAccountBalance; 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.GetAccountBalances {\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 (token *Token) GetBalance(addr crypto.Address) (uint64, error) {\n\tret, _, err := token.invokeContract(addr, \"get_balance\", []string{addr.String()})\n\treturn ret, err\n}",
"func (m *Monzgo) Balance(accountID string) (*Balance, error) {\n\trequestParams := make(map[string]string)\n\trequestParams[\"account_id\"] = accountID\n\n\tbalance := &Balance{}\n\tif err := m.request(\"GET\", \"balance\", balance, requestParams); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn balance, nil\n}",
"func (_Token *TokenCaller) GetBalance(opts *bind.CallOpts) (struct {\n\tTokenList [][32]byte\n\tBalances []*big.Int\n}, error) {\n\tret := new(struct {\n\t\tTokenList [][32]byte\n\t\tBalances []*big.Int\n\t})\n\tout := ret\n\terr := _Token.contract.Call(opts, out, \"getBalance\")\n\treturn *ret, err\n}",
"func (c *Client) GetAccountBalance(params *GetAccountBalanceParams) (*GetAccountBalance, error) {\n\tresp, err := c.get(\"getAccountBalance\", params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() { _ = resp.Body.Close() }()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"error: HTTP status code %v\", resp.StatusCode)\n\t}\n\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\top := &GetAccountBalance{}\n\terr = xml.Unmarshal(bytes, op)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode: %v: %s\", err, bytes)\n\t}\n\n\tswitch op.Reply.Code {\n\tcase SuccessfulAPIOperation:\n\t\t// Successful API operation\n\t\treturn op, nil\n\tcase SuccessfulRegistration:\n\t\t// Successful registration, but not all provided hosts were valid resulting in our nameservers being used\n\t\treturn op, nil\n\tcase SuccessfulOrder:\n\t\t// Successful order, but there was an error with the contact information provided so your account default contact profile was used\n\t\treturn op, nil\n\tdefault:\n\t\t// error\n\t\treturn op, fmt.Errorf(\"code: %s, details: %s\", op.Reply.Code, op.Reply.Detail)\n\t}\n}",
"func (p *Bittrex) GetBalance() map[string]interface{} {\n\tif err, response := p.marketRequest(\"/account/getbalances\", map[string]string{\n\t\t\"apikey\": p.config.API,\n\t}, true); err != nil {\n\t\tlogger.Errorf(\"Fail to get balance:%v\", err)\n\t\treturn nil\n\t} else {\n\n\t\tif response == nil || response[\"success\"] != true {\n\t\t\tlogger.Errorf(\"Fail to get the balances:%v\", response[\"message\"])\n\t\t\treturn nil\n\t\t}\n\n\t\tbalances := make(map[string]interface{})\n\t\tresult := response[\"result\"].([]interface{})\n\t\tif result != nil {\n\t\t\tfor _, item := range result {\n\t\t\t\tbalance := item.(map[string]interface{})\n\t\t\t\tbalances[balance[\"Currency\"].(string)] = balance[\"Available\"].(float64)\n\t\t\t}\n\n\t\t\treturn balances\n\t\t}\n\n\t}\n\n\treturn nil\n}",
"func (l *Loan) GetBalance(d custom.Date) (float64, error) {\n\t// validate d > l.StartDate\n\terr := ValidateGetBalanceDate(*l, d)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t// Get last adjustment data before date.\n\tadj := l.getLastAdjustmentAsOfDate(d)\n\t// calculate interest till date.\n\tinterest := l.calculateInterest(adj.CurrPrincipal, adj.Date, d)\n\tfmt.Println(\"Interest : \", interest, \"Current Principal : \", adj.CurrPrincipal)\n\t// Add principal and interest to get current balance.\n\treturn adj.CurrPrincipal + adj.PendingInterest + interest, nil\n}",
"func (me *XsdGoPkgHasElem_GetAccountBalance) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_GetAccountBalance; 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.GetAccountBalance.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
CancelWithdraw cancels a withdraw request
|
func (h *HUOBI) CancelWithdraw(ctx context.Context, withdrawID int64) (int64, error) {
resp := struct {
WithdrawID int64 `json:"data"`
}{}
vals := url.Values{}
vals.Set("withdraw-id", strconv.FormatInt(withdrawID, 10))
endpoint := fmt.Sprintf(huobiWithdrawCancel, strconv.FormatInt(withdrawID, 10))
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, endpoint, vals, nil, &resp, false)
return resp.WithdrawID, err
}
|
[
"func (h *HUOBIHADAX) CancelWithdraw(withdrawID int64) (int64, error) {\n\ttype response struct {\n\t\tResponse\n\t\tWithdrawID int64 `json:\"data\"`\n\t}\n\n\tvals := url.Values{}\n\tvals.Set(\"withdraw-id\", strconv.FormatInt(withdrawID, 10))\n\n\tvar result response\n\tendpoint := fmt.Sprintf(huobihadaxWithdrawCancel, strconv.FormatInt(withdrawID, 10))\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodPost, endpoint, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.WithdrawID, err\n}",
"func (_Vault *VaultTransactor) RequestWithdraw(opts *bind.TransactOpts, incognitoAddress string, token common.Address, amount *big.Int, signData []byte, timestamp []byte) (*types.Transaction, error) {\n\treturn _Vault.contract.Transact(opts, \"requestWithdraw\", incognitoAddress, token, amount, signData, timestamp)\n}",
"func (_Incmode *IncmodeTransactor) RequestWithdraw(opts *bind.TransactOpts, incognitoAddress string, token common.Address, amount *big.Int, signData []byte, hash [32]byte) (*types.Transaction, error) {\n\treturn _Incmode.contract.Transact(opts, \"requestWithdraw\", incognitoAddress, token, amount, signData, hash)\n}",
"func (_Incmode *IncmodeSession) RequestWithdraw(incognitoAddress string, token common.Address, amount *big.Int, signData []byte, hash [32]byte) (*types.Transaction, error) {\n\treturn _Incmode.Contract.RequestWithdraw(&_Incmode.TransactOpts, incognitoAddress, token, amount, signData, hash)\n}",
"func (_Vault *VaultSession) RequestWithdraw(incognitoAddress string, token common.Address, amount *big.Int, signData []byte, timestamp []byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.RequestWithdraw(&_Vault.TransactOpts, incognitoAddress, token, amount, signData, timestamp)\n}",
"func (_BREMICO *BREMICOTransactor) ConfirmWithdraw(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BREMICO.contract.Transact(opts, \"confirmWithdraw\")\n}",
"func (_BREMICO *BREMICOTransactorSession) ConfirmWithdraw() (*types.Transaction, error) {\n\treturn _BREMICO.Contract.ConfirmWithdraw(&_BREMICO.TransactOpts)\n}",
"func (_SfcContract *SfcContractSession) Withdraw(toValidatorID *big.Int, wrID *big.Int) (*types.Transaction, error) {\n\treturn _SfcContract.Contract.Withdraw(&_SfcContract.TransactOpts, toValidatorID, wrID)\n}",
"func (_SfcContract *SfcContractTransactorSession) Withdraw(toValidatorID *big.Int, wrID *big.Int) (*types.Transaction, error) {\n\treturn _SfcContract.Contract.Withdraw(&_SfcContract.TransactOpts, toValidatorID, wrID)\n}",
"func (_IWETH *IWETHTransactorSession) Withdraw(arg0 *big.Int) (*types.Transaction, error) {\r\n\treturn _IWETH.Contract.Withdraw(&_IWETH.TransactOpts, arg0)\r\n}",
"func (_BREMICO *BREMICOTransactor) Withdraw(opts *bind.TransactOpts, _value *big.Int) (*types.Transaction, error) {\n\treturn _BREMICO.contract.Transact(opts, \"withdraw\", _value)\n}",
"func (_IWETH *IWETHTransactorSession) Withdraw(arg0 *big.Int) (*types.Transaction, error) {\n\treturn _IWETH.Contract.Withdraw(&_IWETH.TransactOpts, arg0)\n}",
"func (_IWETH *IWETHSession) Withdraw(arg0 *big.Int) (*types.Transaction, error) {\r\n\treturn _IWETH.Contract.Withdraw(&_IWETH.TransactOpts, arg0)\r\n}",
"func (c *Client) Withdraw(ctx context.Context, p *WithdrawRequestBody) (err error) {\n\t_, err = c.WithdrawEndpoint(ctx, p)\n\treturn\n}",
"func (_Contract *ContractTransactor) Withdraw(opts *bind.TransactOpts, value *big.Int) (*types.Transaction, error) {\n\treturn _Contract.contract.Transact(opts, \"withdraw\", value)\n}",
"func (_V1 *V1Transactor) Withdraw(opts *bind.TransactOpts, _token common.Address) (*types.Transaction, error) {\n\treturn _V1.contract.Transact(opts, \"withdraw\", _token)\n}",
"func (_SmartTgStats *SmartTgStatsTransactor) CEOWithdraw(opts *bind.TransactOpts, _to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _SmartTgStats.contract.Transact(opts, \"CEOWithdraw\", _to, _amount)\n}",
"func (_Lmc *LmcTransactor) Withdraw(opts *bind.TransactOpts, _tokenAmount *big.Int) (*types.Transaction, error) {\n\treturn _Lmc.contract.Transact(opts, \"withdraw\", _tokenAmount)\n}",
"func (k *Keeper) cancelAndWithdrawUpkeeps(ctx context.Context, registryInstance *keeperRegV1.KeeperRegistry) error {\n\tcount, err := registryInstance.GetUpkeepCount(&bind.CallOpts{Context: ctx})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get upkeeps count: %s\", err)\n\t}\n\n\tfor i := int64(0); i < count.Int64(); i++ {\n\t\tvar tx *ethtypes.Transaction\n\t\tif tx, err = registryInstance.CancelUpkeep(k.buildTxOpts(ctx), big.NewInt(i)); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to cancel upkeep %d: %s\", i, err)\n\t\t}\n\t\tk.waitTx(ctx, tx)\n\n\t\tif tx, err = registryInstance.WithdrawFunds(k.buildTxOpts(ctx), big.NewInt(i), k.fromAddr); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to withdraw upkeep %d: %s\", i, err)\n\t\t}\n\t\tk.waitTx(ctx, tx)\n\n\t\tlog.Println(\"Upkeep successfully canceled and refunded: \", i)\n\t}\n\n\tvar tx *ethtypes.Transaction\n\tif tx, err = registryInstance.RecoverFunds(k.buildTxOpts(ctx)); err != nil {\n\t\treturn fmt.Errorf(\"failed to recover funds: %s\", err)\n\t}\n\tk.waitTx(ctx, tx)\n\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
QueryDepositAddress returns the deposit address for a specified currency
|
func (h *HUOBI) QueryDepositAddress(ctx context.Context, cryptocurrency currency.Code) ([]DepositAddress, error) {
resp := struct {
DepositAddress []DepositAddress `json:"data"`
}{}
vals := url.Values{}
vals.Set("currency", cryptocurrency.Lower().String())
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiAccountDepositAddress, vals, nil, &resp, true)
if err != nil {
return nil, err
}
if len(resp.DepositAddress) == 0 {
return nil, errors.New("deposit address data isn't populated")
}
return resp.DepositAddress, nil
}
|
[
"func (b *NovaExchange) GetDepositAddress(currency string) (address string, err error) {\n\tr, err := b.client.do(\"POST\", \"private/getdepositaddress/\"+strings.ToUpper(currency)+\"/\", \"\", true)\n\tif err != nil {\n\t\treturn\n\t}\n\tvar response jsonResponse\n\tif err = json.Unmarshal(r, &response); err != nil {\n\t\treturn\n\t}\n\tif err = handleErr(response); err != nil {\n\t\treturn\n\t}\n\terr = json.Unmarshal(response.Result[\"address\"], &address)\n\treturn\n}",
"func (ds *SQLDepositStore) GetDepositAddress(pubkey *koblitz.PublicKey) (addr string, err error) {\n\t// ACID\n\tvar tx *sql.Tx\n\tif tx, err = ds.DBHandler.Begin(); err != nil {\n\t\terr = fmt.Errorf(\"Error when beginning transaction for GetDepositAddress: %s\", err)\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\terr = fmt.Errorf(\"Error for GetDepositAddress: \\n%s\", err)\n\t\t\treturn\n\t\t}\n\t\terr = tx.Commit()\n\t}()\n\n\t// First use the deposit address schema\n\tif _, err = tx.Exec(\"USE \" + ds.depositAddrSchemaName + \";\"); err != nil {\n\t\terr = fmt.Errorf(\"Error using puzzle schema for GetDepositAddress: %s\", err)\n\t\treturn\n\t}\n\n\tvar row *sql.Row\n\tselectAddrQuery := fmt.Sprintf(\"SELECT address FROM %s WHERE pubkey='%s';\", ds.coin.Name, pubkey.SerializeCompressed())\n\t// errors deferred to scan\n\trow = tx.QueryRow(selectAddrQuery)\n\n\tif err = row.Scan(&addr); err != nil {\n\t\terr = fmt.Errorf(\"Error scanning for address for GetDepositAddress: %s\", err)\n\t\treturn\n\t}\n\n\treturn\n}",
"func (e Exchange) DepositAddress(exch string, currencyCode currency.Code) (out string, err error) {\n\tif currencyCode.IsEmpty() {\n\t\terr = errors.New(\"currency code is empty\")\n\t\treturn\n\t}\n\treturn engine.Bot.DepositAddressManager.GetDepositAddressByExchange(exch, currencyCode)\n}",
"func (k *Kraken) GetDepositAddress(cryptocurrency currency.Code, _ string) (string, error) {\n\tmethods, err := k.GetDepositMethods(cryptocurrency.String())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar method string\n\tfor _, m := range methods {\n\t\tmethod = m.Method\n\t}\n\n\tif method == \"\" {\n\t\treturn \"\", errors.New(\"method not found\")\n\t}\n\n\treturn k.GetCryptoDepositAddress(method, cryptocurrency.String())\n}",
"func GetDepositAddress(coin string) (address string, error error) {\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/getdepositaddress?coin=\"+coin, nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"TauDepositAddress-> %v\", err)\n\t}\n\tvar d struct {\n\t\tCoin string `json:\"coin\"`\n\t\tAddress string `json:\"address\"`\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn \"\", fmt.Errorf(\"TauDepositAddress-> %v\", err)\n\t}\n\treturn d.Address, nil\n}",
"func (t *TauAPI) GetDepositAddress(coin string) (address string, error error) {\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 1,\n\t\tMethod: \"GET\",\n\t\tPath: \"data/getdepositaddress?coin=\" + coin,\n\t\tNeedsAuth: true,\n\t})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"TauDepositAddress-> %v\", err)\n\t}\n\tvar d struct {\n\t\tCoin string `json:\"coin\"`\n\t\tAddress string `json:\"address\"`\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn \"\", fmt.Errorf(\"TauDepositAddress-> %v\", err)\n\t}\n\treturn d.Address, nil\n}",
"func (y *Yobit) GetDepositAddress(ctx context.Context, cryptocurrency currency.Code, _, _ string) (*deposit.Address, error) {\n\tif cryptocurrency == currency.XRP {\n\t\t// {\"success\":1,\"return\":{\"status\":\"online\",\"blocks\":65778672,\"address\":996707783,\"processed_amount\":0.00000000,\"server_time\":1629425030}}\n\t\treturn nil, errors.New(\"XRP isn't supported as the API does not return a valid address\")\n\t}\n\n\taddr, err := y.GetCryptoDepositAddress(ctx, cryptocurrency.String(), false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &deposit.Address{Address: addr.Return.Address}, nil\n}",
"func (b *Binance) GetDepositAddressForCurrency(currency string) (string, error) {\n\tpath := fmt.Sprintf(\"%s%s\", b.APIUrl, depositAddress)\n\n\tresp := struct {\n\t\tAddress string `json:\"address\"`\n\t\tSuccess bool `json:\"success\"`\n\t\tAddressTag string `json:\"addressTag\"`\n\t}{}\n\n\tparams := url.Values{}\n\tparams.Set(\"asset\", currency)\n\tparams.Set(\"status\", \"true\")\n\n\treturn resp.Address,\n\t\tb.SendAuthHTTPRequest(http.MethodGet, path, params, &resp)\n}",
"func (w *ServerInterfaceWrapper) GetDepositAddress(ctx echo.Context) error {\n\tvar err error\n\t// ------------- Path parameter \"currency\" -------------\n\tvar currency CurrencyParam\n\n\terr = runtime.BindStyledParameterWithLocation(\"simple\", false, \"currency\", runtime.ParamLocationPath, ctx.Param(\"currency\"), ¤cy)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter currency: %s\", err))\n\t}\n\n\tctx.Set(ApiKeyAuthScopes, []string{\"\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetDepositAddress(ctx, currency)\n\treturn err\n}",
"func (f *FTX) FetchDepositAddress(ctx context.Context, coin currency.Code, chain string) (*DepositData, error) {\n\tresp := struct {\n\t\tData DepositData `json:\"result\"`\n\t}{}\n\tvals := url.Values{}\n\tif chain != \"\" {\n\t\tvals.Set(\"method\", strings.ToLower(chain))\n\t}\n\tpath := common.EncodeURLValues(getDepositAddress+coin.Upper().String(), vals)\n\treturn &resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, path, nil, &resp)\n}",
"func (dcr *ExchangeWallet) DepositAddress() (string, error) {\n\taddr, err := dcr.wallet.ExternalAddress(dcr.ctx, dcr.depositAccount())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn addr.String(), nil\n}",
"func (g *Gemini) GetExchangeDepositAddress(p pair.CurrencyPair) (string, error) {\n\treturn \"\", errors.New(\"not yet implemented\")\n}",
"func (ds *SQLDepositStore) GetDepositAddressMap() (depAddrMap map[string]*koblitz.PublicKey, err error) {\n\tdepAddrMap = make(map[string]*koblitz.PublicKey)\n\t// ACID\n\tvar tx *sql.Tx\n\tif tx, err = ds.DBHandler.Begin(); err != nil {\n\t\terr = fmt.Errorf(\"Error when beginning transaction for GetDepositAddressMap: %s\", err)\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\terr = fmt.Errorf(\"Error for GetDepositAddressMap: \\n%s\", err)\n\t\t\treturn\n\t\t}\n\t\terr = tx.Commit()\n\t}()\n\n\t// First use the deposit address schema\n\tif _, err = tx.Exec(\"USE \" + ds.depositAddrSchemaName + \";\"); err != nil {\n\t\terr = fmt.Errorf(\"Error using puzzle schema for GetDepositAddressMap: %s\", err)\n\t\treturn\n\t}\n\n\tvar rows *sql.Rows\n\tselectAddrQuery := fmt.Sprintf(\"SELECT pubkey, address FROM %s;\", ds.coin.Name)\n\t// errors deferred to scan\n\tif rows, err = tx.Query(selectAddrQuery); err != nil {\n\t\terr = fmt.Errorf(\"Error querying for pubkey address map for GetDepositAddressMap: %s\", err)\n\t\treturn\n\t}\n\n\tvar currAddr string\n\tvar currPubkeyBytes []byte\n\tfor rows.Next() {\n\t\tif err = rows.Scan(&currPubkeyBytes, &currAddr); err != nil {\n\t\t\terr = fmt.Errorf(\"Error scanning for address for GetDepositAddressMap: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\t// frustrating sql marshalling\n\t\tif currPubkeyBytes, err = hex.DecodeString(string(currPubkeyBytes)); err != nil {\n\t\t\terr = fmt.Errorf(\"Error decoding pubkey for GetDepositAddressMap: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif depAddrMap[currAddr], err = koblitz.ParsePubKey(currPubkeyBytes, koblitz.S256()); err != nil {\n\t\t\terr = fmt.Errorf(\"Error parsing pub key from bytes for GetDepositAddressMap: %s\", err)\n\t\t\treturn\n\t\t}\n\t}\n\tif err = rows.Close(); err != nil {\n\t\terr = fmt.Errorf(\"Error closing rows for GetDepositAddressMap: %s\", err)\n\t\treturn\n\t}\n\treturn\n}",
"func ExampleAddDepositAddress() {}",
"func NewGetDepositAddressRequest(server string, currency CurrencyParam) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParamWithLocation(\"simple\", false, \"currency\", runtime.ParamLocationPath, currency)\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(\"/deposits/%s\", pathParam0)\n\tif operationPath[0] == '/' {\n\t\toperationPath = operationPath[1:]\n\t}\n\toperationURL := url.URL{\n\t\tPath: operationPath,\n\t}\n\n\tqueryURL := serverURL.ResolveReference(&operationURL)\n\n\treq, err := http.NewRequest(\"POST\", queryURL.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}",
"func (c *ClientWithResponses) GetDepositAddressWithResponse(ctx context.Context, currency CurrencyParam, reqEditors ...RequestEditorFn) (*GetDepositAddressResponse, error) {\n\trsp, err := c.GetDepositAddress(ctx, currency, reqEditors...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseGetDepositAddressResponse(rsp)\n}",
"func (as *ApiService) DepositAddresses(currency string) (*ApiResponse, error) {\n\treq := NewRequest(http.MethodGet, \"/api/v1/deposit-addresses\", map[string]string{\"currency\": currency})\n\treturn as.Call(req)\n}",
"func (e Endpoints) QueryBalance(ctx context.Context, symbol string, address string) (balance string, err error) {\n\trequest := QueryBalanceRequest{\n\t\tAddress: address,\n\t\tSymbol: symbol,\n\t}\n\tresponse, err := e.QueryBalanceEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn response.(QueryBalanceResponse).Balance, nil\n}",
"func (as *ApiService) CreateDepositAddress(currency string) (*ApiResponse, error) {\n\treq := NewRequest(http.MethodPost, \"/api/v1/deposit-addresses\", map[string]string{\"currency\": currency})\n\treturn as.Call(req)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
QueryWithdrawQuotas returns the users cryptocurrency withdraw quotas
|
func (h *HUOBI) QueryWithdrawQuotas(ctx context.Context, cryptocurrency string) (WithdrawQuota, error) {
resp := struct {
WithdrawQuota WithdrawQuota `json:"data"`
}{}
vals := url.Values{}
vals.Set("currency", cryptocurrency)
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiAccountWithdrawQuota, vals, nil, &resp, true)
if err != nil {
return WithdrawQuota{}, err
}
return resp.WithdrawQuota, nil
}
|
[
"func QueryWithdraws(rpcAddr string) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\trequest := common.GetInterxRequest(r)\n\t\tresponse := common.GetResponseFormat(request, rpcAddr)\n\t\tstatusCode := http.StatusOK\n\n\t\tcommon.GetLogger().Info(\"[query-withdraws] Entering withdraws query\")\n\n\t\tif !common.RPCMethods[\"GET\"][config.QueryWithdraws].Enabled {\n\t\t\tresponse.Response, response.Error, statusCode = common.ServeError(0, \"\", \"API disabled\", http.StatusForbidden)\n\t\t} else {\n\t\t\tif common.RPCMethods[\"GET\"][config.QueryWithdraws].CachingEnabled {\n\t\t\t\tfound, cacheResponse, cacheError, cacheStatus := common.SearchCache(request, response)\n\t\t\t\tif found {\n\t\t\t\t\tresponse.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus\n\t\t\t\t\tcommon.WrapResponse(w, request, *response, statusCode, false)\n\n\t\t\t\t\tcommon.GetLogger().Info(\"[query-withdraws] Returning from the cache\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse.Response, response.Error, statusCode = QueryBlockTransactionsHandler(rpcAddr, r, true)\n\t\t}\n\n\t\tcommon.WrapResponse(w, request, *response, statusCode, common.RPCMethods[\"GET\"][config.QueryStatus].CachingEnabled)\n\t}\n}",
"func (m *DataManager) getWithdraws(fromNonce *big.Int, toNonce *big.Int, offset uint64) []*Withdraw {\n\trows, err := m.db.Query(`\n\tSELECT user_address, \n\t currency,\n amount\n\tFROM t_withdraw\n\tWHERE status IN ( \"onchainsettled\", \"onchainconfirmed\" ) \n\t\tAND tx_nonce BETWEEN ? AND ? \n\t\tAND create_time > ?\n\tORDER BY id\n\tLIMIT ?, ? `, fromNonce.Int64(), toNonce.Int64(), m.dexStartTime, offset, maxRecordsPerQuery)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer rows.Close()\n\n\twithdraws := []*Withdraw{}\n\tfor rows.Next() {\n\t\twithdraw := Withdraw{}\n\t\tif err := rows.Scan(&withdraw.userAddress,\n\t\t\t&withdraw.currency,\n\t\t\t&withdraw.amount); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\twithdraws = append(withdraws, &withdraw)\n\t}\n\treturn withdraws\n}",
"func GetWithdraws(queryRoute string, cdc *codec.Codec) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"withdraws\",\n\t\tShort: \"Get withdraw list by page and limit\",\n\t\tExample: \"withdraws --page=1 --limit=10\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcliCtx := context.NewCLIContext().WithCodec(cdc)\n\n\t\t\t// parse inputs\n\t\t\tpage, limit, err := helpers.ParsePaginationParams(viper.GetString(flags.FlagPage), viper.GetString(flags.FlagLimit), helpers.ParamTypeCliFlag)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// prepare request\n\t\t\treq := types.WithdrawsReq{\n\t\t\t\tPage: page,\n\t\t\t\tLimit: limit,\n\t\t\t}\n\n\t\t\tbz, err := cliCtx.Codec.MarshalJSON(req)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// query and parse the result\n\t\t\tres, _, err := cliCtx.QueryWithData(fmt.Sprintf(\"custom/%s/%s\", queryRoute, types.QueryWithdraws), bz)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tvar out types.Withdraws\n\t\t\tcdc.MustUnmarshalJSON(res, &out)\n\n\t\t\treturn cliCtx.PrintOutput(out)\n\t\t},\n\t}\n\thelpers.AddPaginationCmdFlags(cmd)\n\n\treturn cmd\n}",
"func (s *Service) GetWithdraw(c context.Context, dateVersion string, from, limit int) (count int, withdrawVos []*model.WithdrawVo, err error) {\n\tcount, upAccounts, err := s.UpWithdraw(c, dateVersion, from, limit)\n\tif err != nil {\n\t\tlog.Error(\"s.UpWithdraw error(%v)\", err)\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\twithdrawVos = make([]*model.WithdrawVo, 0)\n\tif len(mids) == 0 {\n\t\treturn\n\t}\n\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 upIncomeWithdraw, ok := upIncomeWithdrawMap[up.MID]; ok && upIncomeWithdraw.State == _withdrawing {\n\t\t\tvo := &model.WithdrawVo{\n\t\t\t\tMID: up.MID,\n\t\t\t\tThirdCoin: float64(up.TotalUnwithdrawIncome) * float64(0.01),\n\t\t\t\tThirdOrderNo: strconv.FormatInt(upIncomeWithdraw.ID, 10),\n\t\t\t\tCTime: time.Unix(int64(upIncomeWithdraw.CTime), 0).Format(\"2006-01-02 15:04:05\"),\n\t\t\t\tNotifyURL: \"http://up-profit.bilibili.co/allowance/api/x/internal/growup/up/withdraw/success\",\n\t\t\t}\n\n\t\t\twithdrawVos = append(withdrawVos, vo)\n\t\t}\n\t}\n\n\treturn\n}",
"func (_IWETH *IWETHSession) Withdraw(arg0 *big.Int) (*types.Transaction, error) {\r\n\treturn _IWETH.Contract.Withdraw(&_IWETH.TransactOpts, arg0)\r\n}",
"func (_IWETH *IWETHTransactorSession) Withdraw(arg0 *big.Int) (*types.Transaction, error) {\r\n\treturn _IWETH.Contract.Withdraw(&_IWETH.TransactOpts, arg0)\r\n}",
"func (_IWETH *IWETHTransactorSession) Withdraw(arg0 *big.Int) (*types.Transaction, error) {\n\treturn _IWETH.Contract.Withdraw(&_IWETH.TransactOpts, arg0)\n}",
"func (_Vault *VaultTransactor) RequestWithdraw(opts *bind.TransactOpts, incognitoAddress string, token common.Address, amount *big.Int, signData []byte, timestamp []byte) (*types.Transaction, error) {\n\treturn _Vault.contract.Transact(opts, \"requestWithdraw\", incognitoAddress, token, amount, signData, timestamp)\n}",
"func withdraw(ctx iscp.Sandbox) (dict.Dict, error) {\n\tstate := ctx.State()\n\tmustCheckLedger(state, \"accounts.withdraw.begin\")\n\n\tif ctx.Caller().Address().Equals(ctx.ChainID().AsAddress()) {\n\t\t// if the caller is on the same chain, do nothing\n\t\treturn nil, nil\n\t}\n\ttokensToWithdraw, ok := GetAccountBalances(state, ctx.Caller())\n\tif !ok {\n\t\t// empty balance, nothing to withdraw\n\t\treturn nil, nil\n\t}\n\t// will be sending back to default entry point\n\ta := assert.NewAssert(ctx.Log())\n\t// bring balances to the current account (owner's account). It is needed for subsequent Send call\n\ta.Require(MoveBetweenAccounts(state, ctx.Caller(), commonaccount.Get(ctx.ChainID()), tokensToWithdraw),\n\t\t\"accounts.withdraw.inconsistency. failed to move tokens to owner's account\")\n\n\t// add incoming tokens (after fees) to the balances to be withdrawn. Otherwise they would end up in the common account\n\ttokensToWithdraw.AddAll(ctx.IncomingTransfer())\n\t// Send call assumes tokens are in the current account\n\ta.Require(ctx.Send(ctx.Caller().Address(), tokensToWithdraw, &iscp.SendMetadata{\n\t\tTargetContract: ctx.Caller().Hname(),\n\t}), \"accounts.withdraw.inconsistency: failed sending tokens \")\n\n\tctx.Log().Debugf(\"accounts.withdraw.success. Sent to address %s\", tokensToWithdraw.String())\n\n\tmustCheckLedger(state, \"accounts.withdraw.exit\")\n\treturn nil, nil\n}",
"func (_BREMICO *BREMICOTransactor) Withdraw(opts *bind.TransactOpts, _value *big.Int) (*types.Transaction, error) {\n\treturn _BREMICO.contract.Transact(opts, \"withdraw\", _value)\n}",
"func Withdraw(acntnum int, withdrawal float64, balance float64) {\n\tdb := opendb.OpenDB()\n\tdefer db.Close()\n\tfor withdrawal > balance {\n\t\tfmt.Printf(\"Not enough money in balance please enter another amount: \")\n\t\tfmt.Scanln(&withdrawal)\n\t}\n\tdb.Exec(\"UPDATE accounts SET balance = $1 WHERE acntnumber = $2\", balance-withdrawal, acntnum)\n\tfmt.Println(\"Withdraw Successful!\")\n}",
"func (_Wmatic *WmaticSession) Withdraw(wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.Contract.Withdraw(&_Wmatic.TransactOpts, wad)\n}",
"func (_Contract *ContractTransactor) Withdraw(opts *bind.TransactOpts, value *big.Int) (*types.Transaction, error) {\n\treturn _Contract.contract.Transact(opts, \"withdraw\", value)\n}",
"func (_StakingPortBacker *StakingPortBackerFilterer) FilterTokensWithdrawn(opts *bind.FilterOpts) (*StakingPortBackerTokensWithdrawnIterator, error) {\n\n\tlogs, sub, err := _StakingPortBacker.contract.FilterLogs(opts, \"TokensWithdrawn\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &StakingPortBackerTokensWithdrawnIterator{contract: _StakingPortBacker.contract, event: \"TokensWithdrawn\", logs: logs, sub: sub}, nil\n}",
"func (_BREMICO *BREMICOTransactorSession) ConfirmWithdraw() (*types.Transaction, error) {\n\treturn _BREMICO.Contract.ConfirmWithdraw(&_BREMICO.TransactOpts)\n}",
"func (_Vault *VaultSession) RequestWithdraw(incognitoAddress string, token common.Address, amount *big.Int, signData []byte, timestamp []byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.RequestWithdraw(&_Vault.TransactOpts, incognitoAddress, token, amount, signData, timestamp)\n}",
"func (_TokenStakingEscrow *TokenStakingEscrowTransactor) Withdraw(opts *bind.TransactOpts, operator common.Address) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.contract.Transact(opts, \"withdraw\", operator)\n}",
"func (_TokenStakingEscrow *TokenStakingEscrowFilterer) FilterDepositWithdrawn(opts *bind.FilterOpts, operator []common.Address, grantee []common.Address) (*TokenStakingEscrowDepositWithdrawnIterator, error) {\n\n\tvar operatorRule []interface{}\n\tfor _, operatorItem := range operator {\n\t\toperatorRule = append(operatorRule, operatorItem)\n\t}\n\tvar granteeRule []interface{}\n\tfor _, granteeItem := range grantee {\n\t\tgranteeRule = append(granteeRule, granteeItem)\n\t}\n\n\tlogs, sub, err := _TokenStakingEscrow.contract.FilterLogs(opts, \"DepositWithdrawn\", operatorRule, granteeRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokenStakingEscrowDepositWithdrawnIterator{contract: _TokenStakingEscrow.contract, event: \"DepositWithdrawn\", logs: logs, sub: sub}, nil\n}",
"func (_SfcContract *SfcContractSession) Withdraw(toValidatorID *big.Int, wrID *big.Int) (*types.Transaction, error) {\n\treturn _SfcContract.Contract.Withdraw(&_SfcContract.TransactOpts, toValidatorID, wrID)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SearchForExistedWithdrawsAndDeposits returns withdrawal and deposit data
|
func (h *HUOBI) SearchForExistedWithdrawsAndDeposits(ctx context.Context, c currency.Code, transferType, direction string, fromID, limit int64) (WithdrawalHistory, error) {
var resp WithdrawalHistory
vals := url.Values{}
vals.Set("type", transferType)
if !c.IsEmpty() {
vals.Set("currency", c.Lower().String())
}
if direction != "" {
vals.Set("direction", direction)
}
if fromID > 0 {
vals.Set("from", strconv.FormatInt(fromID, 10))
}
if limit > 0 {
vals.Set("size", strconv.FormatInt(limit, 10))
}
return resp, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiWithdrawHistory, vals, nil, &resp, false)
}
|
[
"func (m *DataManager) getWithdraws(fromNonce *big.Int, toNonce *big.Int, offset uint64) []*Withdraw {\n\trows, err := m.db.Query(`\n\tSELECT user_address, \n\t currency,\n amount\n\tFROM t_withdraw\n\tWHERE status IN ( \"onchainsettled\", \"onchainconfirmed\" ) \n\t\tAND tx_nonce BETWEEN ? AND ? \n\t\tAND create_time > ?\n\tORDER BY id\n\tLIMIT ?, ? `, fromNonce.Int64(), toNonce.Int64(), m.dexStartTime, offset, maxRecordsPerQuery)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer rows.Close()\n\n\twithdraws := []*Withdraw{}\n\tfor rows.Next() {\n\t\twithdraw := Withdraw{}\n\t\tif err := rows.Scan(&withdraw.userAddress,\n\t\t\t&withdraw.currency,\n\t\t\t&withdraw.amount); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\twithdraws = append(withdraws, &withdraw)\n\t}\n\treturn withdraws\n}",
"func (s *Service) GetWithdraw(c context.Context, dateVersion string, from, limit int) (count int, withdrawVos []*model.WithdrawVo, err error) {\n\tcount, upAccounts, err := s.UpWithdraw(c, dateVersion, from, limit)\n\tif err != nil {\n\t\tlog.Error(\"s.UpWithdraw error(%v)\", err)\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\twithdrawVos = make([]*model.WithdrawVo, 0)\n\tif len(mids) == 0 {\n\t\treturn\n\t}\n\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 upIncomeWithdraw, ok := upIncomeWithdrawMap[up.MID]; ok && upIncomeWithdraw.State == _withdrawing {\n\t\t\tvo := &model.WithdrawVo{\n\t\t\t\tMID: up.MID,\n\t\t\t\tThirdCoin: float64(up.TotalUnwithdrawIncome) * float64(0.01),\n\t\t\t\tThirdOrderNo: strconv.FormatInt(upIncomeWithdraw.ID, 10),\n\t\t\t\tCTime: time.Unix(int64(upIncomeWithdraw.CTime), 0).Format(\"2006-01-02 15:04:05\"),\n\t\t\t\tNotifyURL: \"http://up-profit.bilibili.co/allowance/api/x/internal/growup/up/withdraw/success\",\n\t\t\t}\n\n\t\t\twithdrawVos = append(withdrawVos, vo)\n\t\t}\n\t}\n\n\treturn\n}",
"func (_TokenStakingEscrow *TokenStakingEscrowFilterer) FilterDepositWithdrawn(opts *bind.FilterOpts, operator []common.Address, grantee []common.Address) (*TokenStakingEscrowDepositWithdrawnIterator, error) {\n\n\tvar operatorRule []interface{}\n\tfor _, operatorItem := range operator {\n\t\toperatorRule = append(operatorRule, operatorItem)\n\t}\n\tvar granteeRule []interface{}\n\tfor _, granteeItem := range grantee {\n\t\tgranteeRule = append(granteeRule, granteeItem)\n\t}\n\n\tlogs, sub, err := _TokenStakingEscrow.contract.FilterLogs(opts, \"DepositWithdrawn\", operatorRule, granteeRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokenStakingEscrowDepositWithdrawnIterator{contract: _TokenStakingEscrow.contract, event: \"DepositWithdrawn\", logs: logs, sub: sub}, nil\n}",
"func (p *Poloniex) GetDepositsWithdrawals(ctx context.Context, start, end string) (DepositsWithdrawals, error) {\n\tresp := DepositsWithdrawals{}\n\tvalues := url.Values{}\n\n\tif start != \"\" {\n\t\tvalues.Set(\"start\", start)\n\t} else {\n\t\tvalues.Set(\"start\", \"0\")\n\t}\n\n\tif end != \"\" {\n\t\tvalues.Set(\"end\", end)\n\t} else {\n\t\tvalues.Set(\"end\", strconv.FormatInt(time.Now().Unix(), 10))\n\t}\n\n\treturn resp, p.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, poloniexDepositsWithdrawals, values, &resp)\n}",
"func (s *Store) getDepositInfo(Txid string) (DepositInfo, error) {\n\tvar di DepositInfo\n\n\terr := s.db.View(func(tx *bolt.Tx) error {\n\t\tvar err error\n\t\tdi, err = s.getDepositInfoTx(tx, Txid)\n\t\treturn err\n\t})\n\n\treturn di, err\n}",
"func (s *Store) GetOrCreateDepositInfo(dv scanner.Deposit) (DepositInfo, error) {\n\tlog := s.log.WithField(\"deposit\", dv)\n\n\tvar finalDepositInfo DepositInfo\n\tif err := s.db.Update(func(tx *bolt.Tx) error {\n\t\tdi, err := s.getDepositInfoTx(tx, dv.ID())\n\t\tswitch err.(type) {\n\t\tcase nil:\n\t\t\tfinalDepositInfo = di\n\t\t\treturn nil\n\n\t\tcase dbutil.ObjectNotExistErr:\n\t\t\tlog.Info(\"DepositInfo not found in DB, inserting\")\n\t\t\tboundAddr, err := s.getBindAddressTx(tx, dv.Address, dv.CoinType)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"GetBindAddress failed: %v\", err)\n\t\t\t\tlog.WithError(err).Error(err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif boundAddr == nil {\n\t\t\t\terr = ErrNoBoundAddress\n\t\t\t\tlog.WithError(err).Error(err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = s.createDepositTrackTx(tx, boundAddr)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"CreateDepositTrack failed: %v\", err)\n\t\t\t\tlog.WithError(err).Error(err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlog = log.WithField(\"boundAddr\", boundAddr)\n\n\t\t\t// Integrity check of the boundAddr data against the deposit value data\n\t\t\tif boundAddr.CoinType != dv.CoinType {\n\t\t\t\terr := fmt.Errorf(\"boundAddr.CoinType != dv.CoinType\")\n\t\t\t\tlog.WithError(err).Error()\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t//TODO (therealssj): add owner address?\n\t\t\tdi := DepositInfo{\n\t\t\t\tCoinType: dv.CoinType,\n\t\t\t\tDepositAddress: dv.Address,\n\t\t\t\tKittyID: boundAddr.KittyID,\n\t\t\t\tDepositID: dv.ID(),\n\t\t\t\tStatus: StatusWaitDecide,\n\t\t\t\tDepositValue: dv.Value,\n\t\t\t\tDeposit: dv,\n\t\t\t}\n\n\t\t\tlog = log.WithField(\"depositInfo\", di)\n\n\t\t\tupdatedDi, err := s.addDepositInfoTx(tx, di)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"addDepositInfoTx failed: %v\", err)\n\t\t\t\tlog.WithError(err).Error(err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfinalDepositInfo = updatedDi\n\n\t\t\treturn nil\n\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"getDepositInfo failed: %v\", err)\n\t\t\tlog.WithError(err).Error(err)\n\t\t\treturn err\n\t\t}\n\t}); err != nil {\n\t\treturn DepositInfo{}, err\n\t}\n\n\treturn finalDepositInfo, nil\n\n}",
"func AllDeposit() []Deposit {\n\torm := get_DBFront()\n\tvar depo []Deposit\n\terr := orm.SetTable(\"deposit\").FindAll(&depo)\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_671\", err})\n\t}\n\tSliceReverse(depo)\n\treturn depo\n}",
"func (p *TDepositWithdrawServiceClient) AuditDepositWithdraw(ctx context.Context, traceId string, status string, mark string, withdrawId int32) (r bool, err error) {\n var _args5 TDepositWithdrawServiceAuditDepositWithdrawArgs\n _args5.TraceId = traceId\n _args5.Status = status\n _args5.Mark = mark\n _args5.WithdrawId = withdrawId\n var _result6 TDepositWithdrawServiceAuditDepositWithdrawResult\n if err = p.c.Call(ctx, \"auditDepositWithdraw\", &_args5, &_result6); err != nil {\n return\n }\n return _result6.GetSuccess(), nil\n}",
"func (_TokenStakingEscrow *TokenStakingEscrowFilterer) WatchDepositWithdrawn(opts *bind.WatchOpts, sink chan<- *TokenStakingEscrowDepositWithdrawn, operator []common.Address, grantee []common.Address) (event.Subscription, error) {\n\n\tvar operatorRule []interface{}\n\tfor _, operatorItem := range operator {\n\t\toperatorRule = append(operatorRule, operatorItem)\n\t}\n\tvar granteeRule []interface{}\n\tfor _, granteeItem := range grantee {\n\t\tgranteeRule = append(granteeRule, granteeItem)\n\t}\n\n\tlogs, sub, err := _TokenStakingEscrow.contract.WatchLogs(opts, \"DepositWithdrawn\", operatorRule, granteeRule)\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(TokenStakingEscrowDepositWithdrawn)\n\t\t\t\tif err := _TokenStakingEscrow.contract.UnpackLog(event, \"DepositWithdrawn\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}",
"func (k Keeper) GetDeposit(ctx sdk.Context, depositor sdk.AccAddress, denom string) (types.Deposit, bool) {\n\tstore := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix)\n\tbz := store.Get(types.DepositKey(denom, depositor))\n\tif bz == nil {\n\t\treturn types.Deposit{}, false\n\t}\n\tvar deposit types.Deposit\n\tk.cdc.MustUnmarshalBinaryBare(bz, &deposit)\n\treturn deposit, true\n}",
"func (s queryServer) Deposits(c context.Context, req *types.QueryDepositsRequest) (*types.QueryDepositsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tstore := prefix.NewStore(ctx.KVStore(s.keeper.key), types.DepositorPoolSharesPrefix)\n\n\trecords := types.ShareRecords{}\n\tpageRes, err := query.FilteredPaginate(\n\t\tstore,\n\t\treq.Pagination,\n\t\tfunc(key []byte, value []byte, accumulate bool) (bool, error) {\n\t\t\tvar record types.ShareRecord\n\t\t\terr := s.keeper.cdc.Unmarshal(value, &record)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\t// Filter for results match the request's pool ID/owner params if given\n\t\t\tmatchOwner, matchPool := true, true\n\t\t\tif len(req.Owner) > 0 {\n\t\t\t\tmatchOwner = record.Depositor.String() == req.Owner\n\t\t\t}\n\t\t\tif len(req.PoolId) > 0 {\n\t\t\t\tmatchPool = strings.Compare(record.PoolID, req.PoolId) == 0\n\t\t\t}\n\t\t\tif !(matchOwner && matchPool) {\n\t\t\t\t// inform paginate that there was no match on this key\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tif accumulate {\n\t\t\t\t// only add to results if paginate tells us to\n\t\t\t\trecords = append(records, record)\n\t\t\t}\n\t\t\t// inform paginate that were was a match on this key\n\t\t\treturn true, nil\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tvar queryResults []types.DepositResponse\n\tfor _, record := range records {\n\t\tpool, err := s.keeper.loadDenominatedPool(ctx, record.PoolID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tshareValue := pool.ShareValue(record.SharesOwned)\n\t\tqueryResult := types.DepositResponse{\n\t\t\tDepositor: record.Depositor.String(),\n\t\t\tPoolId: record.PoolID,\n\t\t\tSharesOwned: record.SharesOwned,\n\t\t\tSharesValue: shareValue,\n\t\t}\n\t\tqueryResults = append(queryResults, queryResult)\n\t}\n\n\treturn &types.QueryDepositsResponse{\n\t\tDeposits: queryResults,\n\t\tPagination: pageRes,\n\t}, nil\n}",
"func (_OracleMgr *OracleMgrSession) GetDepositAtIndex(index *big.Int) (struct {\n\tAmount *big.Int\n\tAvailableAt *big.Int\n}, error) {\n\treturn _OracleMgr.Contract.GetDepositAtIndex(&_OracleMgr.CallOpts, index)\n}",
"func QueryWithdraws(rpcAddr string) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\trequest := common.GetInterxRequest(r)\n\t\tresponse := common.GetResponseFormat(request, rpcAddr)\n\t\tstatusCode := http.StatusOK\n\n\t\tcommon.GetLogger().Info(\"[query-withdraws] Entering withdraws query\")\n\n\t\tif !common.RPCMethods[\"GET\"][config.QueryWithdraws].Enabled {\n\t\t\tresponse.Response, response.Error, statusCode = common.ServeError(0, \"\", \"API disabled\", http.StatusForbidden)\n\t\t} else {\n\t\t\tif common.RPCMethods[\"GET\"][config.QueryWithdraws].CachingEnabled {\n\t\t\t\tfound, cacheResponse, cacheError, cacheStatus := common.SearchCache(request, response)\n\t\t\t\tif found {\n\t\t\t\t\tresponse.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus\n\t\t\t\t\tcommon.WrapResponse(w, request, *response, statusCode, false)\n\n\t\t\t\t\tcommon.GetLogger().Info(\"[query-withdraws] Returning from the cache\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse.Response, response.Error, statusCode = QueryBlockTransactionsHandler(rpcAddr, r, true)\n\t\t}\n\n\t\tcommon.WrapResponse(w, request, *response, statusCode, common.RPCMethods[\"GET\"][config.QueryStatus].CachingEnabled)\n\t}\n}",
"func (keeper Keeper) GetDeposit(ctx sdk.Context, symbol string, address sdk.CUAddress, hash string, index uint64) sdk.DepositItem {\n\tstore := ctx.KVStore(keeper.key)\n\tbz := store.Get(types.DepositStoreKey(symbol, address, hash, index))\n\tif bz == nil {\n\t\treturn sdk.DepositNil\n\t}\n\tvar item sdk.DepositItem\n\tkeeper.cdc.MustUnmarshalBinaryBare(bz, &item)\n\n\treturn item\n}",
"func (ds DataStore) GetDeposit(ctx sdk.Context, nonce *big.Int) (Deposit, bool) {\n\tkey := GetDepositKey(nonce)\n\tdata := ds.Get(ctx, key)\n\tif data == nil {\n\t\treturn Deposit{}, false\n\t}\n\n\tvar deposit Deposit\n\tif err := rlp.DecodeBytes(data, &deposit); err != nil {\n\t\tpanic(fmt.Sprintf(\"deposit store corrupted: %s\", err))\n\t}\n\n\treturn deposit, true\n}",
"func (_OracleMgr *OracleMgrCallerSession) GetDepositAtIndex(index *big.Int) (struct {\n\tAmount *big.Int\n\tAvailableAt *big.Int\n}, error) {\n\treturn _OracleMgr.Contract.GetDepositAtIndex(&_OracleMgr.CallOpts, index)\n}",
"func (s *Store) GetDepositStats() (int64, int64, int64, error) {\n\tvar totalBTCReceived int64\n\tvar totalSKYReceived int64\n\tvar totalBoxesSent int64\n\n\tif err := s.db.View(func(tx *bolt.Tx) error {\n\t\treturn dbutil.ForEach(tx, DepositInfoBkt, func(k, v []byte) error {\n\t\t\tvar dpi DepositInfo\n\t\t\tif err := json.Unmarshal(v, &dpi); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif dpi.CoinType == scanner.CoinTypeBTC {\n\t\t\t\ttotalBTCReceived += dpi.DepositValue\n\t\t\t}\n\n\t\t\tif dpi.CoinType == scanner.CoinTypeSKY {\n\t\t\t\ttotalSKYReceived += dpi.DepositValue\n\t\t\t}\n\n\t\t\t// TotalBoxesSent = no. of deposits with status == done\n\t\t\tif dpi.Status == StatusDone {\n\t\t\t\ttotalBoxesSent++\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}); err != nil {\n\t\treturn -1, -1, -1, err\n\t}\n\n\treturn totalBTCReceived, totalSKYReceived, totalBoxesSent, nil\n}",
"func (w Wrapper) WithdrawalFiatFunds(_ context.Context, _ string, r *withdraw.Request) (out string, err error) {\n\tif r.Exchange == exchError.String() {\n\t\treturn r.Exchange, errTestFailed\n\t}\n\n\treturn \"123\", nil\n}",
"func ReadDeposits(rows *sql.Rows, a *Deposit) error {\n\treturn rows.Scan(&a.DID, &a.BID, &a.DEPID, &a.DPMID, &a.Dt, &a.Amount, &a.ClearedAmount, &a.FLAGS, &a.CreateTS, &a.CreateBy, &a.LastModTime, &a.LastModBy)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SendAuthenticatedHTTPRequest sends authenticated requests to the HUOBI API
|
func (h *HUOBI) SendAuthenticatedHTTPRequest(ctx context.Context, ep exchange.URL, method, endpoint string, values url.Values, data, result interface{}, isVersion2API bool) error {
var err error
creds, err := h.GetCredentials(ctx)
if err != nil {
return err
}
ePoint, err := h.API.Endpoints.GetURL(ep)
if err != nil {
return err
}
if values == nil {
values = url.Values{}
}
interim := json.RawMessage{}
newRequest := func() (*request.Item, error) {
values.Set("AccessKeyId", creds.Key)
values.Set("SignatureMethod", "HmacSHA256")
values.Set("SignatureVersion", "2")
values.Set("Timestamp", time.Now().UTC().Format("2006-01-02T15:04:05"))
if isVersion2API {
endpoint = "/v" + huobiAPIVersion2 + endpoint
} else {
endpoint = "/v" + huobiAPIVersion + endpoint
}
payload := fmt.Sprintf("%s\napi.huobi.pro\n%s\n%s",
method, endpoint, values.Encode())
headers := make(map[string]string)
if method == http.MethodGet {
headers["Content-Type"] = "application/x-www-form-urlencoded"
} else {
headers["Content-Type"] = "application/json"
}
var hmac []byte
hmac, err = crypto.GetHMAC(crypto.HashSHA256,
[]byte(payload),
[]byte(creds.Secret))
if err != nil {
return nil, err
}
values.Set("Signature", crypto.Base64Encode(hmac))
urlPath := ePoint + common.EncodeURLValues(endpoint, values)
var body []byte
if data != nil {
body, err = json.Marshal(data)
if err != nil {
return nil, err
}
}
return &request.Item{
Method: method,
Path: urlPath,
Headers: headers,
Body: bytes.NewReader(body),
Result: &interim,
Verbose: h.Verbose,
HTTPDebugging: h.HTTPDebugging,
HTTPRecording: h.HTTPRecording,
}, nil
}
err = h.SendPayload(ctx, request.Unset, newRequest, request.AuthenticatedRequest)
if err != nil {
return err
}
if isVersion2API {
var errCap ResponseV2
if err = json.Unmarshal(interim, &errCap); err == nil {
if errCap.Code != 200 && errCap.Message != "" {
return fmt.Errorf("%w error code: %v error message: %s", request.ErrAuthRequestFailed, errCap.Code, errCap.Message)
}
}
} else {
var errCap Response
if err = json.Unmarshal(interim, &errCap); err == nil {
if errCap.Status == huobiStatusError && errCap.ErrorMessage != "" {
return fmt.Errorf("%w error code: %v error message: %s", request.ErrAuthRequestFailed, errCap.ErrorCode, errCap.ErrorMessage)
}
}
}
err = json.Unmarshal(interim, result)
if err != nil {
return common.AppendError(err, request.ErrAuthRequestFailed)
}
return nil
}
|
[
"func (h *HUOBIHADAX) SendAuthenticatedHTTPRequest(method, endpoint string, values url.Values, result interface{}) error {\n\tif !h.AuthenticatedAPISupport {\n\t\treturn fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet, h.Name)\n\t}\n\n\tvalues.Set(\"AccessKeyId\", h.APIKey)\n\tvalues.Set(\"SignatureMethod\", \"HmacSHA256\")\n\tvalues.Set(\"SignatureVersion\", \"2\")\n\tvalues.Set(\"Timestamp\", time.Now().UTC().Format(\"2006-01-02T15:04:05\"))\n\n\tendpoint = fmt.Sprintf(\"/v%s/%s\", huobihadaxAPIVersion, endpoint)\n\tpayload := fmt.Sprintf(\"%s\\napi.hadax.com\\n%s\\n%s\",\n\t\tmethod, endpoint, values.Encode())\n\n\theaders := make(map[string]string)\n\theaders[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n\n\thmac := common.GetHMAC(common.HashSHA256, []byte(payload), []byte(h.APISecret))\n\tvalues.Set(\"Signature\", common.Base64Encode(hmac))\n\n\turlPath := common.EncodeURLValues(fmt.Sprintf(\"%s%s\", h.APIUrl, endpoint),\n\t\tvalues)\n\treturn h.SendPayload(method, urlPath, headers, bytes.NewBufferString(\"\"), result, true, false, h.Verbose, h.HTTPDebugging)\n}",
"func (h *HitBTC) SendAuthenticatedHTTPRequest(ctx context.Context, ep exchange.URL, method, endpoint string, values url.Values, f request.EndpointLimit, result interface{}) error {\n\tcreds, err := h.GetCredentials(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tePoint, err := h.API.Endpoints.GetURL(ep)\n\tif err != nil {\n\t\treturn err\n\t}\n\theaders := make(map[string]string)\n\theaders[\"Authorization\"] = \"Basic \" + crypto.Base64Encode([]byte(creds.Key+\":\"+creds.Secret))\n\n\tpath := fmt.Sprintf(\"%s/%s\", ePoint, endpoint)\n\n\titem := &request.Item{\n\t\tMethod: method,\n\t\tPath: path,\n\t\tHeaders: headers,\n\t\tResult: result,\n\t\tVerbose: h.Verbose,\n\t\tHTTPDebugging: h.HTTPDebugging,\n\t\tHTTPRecording: h.HTTPRecording,\n\t}\n\n\treturn h.SendPayload(ctx, f, func() (*request.Item, error) {\n\t\titem.Body = bytes.NewBufferString(values.Encode())\n\t\treturn item, nil\n\t}, request.AuthenticatedRequest)\n}",
"func (p *Poloniex) SendAuthenticatedHTTPRequest(ctx context.Context, ep exchange.URL, method, endpoint string, values url.Values, result interface{}) error {\n\tcreds, err := p.GetCredentials(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tePoint, err := p.API.Endpoints.GetURL(ep)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn p.SendPayload(ctx, request.Unset, func() (*request.Item, error) {\n\t\theaders := make(map[string]string)\n\t\theaders[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n\t\theaders[\"Key\"] = creds.Key\n\t\tvalues.Set(\"nonce\", p.Requester.GetNonce(true).String())\n\t\tvalues.Set(\"command\", endpoint)\n\n\t\thmac, err := crypto.GetHMAC(crypto.HashSHA512,\n\t\t\t[]byte(values.Encode()),\n\t\t\t[]byte(creds.Secret))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\theaders[\"Sign\"] = crypto.HexEncodeToString(hmac)\n\n\t\tpath := fmt.Sprintf(\"%s/%s\", ePoint, poloniexAPITradingEndpoint)\n\t\treturn &request.Item{\n\t\t\tMethod: method,\n\t\t\tPath: path,\n\t\t\tHeaders: headers,\n\t\t\tBody: bytes.NewBufferString(values.Encode()),\n\t\t\tResult: result,\n\t\t\tNonceEnabled: true,\n\t\t\tVerbose: p.Verbose,\n\t\t\tHTTPDebugging: p.HTTPDebugging,\n\t\t\tHTTPRecording: p.HTTPRecording,\n\t\t}, nil\n\t}, request.AuthenticatedRequest)\n}",
"func (c *Coinbene) SendAuthHTTPRequest(ep exchange.URL, method, path, epPath string, isSwap bool,\n\tparams, result interface{}, f request.EndpointLimit) error {\n\tif !c.AllowAuthenticatedRequest() {\n\t\treturn fmt.Errorf(\"%s %w\", c.Name, exchange.ErrAuthenticatedRequestWithoutCredentialsSet)\n\t}\n\tendpoint, err := c.API.Endpoints.GetURL(ep)\n\tif err != nil {\n\t\treturn err\n\t}\n\tauthPath := coinbeneAuthPath\n\tif isSwap {\n\t\tauthPath = coinbeneSwapAuthPath\n\t}\n\tnow := time.Now()\n\ttimestamp := now.UTC().Format(\"2006-01-02T15:04:05.999Z\")\n\tvar finalBody io.Reader\n\tvar preSign string\n\tswitch {\n\tcase params != nil && method == http.MethodGet:\n\t\tp, ok := params.(url.Values)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"params is not of type url.Values\")\n\t\t}\n\t\tpreSign = timestamp + method + authPath + epPath + \"?\" + p.Encode()\n\t\tpath = common.EncodeURLValues(path, p)\n\tcase params != nil:\n\t\tvar i interface{}\n\t\tswitch p := params.(type) {\n\t\tcase url.Values:\n\t\t\tm := make(map[string]string)\n\t\t\tfor k, v := range p {\n\t\t\t\tm[k] = strings.Join(v, \"\")\n\t\t\t}\n\t\t\ti = m\n\t\tdefault:\n\t\t\ti = p\n\t\t}\n\t\ttempBody, err := json.Marshal(i)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfinalBody = bytes.NewBufferString(string(tempBody))\n\t\tpreSign = timestamp + method + authPath + epPath + string(tempBody)\n\tdefault:\n\t\tpreSign = timestamp + method + authPath + epPath\n\t}\n\ttempSign := crypto.GetHMAC(crypto.HashSHA256,\n\t\t[]byte(preSign),\n\t\t[]byte(c.API.Credentials.Secret))\n\theaders := make(map[string]string)\n\theaders[\"Content-Type\"] = \"application/json\"\n\theaders[\"ACCESS-KEY\"] = c.API.Credentials.Key\n\theaders[\"ACCESS-SIGN\"] = crypto.HexEncodeToString(tempSign)\n\theaders[\"ACCESS-TIMESTAMP\"] = timestamp\n\n\tvar resp json.RawMessage\n\terrCap := struct {\n\t\tCode int `json:\"code\"`\n\t\tMessage string `json:\"message\"`\n\t}{}\n\n\t// Expiry of timestamp doesn't appear to be documented, so making a reasonable assumption\n\tctx, cancel := context.WithDeadline(context.Background(), now.Add(15*time.Second))\n\tdefer cancel()\n\tif err := c.SendPayload(ctx, &request.Item{\n\t\tMethod: method,\n\t\tPath: endpoint + path,\n\t\tHeaders: headers,\n\t\tBody: finalBody,\n\t\tResult: &resp,\n\t\tAuthRequest: true,\n\t\tVerbose: c.Verbose,\n\t\tHTTPDebugging: c.HTTPDebugging,\n\t\tHTTPRecording: c.HTTPRecording,\n\t\tEndpoint: f,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(resp, &errCap); err == nil {\n\t\tif errCap.Code != 200 && errCap.Message != \"\" {\n\t\t\treturn errors.New(errCap.Message)\n\t\t}\n\t}\n\treturn json.Unmarshal(resp, result)\n}",
"func (b *Binance) SendAuthHTTPRequest(method, path string, params url.Values, result interface{}) error {\n\tif !b.AuthenticatedAPISupport {\n\t\treturn fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet, b.Name)\n\t}\n\n\tif params == nil {\n\t\tparams = url.Values{}\n\t}\n\tparams.Set(\"recvWindow\", strconv.FormatInt(common.RecvWindow(5*time.Second), 10))\n\tparams.Set(\"timestamp\", strconv.FormatInt(time.Now().Unix()*1000, 10))\n\n\tsignature := params.Encode()\n\thmacSigned := common.GetHMAC(common.HashSHA256, []byte(signature), []byte(b.APISecret))\n\thmacSignedStr := common.HexEncodeToString(hmacSigned)\n\n\theaders := make(map[string]string)\n\theaders[\"X-MBX-APIKEY\"] = b.APIKey\n\n\tif b.Verbose {\n\t\tlog.Debugf(\"sent path: %s\", path)\n\t}\n\n\tpath = common.EncodeURLValues(path, params)\n\tpath += fmt.Sprintf(\"&signature=%s\", hmacSignedStr)\n\n\tinterim := json.RawMessage{}\n\n\terrCap := struct {\n\t\tSuccess bool `json:\"success\"`\n\t\tMessage string `json:\"msg\"`\n\t}{}\n\n\terr := b.SendPayload(method, path, headers, bytes.NewBuffer(nil), &interim, true, false, b.Verbose, b.HTTPDebugging)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := common.JSONDecode(interim, &errCap); err == nil {\n\t\tif !errCap.Success && errCap.Message != \"\" {\n\t\t\treturn errors.New(errCap.Message)\n\t\t}\n\t}\n\n\treturn common.JSONDecode(interim, result)\n}",
"func (f *FTX) SendAuthHTTPRequest(ctx context.Context, ep exchange.URL, method, path string, data, result interface{}) error {\n\tif !f.AllowAuthenticatedRequest() {\n\t\treturn fmt.Errorf(\"%s %w\", f.Name, exchange.ErrAuthenticatedRequestWithoutCredentialsSet)\n\t}\n\n\tendpoint, err := f.API.Endpoints.GetURL(ep)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewRequest := func() (*request.Item, error) {\n\t\tts := strconv.FormatInt(time.Now().UnixMilli(), 10)\n\t\tvar body io.Reader\n\t\tvar hmac, payload []byte\n\n\t\tsigPayload := ts + method + \"/api\" + path\n\t\tif data != nil {\n\t\t\tpayload, err = json.Marshal(data)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tbody = bytes.NewBuffer(payload)\n\t\t\tsigPayload += string(payload)\n\t\t}\n\n\t\thmac, err = crypto.GetHMAC(crypto.HashSHA256,\n\t\t\t[]byte(sigPayload),\n\t\t\t[]byte(f.API.Credentials.Secret))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\theaders := make(map[string]string)\n\t\theaders[\"FTX-KEY\"] = f.API.Credentials.Key\n\t\theaders[\"FTX-SIGN\"] = crypto.HexEncodeToString(hmac)\n\t\theaders[\"FTX-TS\"] = ts\n\t\tif f.API.Credentials.Subaccount != \"\" {\n\t\t\theaders[\"FTX-SUBACCOUNT\"] = url.QueryEscape(f.API.Credentials.Subaccount)\n\t\t}\n\t\theaders[\"Content-Type\"] = \"application/json\"\n\n\t\treturn &request.Item{\n\t\t\tMethod: method,\n\t\t\tPath: endpoint + path,\n\t\t\tHeaders: headers,\n\t\t\tBody: body,\n\t\t\tResult: result,\n\t\t\tAuthRequest: true,\n\t\t\tVerbose: f.Verbose,\n\t\t\tHTTPDebugging: f.HTTPDebugging,\n\t\t\tHTTPRecording: f.HTTPRecording,\n\t\t}, nil\n\t}\n\treturn f.SendPayload(ctx, request.Unset, newRequest)\n}",
"func (h *HUOBIHADAX) SendAuthenticatedHTTPPostRequest(method, endpoint, postBodyValues string, result interface{}) error {\n\tif !h.AuthenticatedAPISupport {\n\t\treturn fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet, h.Name)\n\t}\n\n\tsignatureParams := url.Values{}\n\tsignatureParams.Set(\"AccessKeyId\", h.APIKey)\n\tsignatureParams.Set(\"SignatureMethod\", \"HmacSHA256\")\n\tsignatureParams.Set(\"SignatureVersion\", \"2\")\n\tsignatureParams.Set(\"Timestamp\", time.Now().UTC().Format(\"2006-01-02T15:04:05\"))\n\n\tendpoint = fmt.Sprintf(\"/v%s/%s\", huobihadaxAPIVersion, endpoint)\n\tpayload := fmt.Sprintf(\"%s\\napi.hadax.com\\n%s\\n%s\",\n\t\tmethod, endpoint, signatureParams.Encode())\n\n\theaders := make(map[string]string)\n\theaders[\"Content-Type\"] = \"application/json\"\n\theaders[\"Accept-Language\"] = \"zh-cn\"\n\n\thmac := common.GetHMAC(common.HashSHA256, []byte(payload), []byte(h.APISecret))\n\tsignatureParams.Set(\"Signature\", common.Base64Encode(hmac))\n\turlPath := common.EncodeURLValues(fmt.Sprintf(\"%s%s\", h.APIUrl, endpoint),\n\t\tsignatureParams)\n\treturn h.SendPayload(method, urlPath, headers, bytes.NewBufferString(postBodyValues), result, true, false, h.Verbose, h.HTTPDebugging)\n}",
"func (by *Bybit) SendUSDCAuthHTTPRequest(ctx context.Context, ePath exchange.URL, method, path string, data interface{}, result UnmarshalTo, f request.EndpointLimit) error {\n\tcreds, err := by.GetCredentials(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif result == nil {\n\t\tresult = &USDCError{}\n\t}\n\n\tendpointPath, err := by.API.Endpoints.GetURL(ePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = by.SendPayload(ctx, f, func() (*request.Item, error) {\n\t\tnowTimeInMilli := strconv.FormatInt(time.Now().UnixMilli(), 10)\n\t\theaders := make(map[string]string)\n\t\tvar payload, hmacSigned []byte\n\n\t\tif data != nil {\n\t\t\td, ok := data.(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, common.GetTypeAssertError(\"map[string]interface{}\", data)\n\t\t\t}\n\t\t\tpayload, err = json.Marshal(d)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tsignInput := nowTimeInMilli + creds.Key + defaultRecvWindow + string(payload)\n\t\thmacSigned, err = crypto.GetHMAC(crypto.HashSHA256, []byte(signInput), []byte(creds.Secret))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\theaders[\"Content-Type\"] = \"application/json\"\n\t\theaders[\"X-BAPI-API-KEY\"] = creds.Key\n\t\theaders[\"X-BAPI-SIGN\"] = crypto.HexEncodeToString(hmacSigned)\n\t\theaders[\"X-BAPI-SIGN-TYPE\"] = \"2\"\n\t\theaders[\"X-BAPI-TIMESTAMP\"] = nowTimeInMilli\n\t\theaders[\"X-BAPI-RECV-WINDOW\"] = defaultRecvWindow\n\n\t\treturn &request.Item{\n\t\t\tMethod: method,\n\t\t\tPath: endpointPath + path,\n\t\t\tHeaders: headers,\n\t\t\tBody: bytes.NewBuffer(payload),\n\t\t\tResult: &result,\n\t\t\tVerbose: by.Verbose,\n\t\t\tHTTPDebugging: by.HTTPDebugging,\n\t\t\tHTTPRecording: by.HTTPRecording}, nil\n\t}, request.AuthenticatedRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn result.GetError(true)\n}",
"func HttpPOSTAuthenticated(url string, data string, password string) (resp *http.Response, err error) {\n\treq, err := http.NewRequest(\"POST\", url, strings.NewReader(data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"User-Agent\", \"Hyperspace-Agent\")\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.SetBasicAuth(\"\", password)\n\treturn http.DefaultClient.Do(req)\n}",
"func SendRequest(method, url, token string, reqBody io.Reader) (*http.Response, error) {\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttimestamp := fmt.Sprintf(\"%d\", Now())\n\thash := hmac.New(sha256.New, []byte(token))\n\thash.Write([]byte(timestamp))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"timestamp\", timestamp)\n\treq.Header.Set(\"auth\", hex.EncodeToString(hash.Sum(nil)))\n\n\trsp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rsp, err\n}",
"func HttpPOSTAuthenticated(url string, data string, password string) (resp *http.Response, err error) {\n\treq, err := http.NewRequest(\"POST\", url, strings.NewReader(data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"User-Agent\", \"Sia-Agent\")\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.SetBasicAuth(\"\", password)\n\treturn http.DefaultClient.Do(req)\n}",
"func (a APIKeyAuthentication) Authenticate(req *http.Request, endpoint string, params []byte) error {\n\ttimestamp := fmt.Sprintf(\"%v\", time.Now().UTC().Unix())\n\tmessage := fmt.Sprintf(\"%v%s/%s\", timestamp, req.Method, endpoint)\n\tif params != nil {\n\t\tmessage += string(params)\n\t}\n\th := hmac.New(sha256.New, []byte(a.Secret))\n\th.Write([]byte(message))\n\n\tsignature := hex.EncodeToString(h.Sum(nil))\n\n\treq.Header.Set(\"CB-ACCESS-KEY\", a.Key)\n\treq.Header.Set(\"CB-ACCESS-SIGN\", signature)\n\treq.Header.Set(\"CB-ACCESS-TIMESTAMP\", timestamp)\n\treq.Header.Set(\"CB-VERSION\", APIVersion)\n\n\treturn nil\n}",
"func HttpGETAuthenticated(url string, password string) (resp *http.Response, err error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"User-Agent\", \"Hyperspace-Agent\")\n\treq.SetBasicAuth(\"\", password)\n\treturn http.DefaultClient.Do(req)\n}",
"func HttpGETAuthenticated(url string, password string) (resp *http.Response, err error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"User-Agent\", \"Sia-Agent\")\n\treq.SetBasicAuth(\"\", password)\n\treturn http.DefaultClient.Do(req)\n}",
"func Authenticate(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"Could not read request body\"))\n\t\treturn\n\t}\n\n\tvar credentials datastructures.Credentials\n\n\tif err := json.Unmarshal(body, &credentials); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"Could not read request body\"))\n\t\treturn\n\t}\n\n\tif correct, err := utils.VerifyCredentials(credentials); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"Could not access database\"))\n\t\treturn\n\t} else if !correct {\n\t\tlog.Println(\"Incorrect credentials\")\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"Incorrect credentials\"))\n\t\treturn\n\t}\n\n\tuserdata, err := utils.GetUserData(credentials.Username)\n\n\tif b, err := json.Marshal(userdata); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"Could not access database\"))\n\t} else {\n\t\tw.Write(b)\n\t}\n}",
"func SendHTTPRequest(ctx context.Context, method, urlPath string, headers map[string]string, body io.Reader, verbose bool) ([]byte, error) {\n\tmethod = strings.ToUpper(method)\n\n\tif method != http.MethodOptions && method != http.MethodGet &&\n\t\tmethod != http.MethodHead && method != http.MethodPost &&\n\t\tmethod != http.MethodPut && method != http.MethodDelete &&\n\t\tmethod != http.MethodTrace && method != http.MethodConnect {\n\t\treturn nil, errors.New(\"invalid HTTP method specified\")\n\t}\n\n\treq, err := http.NewRequestWithContext(ctx, method, urlPath, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor k, v := range headers {\n\t\treq.Header.Add(k, v)\n\t}\n\n\tif verbose {\n\t\tlog.Debugf(log.Global, \"Request path: %s\", urlPath)\n\t\tfor k, d := range req.Header {\n\t\t\tlog.Debugf(log.Global, \"Request header [%s]: %s\", k, d)\n\t\t}\n\t\tlog.Debugf(log.Global, \"Request type: %s\", method)\n\t\tif body != nil {\n\t\t\tlog.Debugf(log.Global, \"Request body: %v\", body)\n\t\t}\n\t}\n\n\tm.RLock()\n\tif _HTTPUserAgent != \"\" && req.Header.Get(\"User-Agent\") == \"\" {\n\t\treq.Header.Add(\"User-Agent\", _HTTPUserAgent)\n\t}\n\n\tif _HTTPClient == nil {\n\t\tm.RUnlock()\n\t\tm.Lock()\n\t\t// Set *http.Client with default timeout if not populated.\n\t\t_HTTPClient = NewHTTPClientWithTimeout(defaultTimeout)\n\t\tm.Unlock()\n\t\tm.RLock()\n\t}\n\n\tresp, err := _HTTPClient.Do(req)\n\tm.RUnlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tcontents, err := io.ReadAll(resp.Body)\n\n\tif verbose {\n\t\tlog.Debugf(log.Global, \"HTTP status: %s, Code: %v\",\n\t\t\tresp.Status,\n\t\t\tresp.StatusCode)\n\t\tlog.Debugf(log.Global, \"Raw response: %s\", string(contents))\n\t}\n\n\treturn contents, err\n}",
"func (h *Handler) serveAuthenticate(w http.ResponseWriter, r *http.Request) {}",
"func (h *Handler) serveAuthenticateDBUser(w http.ResponseWriter, r *http.Request) {}",
"func (p *SignatureProvider) SignHTTPRequest(req *http.Request) error {\n\n\t// no matter what, we set the compartmentID in the header\n\treq.Header.Set(requestHeaderXNoSQLCompartmentID, p.compartmentID)\n\n\t// if used, set the delegation token\n\tif p.delegationToken != \"\" {\n\t\treq.Header.Set(requestHeaderDelegationToken, p.delegationToken)\n\t}\n\n\t// use cached signature and date, if not expired\n\tnow := time.Now()\n\tif p.signature != \"\" && p.signatureExpiresAt.After(now) {\n\t\tp.mutex.RLock()\n\t\tdefer p.mutex.RUnlock()\n\t\treq.Header.Set(requestHeaderDate, p.signatureFormattedDate)\n\t\treq.Header.Set(requestHeaderAuthorization, p.signature)\n\t\treturn nil\n\t}\n\n\t// calculate new signature\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\tp.signatureFormattedDate = now.UTC().Format(http.TimeFormat)\n\treq.Header.Set(requestHeaderDate, p.signatureFormattedDate)\n\terr := p.signer.Sign(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.signature = req.Header.Get(requestHeaderAuthorization)\n\n\tp.signatureExpiresAt = now.Add(p.expiryInterval)\n\n\t// need to use min(expiryInterval, tokenExpiration)\n\texp := p.signer.ExpirationTime()\n\tif p.signatureExpiresAt.After(exp) {\n\t\tp.signatureExpiresAt = exp\n\t}\n\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetGaugeMetric func(name string, help string, env string, envValue string, version string, versionValue string) (prometheusGauge Gauge)
|
func SetGaugeMetric(name string, help string, env string, envValue string, version string, versionValue string) (prometheusGauge prometheus.Gauge) {
var (
gaugeMetric = prometheus.NewGauge(prometheus.GaugeOpts{
Name: name,
Help: help,
ConstLabels: prometheus.Labels{env: envValue, version: versionValue},
})
)
return gaugeMetric
}
|
[
"func (cm *customMetrics) SetGauge(gauge string, value float64) {\n\n\tcm.gauges[gauge].Set(value)\n}",
"func gauge(name string, desc string) metric {\n\treturn metric{\n\t\ttyp: prometheus.GaugeValue,\n\t\taeroName: name,\n\t\tdesc: desc,\n\t}\n}",
"func (m *CirconusMetrics) SetGauge(metric string, val interface{}) {\n\tm.gm.Lock()\n\tdefer m.gm.Unlock()\n\tm.gauges[metric] = m.gaugeValString(val)\n}",
"func (r *Reporter) Gauge(metricName string, value float64, tags metrics.Tags) error {\n\treturn nil\n}",
"func (rc *nopS) Gauge(stat string, value float64, tags ...string) {\n}",
"func NewGaugeMetric(name, unit, sourceID string, opts ...MetricOption) GaugeMetric {\n\tg := &gaugeMetric{\n\t\tname: name,\n\t\tunit: unit,\n\t\tsourceID: sourceID,\n\t\ttags: make(map[string]string),\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(g.tags)\n\t}\n\n\treturn g\n}",
"func (_m *Reporter) Gauge(name string, value float64, tags ...monitoring.Tag) {\n\t_va := make([]interface{}, len(tags))\n\tfor _i := range tags {\n\t\t_va[_i] = tags[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, name, value)\n\t_ca = append(_ca, _va...)\n\t_m.Called(_ca...)\n}",
"func NewGauge(metric string, dimensions map[string]string, value int64) *Gauge {\n\treturn &Gauge{metric: metric, dimensions: dimensions, value: value}\n}",
"func (c *Client) Gauge(name string, value float64, tags []string, common bool) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tif !c.started {\n\t\treturn\n\t}\n\tkey := metricKey(name, tags)\n\tm, ok := c.metrics[key]\n\tif !ok {\n\t\tm = newmetric(name, metricKindGauge, tags, common)\n\t\tc.metrics[key] = m\n\t}\n\tm.value = value\n\tm.ts = float64(time.Now().Unix())\n\tc.newMetrics = true\n}",
"func (e *Exporter) addGauge(name string, value float64, help string) {\n\tif e.lowercase {\n\t\tname = strings.ToLower(name)\n\t}\n\tif e.matchMetric(name) {\n\t\tif _, exists := e.gauges[name]; !exists {\n\t\t\te.gauges[name] = prometheus.NewGaugeVec(prometheus.GaugeOpts{Namespace: e.namespace, Name: name, Help: help}, e.labels)\n\t\t\te.updated[name] = 0\n\t\t\te.exist[name] = 0\n\t\t}\n\t\te.gauges[name].WithLabelValues(e.labelvalues...).Set(value)\n\t\te.updated[name]++\n\t}\n}",
"func WrapGauge(\n\tmetric string,\n\tdimensions map[string]string,\n\tvalue Getter,\n) *WrappedGauge {\n\treturn &WrappedGauge{\n\t\tmetric: metric,\n\t\tdimensions: dimensions,\n\t\tvalue: value,\n\t}\n}",
"func (w *Gauge) Set(value float64, labelValues ...string) {\n\tw.watcher.WithLabelValues(labelValues...).Set(value)\n\tmetaLabel := w.prefix + \".\" + strings.Join(labelValues, \".\")\n\t(*w.client).Gauge(metaLabel, int64(value), 1.0)\n}",
"func (cm *customMetrics) AddGauge(namespace, subsystem, name, help, internalKey string) {\n\n\tcm.gauges[internalKey] = promauto.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: subsystem,\n\t\tName: name,\n\t\tHelp: help,\n\t})\n}",
"func (s *DogStatsdSink) SetGauge(key []string, val float32, tags []Tag) {\n\tflatKey, t := s.getFlatkeyAndCombinedLabels(key, tags)\n\trate := 1.0\n\ts.client.Gauge(flatKey, float64(val), t, rate)\n}",
"func NewGauge(opts GaugeOpts) Gauge {\n\treturn newValue(NewDesc(\n\t\tBuildFQName(opts.Namespace, opts.Subsystem, opts.Name),\n\t\topts.Help,\n\t\tnil,\n\t\topts.ConstLabels,\n\t), GaugeValue, 0)\n}",
"func (m *MockStats) Gauge(stat string, value float64, tags ...Tag) {\n\tvarargs := []interface{}{stat, value}\n\tfor _, a := range tags {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Gauge\", varargs...)\n}",
"func (g *Gauge) Set(v float64) {\n\tg.Gauge.Set(v)\n}",
"func SetMetric() {\n\tmetricsstore.DefaultMetricsStore.VersionInfo.WithLabelValues(Version, BuildDate, GitCommit).Set(1)\n}",
"func (bag MetricsBag) AddGauge(name string, value float64) {\n\tbag[\"g:\"+name] = value\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Resume rehydrates a AdaptiveNetworkHardeningsEnforcePollerResponse from the provided client and resume token.
|
func (l *AdaptiveNetworkHardeningsEnforcePollerResponse) Resume(ctx context.Context, client *AdaptiveNetworkHardeningsClient, token string) error {
pt, err := armruntime.NewPollerFromResumeToken("AdaptiveNetworkHardeningsClient.Enforce", token, client.pl, client.enforceHandleError)
if err != nil {
return err
}
poller := &AdaptiveNetworkHardeningsEnforcePoller{
pt: pt,
}
resp, err := poller.Poll(ctx)
if err != nil {
return err
}
l.Poller = poller
l.RawResponse = resp
return nil
}
|
[
"func (l *WorkspaceManagedSQLServerEncryptionProtectorClientRevalidatePollerResponse) Resume(ctx context.Context, client *WorkspaceManagedSQLServerEncryptionProtectorClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"WorkspaceManagedSQLServerEncryptionProtectorClient.Revalidate\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &WorkspaceManagedSQLServerEncryptionProtectorClientRevalidatePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ManagedInstanceEncryptionProtectorsRevalidatePollerResponse) Resume(ctx context.Context, client *ManagedInstanceEncryptionProtectorsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ManagedInstanceEncryptionProtectorsClient.Revalidate\", token, client.pl, client.revalidateHandleError)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ManagedInstanceEncryptionProtectorsRevalidatePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ApplicationGatewaysClientStartPollerResponse) Resume(ctx context.Context, client *ApplicationGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ApplicationGatewaysClient.Start\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ApplicationGatewaysClientStartPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualNetworkGatewaysClientResetPollerResponse) Resume(ctx context.Context, client *VirtualNetworkGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualNetworkGatewaysClient.Reset\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualNetworkGatewaysClientResetPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VPNGatewaysClientResetPollerResponse) Resume(ctx context.Context, client *VPNGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VPNGatewaysClient.Reset\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VPNGatewaysClientResetPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualNetworkGatewaysClientResetVPNClientSharedKeyPollerResponse) Resume(ctx context.Context, client *VirtualNetworkGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualNetworkGatewaysClient.ResetVPNClientSharedKey\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualNetworkGatewaysClientResetVPNClientSharedKeyPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ApplicationGatewaysClientCreateOrUpdatePollerResponse) Resume(ctx context.Context, client *ApplicationGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ApplicationGatewaysClient.CreateOrUpdate\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ApplicationGatewaysClientCreateOrUpdatePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ApplicationGatewaysClientBackendHealthOnDemandPollerResponse) Resume(ctx context.Context, client *ApplicationGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ApplicationGatewaysClient.BackendHealthOnDemand\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ApplicationGatewaysClientBackendHealthOnDemandPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *LiveEventsClientAllocatePollerResponse) Resume(ctx context.Context, client *LiveEventsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"LiveEventsClient.Allocate\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &LiveEventsClientAllocatePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *SharesClientRefreshPollerResponse) Resume(ctx context.Context, client *SharesClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"SharesClient.Refresh\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &SharesClientRefreshPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualNetworkGatewaysClientGeneratevpnclientpackagePollerResponse) Resume(ctx context.Context, client *VirtualNetworkGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualNetworkGatewaysClient.Generatevpnclientpackage\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualNetworkGatewaysClientGeneratevpnclientpackagePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *SQLPoolsClientResumePollerResponse) Resume(ctx context.Context, client *SQLPoolsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"SQLPoolsClient.Resume\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &SQLPoolsClientResumePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *WatchersClientVerifyIPFlowPollerResponse) Resume(ctx context.Context, client *WatchersClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"WatchersClient.VerifyIPFlow\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &WatchersClientVerifyIPFlowPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *BackupPoliciesClientUpdatePollerResponse) Resume(ctx context.Context, client *BackupPoliciesClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"BackupPoliciesClient.Update\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &BackupPoliciesClientUpdatePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualNetworkGatewaysClientCreateOrUpdatePollerResponse) Resume(ctx context.Context, client *VirtualNetworkGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualNetworkGatewaysClient.CreateOrUpdate\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualNetworkGatewaysClientCreateOrUpdatePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *LivePipelinesClientActivatePollerResponse) Resume(ctx context.Context, client *LivePipelinesClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"LivePipelinesClient.Activate\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &LivePipelinesClientActivatePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *P2SVPNGatewaysClientResetPollerResponse) Resume(ctx context.Context, client *P2SVPNGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"P2SVPNGatewaysClient.Reset\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &P2SVPNGatewaysClientResetPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ExpressRouteGatewaysClientCreateOrUpdatePollerResponse) Resume(ctx context.Context, client *ExpressRouteGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ExpressRouteGatewaysClient.CreateOrUpdate\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ExpressRouteGatewaysClientCreateOrUpdatePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VPNServerConfigurationsAssociatedWithVirtualWanClientListPollerResponse) Resume(ctx context.Context, client *VPNServerConfigurationsAssociatedWithVirtualWanClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VPNServerConfigurationsAssociatedWithVirtualWanClient.List\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VPNServerConfigurationsAssociatedWithVirtualWanClientListPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Resume rehydrates a AlertsSimulatePollerResponse from the provided client and resume token.
|
func (l *AlertsSimulatePollerResponse) Resume(ctx context.Context, client *AlertsClient, token string) error {
pt, err := armruntime.NewPollerFromResumeToken("AlertsClient.Simulate", token, client.pl, client.simulateHandleError)
if err != nil {
return err
}
poller := &AlertsSimulatePoller{
pt: pt,
}
resp, err := poller.Poll(ctx)
if err != nil {
return err
}
l.Poller = poller
l.RawResponse = resp
return nil
}
|
[
"func (l *ApplicationGatewaysClientStartPollerResponse) Resume(ctx context.Context, client *ApplicationGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ApplicationGatewaysClient.Start\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ApplicationGatewaysClientStartPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *LiveEventsClientResetPollerResponse) Resume(ctx context.Context, client *LiveEventsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"LiveEventsClient.Reset\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &LiveEventsClientResetPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VPNGatewaysClientResetPollerResponse) Resume(ctx context.Context, client *VPNGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VPNGatewaysClient.Reset\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VPNGatewaysClientResetPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *TriggersClientStartPollerResponse) Resume(ctx context.Context, client *TriggersClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"TriggersClient.Start\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &TriggersClientStartPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *LivePipelinesClientActivatePollerResponse) Resume(ctx context.Context, client *LivePipelinesClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"LivePipelinesClient.Activate\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &LivePipelinesClientActivatePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ManagedClustersClientStartPollerResponse) Resume(ctx context.Context, client *ManagedClustersClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ManagedClustersClient.Start\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ManagedClustersClientStartPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *LiveEventsClientStartPollerResponse) Resume(ctx context.Context, client *LiveEventsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"LiveEventsClient.Start\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &LiveEventsClientStartPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualNetworkGatewaysClientResetPollerResponse) Resume(ctx context.Context, client *VirtualNetworkGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualNetworkGatewaysClient.Reset\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualNetworkGatewaysClientResetPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *SQLPoolsClientResumePollerResponse) Resume(ctx context.Context, client *SQLPoolsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"SQLPoolsClient.Resume\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &SQLPoolsClientResumePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *SharesClientRefreshPollerResponse) Resume(ctx context.Context, client *SharesClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"SharesClient.Refresh\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &SharesClientRefreshPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *P2SVPNGatewaysClientResetPollerResponse) Resume(ctx context.Context, client *P2SVPNGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"P2SVPNGatewaysClient.Reset\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &P2SVPNGatewaysClientResetPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ServersClientStartPollerResponse) Resume(ctx context.Context, client *ServersClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ServersClient.Start\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ServersClientStartPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ContainersClientRefreshPollerResponse) Resume(ctx context.Context, client *ContainersClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ContainersClient.Refresh\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ContainersClientRefreshPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualNetworkGatewaysClientResetVPNClientSharedKeyPollerResponse) Resume(ctx context.Context, client *VirtualNetworkGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualNetworkGatewaysClient.ResetVPNClientSharedKey\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualNetworkGatewaysClientResetVPNClientSharedKeyPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ManagementClientGetActiveSessionsPollerResponse) Resume(ctx context.Context, client *ManagementClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ManagementClient.GetActiveSessions\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ManagementClientGetActiveSessionsPoller{\n\t\tpt: pt,\n\t\tclient: client,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *WorkspaceManagedSQLServerEncryptionProtectorClientRevalidatePollerResponse) Resume(ctx context.Context, client *WorkspaceManagedSQLServerEncryptionProtectorClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"WorkspaceManagedSQLServerEncryptionProtectorClient.Revalidate\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &WorkspaceManagedSQLServerEncryptionProtectorClientRevalidatePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ManagedClustersClientRunCommandPollerResponse) Resume(ctx context.Context, client *ManagedClustersClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ManagedClustersClient.RunCommand\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ManagedClustersClientRunCommandPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *IntegrationRuntimeObjectMetadataClientRefreshPollerResponse) Resume(ctx context.Context, client *IntegrationRuntimeObjectMetadataClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"IntegrationRuntimeObjectMetadataClient.Refresh\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &IntegrationRuntimeObjectMetadataClientRefreshPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ServersClientRestartPollerResponse) Resume(ctx context.Context, client *ServersClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ServersClient.Restart\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ServersClientRestartPoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Resume rehydrates a ServerVulnerabilityAssessmentDeletePollerResponse from the provided client and resume token.
|
func (l *ServerVulnerabilityAssessmentDeletePollerResponse) Resume(ctx context.Context, client *ServerVulnerabilityAssessmentClient, token string) error {
pt, err := armruntime.NewPollerFromResumeToken("ServerVulnerabilityAssessmentClient.Delete", token, client.pl, client.deleteHandleError)
if err != nil {
return err
}
poller := &ServerVulnerabilityAssessmentDeletePoller{
pt: pt,
}
resp, err := poller.Poll(ctx)
if err != nil {
return err
}
l.Poller = poller
l.RawResponse = resp
return nil
}
|
[
"func (l *VPNGatewaysClientDeletePollerResponse) Resume(ctx context.Context, client *VPNGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VPNGatewaysClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VPNGatewaysClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualApplianceSitesClientDeletePollerResponse) Resume(ctx context.Context, client *VirtualApplianceSitesClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualApplianceSitesClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualApplianceSitesClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualRouterPeeringsClientDeletePollerResponse) Resume(ctx context.Context, client *VirtualRouterPeeringsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualRouterPeeringsClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualRouterPeeringsClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *P2SVPNGatewaysClientDeletePollerResponse) Resume(ctx context.Context, client *P2SVPNGatewaysClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"P2SVPNGatewaysClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &P2SVPNGatewaysClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ManagedInstanceAzureADOnlyAuthenticationsDeletePollerResponse) Resume(ctx context.Context, client *ManagedInstanceAzureADOnlyAuthenticationsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ManagedInstanceAzureADOnlyAuthenticationsClient.Delete\", token, client.pl, client.deleteHandleError)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ManagedInstanceAzureADOnlyAuthenticationsDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualNetworkTapsClientDeletePollerResponse) Resume(ctx context.Context, client *VirtualNetworkTapsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualNetworkTapsClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualNetworkTapsClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ManagedInstancesDeletePollerResponse) Resume(ctx context.Context, client *ManagedInstancesClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ManagedInstancesClient.Delete\", token, client.pl, client.deleteHandleError)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ManagedInstancesDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *IPAllocationsClientDeletePollerResponse) Resume(ctx context.Context, client *IPAllocationsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"IPAllocationsClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &IPAllocationsClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualAppliancesClientDeletePollerResponse) Resume(ctx context.Context, client *VirtualAppliancesClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualAppliancesClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualAppliancesClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *AgentPoolsClientDeletePollerResponse) Resume(ctx context.Context, client *AgentPoolsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"AgentPoolsClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &AgentPoolsClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VPNServerConfigurationsClientDeletePollerResponse) Resume(ctx context.Context, client *VPNServerConfigurationsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VPNServerConfigurationsClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VPNServerConfigurationsClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *LiveEventsClientDeletePollerResponse) Resume(ctx context.Context, client *LiveEventsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"LiveEventsClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &LiveEventsClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ServerAzureADOnlyAuthenticationsDeletePollerResponse) Resume(ctx context.Context, client *ServerAzureADOnlyAuthenticationsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ServerAzureADOnlyAuthenticationsClient.Delete\", token, client.pl, client.deleteHandleError)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ServerAzureADOnlyAuthenticationsDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ApplicationSecurityGroupsClientDeletePollerResponse) Resume(ctx context.Context, client *ApplicationSecurityGroupsClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ApplicationSecurityGroupsClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ApplicationSecurityGroupsClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualRoutersClientDeletePollerResponse) Resume(ctx context.Context, client *VirtualRoutersClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualRoutersClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualRoutersClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *VirtualWansClientDeletePollerResponse) Resume(ctx context.Context, client *VirtualWansClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"VirtualWansClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &VirtualWansClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ServerDNSAliasesDeletePollerResponse) Resume(ctx context.Context, client *ServerDNSAliasesClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ServerDNSAliasesClient.Delete\", token, client.pl, client.deleteHandleError)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ServerDNSAliasesDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *ManagedClustersClientDeletePollerResponse) Resume(ctx context.Context, client *ManagedClustersClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"ManagedClustersClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &ManagedClustersClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}",
"func (l *PacketCapturesClientDeletePollerResponse) Resume(ctx context.Context, client *PacketCapturesClient, token string) error {\n\tpt, err := armruntime.NewPollerFromResumeToken(\"PacketCapturesClient.Delete\", token, client.pl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpoller := &PacketCapturesClientDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.Poller = poller\n\tl.RawResponse = resp\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
UnmarshalJSON implements the json.Unmarshaller interface for type SettingsGetResult.
|
func (s *SettingsGetResult) UnmarshalJSON(data []byte) error {
res, err := unmarshalSettingClassification(data)
if err != nil {
return err
}
s.SettingClassification = res
return nil
}
|
[
"func (tsgr *ThroughputSettingsGetResults) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar throughputSettingsGetProperties ThroughputSettingsGetProperties\n\t\t\t\terr = json.Unmarshal(*v, &throughputSettingsGetProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttsgr.ThroughputSettingsGetProperties = &throughputSettingsGetProperties\n\t\t\t}\n\t\tcase \"id\":\n\t\t\tif v != nil {\n\t\t\t\tvar ID string\n\t\t\t\terr = json.Unmarshal(*v, &ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttsgr.ID = &ID\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttsgr.Name = &name\n\t\t\t}\n\t\tcase \"type\":\n\t\t\tif v != nil {\n\t\t\t\tvar typeVar string\n\t\t\t\terr = json.Unmarshal(*v, &typeVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttsgr.Type = &typeVar\n\t\t\t}\n\t\tcase \"location\":\n\t\t\tif v != nil {\n\t\t\t\tvar location string\n\t\t\t\terr = json.Unmarshal(*v, &location)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttsgr.Location = &location\n\t\t\t}\n\t\tcase \"tags\":\n\t\t\tif v != nil {\n\t\t\t\tvar tags map[string]*string\n\t\t\t\terr = json.Unmarshal(*v, &tags)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttsgr.Tags = tags\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (p *ProductSettingsClientGetResult) UnmarshalJSON(data []byte) error {\n\tres, err := unmarshalSettingsClassification(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.SettingsClassification = res\n\treturn nil\n}",
"func (s *SettingsUpdateResult) UnmarshalJSON(data []byte) error {\n\tres, err := unmarshalSettingClassification(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.SettingClassification = res\n\treturn nil\n}",
"func (p *ProductSettingsClientUpdateResult) UnmarshalJSON(data []byte) error {\n\tres, err := unmarshalSettingsClassification(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.SettingsClassification = res\n\treturn nil\n}",
"func (r *RemoteSupportSettings) 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\", r, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"accessLevel\":\n\t\t\terr = unpopulate(val, \"AccessLevel\", &r.AccessLevel)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"expirationTimeStampInUTC\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"ExpirationTimeStampInUTC\", &r.ExpirationTimeStampInUTC)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"remoteApplicationType\":\n\t\t\terr = unpopulate(val, \"RemoteApplicationType\", &r.RemoteApplicationType)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", r, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (l *ListMaintenanceConfigurationsResult) 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\", l, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &l.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", l, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (r *ResourceForestSettings) 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\", r, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"resourceForest\":\n\t\t\terr = unpopulate(val, \"ResourceForest\", &r.ResourceForest)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"settings\":\n\t\t\terr = unpopulate(val, \"Settings\", &r.Settings)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", r, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (h *HlsSettings) 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\", h, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"characteristics\":\n\t\t\terr = unpopulate(val, \"Characteristics\", &h.Characteristics)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"default\":\n\t\t\terr = unpopulate(val, \"Default\", &h.Default)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"forced\":\n\t\t\terr = unpopulate(val, \"Forced\", &h.Forced)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", h, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (a *AccountSKUListResult) 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\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (a *ApplicationGatewayAvailableWafRuleSetsResult) 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\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (h *HostSettingsResponse) 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\", h, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"BotOpenIdMetadata\":\n\t\t\terr = unpopulate(val, \"BotOpenIDMetadata\", &h.BotOpenIDMetadata)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"OAuthUrl\":\n\t\t\terr = unpopulate(val, \"OAuthURL\", &h.OAuthURL)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"ToBotFromChannelOpenIdMetadataUrl\":\n\t\t\terr = unpopulate(val, \"ToBotFromChannelOpenIDMetadataURL\", &h.ToBotFromChannelOpenIDMetadataURL)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"ToBotFromChannelTokenIssuer\":\n\t\t\terr = unpopulate(val, \"ToBotFromChannelTokenIssuer\", &h.ToBotFromChannelTokenIssuer)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"ToBotFromEmulatorOpenIdMetadataUrl\":\n\t\t\terr = unpopulate(val, \"ToBotFromEmulatorOpenIDMetadataURL\", &h.ToBotFromEmulatorOpenIDMetadataURL)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"ToChannelFromBotLoginUrl\":\n\t\t\terr = unpopulate(val, \"ToChannelFromBotLoginURL\", &h.ToChannelFromBotLoginURL)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"ToChannelFromBotOAuthScope\":\n\t\t\terr = unpopulate(val, \"ToChannelFromBotOAuthScope\", &h.ToChannelFromBotOAuthScope)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"ValidateAuthority\":\n\t\t\terr = unpopulate(val, \"ValidateAuthority\", &h.ValidateAuthority)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", h, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (stgr *SQLTriggerGetResults) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar SQLTriggerGetProperties SQLTriggerGetProperties\n\t\t\t\terr = json.Unmarshal(*v, &SQLTriggerGetProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstgr.SQLTriggerGetProperties = &SQLTriggerGetProperties\n\t\t\t}\n\t\tcase \"id\":\n\t\t\tif v != nil {\n\t\t\t\tvar ID string\n\t\t\t\terr = json.Unmarshal(*v, &ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstgr.ID = &ID\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstgr.Name = &name\n\t\t\t}\n\t\tcase \"type\":\n\t\t\tif v != nil {\n\t\t\t\tvar typeVar string\n\t\t\t\terr = json.Unmarshal(*v, &typeVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstgr.Type = &typeVar\n\t\t\t}\n\t\tcase \"location\":\n\t\t\tif v != nil {\n\t\t\t\tvar location string\n\t\t\t\terr = json.Unmarshal(*v, &location)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstgr.Location = &location\n\t\t\t}\n\t\tcase \"tags\":\n\t\t\tif v != nil {\n\t\t\t\tvar tags map[string]*string\n\t\t\t\terr = json.Unmarshal(*v, &tags)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstgr.Tags = tags\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (this *ConnectionPoolSettings_HTTPSettings) UnmarshalJSON(b []byte) error {\n\treturn DestinationRuleUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}",
"func (c *ChannelSettings) 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\", c, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"botId\":\n\t\t\terr = unpopulate(val, \"BotID\", &c.BotID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"botIconUrl\":\n\t\t\terr = unpopulate(val, \"BotIconURL\", &c.BotIconURL)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"channelDisplayName\":\n\t\t\terr = unpopulate(val, \"ChannelDisplayName\", &c.ChannelDisplayName)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"channelId\":\n\t\t\terr = unpopulate(val, \"ChannelID\", &c.ChannelID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"disableLocalAuth\":\n\t\t\terr = unpopulate(val, \"DisableLocalAuth\", &c.DisableLocalAuth)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"extensionKey1\":\n\t\t\terr = unpopulate(val, \"ExtensionKey1\", &c.ExtensionKey1)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"extensionKey2\":\n\t\t\terr = unpopulate(val, \"ExtensionKey2\", &c.ExtensionKey2)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isEnabled\":\n\t\t\terr = unpopulate(val, \"IsEnabled\", &c.IsEnabled)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"requireTermsAgreement\":\n\t\t\terr = unpopulate(val, \"RequireTermsAgreement\", &c.RequireTermsAgreement)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"sites\":\n\t\t\terr = unpopulate(val, \"Sites\", &c.Sites)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", c, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func UnmarshalAccountSettingsResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(AccountSettingsResponse)\n\terr = core.UnmarshalModel(m, \"context\", &obj.Context, UnmarshalResponseContext)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"account_id\", &obj.AccountID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"restrict_create_service_id\", &obj.RestrictCreateServiceID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"restrict_create_platform_apikey\", &obj.RestrictCreatePlatformApikey)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"allowed_ip_addresses\", &obj.AllowedIPAddresses)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"entity_tag\", &obj.EntityTag)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"mfa\", &obj.Mfa)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalModel(m, \"user_mfa\", &obj.UserMfa, UnmarshalAccountSettingsUserMfa)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalModel(m, \"history\", &obj.History, UnmarshalEnityHistoryRecord)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"session_expiration_in_seconds\", &obj.SessionExpirationInSeconds)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"session_invalidation_in_seconds\", &obj.SessionInvalidationInSeconds)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"max_sessions_per_identity\", &obj.MaxSessionsPerIdentity)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"system_access_token_expiration_in_seconds\", &obj.SystemAccessTokenExpirationInSeconds)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"system_refresh_token_expiration_in_seconds\", &obj.SystemRefreshTokenExpirationInSeconds)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}",
"func GetSettings(jsonByteArray []byte) Settings {\n\tvar settings Settings\n\tjson.Unmarshal(jsonByteArray, &settings)\n\treturn settings\n}",
"func (a *ApplicationGatewayWafDynamicManifestPropertiesResult) 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\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"availableRuleSets\":\n\t\t\terr = unpopulate(val, \"AvailableRuleSets\", &a.AvailableRuleSets)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"defaultRuleSet\":\n\t\t\terr = unpopulate(val, \"DefaultRuleSet\", &a.DefaultRuleSet)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (k *KeyVaultResourceSettings) 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\", k, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"resourceType\":\n\t\t\terr = unpopulate(val, \"ResourceType\", &k.ResourceType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"targetResourceName\":\n\t\t\terr = unpopulate(val, \"TargetResourceName\", &k.TargetResourceName)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", k, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (d *DefenderSettingsList) 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\", d, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &d.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t\t}\n\t}\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
UnmarshalJSON implements the json.Unmarshaller interface for type SettingsUpdateResult.
|
func (s *SettingsUpdateResult) UnmarshalJSON(data []byte) error {
res, err := unmarshalSettingClassification(data)
if err != nil {
return err
}
s.SettingClassification = res
return nil
}
|
[
"func (p *ProductSettingsClientUpdateResult) UnmarshalJSON(data []byte) error {\n\tres, err := unmarshalSettingsClassification(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.SettingsClassification = res\n\treturn nil\n}",
"func (l *ListUpdatesResult) 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\", l, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &l.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", l, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (s *SettingsGetResult) UnmarshalJSON(data []byte) error {\n\tres, err := unmarshalSettingClassification(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.SettingClassification = res\n\treturn nil\n}",
"func (a *ApplyUpdate) 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\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &a.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &a.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &a.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"systemData\":\n\t\t\terr = unpopulate(val, \"SystemData\", &a.SystemData)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &a.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (s *SecretUpdate) 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 \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &s.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"systemData\":\n\t\t\terr = unpopulate(val, \"SystemData\", &s.SystemData)\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 (t *TaskRunPropertiesUpdateParameters) 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\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"forceUpdateTag\":\n\t\t\terr = unpopulate(val, \"ForceUpdateTag\", &t.ForceUpdateTag)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"runRequest\":\n\t\t\tt.RunRequest, err = unmarshalRunRequestClassification(val)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (u *UpdateDetails) 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\", u, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"estimatedInstallTimeInMins\":\n\t\t\terr = unpopulate(val, \"EstimatedInstallTimeInMins\", &u.EstimatedInstallTimeInMins)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"friendlyVersionNumber\":\n\t\t\terr = unpopulate(val, \"FriendlyVersionNumber\", &u.FriendlyVersionNumber)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"installationImpact\":\n\t\t\terr = unpopulate(val, \"InstallationImpact\", &u.InstallationImpact)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"rebootBehavior\":\n\t\t\terr = unpopulate(val, \"RebootBehavior\", &u.RebootBehavior)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &u.Status)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"targetVersion\":\n\t\t\terr = unpopulate(val, \"TargetVersion\", &u.TargetVersion)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"updateSize\":\n\t\t\terr = unpopulate(val, \"UpdateSize\", &u.UpdateSize)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"updateTitle\":\n\t\t\terr = unpopulate(val, \"UpdateTitle\", &u.UpdateTitle)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"updateType\":\n\t\t\terr = unpopulate(val, \"UpdateType\", &u.UpdateType)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (p *ProductSettingsClientGetResult) UnmarshalJSON(data []byte) error {\n\tres, err := unmarshalSettingsClassification(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.SettingsClassification = res\n\treturn nil\n}",
"func (r *RemoteSupportSettings) 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\", r, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"accessLevel\":\n\t\t\terr = unpopulate(val, \"AccessLevel\", &r.AccessLevel)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"expirationTimeStampInUTC\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"ExpirationTimeStampInUTC\", &r.ExpirationTimeStampInUTC)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"remoteApplicationType\":\n\t\t\terr = unpopulate(val, \"RemoteApplicationType\", &r.RemoteApplicationType)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", r, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (a *ApplyUpdateProperties) 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\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"lastUpdateTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"LastUpdateTime\", &a.LastUpdateTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resourceId\":\n\t\t\terr = unpopulate(val, \"ResourceID\", &a.ResourceID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &a.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (s *ServerGroupPropertiesForUpdate) 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 \"administratorLoginPassword\":\n\t\t\terr = unpopulate(val, \"AdministratorLoginPassword\", &s.AdministratorLoginPassword)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"availabilityZone\":\n\t\t\terr = unpopulate(val, \"AvailabilityZone\", &s.AvailabilityZone)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"backupRetentionDays\":\n\t\t\terr = unpopulate(val, \"BackupRetentionDays\", &s.BackupRetentionDays)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"citusVersion\":\n\t\t\terr = unpopulate(val, \"CitusVersion\", &s.CitusVersion)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"enableShardsOnCoordinator\":\n\t\t\terr = unpopulate(val, \"EnableShardsOnCoordinator\", &s.EnableShardsOnCoordinator)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"maintenanceWindow\":\n\t\t\terr = unpopulate(val, \"MaintenanceWindow\", &s.MaintenanceWindow)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"postgresqlVersion\":\n\t\t\terr = unpopulate(val, \"PostgresqlVersion\", &s.PostgresqlVersion)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"serverRoleGroups\":\n\t\t\terr = unpopulate(val, \"ServerRoleGroups\", &s.ServerRoleGroups)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"standbyAvailabilityZone\":\n\t\t\terr = unpopulate(val, \"StandbyAvailabilityZone\", &s.StandbyAvailabilityZone)\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 (a *AccountSKUListResult) 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\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (u *Update) 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\", u, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"impactDurationInSec\":\n\t\t\terr = unpopulate(val, \"ImpactDurationInSec\", &u.ImpactDurationInSec)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"impactType\":\n\t\t\terr = unpopulate(val, \"ImpactType\", &u.ImpactType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"maintenanceScope\":\n\t\t\terr = unpopulate(val, \"MaintenanceScope\", &u.MaintenanceScope)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"notBefore\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"NotBefore\", &u.NotBefore)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &u.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &u.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (l *ListApplyUpdate) 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\", l, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &l.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", l, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (m *MediaServiceUpdate) 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\", m, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"identity\":\n\t\t\terr = unpopulate(val, \"Identity\", &m.Identity)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &m.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &m.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", m, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (u *UpdateInstallProgress) 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\", u, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"numberOfUpdatesInstalled\":\n\t\t\terr = unpopulate(val, \"NumberOfUpdatesInstalled\", &u.NumberOfUpdatesInstalled)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"numberOfUpdatesToInstall\":\n\t\t\terr = unpopulate(val, \"NumberOfUpdatesToInstall\", &u.NumberOfUpdatesToInstall)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"percentComplete\":\n\t\t\terr = unpopulate(val, \"PercentComplete\", &u.PercentComplete)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (s *ServiceUpdate) 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 \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &s.Properties)\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 (u *Update) 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\", u, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &u.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &u.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (d *DeploymentUpdateParameters) 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\", d, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"identity\":\n\t\t\terr = unpopulate(val, \"Identity\", &d.Identity)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"location\":\n\t\t\terr = unpopulate(val, \"Location\", &d.Location)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &d.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"sku\":\n\t\t\terr = unpopulate(val, \"SKU\", &d.SKU)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &d.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t\t}\n\t}\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test that an initially expired promo may not be displayed
|
func TestPreExpired(t *testing.T) {
var tm time.Time // initial value is in the past
reset()
p, _ := New("Promo1", tm, tm)
if res := p.AllowDisplay(ip); res != false {
t.Errorf("Bad Promo status, got: %v want %v", res, false)
}
}
|
[
"func (cp customProvider) IsExpired() bool { return false }",
"func notExpired(s *link.PublicShare) bool {\n\tt := time.Unix(int64(s.Expiration.GetSeconds()), int64(s.Expiration.GetNanos()))\n\tif (s.Expiration != nil && t.After(time.Now())) || s.Expiration == nil {\n\t\treturn true\n\t}\n\treturn false\n}",
"func TestUnitGetExpirationNonePresent(t *testing.T) {\n\n\tConvey(\"Given I have some session data with no 'expires_in' token\", t, func() {\n\n\t\tvar sessionData Session = map[string]interface{}{\n\t\t\t\"signin_info\": map[string]interface{}{\n\t\t\t\t\"access_token\": map[string]interface{}{},\n\t\t\t},\n\t\t}\n\n\t\tConvey(\"When I call GetExpiration\", func() {\n\n\t\t\texpiration := sessionData.GetExpiration()\n\n\t\t\tConvey(\"Then 0 should be returned\", func() {\n\n\t\t\t\tSo(expiration, ShouldEqual, uint64(0))\n\t\t\t})\n\t\t})\n\t})\n}",
"func TestExpiration(t *testing.T) {\n\tr := NewRegistrar()\n\tr.Add(session)\n\ttime.Sleep(expireDuration)\n\tif r.Validate(user) {\n\t\tt.Error(\"The token has expired, but the user was still validated!\")\n\t}\n\tt.Log(\"The token expired, and the user was succesfully reported Invalid.\")\n}",
"func isUFAExpired(ufaDetails map[string]interface{}) bool {\n\tif ufaDetails != nil {\n\t\traisedTotal := getSafeNumber(ufaDetails[\"raisedInvTotal\"])\n\t\ttotalCharge := getSafeNumber(ufaDetails[\"netCharge\"])\n\t\ttolerance := getSafeNumber(ufaDetails[\"chargTolrence\"])\n\t\tmaxCharge := totalCharge + (totalCharge * tolerance / 100)\n\t\treturn !(raisedTotal < maxCharge)\n\t}\n\treturn true\n}",
"func (err *ValidationError) IsExpired() bool { return err.exp }",
"func TestPacketDropIsExpired(t *testing.T) {\n\texpiredTime := util.GetExpiredTimeInString(util.DefaultPacketDropExpirationMinutes, PacketDropLogTimeLayout)\n\texpiredPacketDrop := PacketDrop{LogTime: expiredTime}\n\tif !expiredPacketDrop.IsExpired() {\n\t\tt.Fatal(\"Expected IsExpired() return true, got false\")\n\t}\n\n\tcurTime := time.Now().Format(PacketDropLogTimeLayout)\n\tcurPacketDrop := PacketDrop{LogTime: curTime}\n\tif curPacketDrop.IsExpired() {\n\t\tt.Fatal(\"Expected IsExpired() return false, got true\")\n\t}\n\n}",
"func (me TGetReviewableHITsSortProperty) IsExpiration() bool { return me.String() == \"Expiration\" }",
"func isExpired(cli *clientv3.Client, ev *clientv3.Event) (bool, error) {\n\tif ev.PrevKv == nil {\n\t\treturn false, nil\n\t}\n\n\tleaseID := clientv3.LeaseID(ev.PrevKv.Lease)\n\tif leaseID == clientv3.NoLease {\n\t\treturn false, nil\n\t}\n\n\tttlResponse, err := cli.TimeToLive(context.Background(), leaseID)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn ttlResponse.TTL == -1, nil\n}",
"func TestVerifyExpired(t *testing.T) {\n\toptions := iniVerifyOptions(t)\n\toptions.CurrentTime = time.Date(2020, 01, 01, 01, 01, 01, 0, gmt)\n\n\tp := loadProxy(\"test-samples/RfcProxy.pem\", t)\n\tif e := p.Verify(options); e == nil {\n\t\tt.Error(\"Verification must fail\")\n\t} else {\n\t\tt.Log(e)\n\t}\n}",
"func (me TEventType) IsHITExpired() bool { return me.String() == \"HITExpired\" }",
"func (me TSearchHITsSortProperty) IsExpiration() bool { return me.String() == \"Expiration\" }",
"func (r *OperationReqReconciler) isExpired(request *userv1.Operationrequest) bool {\n\tif request.Status.Phase != userv1.RequestCompleted && request.CreationTimestamp.Add(r.expirationTime).Before(time.Now()) {\n\t\tr.Logger.Info(\"operation request is expired\", \"name\", request.Name)\n\t\treturn true\n\t}\n\treturn false\n}",
"func (dbi *DbItem) expired() bool {\n\treturn dbi.opts != nil && dbi.opts.ex && time.Now().After(dbi.opts.exat)\n}",
"func checkExpiredAt(exp time.Time) bool {\n\treturn time.Now().UTC().Unix() < exp.UTC().Unix()\n}",
"func (r IABResponse) IsExpired() bool {\n\tswitch {\n\tcase !r.IsValidSubscription():\n\t\treturn false\n\tdefault:\n\t\tnow := time.Now().UnixNano() / int64(time.Millisecond)\n\t\treturn r.SubscriptionPurchase.ExpiryTimeMillis < now\n\t}\n}",
"func (m *VaultCredsProvider) IsExpired() bool {\n\treturn false\n}",
"func (dc *DelegatedCredential) isExpired(start, now time.Time) bool {\n\tend := start.Add(dc.cred.validTime)\n\treturn !now.Before(end)\n}",
"func TestUnitRefreshExpiration(t *testing.T) {\n\tinitConfig()\n\n\tConvey(\"Given I have some session data\", t, func() {\n\n\t\tvar sessionData Session = map[string]interface{}{\n\t\t\t\"signin_info\": map[string]interface{}{\n\t\t\t\t\"access_token\": map[string]interface{}{},\n\t\t\t},\n\t\t\t\"expires\": 5,\n\t\t}\n\n\t\tConvey(\"When I call RefreshExpiration\", func() {\n\n\t\t\tsessionData.RefreshExpiration()\n\n\t\t\tConvey(\"Then 'expires' should be set\", func() {\n\n\t\t\t\tSo(sessionData.getExpiry(), ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n\n\tcleanupConfig()\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Callback sends the CallbackRequest type to the configured StatusCallbackUrl. If it fails to deliver in n attempts or the request is invalid it will return an error.
|
func Callback(cbReq *CallbackRequest, opts *CallbackOptions) error {
client := opts.Client
if client == nil {
client = http.DefaultClient
}
buf := bytes.NewBuffer(nil)
err := json.NewEncoder(buf).Encode(cbReq)
if err != nil {
return err
}
signature, err := opts.Signer.Sign(buf.Bytes())
if err != nil {
return err
}
req, err := http.NewRequest("POST", cbReq.StatusCallbackUrl, buf)
if err != nil {
return err
}
req.Header.Set("X-OpenGDPR-Processor-Domain", opts.ProcessorDomain)
req.Header.Set("X-OpenGDPR-Signature", signature)
// Attempt to make callback
for i := 0; i < opts.MaxAttempts; i++ {
resp, err := client.Do(req)
if err != nil || resp.StatusCode != 200 {
time.Sleep(opts.Backoff)
continue
}
// Success
return nil
}
return fmt.Errorf("callback timed out for %s", cbReq.StatusCallbackUrl)
}
|
[
"func (client *Client) ServiceStatusWithCallback(request *ServiceStatusRequest, callback func(response *ServiceStatusResponse, err error)) (<-chan int) {\nresult := make(chan int, 1)\nerr := client.AddAsyncTask(func() {\nvar response *ServiceStatusResponse\nvar err error\ndefer close(result)\nresponse, err = client.ServiceStatus(request)\ncallback(response, err)\nresult <- 1\n})\nif err != nil {\ndefer close(result)\ncallback(nil, err)\nresult <- 0\n}\nreturn result\n}",
"func (client *Client) UpdateNumberStatusWithCallback(request *UpdateNumberStatusRequest, callback func(response *UpdateNumberStatusResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *UpdateNumberStatusResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.UpdateNumberStatus(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}",
"func callback(\n\tservice models.DeviceService,\n\tid string,\n\taction string,\n\tactionType models.ActionType,\n\tlc logger.LoggingClient) error {\n\n\tclient := &http.Client{}\n\turl := service.Addressable.GetCallbackURL()\n\tif len(url) > 0 {\n\t\tbody, err := getBody(id, actionType)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq, err := http.NewRequest(string(action), url, bytes.NewReader(body))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq.Header.Add(clients.ContentType, clients.ContentTypeJSON)\n\n\t\tgo makeRequest(client, req, lc)\n\t} else {\n\t\tlc.Info(\"callback::no addressable for \" + service.Name)\n\t}\n\treturn nil\n}",
"func CallbackHandler(callbackChan chan Callback) http.HandlerFunc {\n\treturn http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\tvar cb Callback\n\t\terr := cb.Parse(req)\n\t\tif err != nil {\n\t\t\tresp.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tresp.WriteHeader(http.StatusOK)\n\t\t// start seperate goroutine to allow http request to return.\n\t\tgo func() {\n\t\t\tcallbackChan <- cb\n\t\t}()\n\t})\n}",
"func (cioLite CioLite) CreateStatusCallbackURL(formValues CreateStatusCallbackURLParams) (CreateDeleteStatusCallbackURLResponse, error) {\n\n\t// Make request\n\trequest := clientRequest{\n\t\tMethod: \"POST\",\n\t\tPath: \"/app/status_callback_url\",\n\t\tFormValues: formValues,\n\t}\n\n\t// Make response\n\tvar response CreateDeleteStatusCallbackURLResponse\n\n\t// Request\n\terr := cioLite.doFormRequest(request, &response)\n\n\treturn response, err\n}",
"func (cioLite CioLite) GetStatusCallbackURL() (GetStatusCallbackURLResponse, error) {\n\n\t// Make request\n\trequest := clientRequest{\n\t\tMethod: \"GET\",\n\t\tPath: \"/app/status_callback_url\",\n\t}\n\n\t// Make response\n\tvar response GetStatusCallbackURLResponse\n\n\t// Request\n\terr := cioLite.doFormRequest(request, &response)\n\n\treturn response, err\n}",
"func HandleCallback(cb mock.Callback) (*http.Response, error) {\n\tif d := cb.Delay.Duration; d > 0 {\n\t\tlog.Printf(\"Delaying callback by: %s\\n\", d)\n\t\ttime.Sleep(d)\n\t}\n\n\turl := cb.Url\n\tlog.Printf(\"Making callback to %s\\n\", url)\n\treq, err := http.NewRequest(cb.Method, url, bytes.NewBufferString(cb.Body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating HTTP request: %w\", err)\n\t}\n\t// add headers\n\tfor h, vs := range cb.Headers {\n\t\tfor _, v := range vs {\n\t\t\treq.Header.Set(h, v)\n\t\t}\n\t}\n\n\t// Default timeout 10s\n\ttimeout := time.Second * 10\n\tif cb.Timeout.Duration > 0 {\n\t\ttimeout = cb.Timeout.Duration\n\t}\n\tclient := &http.Client{Timeout: timeout}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error making HTTP request: %w\", err)\n\t}\n\tstatusCode := resp.StatusCode\n\tif statusCode >= 400 {\n\t\tbody, errBody := ioutil.ReadAll(resp.Body)\n\t\tif errBody != nil {\n\t\t\t// Can't read a body, just log the statusCode\n\t\t\terr = fmt.Errorf(\"Unexpected HTTP response. Status code %d\", statusCode)\n\t\t\treturn resp, err\n\t\t}\n\n\t\t// Include the response body\n\t\terr = fmt.Errorf(\"Unexpected HTTP response. Status code %d, Body %s\", statusCode, body)\n\t\treturn resp, err\n\t}\n\treturn resp, nil\n}",
"func (cioLite CioLite) DeleteStatusCallbackURL() (CreateDeleteStatusCallbackURLResponse, error) {\n\n\t// Make request\n\trequest := clientRequest{\n\t\tMethod: \"DELETE\",\n\t\tPath: \"/app/status_callback_url\",\n\t}\n\n\t// Make response\n\tvar response CreateDeleteStatusCallbackURLResponse\n\n\t// Request\n\terr := cioLite.doFormRequest(request, &response)\n\n\treturn response, err\n}",
"func (api *APIServer) successCallback(ctx context.Context, callback callbackFn) {\n\tpayload := &CallbackResponse{\n\t\tStatus: \"success\",\n\t\tError: \"\",\n\t}\n\tfor _, e := range callback(ctx, payload) {\n\t\tapi.log.Error(e.Error())\n\t}\n}",
"func CallbackHandler(callbackChan chan Callback) http.HandlerFunc {\n\treturn http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\tvar cb Callback\n\t\tcb.Parse(req)\n\t\tresp.WriteHeader(http.StatusOK)\n\t\tgo func() {\n\t\t\tcallbackChan <- cb\n\t\t}()\n\t})\n}",
"func (client *Client) QueryCustomerAddressListWithCallback(request *QueryCustomerAddressListRequest, callback func(response *QueryCustomerAddressListResponse, err error)) (<-chan int) {\nresult := make(chan int, 1)\nerr := client.AddAsyncTask(func() {\nvar response *QueryCustomerAddressListResponse\nvar err error\ndefer close(result)\nresponse, err = client.QueryCustomerAddressList(request)\ncallback(response, err)\nresult <- 1\n})\nif err != nil {\ndefer close(result)\ncallback(nil, err)\nresult <- 0\n}\nreturn result\n}",
"func (c *SearchCall) Callback(callback string) *SearchCall {\n\tc.urlParams_.Set(\"callback\", callback)\n\treturn c\n}",
"func (client *Client) OperateLorneTaskStatusWithCallback(request *OperateLorneTaskStatusRequest, callback func(response *OperateLorneTaskStatusResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *OperateLorneTaskStatusResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.OperateLorneTaskStatus(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}",
"func Callback(c *gin.Context) {\n\tprovider := c.Param(\"provider\")\n\n\tvar logincode vo.LoginReq\n\tif err := c.ShouldBindQuery(&logincode); err != nil {\n\t\tfmt.Println(\"xxxx\", err)\n\t}\n\n\tfmt.Println(\"provider\", provider, logincode)\n\n\tuserInfo := vo.GetUserInfoFromOauth(provider, logincode.Code, logincode.State)\n\tfmt.Println(\"get user info\", userInfo)\n\n\tif userInfo == nil {\n\t\tc.JSON(http.StatusOK, sailor.HTTPAirdbResponse{\n\t\t\tCode: enum.AirdbSuccess,\n\t\t\tSuccess: true,\n\t\t\tData: vo.LoginResp{\n\t\t\t\tNickname: \"xxx\",\n\t\t\t\tHeadimgurl: \"xxx.png\",\n\t\t\t},\n\t\t})\n\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, sailor.HTTPAirdbResponse{\n\t\tCode: enum.AirdbSuccess,\n\t\tSuccess: true,\n\t\tData: vo.LoginResp{\n\t\t\tNickname: userInfo.Login,\n\t\t\tHeadimgurl: userInfo.AvatarURL,\n\t\t},\n\t})\n}",
"func (client *Client) GetCustomerAccountInfoWithCallback(request *GetCustomerAccountInfoRequest, callback func(response *GetCustomerAccountInfoResponse, err error)) (<-chan int) {\nresult := make(chan int, 1)\nerr := client.AddAsyncTask(func() {\nvar response *GetCustomerAccountInfoResponse\nvar err error\ndefer close(result)\nresponse, err = client.GetCustomerAccountInfo(request)\ncallback(response, err)\nresult <- 1\n})\nif err != nil {\ndefer close(result)\ncallback(nil, err)\nresult <- 0\n}\nreturn result\n}",
"func parseCallback(r *http.Request, cb *callback) (int, error) {\n\tdefer func() {\n\t\terr := r.Body.Close()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"body close: %v\", err)\n\t\t}\n\t}()\n\n\tcontentType := r.Header.Get(\"Content-Type\")\n\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tswitch contentType {\n\t\tcase \"application/json\":\n\t\t\t// unmarshall JSON to callback struct\n\t\t\tdecoder := json.NewDecoder(r.Body)\n\t\t\tif err := decoder.Decode(cb); err != nil {\n\t\t\t\treturn http.StatusBadRequest, err\n\t\t\t}\n\n\t\tdefault:\n\t\t\treturn http.StatusBadRequest, fmt.Errorf(\"Unsupported content type: %s\", contentType)\n\t\t}\n\n\tdefault:\n\t\treturn http.StatusMethodNotAllowed, fmt.Errorf(\"Unsupported request method: %s\", r.Method)\n\t}\n\n\treturn 0, nil\n}",
"func (h *GitHubOAuth) Callback(c *router.Control) {\n\tstate := c.Get(\"state\")\n\tcode := c.Get(\"code\")\n\n\tif state != h.state {\n\t\th.log.Errorf(\"Wrong state %s with code %s\", state, code)\n\t\thttp.Redirect(c.Writer, c.Request, \"/\", http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tctx := context.Background()\n\ttoken, err := h.oAuthConf.Exchange(ctx, code)\n\n\tif err != nil {\n\t\th.log.Errorf(\"Exchange failed for code %s: %+v\", code, err)\n\t\thttp.Redirect(c.Writer, c.Request, \"/\", http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\toauthClient := h.oAuthConf.Client(ctx, token)\n\tgithubClient := ghClient.NewClient(oauthClient)\n\tuser, _, err := githubClient.Users.Get(ctx, \"\")\n\tif err != nil || user.Login == nil {\n\t\th.log.Errorf(\"Couldn't get user for code %s: %+v\", code, err)\n\t\thttp.Redirect(c.Writer, c.Request, \"/\", http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\th.log.WithField(\"user\", *user.Login).Info(\"GitHub user was authorized in oauth-proxy\")\n\n\tsessionData := session.NewSessionOptions(&session.SessOptions{\n\t\tCAttrs: map[string]interface{}{\"Login\": *user.Login, \"Source\": models.SourceGitHub},\n\t\tAttrs: map[string]interface{}{\"Activated\": false, \"HasError\": false},\n\t})\n\tsession.Add(sessionData, c.Writer)\n\n\tgo h.syncUser(*user.Login, sessionData, c.Writer)\n\n\thttp.Redirect(c.Writer, c.Request, \"/\", http.StatusMovedPermanently)\n}",
"func (s *Service) SendCallbackRetry(c context.Context, cb *model.Callback, payload *model.Payload) (err error) {\n\tattempts := 3\n\tfor i := 0; i < attempts; i++ {\n\t\terr = s.dao.SendCallback(c, cb, payload)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\n\t\tif i >= (attempts - 1) {\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(time.Second * 1)\n\t}\n\treturn errors.Wrapf(err, \"after %d attempts\", attempts)\n}",
"func CallbackUrl(val string) Argument {\n\treturn func(request *requests.Request) error {\n\t\tif len(val) > 256 {\n\t\t\treturn errors.New(\"callback url too long, max 256 caracteres\")\n\t\t}\n\t\trequest.AddArgument(\"callback_url\", val)\n\t\treturn nil\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Add indexes into MongoDB
|
func addIndexes() {
var err error
ufIndex1 := mgo.Index{
Key: []string{"codigo"},
Unique: true,
Background: true,
Sparse: true,
}
municipioIndex1 := mgo.Index{
Key: []string{"codigo"},
Unique: true,
Background: true,
Sparse: true,
}
// Add indexes into MongoDB
session := Session.Copy()
defer session.Close()
ufCol := session.DB(commons.AppConfig.Database).C("ufs")
municipioCol := session.DB(commons.AppConfig.Database).C("municipios")
// cria indice codigo para UF
err = ufCol.EnsureIndex(ufIndex1)
if err != nil {
log.Fatalf("[addIndexes]: %s\n", err)
}
log.Println("Indice para UF criado com sucesso")
// cria indice codigo para Municipio
err = municipioCol.EnsureIndex(municipioIndex1)
if err != nil {
log.Fatalf("[addIndexes]: %s\n", err)
}
log.Println("Indice para Municipio criado com sucesso")
}
|
[
"func addIndexes() {\n\tvar err error\n\tuserIndex := mgo.Index{\n\t\tKey: []string{\"email\"},\n\t\tUnique: true,\n\t\tBackground: true,\n\t\tSparse: true,\n\t}\n\n\tauthIndex := mgo.Index{\n\t\tKey: []string{\"sender_id\"},\n\t\tUnique: true,\n\t\tBackground: true,\n\t\tSparse: true,\n\t}\n\n\t// Add indexes into MongoDB\n\tsession := GetSession().Copy()\n\tdefer session.Close()\n\tuserCol := session.DB(AppConfig.MongoDBName).C(\"users\")\n\tauthCol := session.DB(AppConfig.MongoDBName).C(\"auth\")\n\n\terr = userCol.EnsureIndex(userIndex)\n\tif err != nil {\n\t\tlog.Fatalf(\"[addIndexes]: %s\\n\", err)\n\t}\n\n\terr = authCol.EnsureIndex(authIndex)\n\tif err != nil {\n\t\tlog.Fatalf(\"[addIndexes]: %s\\n\", err)\n\t}\n\n}",
"func (api *Api) createIndexes() {\n\t// username and email will be unique.\n\tkeys := bsonx.Doc{\n\t\t{Key: \"username\", Value: bsonx.Int32(1)},\n\t\t{Key: \"email\", Value: bsonx.Int32(1)},\n\t}\n\tpeople := api.DB.Collection(\"people\")\n\tdb.SetIndexes(people, keys)\n}",
"func (db *Mongo) Index() error {\n\t// if err := db.Dirs().DropAllIndexes(); err != nil {\n\t// \treturn err\n\t// }\n\tidx := mgo.Index{\n\t\tKey: []string{\"email\"},\n\t\tUnique: true,\n\t\tDropDups: true,\n\t\tName: \"user_email_index\",\n\t}\n\t// user indexes\n\tif err := db.Users().EnsureIndex(idx); err != nil {\n\t\treturn err\n\t}\n\n\tidx = mgo.Index{\n\t\tKey: []string{\"removed\", \"name\"},\n\t\tName: \"user_name_index\",\n\t}\n\t// user indexes\n\tif err := db.Users().EnsureIndex(idx); err != nil {\n\t\treturn err\n\t}\n\n\tidx = mgo.Index{\n\t\tKey: []string{\"removed\", \"title\", \"description\", \"createdBy\"},\n\t\tName: \"todos_index\",\n\t}\n\t// todo indexes\n\tif err := db.Todos().EnsureIndex(idx); err != nil {\n\t\treturn err\n\t}\n\n\tidx = mgo.Index{\n\t\tKey: []string{\"removed\", \"title\", \"createdBy\"},\n\t\tName: \"directory_index\",\n\t}\n\t// directory indexes\n\treturn db.Dirs().EnsureIndex(idx)\n}",
"func (b *Backend) createMongoIndexes() error {\n\top, err := b.connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn op.Do(func() error {\n\t\tindexes := []mgo.Index{\n\t\t\t{\n\t\t\t\tKey: []string{\"state\"},\n\t\t\t\tBackground: true, // can be used while index is being built\n\t\t\t\tExpireAfter: time.Duration(b.GetConfig().ResultsExpireIn) * time.Second,\n\t\t\t},\n\t\t\t{\n\t\t\t\tKey: []string{\"lock\"},\n\t\t\t\tBackground: true, // can be used while index is being built\n\t\t\t\tExpireAfter: time.Duration(b.GetConfig().ResultsExpireIn) * time.Second,\n\t\t\t},\n\t\t}\n\n\t\tfor _, index := range indexes {\n\t\t\t// Check if index already exists, if it does, skip\n\t\t\tif err := op.tasksCollection.EnsureIndex(index); err == nil {\n\t\t\t\tlog.INFO.Printf(\"%s index already exist, skipping create step\", index.Key[0])\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Create index (keep in mind EnsureIndex is blocking operation)\n\t\t\tlog.INFO.Printf(\"Creating %s index\", index.Key[0])\n\t\t\tif err := op.tasksCollection.DropIndex(index.Key[0]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := op.tasksCollection.EnsureIndex(index); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}",
"func ConfigureIndexes(mClient *mongo.Client) {\n\tcollection := getMarkdownCollection(mClient)\n\n\tindex := []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bsonx.Doc{\n\t\t\t\t{Key: \"title\", Value: bsonx.String(\"text\")},\n\t\t\t\t{Key: \"body\", Value: bsonx.String(\"text\")},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tKeys: bsonx.Doc{{Key: \"createDate\", Value: bsonx.Int32(1)}},\n\t\t},\n\t}\n\tname, err := collection.Indexes().CreateMany(context.TODO(), index)\n\tif err != nil {\n\t\tfmt.Printf(\"Error Creating Text Index: %s\", err)\n\t\treturn\n\t}\n\tfmt.Printf(\"Index Created: %s\\n\", name)\n}",
"func DbIndexes(collection string) []IndexModel {\n\tcursor, err := db.Collection(collection).Indexes().List(context.TODO())\n\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n\n\tdbIndexes := make([]IndexModel, 0)\n\n\tfor cursor.Next(context.TODO()) {\n\t\tsrc := bson.D{}\n\t\tvar dst IndexModel\n\n\t\tif err := cursor.Decode(&src); err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t}\n\n\t\tfor _, s := range src {\n\t\t\tswitch s.Key {\n\t\t\tcase \"name\":\n\t\t\t\tdst.Name = s.Value.(string)\n\t\t\tcase \"key\":\n\t\t\t\tvar keys bson.D\n\t\t\t\tkeysByte, _ := bson.Marshal(s.Value)\n\t\t\t\tif err := bson.Unmarshal(keysByte, &keys); err != nil {\n\t\t\t\t\tlog.Fatalf(\"unmarshal bson key: %v\", err)\n\t\t\t\t}\n\t\t\t\tfor _, k := range keys {\n\t\t\t\t\tdst.Key = append(dst.Key, map[string]int32{\n\t\t\t\t\t\tk.Key: k.Value.(int32),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\tcase \"unique\":\n\t\t\t\tdst.Unique = s.Value.(bool)\n\t\t\tcase \"expireAfterSeconds\":\n\t\t\t\tvar v int32\n\t\t\t\tswitch sv := s.Value.(type) {\n\t\t\t\tcase int32:\n\t\t\t\t\tv = sv\n\t\t\t\tcase int64:\n\t\t\t\t\tif sv > int64(math.MaxInt32) {\n\t\t\t\t\t\tlog.Fatalf(\"unpexpected expireAfterSeconds %d (must be <= MaxInt32) [%s.%s] %v\", sv, db.Name(), collection, src)\n\t\t\t\t\t}\n\t\t\t\t\tv = int32(sv)\n\t\t\t\t}\n\t\t\t\tdst.ExpireAfterSeconds = &v\n\t\t\tcase \"sparse\":\n\t\t\t\tdst.Sparse = s.Value.(bool)\n\t\t\t}\n\t\t}\n\t\t// ignore the _id_ index as it's the default index\n\t\tif dst.Name == \"_id_\" {\n\t\t\tcontinue\n\t\t}\n\t\tdbIndexes = append(dbIndexes, dst)\n\t}\n\n\treturn dbIndexes\n}",
"func SetIndexes(collection *mongo.Collection, keys bsonx.Doc) {\n\tindex := mongo.IndexModel{}\n\tindex.Keys = keys\n\tunique := true\n\tindex.Options = &options.IndexOptions{\n\t\tUnique: &unique,\n\t}\n\topts := options.CreateIndexes().SetMaxTime(10 * time.Second)\n\t_, err := collection.Indexes().CreateOne(context.Background(), index, opts)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while creating indexs: %v\", err)\n\t}\n}",
"func AddIndex(db MongoDB, m metrics.Metrics, col string, indexes ...mgo.Index) error {\n\tdefer m.CollectMetrics(\"DB.AddIndex\")\n\n\tif len(indexes) == 0 {\n\t\treturn nil\n\t}\n\n\tdatabase, session, err := db.New(false)\n\tif err != nil {\n\t\tm.Emit(metrics.Errorf(\"Failed to create session for index\"), metrics.With(\"collection\", col), metrics.With(\"error\", err.Error()))\n\t\treturn err\n\t}\n\n\tdefer session.Close()\n\n\tcollection := database.C(col)\n\n\tfor _, index := range indexes {\n\t\tif err := collection.EnsureIndex(index); err != nil {\n\t\t\tm.Emit(metrics.Errorf(\"Failed to ensure session index\"), metrics.With(\"collection\", col), metrics.With(\"index\", index), metrics.With(\"error\", err.Error()))\n\t\t\treturn err\n\t\t}\n\n\t\tm.Emit(metrics.Info(\"Succeeded in ensuring collection index\"), metrics.With(\"collection\", col), metrics.With(\"index\", index))\n\t}\n\n\tm.Emit(metrics.Info(\"Finished adding index\"), metrics.With(\"collection\", col))\n\treturn nil\n}",
"func (b *Bucket) createIndexes(ctx context.Context) error {\n\t// must use primary read pref mode to check if files coll empty\n\tcloned, err := b.filesColl.Clone(options.Collection().SetReadPreference(readpref.Primary()))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdocRes := cloned.FindOne(ctx, bson.D{}, options.FindOne().SetProjection(bson.D{{\"_id\", 1}}))\n\n\t_, err = docRes.DecodeBytes()\n\tif err != mongo.ErrNoDocuments {\n\t\t// nil, or error that occurred during the FindOne operation\n\t\treturn err\n\t}\n\n\tfilesIv := b.filesColl.Indexes()\n\tchunksIv := b.chunksColl.Indexes()\n\n\tfilesModel := mongo.IndexModel{\n\t\tKeys: bson.D{\n\t\t\t{\"filename\", int32(1)},\n\t\t\t{\"uploadDate\", int32(1)},\n\t\t},\n\t}\n\n\tchunksModel := mongo.IndexModel{\n\t\tKeys: bson.D{\n\t\t\t{\"files_id\", int32(1)},\n\t\t\t{\"n\", int32(1)},\n\t\t},\n\t\tOptions: options.Index().SetUnique(true),\n\t}\n\n\tif err = createNumericalIndexIfNotExists(ctx, filesIv, filesModel); err != nil {\n\t\treturn err\n\t}\n\treturn createNumericalIndexIfNotExists(ctx, chunksIv, chunksModel)\n}",
"func CreateIndexes(collections []models.Collection) {\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tfor _, collection := range collections {\n\t\tmodels := []mongo.IndexModel{}\n\n\t\tfor _, field := range collection.Fields {\n\t\t\tmodels = append(models, mongo.IndexModel{\n\t\t\t\tKeys: bson.M{field.FieldName: 1},\n\t\t\t\tOptions: options.Index().SetUnique(field.Unique),\n\t\t\t})\n\t\t}\n\n\t\tdatabase := ConnectDB().Database(utils.Config.DatabaseName).Collection(collection.CollectionName)\n\t\t_, err := database.Indexes().CreateMany(ctx, models)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t}\n}",
"func addUserIndexes(db *mgo.Session) error {\n\tsession := db.Copy()\n\tdefer session.Close()\n\tc := session.DB(\"\").C(userCollection)\n\ti := mgo.Index{\n\t\tKey: []string{\"phone\"},\n\t\tUnique: true,\n\t}\n\terr := c.EnsureIndex(i)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to add index: %v\", err)\n\t}\n\n\treturn nil\n}",
"func TestBaseModel_EnsureIndexes(t *testing.T) {\n\tconfig := mongo.Configuration{\n\t\tURL: \"mongodb://localhost:27017/some-test-db\",\n\t\tUseSSL: false,\n\t\tSSLCert: []byte{},\n\t\tPingFrequency: 100,\n\t}\n\n\tdb, teardown := mongo.InitMongoFromConfig(config)\n\tdefer teardown()\n\n\t// initialize the collection..\n\tdb.C(\"some-collection\").Insert(&testDocument{})\n\n\tmodel := &BaseModel{\n\t\tDB: db,\n\t\tCollectionName: \"some-collection\",\n\t\tIndexes: []*mgo.Index{\n\t\t\t{\n\t\t\t\tUnique: true,\n\t\t\t\tName: \"test_1\",\n\t\t\t\tKey: []string{\"first_key\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tEnsureIndexes([]Model{model}, false)\n\n\tindexes, err := db.C(\"some-collection\").Indexes()\n\tassert.Nil(t, err)\n\tassert.Equal(t, []mgo.Index{\n\t\t{Key: []string{\"_id\"}, Name: \"_id_\"},\n\t\t{Key: []string{\"first_key\"}, Name: \"test_1\", Unique: true},\n\t}, indexes)\n}",
"func (c *Collection) addIndex(schema *jsonschema.Schema, index Index, opts ...Option) error {\n\targs := &Options{}\n\tfor _, opt := range opts {\n\t\topt(args)\n\t}\n\n\t// Don't allow the default index to be overwritten\n\tif index.Path == idFieldName {\n\t\tif _, ok := c.indexes[idFieldName]; ok {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// Validate path and type.\n\tjt, err := getSchemaTypeAtPath(schema, index.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar valid bool\n\tfor _, t := range indexTypes {\n\t\tif jt.Type == t {\n\t\t\tvalid = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !valid {\n\t\treturn ErrNotIndexable\n\t}\n\n\t// Skip if nothing to do\n\tif x, ok := c.indexes[index.Path]; ok && index.Unique == x.Unique {\n\t\treturn nil\n\t}\n\n\t// Ensure collection does not contain multiple instances with the same value at path\n\tif index.Unique && index.Path != idFieldName {\n\t\tvals := make(map[interface{}]struct{})\n\t\tall, err := c.Find(&Query{}, WithTxnToken(args.Token))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, i := range all {\n\t\t\tres := gjson.GetBytes(i, index.Path)\n\t\t\tif !res.Exists() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, ok := vals[res.Value()]; ok {\n\t\t\t\treturn ErrCantCreateUniqueIndex\n\t\t\t} else {\n\t\t\t\tvals[res.Value()] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\n\tc.indexes[index.Path] = index\n\treturn c.saveIndexes()\n}",
"func (m *DataRepositoryMongo) CreateIndex(collectionName string, indexes map[string]interface{}) <-chan error {\n\tresult := make(chan error)\n\tgo func() {\n\n\t\tvar (\n\t\t\terr error\n\t\t\tcollection *mongo.Collection\n\t\t\tctx context.Context\n\t\t)\n\n\t\tcollection, err = m.Client.GetCollection(collectionName)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Get collection %s err (%s)! \\n\", collectionName, err.Error())\n\t\t\tresult <- err\n\t\t}\n\n\t\tctx, err = m.Client.GetContext()\n\t\tif err != nil {\n\t\t\tlog.Error(\"Get context err (%s)! \\n\", err.Error())\n\t\t\tresult <- err\n\t\t}\n\n\t\tvar indexList []mongo.IndexModel\n\n\t\tfor key, value := range indexes {\n\t\t\tindexOption := &options.IndexOptions{}\n\t\t\tindexOption = indexOption.SetBackground(true)\n\t\t\tindex := mongo.IndexModel{Keys: bson.M{key: value}, Options: indexOption}\n\t\t\tindexList = append(indexList, index)\n\t\t}\n\n\t\t_, err = collection.Indexes().CreateMany(ctx, indexList)\n\t\tresult <- err\n\t\tclose(result)\n\t}()\n\n\treturn result\n}",
"func (t *table) addIndices(tx *sql.Tx) (err error) {\n\tfor _, c := range t.columns {\n\t\tif !c.index {\n\t\t\tcontinue\n\t\t}\n\n\t\tcol := c.name\n\t\tif c.name == \"title\" {\n\t\t\tcol = fmt.Sprintf(\"LOWER(%v)\", col)\n\t\t}\n\n\t\tvar using string\n\t\tif c.t == \"jsonb\" {\n\t\t\tusing = \"USING gin\"\n\t\t}\n\n\t\tidx := fmt.Sprintf(`CREATE INDEX %v ON %v %v (%v)`, t.indexName(t.temporary, c.name), t.temporary, using, col)\n\t\tif _, err = tx.Exec(idx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn err\n}",
"func updateDBIndexes(mi *modelInfo) {\n\tadapter := adapters[db.DriverName()]\n\t// update column indexes\n\tfor colName, fi := range mi.fields.registryByJSON {\n\t\tif !fi.index {\n\t\t\tcontinue\n\t\t}\n\t\tif !adapter.indexExists(mi.tableName, fmt.Sprintf(\"%s_%s_index\", mi.tableName, colName)) {\n\t\t\tcreateColumnIndex(mi.tableName, colName)\n\t\t}\n\t}\n}",
"func EnsureIndex(cd *mongo.Collection, indexQuery []string) error {\n\n\t// options for index\n\topts := options.CreateIndexes().SetMaxTime(5 * time.Second)\n\n\t// index model\n\tindex := []mongo.IndexModel{}\n\n\t// creating multiple index query\n\tfor _, val := range indexQuery {\n\t\ttemp := mongo.IndexModel{}\n\t\ttemp.Keys = bsonx.Doc{{Key: val, Value: bsonx.Int32(1)}}\n\t\tindex = append(index, temp)\n\t}\n\n\t// executng index query\n\t_, err := cd.Indexes().CreateMany(context.Background(), index, opts)\n\tif err != nil {\n\t\tfmt.Errorf(\"Error while executing index Query\", err.Error())\n\t\treturn err\n\t}\n\n\t// if executed successfully then return nil\n\treturn nil\n}",
"func (c *Collection) indexAdd(tx ds.Txn, key ds.Key, data []byte) error {\n\tfor path, index := range c.indexes {\n\t\terr := c.indexUpdate(path, index, tx, key, data, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}",
"func (m *MongoDB) CreateIndex(name, key string, order int) (string, error) {\n\tcoll, ok := m.coll[name]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"not defined collection %s\", name)\n\t}\n\n\tasscending := 1\n\tif order == -1 {\n\t\tasscending = -1\n\t}\n\n\tmodel := mongo.IndexModel{\n\t\tKeys: bson.D{{Key: key, Value: asscending}},\n\t\t//Options: options.Index().SetBackground(true),\n\t}\n\n\topts := options.CreateIndexes().SetMaxTime(2 * time.Second)\n\n\treturn coll.Indexes().CreateOne(m.ctx, model, opts)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewAccessTokenHandlerFactory return new fake access token handler factory
|
func NewAccessTokenHandlerFactory(userIDFactory UserIDFactory) middleware.AccessTokenHandlerFactory {
return &accessTokenHandlerFactory{
userIDFactory: userIDFactory,
}
}
|
[
"func CreateAccessTokenPostHandler(appCtx *appctx.Context) http.Handler {\n\thandlerFunc := func(w http.ResponseWriter, r *http.Request, user *models.User) {\n\n\t\tif err := r.ParseForm(); err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tappCtx.RequestLogger().Error(r, err)\n\t\t\treturn\n\t\t}\n\n\t\tname := r.Form.Get(\"name\")\n\n\t\tif token, err := appCtx.TokensService().CreateToken(user.ID, name); err != nil {\n\t\t\tappCtx.Sessions().Flash(r, w, \"danger\", err.Error())\n\t\t} else {\n\t\t\tmsg := fmt.Sprintf(\"Your access token is %s\", token.Token)\n\t\t\tappCtx.Sessions().Flash(r, w, \"success\", msg)\n\t\t\tappCtx.Sessions().Flash(r, w, \"success\", \"This is the last time that your token will be displayed to you.\")\n\t\t}\n\n\t\thttp.Redirect(w, r, \"/profile/access-tokens\", http.StatusSeeOther)\n\t}\n\n\thandler := auth.WithUserOrRedirect(handlerFunc, appCtx)\n\n\thandler = middleware.HTMLHeaders(handler)\n\n\treturn handler\n}",
"func newAccessTokenServer(t *testing.T, data url.Values) *httptest.Server {\n\treturn newMockServer(func(w http.ResponseWriter, req *http.Request) {\n\t\tassert.Equal(t, \"POST\", req.Method)\n\t\tassert.NotEmpty(t, req.Header.Get(\"Authorization\"))\n\t\tparams := parseOAuthParamsOrFail(t, req.Header.Get(authorizationHeaderParam))\n\t\tassert.Equal(t, expectedVerifier, params[oauthVerifierParam])\n\t\tw.Header().Set(contentType, formContentType)\n\t\tw.Write([]byte(data.Encode()))\n\t})\n}",
"func (o *oauth) createTokenHandler(auth authable) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tuserId, err := auth.findUserId(extractCookie(r).Value)\n\t\tif err != nil {\n\t\t\t// user not found, return\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\trecords, err := o.clientStore.GetByUserID(userId)\n\t\tif err != nil && !strings.Contains(err.Error(), \"not found\") {\n\t\t\tinternalError(w, err, \"oauth\")\n\t\t\treturn\n\t\t}\n\t\tif len(records) == 0 { // nothing found, so fake one\n\t\t\trecords = append(records, &models.Client{})\n\t\t}\n\n\t\tclients := make([]*models.Client, len(records))\n\t\tfor i := range records {\n\t\t\terr = o.clientStore.DeleteByID(records[i].GetID())\n\t\t\tif err != nil && !strings.Contains(err.Error(), \"not found\") {\n\t\t\t\tinternalError(w, err, \"oauth\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tclients[i] = &models.Client{\n\t\t\t\tID: generateID()[:12],\n\t\t\t\tSecret: generateID(),\n\t\t\t\tDomain: Domain,\n\t\t\t\tUserID: userId,\n\t\t\t}\n\n\t\t\t// Write client into oauth clients db.\n\t\t\tif err := o.clientStore.Set(clients[i].GetID(), clients[i]); err != nil {\n\t\t\t\tinternalError(w, err, \"oauth\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// metrics\n\t\tclientGenerations.Add(1)\n\n\t\t// render back new client info\n\t\ttype response struct {\n\t\t\tClients []*models.Client `json:\"clients\"`\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\tif err := json.NewEncoder(w).Encode(&response{clients}); err != nil {\n\t\t\tinternalError(w, err, \"oauth\")\n\t\t\treturn\n\t\t}\n\t}\n}",
"func RFC7523AssertionGrantFactory(config *Config, storage interface{}, strategy interface{}) interface{} {\n\treturn &rfc7523.Handler{\n\t\tStorage: storage.(rfc7523.RFC7523KeyStorage),\n\t\tScopeStrategy: config.GetScopeStrategy(),\n\t\tAudienceMatchingStrategy: config.GetAudienceStrategy(),\n\t\tTokenURL: config.TokenURL,\n\t\tSkipClientAuth: config.GrantTypeJWTBearerCanSkipClientAuth,\n\t\tJWTIDOptional: config.GrantTypeJWTBearerIDOptional,\n\t\tJWTIssuedDateOptional: config.GrantTypeJWTBearerIssuedDateOptional,\n\t\tJWTMaxDuration: config.GetJWTMaxDuration(),\n\t\tHandleHelper: &oauth2.HandleHelper{\n\t\t\tAccessTokenStrategy: strategy.(oauth2.AccessTokenStrategy),\n\t\t\tAccessTokenStorage: storage.(oauth2.AccessTokenStorage),\n\t\t\tAccessTokenLifespan: config.GetAccessTokenLifespan(),\n\t\t},\n\t}\n}",
"func HandlerFactory(hf krakendgin.HandlerFactory, logger logging.Logger) krakendgin.HandlerFactory {\n\treturn func(configuration *config.EndpointConfig, proxy proxy.Proxy) gin.HandlerFunc {\n\t\tnext := hf(configuration, proxy)\n\n\t\tv := auth.ConfigGetter(configuration.ExtraConfig)\n\t\tif v == nil {\n\t\t\treturn next\n\t\t}\n\t\tcredentials, ok := v.(auth.Credentials)\n\t\tif !ok {\n\t\t\treturn next\n\t\t}\n\n\t\tvalidator := auth.NewCredentialsValidator(credentials)\n\t\tlogger.Info(\"COOKIE: enabled for the endpoint\", configuration.Endpoint)\n\n\t\treturn func(c *gin.Context) {\n\t\t\tcookie, err := c.Request.Cookie(credentials.Cookie)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Warning(\"COOKIE: unable to get cookie\", credentials.Cookie)\n\t\t\t\tc.String(http.StatusForbidden, \"no auth header\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tinfo, err := validator.IsValid(cookie.Value)\n\t\t\tif err != nil {\n\t\t\t\tc.String(http.StatusUnauthorized, \"wrong auth header\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tc.Request.Header.Set(\"X-Session-Id\", info.SessionId)\n\t\t\tc.Request.Header.Set(\"X-User-Id\", strconv.Itoa(info.UserId))\n\t\t\tnext(c)\n\t\t}\n\t}\n}",
"func HandlerClient(adapter TokenAdapter, c *TokenContext) (*TokenResponse, *Error) {\n\tvar jerr *Error\n\tc.Client, jerr = AuthClient(adapter, c)\n\tif jerr != nil {\n\t\treturn nil, jerr\n\t}\n\n\t// Request a new access token\n\tresponse := adapter.NewAccessToken(c)\n\tif response != nil {\n\t\tresponse.State = c.State\n\t}\n\n\treturn response, nil\n}",
"func NewAccessToken(name, issuer, clientID, scope string, persona *cpb.TestPersona) (ga4gh.AccessJWT, string, error) {\n\tnow := time.Now().Unix()\n\tsub := name\n\temail := name\n\tpatient := \"\"\n\tfhirUser := \"\"\n\tif persona != nil {\n\t\tif s := getStandardClaim(persona, \"sub\"); len(s) > 0 {\n\t\t\tsub = s\n\t\t\temail = s\n\t\t}\n\t\tif e := getStandardClaim(persona, \"email\"); len(e) > 0 {\n\t\t\temail = e\n\t\t}\n\t\tpatient = getStandardClaim(persona, \"patient\")\n\t\tfhirUser = getStandardClaim(persona, \"fhirUser\")\n\t}\n\tif len(scope) == 0 {\n\t\tscope = DefaultScope\n\t}\n\td := &ga4gh.AccessData{\n\t\tStdClaims: ga4gh.StdClaims{\n\t\t\tIssuer: issuer,\n\t\t\tSubject: sub,\n\t\t\tIssuedAt: now,\n\t\t\tExpiresAt: now + 10000,\n\t\t\tAudience: ga4gh.NewAudience(clientID),\n\t\t\tID: \"token-id-\" + name,\n\t\t},\n\t\tScope: scope,\n\t\tIdentities: map[string][]string{\n\t\t\temail: []string{\"IC\", \"DAM\"},\n\t\t},\n\t\tPatient: patient,\n\t\tFhirUser: fhirUser,\n\t}\n\n\tctx := context.Background()\n\tsigner := signer(&personaKey)\n\n\taccess, err := ga4gh.NewAccessFromData(ctx, d, signer)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\treturn access.JWT(), sub, nil\n}",
"func newOAuthAccessTokenWatcher(wrappedWatcher watch.Interface, username string) *OAuthAccessTokenWatcher {\n\treturn &OAuthAccessTokenWatcher{\n\t\twrappedWatcher: wrappedWatcher,\n\t\tincoming: wrappedWatcher.ResultChan(),\n\t\toutgoing: make(chan watch.Event),\n\t\tstopCh: make(chan struct{}),\n\t\tstopped: false,\n\n\t\tusername: username,\n\t}\n}",
"func NewUserAccessTokenHandler(base baseHandler) *UserAccessTokenHandler {\n\treturn &UserAccessTokenHandler{\n\t\tbaseHandler: base,\n\t}\n}",
"func NewAccessTokenServer(t *testing.T, json string) *httptest.Server {\n\treturn NewTestServerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tassert.Equal(t, \"POST\", req.Method)\n\t\tw.Header().Set(contentType, jsonContentType)\n\t\tw.Write([]byte(json))\n\t})\n}",
"func oauth2FactoryToken(w http.ResponseWriter, r *http.Request) {\n\tparas, incName := r.URL.Query(), mux.Vars(r)[\"incName\"]\n\t// if error parameter exists.\n\tif _, ok := paras[\"error\"]; ok {\n\t\thttp.Redirect(w, r, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\tform := url.Values{}\n\tform.Add(\"client_id\", oauth2Infos[incName].clientId)\n\tform.Add(\"client_secret\", oauth2Infos[incName].clientSecret)\n\tform.Add(\"code\", paras[\"code\"][0])\n\tform.Add(\"redirect_uri\", oauth2Infos[incName].redirectUrl)\t// the redirectUrl should be my host index\n\tform.Add(\"state\", incName)\n\n\tres, _ := http.Post(oauth2Infos[incName].tokenUrl, \"application/x-www-form-urlencoded\", strings.NewReader(form.Encode()))\n\tbody, _ := ioutil.ReadAll(res.Body)\n\tres, _ = http.Get(oauth2Infos[incName].infoUrl + \"?access_token=\" + jsonProcessString(string(body))[\"access_token\"])\n\tbody, _ = ioutil.ReadAll(res.Body)\n\t// Get the access_token and put user information to mydatabase\n\tinfos := &githubUser{}\n\tjson.Unmarshal(body, &infos)\n\tif users := SelectUser(map[string]interface{}{\"username\": infos.Login, \"source\": incName}); len(users) == 0 {\n\t\tgo AddUser(User{Source: incName, UserId: uuid.Must(uuid.NewV4()).String(), Username: infos.Login, Password: infos.Login, Avatar: infos.AvatarURL, InfoURL: infos.URL, Bio: infos.Bio})\n\t}\n\n\t// Later, we will marsh a better user info cookie.\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: \"user\",\n\t\tValue: infos.Login,\t// user struct json\n\t\tPath: \"/\",\n\t\tExpires: time.Now().AddDate(0, 1, 0),\n\t\tMaxAge: 86400,\t// 100 hours' validate time\n\t})\n\thttp.Redirect(w, r, \"/index\", http.StatusFound)\t\t// redirect to the index page\n}",
"func NewOAuthHandler(session string, dbName string) *OAuthHandler {\n\tsconfig := osin.NewServerConfig()\n\tsconfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.CODE, osin.TOKEN}\n\tsconfig.AllowedAccessTypes = osin.AllowedAccessType{osin.AUTHORIZATION_CODE,\n\t\tosin.REFRESH_TOKEN, osin.PASSWORD, osin.CLIENT_CREDENTIALS, osin.ASSERTION}\n\n\tsconfig.AllowClientSecretInParams = true\n\tsconfig.AllowGetAccessRequest = true\n\tstorage := NewTestStorage()\n\tserver := osin.NewServer(sconfig, storage)\n\treturn &OAuthHandler{sconfig, server, storage}\n\n}",
"func mockExpiredApplicationAccessToken(host string, statusCode int) {\r\n\thttpmock.Reset()\r\n\thttpmock.RegisterResponder(http.MethodPost, fmt.Sprintf(\"%s%s\", host, getAccessTokenURI),\r\n\t\thttpmock.NewStringResponder(\r\n\t\t\tstatusCode, `{\"code\": 0,\"msg\": \"\",\"data\": {\r\n\"access_token\": \"`+testAccessToken+`\",\r\n\"expires_in\": 1,\r\n\"token_type\": \"`+testTokenType+`\"}}`,\r\n\t\t),\r\n\t)\r\n}",
"func NewAccessHandler(logger *zap.Logger, oauth2Config oauth2.Config, verifier *oidc.IDTokenVerifier, state string) AccessHandler {\n\treturn &accessHandler{\n\t\tlogger: logger,\n\t\toauth2Config: oauth2Config,\n\t\tstate: state,\n\t\tverifier: verifier,\n\t}\n}",
"func mockGetUserAccessToken() {\r\n\thttpmock.RegisterResponder(http.MethodPost, fmt.Sprintf(\"%s%s\", testHost, getAccessTokenURI),\r\n\t\thttpmock.NewStringResponder(\r\n\t\t\thttp.StatusOK, `{\"code\": 0,\"msg\": \"\",\r\n \"data\": {\r\n \"access_token\": \"`+testUserAccessToken+`\",\r\n \"expires_in\": `+fmt.Sprintf(\"%d\", testExpiresIn)+`,\r\n \"refresh_token\": \"`+testUserRefreshToken+`\",\r\n \"scope\": \"`+testUserScopes+`\",\r\n \"token_type\": \"`+testTokenType+`\"}}`,\r\n\t\t),\r\n\t)\r\n}",
"func GenerateNewAccessToken(u *domain.User) (string, error) {\n\t// Set secret key from .env file.\n\tsecret := os.Getenv(\"JWT_SECRET_KEY\")\n\n\t// Set expires minutes count for secret key from .env file.\n\tminutesCount, _ := strconv.Atoi(os.Getenv(\"JWT_SECRET_KEY_EXPIRE_MINUTES\"))\n\n\t// Create token\n\ttoken := jwt.New(jwt.SigningMethodHS256)\n\n\t// Set claims\n\tclaims := token.Claims.(jwt.MapClaims)\n\tclaims[\"id\"] = u.ID\n\tclaims[\"email\"] = u.Email\n\tclaims[\"username\"] = u.Username\n\tclaims[\"full_name\"] = u.FullName\n\tclaims[\"exp\"] = time.Now().Add(time.Minute * time.Duration(minutesCount)).Unix()\n\n\t// Generate encoded token and send it as response.\n\tt, err := token.SignedString([]byte(secret))\n\tif err != nil {\n\t\t// Return error, it JWT token generation failed.\n\t\treturn \"\", err\n\t}\n\n\treturn t, nil\n}",
"func (a AccessTokens) Create(w http.ResponseWriter, r *http.Request) error {\n\tvar req createAccessTokenRequest\n\n\tlogger, err := middleware.GetLogger(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := jsonapi.UnmarshalPayload(r.Body, &req); err != nil {\n\t\tapi.InvalidJSONError.Render(w, http.StatusBadRequest)\n\t\treturn nil\n\t}\n\n\tstate := req.State\n\n\tcallback := make(chan OAuthCallback)\n\ta.Callbacks[state] = callback\n\n\ttoken, err := waitForCallback(callback)\n\tdelete(a.Callbacks, state)\n\n\tif err != nil {\n\t\tlogger.With(\"error\", err.Error()).Info(\"oauth request failed\")\n\t\tapi.OauthError.Render(w, http.StatusBadRequest) // TODO: improve error\n\t\treturn nil\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n\terr = json.NewEncoder(w).Encode(token)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to encode access token\")\n\t}\n\treturn nil\n}",
"func (am AppModule) NewHandler() sdk.Handler { return nil }",
"func (ah *AppHandler) AccessTokenHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tconst tokenType string = \"Bearer\"\n\n\t\t\tlogger := *hlog.FromRequest(r)\n\t\t\tvar token string\n\n\t\t\t// retrieve the context from the http.Request\n\t\t\tctx := r.Context()\n\n\t\t\t// Pull the token from the Authorization header\n\t\t\t// by retrieving the value from the Header map with\n\t\t\t// \"Authorization\" as the key\n\t\t\t// format: Authorization: Bearer\n\t\t\theaderValue, ok := r.Header[\"Authorization\"]\n\t\t\tif ok && len(headerValue) >= 1 {\n\t\t\t\ttoken = headerValue[0]\n\t\t\t\ttoken = strings.TrimPrefix(token, tokenType+\" \")\n\t\t\t}\n\n\t\t\t// If the token is empty...\n\t\t\tif token == \"\" {\n\t\t\t\t// For Unauthenticated and Unauthorized errors,\n\t\t\t\t// the response body should be empty. Use logger\n\t\t\t\t// to log the error and then just send\n\t\t\t\t// http.StatusUnauthorized (401) or http.StatusForbidden (403)\n\t\t\t\t// depending on the circumstances. \"In summary, a\n\t\t\t\t// 401 Unauthorized response should be used for missing or bad authentication,\n\t\t\t\t// and a 403 Forbidden response should be used afterwards, when the user is\n\t\t\t\t// authenticated but isn’t authorized to perform the requested operation on\n\t\t\t\t// the given resource.\"\n\t\t\t\terrs.HTTPErrorResponse(w, logger, errs.E(errs.Unauthenticated, errors.New(\"Unauthenticated - empty Bearer token\")))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// add access token to context\n\t\t\tctx = auth.SetAccessToken2Context(ctx, token, tokenType)\n\n\t\t\t// call original, adding access token to request context\n\t\t\th.ServeHTTP(w, r.WithContext(ctx))\n\t\t})\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
TestMockValidity ensures that we don't go into a wild goose chase if our mock system gets screwed up
|
func TestMockValidity(t *testing.T) {
nr := 50
_, hlp := agreement.WireAgreement(nr)
hash, _ := crypto.RandEntropy(32)
handler := agreement.NewHandler(hlp.Keys[0], *hlp.P)
for i := 0; i < nr; i++ {
a := message.MockAgreement(hash, 1, 3, hlp.Keys, hlp.P, i)
if !assert.NoError(t, handler.Verify(a)) {
t.FailNow()
}
}
}
|
[
"func IsMockInvalid(cc ContractCall) bool {\n\treturn false\n}",
"func mockMissedStorageProof(height uint64, state *state.StateDB, prvAndAddresses []PrivkeyAddress) common.Address {\n\twindowEndStr := strconv.FormatUint(height, 10)\n\tstatusAddr := common.BytesToAddress([]byte(StrPrefixExpSC + windowEndStr))\n\tstate.CreateAccount(statusAddr)\n\tstate.SetNonce(statusAddr, 1)\n\n\tcontractID := common.HexToHash(\"0x5e109495581395e5d86c377efb05c2aef6ab6f2046f1bd7336e1ab1bfd96b6ed\")\n\tcontractAddr := common.BytesToAddress(contractID[12:])\n\tstate.CreateAccount(contractAddr)\n\tstate.AddBalance(contractAddr, contractOriginbal)\n\tstate.SetNonce(contractAddr, 1)\n\n\tnotProofedStatus := append(NotProofedStatus, contractAddr[:]...)\n\tstate.SetState(statusAddr, contractID, common.BytesToHash(notProofedStatus))\n\tstate.SetState(contractAddr, KeyClientAddress, common.BytesToHash(prvAndAddresses[0].Address.Bytes()))\n\tstate.SetState(contractAddr, KeyHostAddress, common.BytesToHash(prvAndAddresses[1].Address.Bytes()))\n\tstate.SetState(contractAddr, KeyClientMissedProofOutput, common.BytesToHash(clientMpo.Bytes()))\n\tstate.SetState(contractAddr, KeyHostMissedProofOutput, common.BytesToHash(hostMpo.Bytes()))\n\tstate.Commit(true)\n\n\treturn contractAddr\n}",
"func mockVerifySchnorrSigFail(pubKey *btcec.PublicKey, hash,\n\tsig []byte) error {\n\n\treturn fmt.Errorf(\"invalid sig\")\n}",
"func TestMockShouldFailAtWrongExpects(t *testing.T) {\n\tclient, mocker, _ := New()\n\tmocker.ExpectDeleteSimilarQuestions(\"csbot\", \"test\")\n\terr := client.DeleteSimilarQuestions(\"csbot\", \"test\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.DeleteSimilarQuestions(\"WTF\", \"YA\")\n\tif err == nil {\n\t\tt.Fatal(\"only one expect called with two actual behavior should produce error but got no one.\")\n\t}\n}",
"func TestMimeMessageValidity(t *testing.T) {\n\tm := MimeMessage{\n\t\tToAddress: \"[email protected]\",\n\t\tContent: []byte(\"This is my body. There are many like it but this one is mine.\")}\n\n\tif m.IsValid() != true {\n\t\tt.Error(\"Message should have been valid!\")\n\t}\n\n\tm.ToAddress = \"\"\n\tif m.IsValid() != false {\n\t\tt.Error(\"Message(2) should have been invalid!\")\n\t}\n\n\tm = MimeMessage{ToAddress: \"[email protected]\"}\n\tif m.IsValid() != false {\n\t\tt.Error(\"Message(3) should have been invalid!\")\n\t}\n}",
"func mockNeverRun() bool { return false }",
"func (m *MockValidator) PreflightValidations(arg0 context.Context) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PreflightValidations\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}",
"func TestVerifySignedMessage(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tdesc string\n\t\tsettings *crypt.PkiSettings\n\t\tsetup func(mdb *mocks.MockDepsBundle, setupDone *bool) error\n\t\tmessageToSign string\n\t\tbase64Signature string\n\t\tPEMPublicKey string\n\t\texpectedError *testtools.ErrorSpec\n\t\texpectedValidity bool\n\t}{\n\t\t{\n\t\t\tdesc: \"invalid base64 signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"@#$^&*()_\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"base64.CorruptInputError\",\n\t\t\t\tMessage: \"illegal base64 data at input byte 0\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"empty PEM key\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"No PEM data was found\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"bad key data\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN INVALID DATA-----\\n\" +\n\t\t\t\t\"MTIzNDU2Nzg5MGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6\\n\" +\n\t\t\t\t\"-----END INVALID DATA-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.StructuralError\",\n\t\t\t\tMessage: \"asn1: structure \" +\n\t\t\t\t\t\"error: tags don't match (16 vs {class:0 \" +\n\t\t\t\t\t\"tag:17 \" +\n\t\t\t\t\t\"length:50 \" +\n\t\t\t\t\t\"isCompound:true}) {optional:false \" +\n\t\t\t\t\t\"explicit:false \" +\n\t\t\t\t\t\"application:false \" +\n\t\t\t\t\t\"defaultValue:<nil> \" +\n\t\t\t\t\t\"tag:<nil> \" +\n\t\t\t\t\t\"stringType:0 \" +\n\t\t\t\t\t\"timeType:0 \" +\n\t\t\t\t\t\"set:false \" +\n\t\t\t\t\t\"omitEmpty:false} publicKeyInfo @2\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"invalid signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN ECDSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END ECDSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.SyntaxError\",\n\t\t\t\tMessage: \"asn1: syntax error: truncated tag or length\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"ecdsa key for rsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.RSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"N3SuIdWI7XlXDteTmcOZUd2OBacyUWY+/+A8SC4QUBz9rXnldBqXha6YyGwnTuizxuy6quQ2QDFdtW16dj7EQk3lozfngskyhc2r86q3AUbdFDvrQVphMQhzsgBhHVoMjCL/YRfvtzCTWhBxegjVMLraLDCBb8IZTIqcMYafYyeJTvAnjBuntlZ+14TDuTt14Uqz85T04CXxBEqlIXMMKpTc01ST4Jsxz5HLO+At1htXp5eHOUFtQSilm3G7iO8ynhgPcXHDWfMAWu6VySUoHWCG70pJaCq6ehF7223t0UFOCqAyDyyQyP9yeUHj8F75SPSxfJm8iKXGx2LND/qLYw==\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *rsa.PublicKey, but encountered a *ecdsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"rsa key for ecdsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"MEYCIQDPM0fc/PFauoZzpltH3RpWtlaqRnL0gFk5WFiLMrFqrwIhAIDvlBozU6Ky2UC9xOSq3YZ5iFuO356t9RnHOElaaXFJ\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzCTTFKQBHfTN8jW6q8PT\\n\" +\n\t\t\t\t\"HNZKWnRPxSt9kpgWmyqFaZnEUipgoKGAxSIsVrl2PJSm5OlgkVzx+MY+LWM64VKM\\n\" +\n\t\t\t\t\"bRpUUGJR3zdMNhwZQX0hjOpLpVJvUwD78utVs8vijrU7sH48usFiaZQYjy4m4hQh\\n\" +\n\t\t\t\t\"63/x4h3KVz7YqUnlRMzYJFT43+AwYzYuEpzWRxtW7IObJPtjtmYVoqva98fF6aj5\\n\" +\n\t\t\t\t\"uHAsvaAgZGBalHXmCiPzKiGU/halzXSPvyJ2Cqz2aUqMHgwi/2Ip4z/mrfX+mUTa\\n\" +\n\t\t\t\t\"S+LyBy7GgqJ5vbkGArMagJIc0eARF60r6Uf483xh17oniABdLJy4qlLf6PcEU+ut\\n\" +\n\t\t\t\t\"EwIDAQAB\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *ecdsa.PublicKey, but encountered a *rsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t} {\n\t\tt.Run(fmt.Sprintf(\"Subtest: %s\", tc.desc), func(tt *testing.T) {\n\t\t\tmockDepsBundle := mocks.NewDefaultMockDeps(\"\", []string{\"progname\"}, \"/home/user\", nil)\n\t\t\treturnedNormally := false\n\t\t\tvar tooling *crypt.CryptoTooling\n\t\t\tvar actualErr error\n\t\t\tvar actualValidity bool\n\t\t\terr := mockDepsBundle.InvokeCallInMockedEnv(func() error {\n\t\t\t\tsetupComplete := false\n\t\t\t\tinnerErr := tc.setup(mockDepsBundle, &setupComplete)\n\t\t\t\tif innerErr != nil {\n\t\t\t\t\treturn innerErr\n\t\t\t\t}\n\t\t\t\tvar toolingErr error\n\t\t\t\ttooling, toolingErr = crypt.GetCryptoTooling(mockDepsBundle.Deps, tc.settings)\n\t\t\t\tif toolingErr != nil {\n\t\t\t\t\treturn toolingErr\n\t\t\t\t}\n\t\t\t\tsetupComplete = true\n\t\t\t\tactualValidity, actualErr = tooling.VerifySignedMessage(tc.messageToSign, tc.base64Signature, tc.PEMPublicKey)\n\t\t\t\treturnedNormally = true\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\ttt.Errorf(\"Unexpected error calling mockDepsBundle.InvokeCallInMockedEnv(): %s\", err.Error())\n\t\t\t}\n\t\t\tif exitStatus := mockDepsBundle.GetExitStatus(); (exitStatus != 0) || !returnedNormally {\n\t\t\t\ttt.Error(\"EncodeAndSaveKey() should not have paniced or called os.Exit.\")\n\t\t\t}\n\t\t\tif (mockDepsBundle.OutBuf.String() != \"\") || (mockDepsBundle.ErrBuf.String() != \"\") {\n\t\t\t\ttt.Errorf(\"EncodeAndSaveKey() should not have output any data. Saw stdout:\\n%s\\nstderr:\\n%s\", mockDepsBundle.OutBuf.String(), mockDepsBundle.ErrBuf.String())\n\t\t\t}\n\t\t\tif err := tc.expectedError.EnsureMatches(actualErr); err != nil {\n\t\t\t\ttt.Error(err.Error())\n\t\t\t}\n\t\t\tif tc.expectedError == nil {\n\t\t\t\tif actualValidity != tc.expectedValidity {\n\t\t\t\t\ttt.Errorf(\"Signature is %#v when %#v expected\", actualValidity, tc.expectedValidity)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif tc.expectedValidity {\n\t\t\t\t\ttt.Error(\"TEST CASE INVALID. Should not expect \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t\tif actualValidity {\n\t\t\t\t\ttt.Error(\"Error was expected. Should not report \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}",
"func (m *MockMounter) IsCorruptedMnt(err error) bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IsCorruptedMnt\", err)\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}",
"func (m *MockFromFlags) Validate() error {\n\tret := m.ctrl.Call(m, \"Validate\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}",
"func (m *MockRepo) IsValid() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IsValid\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}",
"func TestAdjustmentAmountValid(t *testing.T) {\n\tadj := mockAdjustment()\n\tadj.RemittanceAmount.Amount = \"X,\"\n\n\terr := adj.Validate()\n\n\trequire.EqualError(t, err, fieldError(\"Amount\", ErrNonAmount, adj.RemittanceAmount.Amount).Error())\n}",
"func newMockKvCapabilityVerifier(t mockConstructorTestingTnewMockKvCapabilityVerifier) *mockKvCapabilityVerifier {\n\tmock := &mockKvCapabilityVerifier{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}",
"func (m *MockUpdaterFromFlags) Validate() error {\n\tret := m.ctrl.Call(m, \"Validate\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}",
"func HaveMappingRulesVerificationFailure(testFramework *framework.Framework) types.GomegaMatcher {\n\tmatcher := hasConditionInStatus{}\n\tmatcher.timeout = 1 * time.Minute\n\tmatcher.pollInterval = 1 * time.Second\n\tmatcher.testFramework = testFramework\n\n\tmatcher.conditionType = v2vv1.MappingRulesVerified\n\tmatcher.status = corev1.ConditionFalse\n\treturn &matcher\n}",
"func BeCausedBy(err error) types.GomegaMatcher { return &causedByMatcher{expected: err} }",
"func (m *MockHasher) IsValid(arg0, arg1 string) bool {\n\tret := m.ctrl.Call(m, \"IsValid\", arg0, arg1)\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}",
"func (m *MockconservativeState) Validation(arg0 types.RawTx) system.ValidationRequest {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Validation\", arg0)\n\tret0, _ := ret[0].(system.ValidationRequest)\n\treturn ret0\n}",
"func TestCV34(t *testing.T) {\n\tstatedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))\n\tmsg := createValidator()\n\tstatedb.AddBalance(msg.ValidatorAddress, tenK)\n\t// MinSelfDelegation not specified\n\tmsg.MinSelfDelegation = nil\n\tif _, err := VerifyAndCreateValidatorFromMsg(\n\t\tstatedb, postStakingEpoch, big.NewInt(0), msg,\n\t); err == nil {\n\t\tt.Error(\"expected\", \"MinSelfDelegation can not be nil\", \"got\", nil)\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test the accumulation of agreement events. It should result in the agreement component publishing a round update. TODO: trap eventual errors
|
func TestAgreement(t *testing.T) {
nr := 50
_, hlp := agreement.WireAgreement(nr)
hash, _ := crypto.RandEntropy(32)
for i := 0; i < nr; i++ {
a := message.MockAgreement(hash, 1, 3, hlp.Keys, hlp.P, i)
msg := message.New(topics.Agreement, a)
hlp.Bus.Publish(topics.Agreement, msg)
}
res := <-hlp.CertificateChan
cert := res.Payload().(message.Agreement)
assert.Equal(t, hash, cert.State().BlockHash)
}
|
[
"func TestSendAgreement(t *testing.T) {\n\tcommitteeMock, _ := agreement.MockCommittee(3, true, 3)\n\teb, _ := initAgreement(committeeMock)\n\n\tstreamer := helper.NewSimpleStreamer()\n\teb.SubscribeStream(string(topics.Gossip), streamer)\n\teb.RegisterPreprocessor(string(topics.Gossip), processing.NewGossip(protocol.TestNet))\n\n\t// Initiate the sending of an agreement message\n\thash, _ := crypto.RandEntropy(32)\n\tbuf := new(bytes.Buffer)\n\tif err := encoding.WriteUint64(buf, binary.LittleEndian, 1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif _, err := buf.ReadFrom(reduction.MockVoteSetBuffer(hash, 1, 2, 10)); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\teb.Publish(msg.ReductionResultTopic, buf)\n\n\t// There should now be an agreement message in the streamer\n\t_, err := streamer.Read()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tseenTopics := streamer.SeenTopics()\n\tif seenTopics[0] != topics.Agreement {\n\t\tt.Fail()\n\t}\n}",
"func MockAgreementEvent(hash []byte, round uint64, step uint8, keys []key.ConsensusKeys, p *user.Provisioners, iterativeIdx ...int) *Agreement {\n\t// Make sure we create an event made by an actual voting committee member\n\tc := p.CreateVotingCommittee(round, step, len(keys))\n\tcKeys := createCommitteeKeySet(c, keys)\n\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\ta := New(header.Header{Round: round, Step: step, BlockHash: hash, PubKeyBLS: cKeys[idx].BLSPubKeyBytes})\n\t// generating reduction events (votes) and signing them\n\tsteps := GenVotes(hash, round, step, keys, p)\n\n\twhole := new(bytes.Buffer)\n\tif err := header.MarshalSignableVote(whole, a.Header); err != nil {\n\t\tpanic(err)\n\t}\n\n\tsig, _ := bls.Sign(cKeys[idx].BLSSecretKey, cKeys[idx].BLSPubKey, whole.Bytes())\n\ta.VotesPerStep = steps\n\ta.SetSignature(sig.Compress())\n\treturn a\n}",
"func initAgreement(c committee.Foldable) (wire.EventBroker, <-chan uint64) {\n\tbus := wire.NewEventBus()\n\troundChan := consensus.InitRoundUpdate(bus)\n\tk, _ := user.NewRandKeys()\n\tgo agreement.Launch(bus, c, k)\n\ttime.Sleep(200 * time.Millisecond)\n\tinit := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(init, 1)\n\tbus.Publish(msg.InitializationTopic, bytes.NewBuffer(init))\n\n\t// we remove the pre-processors here that the Launch function adds, so the mocked\n\t// buffers can be deserialized properly\n\tbus.RemoveAllPreprocessors(string(topics.Agreement))\n\t// we need to discard the first update since it is triggered directly as it is supposed to update the round to all other consensus compoenents\n\t<-roundChan\n\treturn bus, roundChan\n}",
"func MockAgreement(hash []byte, round uint64, step uint8, keys []key.ConsensusKeys, p *user.Provisioners, i ...int) *bytes.Buffer {\n\tbuf := new(bytes.Buffer)\n\tev := MockAgreementEvent(hash, round, step, keys, p, i...)\n\t_ = Marshal(buf, *ev)\n\treturn buf\n}",
"func TestReduction(t *testing.T) {\n\teventBus, rpcBus, streamer, _, k := launchReductionTest(true, 2)\n\tgo launchCandidateVerifier(rpcBus, false)\n\n\t// Because round updates are asynchronous (sent through a channel), we wait\n\t// for a bit to let the broker update its round.\n\ttime.Sleep(200 * time.Millisecond)\n\t// send a hash to start reduction\n\thash, _ := crypto.RandEntropy(32)\n\tsendSelection(1, hash, eventBus)\n\n\t// send mocked events until we get a result from the outgoingAgreement channel\n\tsendReductionBuffers(k, hash, 1, 1, eventBus)\n\tsendReductionBuffers(k, hash, 1, 2, eventBus)\n\n\ttimer := time.AfterFunc(1*time.Second, func() {\n\t\tt.Fatal(\"\")\n\t})\n\n\tfor i := 0; i < 2; i++ {\n\t\tif _, err := streamer.Read(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\ttimer.Stop()\n}",
"func TestNoQuorum(t *testing.T) {\n\tcommitteeMock, keys := agreement.MockCommittee(3, true, 3)\n\teb, roundChan := initAgreement(committeeMock)\n\thash, _ := crypto.RandEntropy(32)\n\teb.Publish(string(topics.Agreement), agreement.MockAgreement(hash, 1, 1, keys))\n\teb.Publish(string(topics.Agreement), agreement.MockAgreement(hash, 1, 1, keys))\n\n\tselect {\n\tcase <-roundChan:\n\t\tassert.FailNow(t, \"not supposed to get a round update without reaching quorum\")\n\tcase <-time.After(100 * time.Millisecond):\n\t\t// all good\n\t}\n}",
"func format_ag_event(ix int, ev rpcFilterChanges, tr *TestResults) {\n // These event strings correspond to event codes from the agreements contract\n ag_cr8 := \"0x0000000000000000000000000000000000000000000000000000000000000000\"\n ag_cr8_detail := \"0x0000000000000000000000000000000000000000000000000000000000000001\"\n ag_cr8_fraud := \"0x0000000000000000000000000000000000000000000000000000000000000002\"\n ag_con_term := \"0x0000000000000000000000000000000000000000000000000000000000000003\"\n ag_pub_term := \"0x0000000000000000000000000000000000000000000000000000000000000004\"\n ag_fraud_term := \"0x0000000000000000000000000000000000000000000000000000000000000005\"\n ag_adm_term := \"0x0000000000000000000000000000000000000000000000000000000000000006\"\n\n if ev.Topics[0] == ag_cr8 {\n log.Printf(\"|%03d| Agreement created %v\\n\",ix,ev.Topics[1]);\n log.Printf(\"Data: %v\\n\",ev.Data);\n log.Printf(\"Block: %v\\n\\n\",ev.BlockNumber);\n tr.Successful += 1\n } else if ev.Topics[0] == ag_cr8_detail {\n log.Printf(\"|%03d| Agreement created detail %v\\n\",ix,ev.Topics[1]);\n log.Printf(\"Data: %v\\n\",ev.Data);\n log.Printf(\"Block: %v\\n\\n\",ev.BlockNumber);\n } else if ev.Topics[0] == ag_cr8_fraud {\n log.Printf(\"|%03d| Agreement creation fraud %v\\n\",ix,ev.Topics[1]);\n log.Printf(\"Data: %v\\n\",ev.Data);\n log.Printf(\"Block: %v\\n\\n\",ev.BlockNumber);\n tr.Fraud += 1\n } else if ev.Topics[0] == ag_con_term {\n log.Printf(\"|%03d| Consumer Terminated %v\\n\",ix,ev.Topics[1]);\n log.Printf(\"Data: %v\\n\",ev.Data);\n log.Printf(\"Block: %v\\n\\n\",ev.BlockNumber);\n tr.Delete += 1\n } else if ev.Topics[0] == ag_pub_term {\n log.Printf(\"|%03d| Publisher Terminated %v\\n\",ix,ev.Topics[1]);\n log.Printf(\"Data: %v\\n\",ev.Data);\n log.Printf(\"Block: %v\\n\\n\",ev.BlockNumber);\n tr.Delete += 1\n } else if ev.Topics[0] == ag_fraud_term {\n log.Printf(\"|%03d| Fraudulent Termination %v\\n\",ix,ev.Topics[1]);\n log.Printf(\"Data: %v\\n\",ev.Data);\n log.Printf(\"Block: %v\\n\\n\",ev.BlockNumber);\n tr.Fraud += 1\n } else if ev.Topics[0] == ag_adm_term {\n log.Printf(\"|%03d| Admin Termination %v\\n\",ix,ev.Topics[1]);\n log.Printf(\"Data: %v\\n\",ev.Data);\n log.Printf(\"Block: %v\\n\\n\",ev.BlockNumber);\n tr.Delete += 1\n } else {\n log.Printf(\"|%03d| Unknown event code in first topic slot.\\n\")\n log.Printf(\"Raw log entry:\\n%v\\n\\n\",ev)\n }\n}",
"func TestUpdateSubscriptions(t *testing.T) {\n\n\tlogger := logtesting.TestLogger(t)\n\tctx := logging.WithLogger(context.TODO(), logger)\n\n\t// Test Data\n\tbrokers := []string{configtesting.DefaultKafkaBroker}\n\tconfig, err := commonclient.NewConfigBuilder().WithDefaults().FromYaml(clienttesting.DefaultSaramaConfigYaml).Build(ctx)\n\tassert.Nil(t, err)\n\n\tdispatcherConfig := DispatcherConfig{\n\t\tLogger: logger.Desugar(),\n\t\tBrokers: brokers,\n\t\tSaramaConfig: config,\n\t}\n\n\t// Define The TestCase Struct\n\ttype fields struct {\n\t\tDispatcherConfig DispatcherConfig\n\t\tsubscribers map[types.UID]*SubscriberWrapper\n\t}\n\ttype args struct {\n\t\tsubscriberSpecs []eventingduck.SubscriberSpec\n\t}\n\n\t// Define The TestCase Struct\n\ttype TestCase struct {\n\t\tonly bool\n\t\tname string\n\t\tfields fields\n\t\targs args\n\t\twant map[eventingduck.SubscriberSpec]error\n\t}\n\n\t// Create The Test Cases\n\ttestCases := []TestCase{\n\t\t{\n\t\t\tname: \"Add First Subscription\",\n\t\t\tfields: fields{\n\t\t\t\tDispatcherConfig: dispatcherConfig,\n\t\t\t\tsubscribers: map[types.UID]*SubscriberWrapper{},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tsubscriberSpecs: []eventingduck.SubscriberSpec{\n\t\t\t\t\t{UID: uid123},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: map[eventingduck.SubscriberSpec]error{},\n\t\t},\n\t\t{\n\t\t\tname: \"Add Second Subscription\",\n\t\t\tfields: fields{\n\t\t\t\tDispatcherConfig: dispatcherConfig,\n\t\t\t\tsubscribers: map[types.UID]*SubscriberWrapper{\n\t\t\t\t\tuid123: createSubscriberWrapper(uid123),\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tsubscriberSpecs: []eventingduck.SubscriberSpec{\n\t\t\t\t\t{UID: uid123},\n\t\t\t\t\t{UID: uid456},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: map[eventingduck.SubscriberSpec]error{},\n\t\t},\n\t\t{\n\t\t\tname: \"Add And Remove Subscriptions\",\n\t\t\tfields: fields{\n\t\t\t\tDispatcherConfig: dispatcherConfig,\n\t\t\t\tsubscribers: map[types.UID]*SubscriberWrapper{\n\t\t\t\t\tuid123: createSubscriberWrapper(uid123),\n\t\t\t\t\tuid456: createSubscriberWrapper(uid456),\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tsubscriberSpecs: []eventingduck.SubscriberSpec{\n\t\t\t\t\t{UID: uid456},\n\t\t\t\t\t{UID: uid789},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: map[eventingduck.SubscriberSpec]error{},\n\t\t},\n\t\t{\n\t\t\tname: \"Remove Penultimate Subscription\",\n\t\t\tfields: fields{\n\t\t\t\tDispatcherConfig: dispatcherConfig,\n\t\t\t\tsubscribers: map[types.UID]*SubscriberWrapper{\n\t\t\t\t\tuid123: createSubscriberWrapper(uid123),\n\t\t\t\t\tuid456: createSubscriberWrapper(uid456),\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tsubscriberSpecs: []eventingduck.SubscriberSpec{\n\t\t\t\t\t{UID: uid123},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: map[eventingduck.SubscriberSpec]error{},\n\t\t},\n\t\t{\n\t\t\tname: \"Remove Last Subscription\",\n\t\t\tfields: fields{\n\t\t\t\tDispatcherConfig: dispatcherConfig,\n\t\t\t\tsubscribers: map[types.UID]*SubscriberWrapper{\n\t\t\t\t\tuid123: createSubscriberWrapper(uid123),\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tsubscriberSpecs: []eventingduck.SubscriberSpec{},\n\t\t\t},\n\t\t\twant: map[eventingduck.SubscriberSpec]error{},\n\t\t},\n\t}\n\n\t// Filter To Those With \"only\" Flag (If Any Specified)\n\tfilteredTestCases := make([]TestCase, 0)\n\tfor _, testCase := range testCases {\n\t\tif testCase.only {\n\t\t\tfilteredTestCases = append(filteredTestCases, testCase)\n\t\t}\n\t}\n\tif len(filteredTestCases) == 0 {\n\t\tfilteredTestCases = testCases\n\t}\n\n\t// Execute The Test Cases (Create A DispatcherImpl & UpdateSubscriptions() :)\n\tfor _, testCase := range filteredTestCases {\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\n\t\t\t// Create A New DispatcherImpl To Test\n\t\t\tdispatcher := &DispatcherImpl{\n\t\t\t\tDispatcherConfig: testCase.fields.DispatcherConfig,\n\t\t\t\tsubscribers: testCase.fields.subscribers,\n\t\t\t\tconsumerGroupFactory: &consumertesting.MockKafkaConsumerGroupFactory{},\n\t\t\t}\n\n\t\t\t// Perform The Test\n\t\t\tgot := dispatcher.UpdateSubscriptions(testCase.args.subscriberSpecs)\n\n\t\t\t// Verify Results\n\t\t\tassert.Equal(t, testCase.want, got)\n\n\t\t\t// Verify The Dispatcher's Tracking Of Subscribers Matches Specified State\n\t\t\tassert.Len(t, dispatcher.subscribers, len(testCase.args.subscriberSpecs))\n\t\t\tfor _, subscriber := range testCase.args.subscriberSpecs {\n\t\t\t\tassert.NotNil(t, dispatcher.subscribers[subscriber.UID])\n\t\t\t}\n\n\t\t\t// Shutdown The Dispatcher to Cleanup Resources\n\t\t\tdispatcher.Shutdown()\n\t\t\tassert.Len(t, dispatcher.subscribers, 0)\n\n\t\t\t// Pause Briefly To Let Any Async Shutdown Finish (Lame But Only For Visual Confirmation Of Logging ;)\n\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t})\n\t}\n}",
"func TestUpdateSubscriptions(t *testing.T) {\n\n\t// Define The TestCase Struct\n\ttype fields struct {\n\t\tDispatcherConfig DispatcherConfig\n\t\tsubscribers map[types.UID]*SubscriberWrapper\n\t}\n\ttype args struct {\n\t\tsubscriberSpecs []eventingduck.SubscriberSpec\n\t}\n\ttype testCase struct {\n\t\tname string\n\t\tfields fields\n\t\targs args\n\t\twant map[eventingduck.SubscriberSpec]error\n\t}\n\n\t// Define The Test Cases\n\ttests := []testCase{\n\t\t{\n\t\t\tname: \"Add First Subscription\",\n\t\t\tfields: fields{\n\t\t\t\tDispatcherConfig: DispatcherConfig{\n\t\t\t\t\tSaramaConfig: getSaramaConfigFromYaml(t, TestConfigBase),\n\t\t\t\t\tLogger: logtesting.TestLogger(t).Desugar(),\n\t\t\t\t},\n\t\t\t\tsubscribers: map[types.UID]*SubscriberWrapper{},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tsubscriberSpecs: []eventingduck.SubscriberSpec{\n\t\t\t\t\t{UID: uid123},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: map[eventingduck.SubscriberSpec]error{},\n\t\t},\n\t\t{\n\t\t\tname: \"Add Second Subscription\",\n\t\t\tfields: fields{\n\t\t\t\tDispatcherConfig: DispatcherConfig{\n\t\t\t\t\tSaramaConfig: getSaramaConfigFromYaml(t, TestConfigBase),\n\t\t\t\t\tLogger: logtesting.TestLogger(t).Desugar(),\n\t\t\t\t},\n\t\t\t\tsubscribers: map[types.UID]*SubscriberWrapper{\n\t\t\t\t\tuid123: createSubscriberWrapper(t, uid123),\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tsubscriberSpecs: []eventingduck.SubscriberSpec{\n\t\t\t\t\t{UID: uid123},\n\t\t\t\t\t{UID: uid456},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: map[eventingduck.SubscriberSpec]error{},\n\t\t},\n\t\t{\n\t\t\tname: \"Add And Remove Subscriptions\",\n\t\t\tfields: fields{\n\t\t\t\tDispatcherConfig: DispatcherConfig{\n\t\t\t\t\tSaramaConfig: getSaramaConfigFromYaml(t, TestConfigBase),\n\t\t\t\t\tLogger: logtesting.TestLogger(t).Desugar(),\n\t\t\t\t},\n\t\t\t\tsubscribers: map[types.UID]*SubscriberWrapper{\n\t\t\t\t\tuid123: createSubscriberWrapper(t, uid123),\n\t\t\t\t\tuid456: createSubscriberWrapper(t, uid456),\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tsubscriberSpecs: []eventingduck.SubscriberSpec{\n\t\t\t\t\t{UID: uid456},\n\t\t\t\t\t{UID: uid789},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: map[eventingduck.SubscriberSpec]error{},\n\t\t},\n\t\t{\n\t\t\tname: \"Remove Penultimate Subscription\",\n\t\t\tfields: fields{\n\t\t\t\tDispatcherConfig: DispatcherConfig{\n\t\t\t\t\tSaramaConfig: getSaramaConfigFromYaml(t, TestConfigBase),\n\t\t\t\t\tLogger: logtesting.TestLogger(t).Desugar(),\n\t\t\t\t},\n\t\t\t\tsubscribers: map[types.UID]*SubscriberWrapper{\n\t\t\t\t\tuid123: createSubscriberWrapper(t, uid123),\n\t\t\t\t\tuid456: createSubscriberWrapper(t, uid456),\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tsubscriberSpecs: []eventingduck.SubscriberSpec{\n\t\t\t\t\t{UID: uid123},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: map[eventingduck.SubscriberSpec]error{},\n\t\t},\n\t\t{\n\t\t\tname: \"Remove Last Subscription\",\n\t\t\tfields: fields{\n\t\t\t\tDispatcherConfig: DispatcherConfig{\n\t\t\t\t\tSaramaConfig: getSaramaConfigFromYaml(t, TestConfigBase),\n\t\t\t\t\tLogger: logtesting.TestLogger(t).Desugar(),\n\t\t\t\t},\n\t\t\t\tsubscribers: map[types.UID]*SubscriberWrapper{\n\t\t\t\t\tuid123: createSubscriberWrapper(t, uid123),\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tsubscriberSpecs: []eventingduck.SubscriberSpec{},\n\t\t\t},\n\t\t\twant: map[eventingduck.SubscriberSpec]error{},\n\t\t},\n\t}\n\n\t// Execute The Test Cases (Create A DispatcherImpl & UpdateSubscriptions() :)\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\n\t\t\t// Mock ConsumerGroup To Test With\n\t\t\tconsumerGroup := kafkatesting.NewMockConsumerGroup(t)\n\n\t\t\t// Replace The NewConsumerGroupWrapper With Mock For Testing & Restore After TestCase\n\t\t\tnewConsumerGroupWrapperPlaceholder := kafkaconsumer.NewConsumerGroupWrapper\n\t\t\tkafkaconsumer.NewConsumerGroupWrapper = func(brokersArg []string, groupIdArg string, configArg *sarama.Config) (sarama.ConsumerGroup, error) {\n\t\t\t\treturn consumerGroup, nil\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tkafkaconsumer.NewConsumerGroupWrapper = newConsumerGroupWrapperPlaceholder\n\t\t\t}()\n\n\t\t\t// Create A New DispatcherImpl To Test\n\t\t\tdispatcher := &DispatcherImpl{\n\t\t\t\tDispatcherConfig: tt.fields.DispatcherConfig,\n\t\t\t\tsubscribers: tt.fields.subscribers,\n\t\t\t}\n\n\t\t\t// Perform The Test\n\t\t\tgot := dispatcher.UpdateSubscriptions(tt.args.subscriberSpecs)\n\n\t\t\t// Verify Results\n\t\t\tassert.Equal(t, tt.want, got)\n\n\t\t\t// Verify The Dispatcher's Tracking Of Subscribers Matches Specified State\n\t\t\tassert.Len(t, dispatcher.subscribers, len(tt.args.subscriberSpecs))\n\t\t\tfor _, subscriber := range tt.args.subscriberSpecs {\n\t\t\t\tassert.NotNil(t, dispatcher.subscribers[subscriber.UID])\n\t\t\t}\n\n\t\t\t// Shutdown The Dispatcher to Cleanup Resources\n\t\t\tdispatcher.Shutdown()\n\t\t\tassert.Len(t, dispatcher.subscribers, 0)\n\n\t\t\t// Pause Briefly To Let Any Async Shutdown Finish (Lame But Only For Visual Confirmation Of Logging ;)\n\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t})\n\t}\n}",
"func TestComboBehavior(t *testing.T) {\n\tassert := audit.NewTestingAssertion(t, true)\n\tgenerator := audit.NewGenerator(audit.FixedRand())\n\tsigc := audit.MakeSigChan()\n\tenv := cells.NewEnvironment(\"combo-behavior\")\n\tdefer env.Stop()\n\n\tmatcher := func(accessor cells.EventSinkAccessor) (cells.CriterionMatch, cells.Payload) {\n\t\tanalyzer := cells.NewEventSinkAnalyzer(accessor)\n\t\tcombo := map[string]int{\n\t\t\t\"a\": 0,\n\t\t\t\"b\": 0,\n\t\t\t\"c\": 0,\n\t\t\t\"d\": 0,\n\t\t}\n\t\tmatches, err := analyzer.Match(func(index int, event cells.Event) (bool, error) {\n\t\t\t_, ok := combo[event.Topic()]\n\t\t\tif ok {\n\t\t\t\tcombo[event.Topic()]++\n\t\t\t}\n\t\t\treturn ok, nil\n\t\t})\n\t\tif err != nil || !matches {\n\t\t\treturn cells.CriterionDropLast, nil\n\t\t}\n\t\tfor _, count := range combo {\n\t\t\tif count == 0 {\n\t\t\t\treturn cells.CriterionKeep, nil\n\t\t\t}\n\t\t}\n\t\tpayload, err := cells.NewPayload(combo)\n\t\tassert.Nil(err)\n\t\treturn cells.CriterionDone, payload\n\t}\n\tprocessor := func(accessor cells.EventSinkAccessor) (cells.Payload, error) {\n\t\tanalyzer := cells.NewEventSinkAnalyzer(accessor)\n\t\tok, err := analyzer.Match(func(index int, event cells.Event) (bool, error) {\n\t\t\tvar payload map[string]int\n\t\t\tif err := event.Payload().Unmarshal(&payload); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tif len(payload) != 4 {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tfor key := range payload {\n\t\t\t\tif payload[key] == 0 {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t\tsigc <- ok\n\t\treturn nil, err\n\t}\n\n\ttopics := []string{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"now\"}\n\n\tenv.StartCell(\"combiner\", behaviors.NewComboBehavior(matcher))\n\tenv.StartCell(\"collector\", behaviors.NewCollectorBehavior(100, processor))\n\tenv.Subscribe(\"combiner\", \"collector\")\n\n\tfor i := 0; i < 1000; i++ {\n\t\ttopic := generator.OneStringOf(topics...)\n\t\tenv.EmitNew(\"combiner\", topic, nil)\n\t}\n\n\tenv.EmitNew(\"collector\", cells.TopicProcess, nil)\n\tassert.Wait(sigc, true, time.Minute)\n}",
"func make_agreement(ag *contract_api.SolidityContract, agID []byte, sig_hash string, sig string, counterparty string, shouldWork bool) {\n tx_delay_toleration := 120\n err := error(nil)\n\n log.Printf(\"Make an agreement with ID:%v\\n\", agID)\n p := make([]interface{},0,10)\n p = append(p, agID)\n p = append(p, sig_hash[2:])\n p = append(p, sig[2:])\n p = append(p, counterparty)\n if _, err = ag.Invoke_method(\"create_agreement\", p); err != nil {\n log.Printf(\"...terminating, could not invoke create_agreement: %v\\n\", err)\n os.Exit(1)\n }\n log.Printf(\"Create agreement %v invoked.\\n\", agID)\n\n var res interface{}\n p = make([]interface{},0,10)\n p = append(p, counterparty)\n p = append(p, agID)\n byte_hash, _ := hex.DecodeString(sig_hash[2:])\n log.Printf(\"Binary Hash is: %v\\n\", byte_hash)\n start_timer := time.Now()\n for {\n if shouldWork {\n fmt.Printf(\"There should be a recorded contract hash, but it might be in a block we can't read yet.\\n\")\n } else {\n fmt.Printf(\"There should NOT be a recorded contract hash.\\n\")\n }\n if res, err = ag.Invoke_method(\"get_contract_hash\", p); err == nil {\n fmt.Printf(\"Received contract hash:%v.\\n\",res)\n if bytes.Compare([]byte(res.(string)), byte_hash) != 0 {\n if int(time.Now().Sub(start_timer).Seconds()) < tx_delay_toleration {\n fmt.Printf(\"Sleeping, waiting for the block with the Update.\\n\")\n time.Sleep(15 * time.Second)\n } else {\n if shouldWork {\n fmt.Printf(\"Timeout waiting for the Update.\\n\")\n os.Exit(1)\n } else {\n fmt.Printf(\"Timeout waiting for the Update. This is expected.\\n\")\n break\n }\n }\n } else {\n if shouldWork {\n log.Printf(\"Created agreement %v.\\n\", agID)\n break\n } else {\n fmt.Printf(\"Received contract hash. This is NOT expected: %v\\n\", res.(string))\n os.Exit(2)\n }\n }\n } else {\n fmt.Printf(\"Error on get_contract_hash: %v\\n\",err)\n os.Exit(1)\n }\n }\n}",
"func TestSubReqAndRouteUpdateNok(t *testing.T) {\n\tCaseBegin(\"TestSubReqAndRouteUpdateNok\")\n\n\t// Init counter check\n\tmainCtrl.CounterValuesToBeVeriefied(t, CountersToBeAdded{\n\t\tCounter{cSubReqFromXapp, 2},\n\t\tCounter{cSubReqToE2, 1},\n\t\tCounter{cSubRespFromE2, 1},\n\t\tCounter{cSubRespToXapp, 1},\n\t\tCounter{cRouteCreateUpdateFail, 1},\n\t\tCounter{cSubDelReqFromXapp, 1},\n\t\tCounter{cSubDelReqToE2, 1},\n\t\tCounter{cSubDelRespFromE2, 1},\n\t\tCounter{cSubDelRespToXapp, 1},\n\t})\n\n\tcretrans := xappConn1.SendSubsReq(t, nil, nil)\n\tcrereq, cremsg := e2termConn1.RecvSubsReq(t)\n\te2termConn1.SendSubsResp(t, crereq, cremsg)\n\te2SubsId := xappConn1.RecvSubsResp(t, cretrans)\n\n\tresp, _ := xapp.Subscription.QuerySubscriptions()\n\tassert.Equal(t, resp[0].SubscriptionID, int64(e2SubsId))\n\tassert.Equal(t, resp[0].Meid, \"RAN_NAME_1\")\n\tassert.Equal(t, resp[0].ClientEndpoint, []string{\"localhost:13560\"})\n\n\twaiter := rtmgrHttp.AllocNextEvent(false)\n\tnewSubsId := mainCtrl.get_registry_next_subid(t)\n\txappConn2.SendSubsReq(t, nil, nil)\n\twaiter.WaitResult(t)\n\n\tdeltrans := xappConn1.SendSubsDelReq(t, nil, e2SubsId)\n\tdelreq, delmsg := e2termConn1.RecvSubsDelReq(t)\n\n\te2termConn1.SendSubsDelResp(t, delreq, delmsg)\n\txappConn1.RecvSubsDelResp(t, deltrans)\n\n\t//Wait that subs is cleaned\n\tmainCtrl.wait_subs_clean(t, newSubsId, 10)\n\tmainCtrl.wait_subs_clean(t, e2SubsId, 10)\n\n\txappConn1.TestMsgChanEmpty(t)\n\txappConn2.TestMsgChanEmpty(t)\n\te2termConn1.TestMsgChanEmpty(t)\n\tmainCtrl.wait_registry_empty(t, 10)\n\n\tmainCtrl.VerifyCounterValues(t)\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 TestReconcileSubscription(t *testing.T) {\n\tnewReconciledAdapter := mustNewReconciledAdapter(t)\n\tnewReconciledSource := mustNewReconciledSource(t)\n\n\ttestCases := rt.TableTest{\n\t\t// Regular lifecycle\n\n\t\t{\n\t\t\tName: \"Not yet subscribed\",\n\t\t\tKey: tKey,\n\t\t\tOtherTestData: mergeTableRowData(\n\t\t\t\tmakeMockTopics(true),\n\t\t\t\tmakeMockSubscriptionsPages(false),\n\t\t\t),\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tnewReconciledSource(),\n\t\t\t\tnewReconciledServiceAccount(),\n\t\t\t\tnewReconciledConfigWatchRoleBinding(),\n\t\t\t\tnewReconciledMTAdapterRoleBinding(),\n\t\t\t\tnewReconciledAdapter(),\n\t\t\t},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{{\n\t\t\t\tObject: newReconciledSource(subscribed),\n\t\t\t}},\n\t\t\tWantEvents: []string{\n\t\t\t\tsubscribedEvent(),\n\t\t\t},\n\t\t\tPostConditions: []func(*testing.T, *rt.TableRow){\n\t\t\t\tcalledSubscribe(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Already subscribed\",\n\t\t\tKey: tKey,\n\t\t\tOtherTestData: mergeTableRowData(\n\t\t\t\tmakeMockTopics(true),\n\t\t\t\tmakeMockSubscriptionsPages(true),\n\t\t\t),\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tnewReconciledSource(subscribed),\n\t\t\t\tnewReconciledServiceAccount(),\n\t\t\t\tnewReconciledConfigWatchRoleBinding(),\n\t\t\t\tnewReconciledMTAdapterRoleBinding(),\n\t\t\t\tnewReconciledAdapter(),\n\t\t\t},\n\t\t\tPostConditions: []func(*testing.T, *rt.TableRow){\n\t\t\t\tcalledSubscribe(false),\n\t\t\t},\n\t\t},\n\n\t\t// Finalization\n\n\t\t{\n\t\t\tName: \"Deletion while subscribed\",\n\t\t\tKey: tKey,\n\t\t\tOtherTestData: mergeTableRowData(\n\t\t\t\tmakeMockTopics(true),\n\t\t\t\tmakeMockSubscriptionsPages(true),\n\t\t\t),\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tnewReconciledSource(subscribed, deleted),\n\t\t\t\tnewReconciledServiceAccount(),\n\t\t\t\tnewReconciledConfigWatchRoleBinding(),\n\t\t\t\tnewReconciledMTAdapterRoleBinding(),\n\t\t\t\tnewReconciledAdapter(),\n\t\t\t},\n\t\t\tWantPatches: []clientgotesting.PatchActionImpl{\n\t\t\t\tunsetFinalizerPatch(),\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tfinalizedEvent(),\n\t\t\t\tunsubscribedEvent(),\n\t\t\t},\n\t\t\tPostConditions: []func(*testing.T, *rt.TableRow){\n\t\t\t\tcalledUnsubscribe(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Deletion while subscribed and topic is gone\",\n\t\t\tKey: tKey,\n\t\t\tOtherTestData: mergeTableRowData(\n\t\t\t\tmakeMockTopics(false),\n\t\t\t\tmakeMockSubscriptionsPages(true),\n\t\t\t),\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tnewReconciledSource(subscribed, deleted),\n\t\t\t\tnewReconciledServiceAccount(),\n\t\t\t\tnewReconciledConfigWatchRoleBinding(),\n\t\t\t\tnewReconciledMTAdapterRoleBinding(),\n\t\t\t\tnewReconciledAdapter(),\n\t\t\t},\n\t\t\tWantPatches: []clientgotesting.PatchActionImpl{\n\t\t\t\tunsetFinalizerPatch(),\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tfinalizedEvent(),\n\t\t\t\tunsubscribedEvent(),\n\t\t\t},\n\t\t\tPostConditions: []func(*testing.T, *rt.TableRow){\n\t\t\t\tcalledUnsubscribe(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Deletion while not subscribed\",\n\t\t\tKey: tKey,\n\t\t\tOtherTestData: mergeTableRowData(\n\t\t\t\tmakeMockTopics(true),\n\t\t\t\tmakeMockSubscriptionsPages(false),\n\t\t\t),\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tnewReconciledSource(deleted),\n\t\t\t\tnewReconciledServiceAccount(),\n\t\t\t\tnewReconciledConfigWatchRoleBinding(),\n\t\t\t\tnewReconciledMTAdapterRoleBinding(),\n\t\t\t\tnewReconciledAdapter(),\n\t\t\t},\n\t\t\tWantPatches: []clientgotesting.PatchActionImpl{\n\t\t\t\tunsetFinalizerPatch(),\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tfinalizedEvent(),\n\t\t\t\tnoopUnsubscribeEvent(),\n\t\t\t},\n\t\t\tPostConditions: []func(*testing.T, *rt.TableRow){\n\t\t\t\tcalledUnsubscribe(false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Deletion while not subscribed and topic is gone\",\n\t\t\tKey: tKey,\n\t\t\tOtherTestData: mergeTableRowData(\n\t\t\t\tmakeMockTopics(false),\n\t\t\t\tmakeMockSubscriptionsPages(false),\n\t\t\t),\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tnewReconciledSource(deleted),\n\t\t\t\tnewReconciledServiceAccount(),\n\t\t\t\tnewReconciledConfigWatchRoleBinding(),\n\t\t\t\tnewReconciledMTAdapterRoleBinding(),\n\t\t\t\tnewReconciledAdapter(),\n\t\t\t},\n\t\t\tWantPatches: []clientgotesting.PatchActionImpl{\n\t\t\t\tunsetFinalizerPatch(),\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tfinalizedEvent(),\n\t\t\t},\n\t\t\tPostConditions: []func(*testing.T, *rt.TableRow){\n\t\t\t\tcalledUnsubscribe(false),\n\t\t\t},\n\t\t},\n\n\t\t// Error cases\n\n\t\t{\n\t\t\tName: \"Topic not found while subscribing\",\n\t\t\tKey: tKey,\n\t\t\tWantErr: true,\n\t\t\tOtherTestData: mergeTableRowData(\n\t\t\t\tmakeMockTopics(false),\n\t\t\t\tmakeMockSubscriptionsPages(false),\n\t\t\t),\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tnewReconciledSource(),\n\t\t\t\tnewReconciledServiceAccount(),\n\t\t\t\tnewReconciledConfigWatchRoleBinding(),\n\t\t\t\tnewReconciledMTAdapterRoleBinding(),\n\t\t\t\tnewReconciledAdapter(),\n\t\t\t},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{{\n\t\t\t\tObject: newReconciledSource(notSubscribedTopicNotFound),\n\t\t\t}},\n\t\t\tWantEvents: []string{\n\t\t\t\ttopicNotFoundSubscribeEvent(),\n\t\t\t},\n\t\t\tPostConditions: []func(*testing.T, *rt.TableRow){\n\t\t\t\tcalledSubscribe(false),\n\t\t\t},\n\t\t},\n\t}\n\n\tctor := reconcilerCtor(adapterCfg)\n\n\ttestCases.Test(t, MakeFactory(ctor))\n}",
"func TestV3ElectionObserve(t *testing.T) {\n\tintegration.BeforeTest(t)\n\tclus := integration.NewCluster(t, &integration.ClusterConfig{Size: 1})\n\tdefer clus.Terminate(t)\n\n\tlc := integration.ToGRPC(clus.Client(0)).Election\n\n\t// observe leadership events\n\tobservec := make(chan struct{}, 1)\n\tgo func() {\n\t\tdefer close(observec)\n\t\ts, err := lc.Observe(context.Background(), &epb.LeaderRequest{Name: []byte(\"foo\")})\n\t\tobservec <- struct{}{}\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tresp, rerr := s.Recv()\n\t\t\tif rerr != nil {\n\t\t\t\tt.Error(rerr)\n\t\t\t}\n\t\t\trespV := 0\n\t\t\tfmt.Sscanf(string(resp.Kv.Value), \"%d\", &respV)\n\t\t\t// leader transitions should not go backwards\n\t\t\tif respV < i {\n\t\t\t\tt.Errorf(`got observe value %q, expected >= \"%d\"`, string(resp.Kv.Value), i)\n\t\t\t}\n\t\t\ti = respV\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-observec:\n\tcase <-time.After(time.Second):\n\t\tt.Fatalf(\"observe stream took too long to start\")\n\t}\n\n\tlease1, err1 := integration.ToGRPC(clus.RandClient()).Lease.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: 30})\n\tif err1 != nil {\n\t\tt.Fatal(err1)\n\t}\n\tc1, cerr1 := lc.Campaign(context.TODO(), &epb.CampaignRequest{Name: []byte(\"foo\"), Lease: lease1.ID, Value: []byte(\"0\")})\n\tif cerr1 != nil {\n\t\tt.Fatal(cerr1)\n\t}\n\n\t// overlap other leader so it waits on resign\n\tleader2c := make(chan struct{})\n\tgo func() {\n\t\tdefer close(leader2c)\n\n\t\tlease2, err2 := integration.ToGRPC(clus.RandClient()).Lease.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: 30})\n\t\tif err2 != nil {\n\t\t\tt.Error(err2)\n\t\t}\n\t\tc2, cerr2 := lc.Campaign(context.TODO(), &epb.CampaignRequest{Name: []byte(\"foo\"), Lease: lease2.ID, Value: []byte(\"5\")})\n\t\tif cerr2 != nil {\n\t\t\tt.Error(cerr2)\n\t\t}\n\t\tfor i := 6; i < 10; i++ {\n\t\t\tv := []byte(fmt.Sprintf(\"%d\", i))\n\t\t\treq := &epb.ProclaimRequest{Leader: c2.Leader, Value: v}\n\t\t\tif _, err := lc.Proclaim(context.TODO(), req); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor i := 1; i < 5; i++ {\n\t\tv := []byte(fmt.Sprintf(\"%d\", i))\n\t\treq := &epb.ProclaimRequest{Leader: c1.Leader, Value: v}\n\t\tif _, err := lc.Proclaim(context.TODO(), req); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\t// start second leader\n\tlc.Resign(context.TODO(), &epb.ResignRequest{Leader: c1.Leader})\n\n\tselect {\n\tcase <-observec:\n\tcase <-time.After(time.Second):\n\t\tt.Fatalf(\"observe did not observe all events in time\")\n\t}\n\n\t<-leader2c\n}",
"func terminate_agreement(ag *contract_api.SolidityContract, agID []byte, counterParty string, shouldWork bool) {\n log.Printf(\"Terminating agreement %v.\\n\", agID)\n tx_delay_toleration := 120\n err := error(nil)\n\n p := make([]interface{},0,10)\n p = append(p, counterParty)\n p = append(p, agID)\n p = append(p, 1)\n if _, err = ag.Invoke_method(\"terminate_agreement\", p); err != nil {\n log.Printf(\"...terminating, could not invoke terminate_agreement: %v\\n\", err)\n os.Exit(1)\n }\n log.Printf(\"Terminate agreement %v invoked.\\n\", agID)\n\n p = make([]interface{},0,10)\n p = append(p, counterParty)\n p = append(p, agID)\n empty_bytes := make([]byte, 32)\n var res interface{}\n start_timer := time.Now()\n for {\n fmt.Printf(\"There should NOT be a recorded contract hash, but it might still be visible for a few blocks.\\n\")\n if res, err = ag.Invoke_method(\"get_contract_hash\", p); err == nil {\n fmt.Printf(\"Received contract hash:%v.\\n\",res)\n if shouldWork {\n if bytes.Compare([]byte(res.(string)), empty_bytes) != 0 {\n if int(time.Now().Sub(start_timer).Seconds()) < tx_delay_toleration {\n fmt.Printf(\"Sleeping, waiting for the block with the Update.\\n\")\n time.Sleep(15 * time.Second)\n } else {\n fmt.Printf(\"Timeout waiting for the Update.\\n\")\n os.Exit(1)\n }\n } else {\n log.Printf(\"Terminated agreement %v.\\n\", agID)\n break\n }\n } else {\n if bytes.Compare([]byte(res.(string)), empty_bytes) == 0 {\n if int(time.Now().Sub(start_timer).Seconds()) < tx_delay_toleration {\n fmt.Printf(\"Sleeping, waiting for the block with the Update.\\n\")\n time.Sleep(15 * time.Second)\n } else {\n fmt.Printf(\"Timeout waiting for the Update. This is expected\\n\")\n break\n }\n } else {\n fmt.Printf(\"Received contract hash. This is NOT expected: %v\\n\", res.(string))\n os.Exit(2)\n }\n }\n } else {\n fmt.Printf(\"Error on get_contract_hash: %v\\n\",err)\n os.Exit(1)\n }\n }\n}",
"func AssessAgreement(a *model.Agreement, ma monitor.MonitoringAdapter, now time.Time) amodel.Result {\n\tvar result amodel.Result\n\tvar err error\n\n\tlog.Debugf(\"AssessAgreement(%s)\", a.Id)\n\tif a.Details.Expiration != nil && a.Details.Expiration.Before(now) {\n\t\t// agreement has expired\n\t\ta.State = model.TERMINATED\n\t}\n\n\tif a.State == model.STARTED {\n\t\tresult, err = EvaluateAgreement(a, ma, now)\n\t\tif err != nil {\n\t\t\tlog.Warn(\"Error evaluating agreement \" + a.Id + \": \" + err.Error())\n\t\t\treturn result\n\t\t}\n\t\tupdateAssessment(a, result, now)\n\t}\n\treturn result\n}",
"func TestSubMergeDelAndRouteUpdateNok(t *testing.T) {\n\tCaseBegin(\"TestSubMergeDelAndRouteUpdateNok\")\n\n\t// Init counter check\n\tmainCtrl.CounterValuesToBeVeriefied(t, CountersToBeAdded{\n\t\tCounter{cSubReqFromXapp, 2},\n\t\tCounter{cMergedSubscriptions, 1},\n\t\tCounter{cSubReqToE2, 1},\n\t\tCounter{cSubRespFromE2, 1},\n\t\tCounter{cSubRespToXapp, 2},\n\t\tCounter{cSubDelReqFromXapp, 2},\n\t\tCounter{cRouteDeleteUpdateFail, 1},\n\t\tCounter{cSubDelReqToE2, 1},\n\t\tCounter{cSubDelRespFromE2, 1},\n\t\tCounter{cSubDelRespToXapp, 2},\n\t\tCounter{cUnmergedSubscriptions, 1},\n\t})\n\n\t//Req1\n\trparams1 := &teststube2ap.E2StubSubsReqParams{}\n\trparams1.Init()\n\tcretrans1 := xappConn1.SendSubsReq(t, rparams1, nil)\n\tcrereq1, cremsg1 := e2termConn1.RecvSubsReq(t)\n\te2termConn1.SendSubsResp(t, crereq1, cremsg1)\n\te2SubsId1 := xappConn1.RecvSubsResp(t, cretrans1)\n\n\t//Req2\n\trparams2 := &teststube2ap.E2StubSubsReqParams{}\n\trparams2.Init()\n\tcretrans2 := xappConn2.SendSubsReq(t, rparams2, nil)\n\te2SubsId2 := xappConn2.RecvSubsResp(t, cretrans2)\n\n\tresp, _ := xapp.Subscription.QuerySubscriptions()\n\tassert.Equal(t, resp[0].SubscriptionID, int64(e2SubsId1))\n\tassert.Equal(t, resp[0].Meid, \"RAN_NAME_1\")\n\tassert.Equal(t, resp[0].ClientEndpoint, []string{\"localhost:13560\", \"localhost:13660\"})\n\n\t//Del1\n\twaiter := rtmgrHttp.AllocNextEvent(false)\n\tdeltrans1 := xappConn1.SendSubsDelReq(t, nil, e2SubsId1)\n\twaiter.WaitResult(t)\n\n\txappConn1.RecvSubsDelResp(t, deltrans1)\n\n\t//Del2\n\tdeltrans2 := xappConn2.SendSubsDelReq(t, nil, e2SubsId2)\n\tdelreq2, delmsg2 := e2termConn1.RecvSubsDelReq(t)\n\te2termConn1.SendSubsDelResp(t, delreq2, delmsg2)\n\txappConn2.RecvSubsDelResp(t, deltrans2)\n\t//Wait that subs is cleaned\n\tmainCtrl.wait_subs_clean(t, e2SubsId2, 10)\n\n\txappConn1.TestMsgChanEmpty(t)\n\txappConn2.TestMsgChanEmpty(t)\n\te2termConn1.TestMsgChanEmpty(t)\n\tmainCtrl.wait_registry_empty(t, 10)\n\n\tmainCtrl.VerifyCounterValues(t)\n}",
"func waitForAgreement(sm *ShardMaster, seq int) interface{} {\n\tto := 10 * time.Millisecond\n\tvar agreed interface{}\n\tvar decided bool\n\tfor true {\n\t\tdecided, agreed = sm.px.Status(seq)\n\t\tif decided {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(to)\n\t\tif to < 10*time.Second {\n\t\t\tto *= 2\n\t\t}\n\t}\n\treturn agreed\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GitCommonDir returns commondir where contains "config" file
|
func (v Repository) GitCommonDir() string {
return v.gitCommonDir
}
|
[
"func (v Repository) CommonDir() string {\n\tdir := v.RepoDir()\n\tcommonDir := dir\n\tif path.IsFile(filepath.Join(dir, \"commondir\")) {\n\t\tf, err := os.Open(filepath.Join(dir, \"commondir\"))\n\t\tif err == nil {\n\t\t\ts := bufio.NewScanner(f)\n\t\t\tif s.Scan() {\n\t\t\t\tcommonDir = s.Text()\n\t\t\t\tif !filepath.IsAbs(commonDir) {\n\t\t\t\t\tcommonDir = filepath.Join(dir, commonDir)\n\t\t\t\t}\n\t\t\t}\n\t\t\tf.Close()\n\t\t}\n\t}\n\treturn commonDir\n}",
"func (repo *GitRepository) commonDir() (dir string, err error) {\n\tdotGitPath := filepath.Join(repo.Path, git.GitDirName)\n\n\tvar rawRepo *git.Repository\n\tif rawRepo, err = git.PlainOpen(repo.Path); err != nil {\n\t\treturn\n\t}\n\n\tparent := repo.Path\n\tvar stat os.FileInfo\n\tif stat, err = os.Stat(dotGitPath); os.IsNotExist(err) {\n\t\t// A .git directory doesn't exist. Are we in a bare repository?\n\t\tvar worktree *git.Worktree\n\t\tif worktree, err = rawRepo.Worktree(); err == git.ErrIsBareRepository {\n\t\t\terr = nil\n\t\t\tdir = parent\n\t\t\treturn\n\t\t} else {\n\t\t\tif stat, err = worktree.Filesystem.Stat(git.GitDirName); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tparent = worktree.Filesystem.Root()\n\t\t}\n\t} else if err != nil {\n\t\treturn\n\t}\n\n\t// .git will either be a directory ...\n\tif stat.IsDir() {\n\t\tdir = filepath.Join(parent, stat.Name())\n\t\treturn\n\t}\n\n\t// or a file with `gitdir: {path}` in the case of a worktree.\n\tvar rawContent []byte\n\tif rawContent, err = ioutil.ReadFile(filepath.Join(parent, stat.Name())); err != nil {\n\t\treturn\n\t}\n\n\tdir = strings.TrimSpace(strings.TrimPrefix(string(rawContent), \"gitdir: \"))\n\treturn\n}",
"func getConfigDirRelativePath() string {\n\treturn viper.GetString(\"configDir\")\n}",
"func FindGitConfig(dir string) (string, error) {\n\tvar err error\n\n\tif dir, err = findGitDir(dir); err != nil {\n\t\treturn \"\", err\n\t}\n\tif dir, err = getGitCommonDir(dir); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(dir, \"config\"), nil\n}",
"func configDir() (string, error) {\n\txdg := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif xdg != \"\" {\n\t\treturn filepath.Join(xdg, botConfigDir), nil\n\t}\n\thome, err := homeDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(home, \".config\", botConfigDir), nil\n}",
"func getConfigDir() string {\n\tconfigRoot := os.ExpandEnv(\"$HOME/.config\")\n\tif xdgConfig, ok := os.LookupEnv(\"XDG_CONFIG_HOME\"); ok {\n\t\tconfigRoot = xdgConfig\n\t}\n\treturn filepath.Join(configRoot, \"barista\", \"oauth\")\n}",
"func (g *GitLocal) FindGitConfigDir(dir string) (string, string, error) {\n\treturn g.GitCLI.FindGitConfigDir(dir)\n}",
"func ConfigDir(app string) string {\n\treturn filepath.Join(HomeDir(), \".config\", app)\n}",
"func GhorgConfDir() string {\n\tif XConfigHomeSet() {\n\t\txdg := os.Getenv(\"XDG_CONFIG_HOME\")\n\t\treturn filepath.Join(xdg, \"ghorg\")\n\t}\n\n\treturn filepath.Join(HomeDir(), \".config\", \"ghorg\")\n}",
"func ConfigDir() string {\n\treturn configDir\n}",
"func SyncGetConfigDir() string {\n\tif errInitRoot != nil {\n\t\treturn \"\"\n\t}\n\treturn configDir\n}",
"func ConfigFolder() string {\n\tgopath := GoPath()\n\treturn filepath.Join(gopath, \"src\", \"github.com\",\n\t\t\"liuchaoren\", \"passphoto\", \"config\")\n}",
"func (s *Scope) configDir() (string, error) {\n\tp, err := s.dataDir()\n\tif err != nil {\n\t\treturn p, err\n\t}\n\n\treturn filepath.Join(p, \"Config\"), nil\n}",
"func ConfigDir() string {\n\tconfigDir := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif configDir != \"\" {\n\t\treturn configDir\n\t}\n\n\treturn filepath.Join(HomeDir(), \".config\")\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 (cf *ConfigFile) ConfigRelativeToWorkingDir() string {\n\t// filepath.Join will clean the resulting path, but here I want to\n\t// leave parent paths in, e.g., `staging/../.flux.yaml`\n\treturn fmt.Sprintf(\"%s%c%s\", cf.workingDirRelative, filepath.Separator, cf.configPathRelative)\n}",
"func GetConfigRootDir() string {\n\tconfigFile := viper.GetString(\"viper.config_file\")\n\tif configFile == \"\" {\n\t\tcwd, _ := os.Getwd()\n\t\treturn cwd\n\t}\n\n\treturn path.Dir(configFile)\n}",
"func GitDir(ctx context.Context, git *Tool) (string, error) {\n\tline, err := git.RunOneLiner(ctx, '\\n', \"rev-parse\", \"--absolute-git-dir\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.EvalSymlinks(string(line))\n}",
"func GetConfDir() string {\n\treturn fileutil.GetConfDir()\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.